plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
scanUCLA/MRtools_Hoffman2-master
|
postpad.m
|
.m
|
MRtools_Hoffman2-master/Utilities/postpad.m
| 2,013 |
utf_8
|
2c9539d77ff0f85c9f89108f4dc811e0
|
% Copyright (C) 1994, 1995, 1996, 1997, 1998, 2000, 2002, 2004, 2005,
% 2006, 2007, 2008, 2009 John W. Eaton
%
% This file is part of Octave.
%
% Octave 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.
%
% Octave 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 Octave; see the file COPYING. If not, see
% <http://www.gnu.org/licenses/>.
% -*- texinfo -*-
% @deftypefn {Function File} {} postpad (@var{x}, @var{l}, @var{c})
% @deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c}, @var{dim})
% @seealso{prepad, resize}
% @end deftypefn
% Author: Tony Richardson <[email protected]>
% Created: June 1994
function y = postpad (x, l, c, dim)
if nargin < 2 || nargin > 4
%print_usage ();
error('wrong number of input arguments, should be between 2 and 4');
end
if nargin < 3 || isempty(c)
c = 0;
else
if ~isscalar(c)
error ('postpad: third argument must be empty or a scalar');
end
end
nd = ndims(x);
sz = size(x);
if nargin < 4
% Find the first non-singleton dimension
dim = 1;
while dim < nd+1 && sz(dim)==1
dim = dim + 1;
end
if dim > nd
dim = 1;
elseif ~(isscalar(dim) && dim == round(dim)) && dim > 0 && dim< nd+1
error('postpad: dim must be an integer and valid dimension');
end
end
if ~isscalar(l) || l<0
error ('second argument must be a positive scalar');
end
if dim > nd
sz(nd+1:dim) = 1;
end
d = sz(dim);
if d >= l
idx = cell(1,nd);
for i = 1:nd
idx{i} = 1:sz(i);
end
idx{dim} = 1:l;
y = x(idx{:});
else
sz(dim) = l-d;
y = cat(dim, x, c * ones(sz));
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
sftrans.m
|
.m
|
MRtools_Hoffman2-master/Utilities/sftrans.m
| 7,947 |
utf_8
|
f64cb2e7d19bcdc6232b39d8a6d70e7c
|
% Copyright (C) 1999 Paul Kienzle
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; If not, see <http://www.gnu.org/licenses/>.
% usage: [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)
%
% Transform band edges of a generic lowpass filter (cutoff at W=1)
% represented in splane zero-pole-gain form. W is the edge of the
% target filter (or edges if band pass or band stop). Stop is true for
% high pass and band stop filters or false for low pass and band pass
% filters. Filter edges are specified in radians, from 0 to pi (the
% nyquist frequency).
%
% Theory: Given a low pass filter represented by poles and zeros in the
% splane, you can convert it to a low pass, high pass, band pass or
% band stop by transforming each of the poles and zeros individually.
% The following table summarizes the transformation:
%
% Transform Zero at x Pole at x
% ---------------- ------------------------- ------------------------
% Low Pass zero: Fc x/C pole: Fc x/C
% S -> C S/Fc gain: C/Fc gain: Fc/C
% ---------------- ------------------------- ------------------------
% High Pass zero: Fc C/x pole: Fc C/x
% S -> C Fc/S pole: 0 zero: 0
% gain: -x gain: -1/x
% ---------------- ------------------------- ------------------------
% Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S^2+FhFl pole: 0 zero: 0
% S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C
% S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
% Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl)
% S -> C -------- gain: -x gain: -1/x
% S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
% Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT)
% 2 z-1 pole: -1 zero: -1
% S -> - --- gain: (2-xT)/T gain: (2-xT)/T
% T z+1
% ---------------- ------------------------- ------------------------
%
% where C is the cutoff frequency of the initial lowpass filter, Fc is
% the edge of the target low/high pass filter and [Fl,Fh] are the edges
% of the target band pass/stop filter. With abundant tedious algebra,
% you can derive the above formulae yourself by substituting the
% transform for S into H(S)=S-x for a zero at x or H(S)=1/(S-x) for a
% pole at x, and converting the result into the form:
%
% H(S)=g prod(S-Xi)/prod(S-Xj)
%
% The transforms are from the references. The actual pole-zero-gain
% changes I derived myself.
%
% Please note that a pole and a zero at the same place exactly cancel.
% This is significant for High Pass, Band Pass and Band Stop filters
% which create numerous extra poles and zeros, most of which cancel.
% Those which do not cancel have a 'fill-in' effect, extending the
% shorter of the sets to have the same number of as the longer of the
% sets of poles and zeros (or at least split the difference in the case
% of the band pass filter). There may be other opportunistic
% cancellations but I will not check for them.
%
% Also note that any pole on the unit circle or beyond will result in
% an unstable filter. Because of cancellation, this will only happen
% if the number of poles is smaller than the number of zeros and the
% filter is high pass or band pass. The analytic design methods all
% yield more poles than zeros, so this will not be a problem.
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
% 2000-03-01 [email protected]
% leave transformed Sg as a complex value since cheby2 blows up
% otherwise (but only for odd-order low-pass filters). bilinear
% will return Zg as real, so there is no visible change to the
% user of the IIR filter design functions.
% 2001-03-09 [email protected]
% return real Sg; don't know what to do for imaginary filters
function [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)
if (nargin ~= 5)
usage('[Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)');
end;
C = 1;
p = length(Sp);
z = length(Sz);
if z > p || p == 0
error('sftrans: must have at least as many poles as zeros in s-plane');
end
if length(W)==2
Fl = W(1);
Fh = W(2);
if stop
% ---------------- ------------------------- ------------------------
% Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl)
% S -> C -------- gain: -x gain: -1/x
% S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
if (isempty(Sz))
Sg = Sg * real (1./ prod(-Sp));
elseif (isempty(Sp))
Sg = Sg * real(prod(-Sz));
else
Sg = Sg * real(prod(-Sz)/prod(-Sp));
end
b = (C*(Fh-Fl)/2)./Sp;
Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
extend = [sqrt(-Fh*Fl), -sqrt(-Fh*Fl)];
if isempty(Sz)
Sz = [extend(1+rem([1:2*p],2))];
else
b = (C*(Fh-Fl)/2)./Sz;
Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if (p > z)
Sz = [Sz, extend(1+rem([1:2*(p-z)],2))];
end
end
else
% ---------------- ------------------------- ------------------------
% Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl)
% S^2+FhFl pole: 0 zero: 0
% S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C
% S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2
% ---------------- ------------------------- ------------------------
Sg = Sg * (C/(Fh-Fl))^(z-p);
b = Sp*((Fh-Fl)/(2*C));
Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if isempty(Sz)
Sz = zeros(1,p);
else
b = Sz*((Fh-Fl)/(2*C));
Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)];
if (p>z)
Sz = [Sz, zeros(1, (p-z))];
end
end
end
else
Fc = W;
if stop
% ---------------- ------------------------- ------------------------
% High Pass zero: Fc C/x pole: Fc C/x
% S -> C Fc/S pole: 0 zero: 0
% gain: -x gain: -1/x
% ---------------- ------------------------- ------------------------
if (isempty(Sz))
Sg = Sg * real (1./ prod(-Sp));
elseif (isempty(Sp))
Sg = Sg * real(prod(-Sz));
else
Sg = Sg * real(prod(-Sz)/prod(-Sp));
end
Sp = C * Fc ./ Sp;
if isempty(Sz)
Sz = zeros(1,p);
else
Sz = [C * Fc ./ Sz];
if (p > z)
Sz = [Sz, zeros(1,p-z)];
end
end
else
% ---------------- ------------------------- ------------------------
% Low Pass zero: Fc x/C pole: Fc x/C
% S -> C S/Fc gain: C/Fc gain: Fc/C
% ---------------- ------------------------- ------------------------
Sg = Sg * (C/Fc)^(z-p);
Sp = Fc * Sp / C;
Sz = Fc * Sz / C;
end
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
filtfilt.m
|
.m
|
MRtools_Hoffman2-master/Utilities/filtfilt.m
| 3,297 |
iso_8859_1
|
d01a26a827bc3379f05bbc57f46ac0a9
|
% Copyright (C) 1999 Paul Kienzle
% Copyright (C) 2007 Francesco Potortì
% Copyright (C) 2008 Luca Citi
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; If not, see <http://www.gnu.org/licenses/>.
% usage: y = filtfilt(b, a, x)
%
% Forward and reverse filter the signal. This corrects for phase
% distortion introduced by a one-pass filter, though it does square the
% magnitude response in the process. That's the theory at least. In
% practice the phase correction is not perfect, and magnitude response
% is distorted, particularly in the stop band.
%%
% Example
% [b, a]=butter(3, 0.1); % 10 Hz low-pass filter
% t = 0:0.01:1.0; % 1 second sample
% x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise
% y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter
% plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;')
% Changelog:
% 2000 02 [email protected]
% - pad with zeros to load up the state vector on filter reverse.
% - add example
% 2007 12 [email protected]
% - use filtic to compute initial and final states
% - work for multiple columns as well
% 2008 12 [email protected]
% - fixed instability issues with IIR filters and noisy inputs
% - initial states computed according to Likhterov & Kopeika, 2003
% - use of a "reflection method" to reduce end effects
% - added some basic tests
% TODO: (pkienzle) My version seems to have similar quality to matlab,
% but both are pretty bad. They do remove gross lag errors, though.
function y = filtfilt(b, a, x)
if (nargin ~= 3)
usage('y=filtfilt(b,a,x)');
end
rotate = (size(x, 1)==1);
if rotate % a row vector
x = x(:); % make it a column vector
end
lx = size(x,1);
a = a(:).';
b = b(:).';
lb = length(b);
la = length(a);
n = max(lb, la);
lrefl = 3 * (n - 1);
if la < n, a(n) = 0; end
if lb < n, b(n) = 0; end
% Compute a the initial state taking inspiration from
% Likhterov & Kopeika, 2003. "Hardware-efficient technique for
% minimizing startup transients in Direct Form II digital filters"
kdc = sum(b) / sum(a);
if (abs(kdc) < inf) % neither NaN nor +/- Inf
si = fliplr(cumsum(fliplr(b - kdc * a)));
else
si = zeros(size(a)); % fall back to zero initialization
end
si(1) = [];
y = zeros(size(x));
for c = 1:size(x, 2) % filter all columns, one by one
v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c);
2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector
% Do forward and reverse filtering
v = filter(b,a,v,si*v(1)); % forward filter
v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter
y(:,c) = v((lrefl+1):(lx+lrefl));
end
if (rotate) % x was a row vector
y = rot90(y); % rotate it back
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
bilinear.m
|
.m
|
MRtools_Hoffman2-master/Utilities/bilinear.m
| 4,339 |
utf_8
|
17250db27826cad87fa3384823e1242f
|
% Copyright (C) 1999 Paul Kienzle
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; If not, see <http://www.gnu.org/licenses/>.
% usage: [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T)
% [Zb, Za] = bilinear(Sb, Sa, T)
%
% Transform a s-plane filter specification into a z-plane
% specification. Filters can be specified in either zero-pole-gain or
% transfer function form. The input form does not have to match the
% output form. 1/T is the sampling frequency represented in the z plane.
%
% Note: this differs from the bilinear function in the signal processing
% toolbox, which uses 1/T rather than T.
%
% Theory: Given a piecewise flat filter design, you can transform it
% from the s-plane to the z-plane while maintaining the band edges by
% means of the bilinear transform. This maps the left hand side of the
% s-plane into the interior of the unit circle. The mapping is highly
% non-linear, so you must design your filter with band edges in the
% s-plane positioned at 2/T tan(w*T/2) so that they will be positioned
% at w after the bilinear transform is complete.
%
% The following table summarizes the transformation:
%
% +---------------+-----------------------+----------------------+
% | Transform | Zero at x | Pole at x |
% | H(S) | H(S) = S-x | H(S)=1/(S-x) |
% +---------------+-----------------------+----------------------+
% | 2 z-1 | zero: (2+xT)/(2-xT) | zero: -1 |
% | S -> - --- | pole: -1 | pole: (2+xT)/(2-xT) |
% | T z+1 | gain: (2-xT)/T | gain: (2-xT)/T |
% +---------------+-----------------------+----------------------+
%
% With tedious algebra, you can derive the above formulae yourself by
% substituting the transform for S into H(S)=S-x for a zero at x or
% H(S)=1/(S-x) for a pole at x, and converting the result into the
% form:
%
% H(Z)=g prod(Z-Xi)/prod(Z-Xj)
%
% Please note that a pole and a zero at the same place exactly cancel.
% This is significant since the bilinear transform creates numerous
% extra poles and zeros, most of which cancel. Those which do not
% cancel have a 'fill-in' effect, extending the shorter of the sets to
% have the same number of as the longer of the sets of poles and zeros
% (or at least split the difference in the case of the band pass
% filter). There may be other opportunistic cancellations but I will
% not check for them.
%
% Also note that any pole on the unit circle or beyond will result in
% an unstable filter. Because of cancellation, this will only happen
% if the number of poles is smaller than the number of zeros. The
% analytic design methods all yield more poles than zeros, so this will
% not be a problem.
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
function [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T)
if nargin==3
T = Sg;
[Sz, Sp, Sg] = tf2zp(Sz, Sp);
elseif nargin~=4
usage('[Zz, Zp, Zg]=bilinear(Sz,Sp,Sg,T) or [Zb, Za]=blinear(Sb,Sa,T)');
end;
p = length(Sp);
z = length(Sz);
if z > p || p==0
error('bilinear: must have at least as many poles as zeros in s-plane');
end
% ---------------- ------------------------- ------------------------
% Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT)
% 2 z-1 pole: -1 zero: -1
% S -> - --- gain: (2-xT)/T gain: (2-xT)/T
% T z+1
% ---------------- ------------------------- ------------------------
Zg = real(Sg * prod((2-Sz*T)/T) / prod((2-Sp*T)/T));
Zp = (2+Sp*T)./(2-Sp*T);
if isempty(Sz)
Zz = -ones(size(Zp));
else
Zz = [(2+Sz*T)./(2-Sz*T)];
Zz = postpad(Zz, p, -1);
end
if nargout==2, [Zz, Zp] = zp2tf(Zz, Zp, Zg); end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
butter.m
|
.m
|
MRtools_Hoffman2-master/Utilities/butter.m
| 3,621 |
utf_8
|
aa8e4440d4f5659bfdc78c05e275a458
|
% Copyright (C) 1999 Paul Kienzle
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; If not, see <http://www.gnu.org/licenses/>.
% Generate a butterworth filter.
% Default is a discrete space (Z) filter.
%
% [b,a] = butter(n, Wc)
% low pass filter with cutoff pi*Wc radians
%
% [b,a] = butter(n, Wc, 'high')
% high pass filter with cutoff pi*Wc radians
%
% [b,a] = butter(n, [Wl, Wh])
% band pass filter with edges pi*Wl and pi*Wh radians
%
% [b,a] = butter(n, [Wl, Wh], 'stop')
% band reject filter with edges pi*Wl and pi*Wh radians
%
% [z,p,g] = butter(...)
% return filter as zero-pole-gain rather than coefficients of the
% numerator and denominator polynomials.
%
% [...] = butter(...,'s')
% return a Laplace space filter, W can be larger than 1.
%
% [a,b,c,d] = butter(...)
% return state-space matrices
%
% References:
%
% Proakis & Manolakis (1992). Digital Signal Processing. New York:
% Macmillan Publishing Company.
% Author: Paul Kienzle <[email protected]>
% Modified by: Doug Stewart <[email protected]> Feb, 2003
function [a, b, c, d] = butter (n, W, varargin)
% keyboard;
if (nargin>4 || nargin<2) || (nargout>4 || nargout<2)
usage ('[b, a] or [z, p, g] or [a,b,c,d] = butter (n, W [, "ftype"][,"s"])');
end
% interpret the input parameters
if (~(length(n)==1 && n == round(n) && n > 0))
error ('butter: filter order n must be a positive integer');
end
stop = 0;
digital = 1;
for i=1:length(varargin)
switch varargin{i}
case 's', digital = 0;
case 'z', digital = 1;
case { 'high', 'stop' }, stop = 1;
case { 'low', 'pass' }, stop = 0;
otherwise, warning('Going with defaults: stop=0; digital=1');%error ('butter: expected [high|stop] or [s|z]');
end
end
[r, c]=size(W);
if (~(length(W)<=2 && (r==1 || c==1)))
error ('butter: frequency must be given as w0 or [w0, w1]');
elseif (~(length(W)==1 || length(W) == 2))
error ('butter: only one filter band allowed');
elseif (length(W)==2 && ~(W(1) < W(2)))
error ('butter: first band edge must be smaller than second');
end
if ( digital && ~all(W >= 0 & W <= 1))
error ('butter: critical frequencies must be in (0 1)');
elseif ( ~digital && ~all(W >= 0 ))
error ('butter: critical frequencies must be in (0 inf)');
end
% Prewarp to the band edges to s plane
if digital
T = 2; % sampling frequency of 2 Hz
W = 2/T*tan(pi*W/T);
end
% Generate splane poles for the prototype butterworth filter
% source: Kuc
C = 1; % default cutoff frequency
pole = C*exp(1i*pi*(2*[1:n] + n - 1)/(2*n));
if mod(n,2) == 1, pole((n+1)/2) = -1; end % pure real value at exp(i*pi)
zero = [];
gain = C^n;
% splane frequency transform
[zero, pole, gain] = sftrans(zero, pole, gain, W, stop);
% Use bilinear transform to convert poles to the z plane
if digital
[zero, pole, gain] = bilinear(zero, pole, gain, T);
end
% convert to the correct output form
if nargout==2,
a = real(gain*poly(zero));
b = real(poly(pole));
elseif nargout==3,
a = zero;
b = pole;
c = gain;
else
% output ss results
[a, b, c, d] = zp2ss (zero, pole, gain);
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
colmap.m
|
.m
|
MRtools_Hoffman2-master/Utilities/colmap.m
| 17,277 |
utf_8
|
34cf76a5861b666aed0e9d9030c68f1d
|
function [cm list] = colmap(map,depth,custom)
%%% Written by Aaron P. Schultz - [email protected]
%%%
%%% Copyright (C) 2014, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01-AG027435
%%%
%%% 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
%%% 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.
list = {'gray' 'hot' 'cool' 'jet' 'hsv' 'pink' 'spring' 'summer' 'autumn' 'winter' 'bone' 'copper' 'red' 'red2' 'green' 'blue' 'yellow' 'yellow2' 'purple' 'purple2' 'cyan2' 'mag2' 'ocean' 'orange' 'my' 'ym' 'mby' 'cy' 'yc' 'mc' 'cm' ...
'jet1' 'jet2' 'cool2' ...
'cbd_rd_yl_gn' 'cbd_rd_yl_bu' 'cbd_rd_gy' 'cbd_rd_bu' 'cbd_pu_or' 'cbd_pu_gn' 'cbd_pi_yl_gn' 'cbd_br_bg' ...
'cbs_yl_or_rd' 'cbs_yl_or_br' 'cbs_yl_gn_bu' 'cbs_yl_gn' 'cbs_rd_pu' 'cbs_pu' 'cbs_pu_rd' 'cbs_pu_bu_gn' 'cbs_pu_bu' 'cbs_or_rd' 'cbs_or' 'cbs_gr' 'cbs_gn' 'cbs_gn_bu' 'cbs_bu_pu' 'cbs_bn_gn' 'cbs_bu' ...
'cbq_set1' 'cbq_paied' 'cbq_dark2' 'cbq_accent' 'cbq_pastel1' 'cbq_pastel2' 'cbq_set2' 'cbq_set3' 'parula' ...
'test1' 'lightgray' ...
'custom'};
if isempty(map);
map = ' ';
end
if nargin<3
custom = [];
end
switch lower(map)
case('gray')
cm = gray(depth);
case('hot')
cm = hot(depth);
case('hot3')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(1,1,depth)';
cm(:,2) = linspace(0,1,depth)';
cm(:,3) = linspace(0,0,depth)';
case('cool')
cm = cool(depth);
case('cool2')
cm = cool(depth);
cm = cm(end:-1:1,:);
case('cool3')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(0,0,depth)';
cm(:,2) = linspace(0,1,depth)';
cm(:,3) = linspace(1,1,depth)';
case('jet')
cm = jet(depth);
case('jet1')
cm = jet(depth*2);
cm = cm(1:depth,:);
case('jet2')
cm = jet(depth*2);
cm = cm(end:-1:end-(depth-1),:);
case('hsv')
cm = hsv(depth);
case('pink')
cm = pink(depth);
case('spring')
cm = spring(depth);
case('summer')
cm = summer(depth);
case('autumn')
cm = autumn(depth);
case('winter')
cm = winter(depth);
case('bone')
cm = bone(depth);
case('copper')
cm = copper(depth);
case('parula')
cm = parula(depth);
case('red')
cm = ones(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,1) = x(end:-1:1);
case('red2')
cm = zeros(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,1) = x(1:end);
case('green')
cm = ones(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,2) = x(end:-1:1);
case('blue')
cm = ones(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,3) = x(1:end);
case('yellow')
cm = ones(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,1) = x(end:-1:1);
cm(:,2) = x(end:-1:1);
case('yellow2')
cm = zeros(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,1) = x(1:end);
cm(:,2) = x(1:end);
case('purple')
cm = ones(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,1) = x(end:-1:1);
cm(:,3) = x(end:-1:1);
case('purple2')
cm = zeros(depth,3);
x = 0:(1/(depth-1)):1;
cm(end:-1:1,1) = x(end:-1:1);
cm(end:-1:1,3) = x(end:-1:1);
case('cyan2')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(0,0,depth)';
cm(:,2) = linspace(0,1,depth)';
cm(:,3) = linspace(0,1,depth)';
case('mag2')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(0,1,depth)';
cm(:,2) = linspace(0,0,depth)';
cm(:,3) = linspace(0,1,depth)';
case('ocean')
cm = ones(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,2) = x(end:-1:1);
cm(:,3) = x(end:-1:1);
case('orange')
cm = ones(depth,3)*0;
x = 0:(1/(depth-1)):1;
cm(:,1) = x(end:-1:1);
cm(:,2) = x(end:-1:1)*.5;
case('my')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(1,1,depth)';
cm(:,2) = linspace(0,1,depth)';
cm(:,3) = linspace(1,0,depth)';
case('ym')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(1,1,depth)';
cm(:,2) = linspace(1,0,depth)';
cm(:,3) = linspace(0,1,depth)';
case 'mby'
n = depth/2;
cm = zeros(depth,3)*0;
cm(1:n,1) = linspace(1,0,n)';
cm(1:n,2) = linspace(0,0,n)';
cm(1:n,3) = linspace(1,0,n)';
cm(n+1:end,1) = linspace(0,1,n)';
cm(n+1:end,2) = linspace(0,1,n)';
cm(n+1:end,3) = linspace(0,0,n)';
case('cy')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(0,1,depth)';
cm(:,2) = linspace(1,1,depth)';
cm(:,3) = linspace(1,0,depth)';
case('yc')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(1,0,depth)';
cm(:,2) = linspace(1,1,depth)';
cm(:,3) = linspace(0,1,depth)';
case('mc')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(1,0,depth)';
cm(:,2) = linspace(0,1,depth)';
cm(:,3) = linspace(1,1,depth)';
case('cm')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(0,1,depth)';
cm(:,2) = linspace(1,0,depth)';
cm(:,3) = linspace(1,1,depth)';
case('lightgray')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(.2,.8,depth)';
cm(:,2) = linspace(.2,.8,depth)';
cm(:,3) = linspace(.2,.8,depth)';
case('lightergray')
cm = zeros(depth,3)*0;
cm(:,1) = linspace(.3,.7,depth)';
cm(:,2) = linspace(.3,.7,depth)';
cm(:,3) = linspace(.3,.7,depth)';
case('cbd_rd_yl_gn')
cols = [0.6471 0 0.1490
1.0000 1.0000 0.7490
0 0.4078 0.2157];
cm = mkmap(cols,depth);
case('cbd_rd_yl_bu')
cols = [0.6471 0 0.1490
1.0000 1.0000 0.7490
0.1922 0.2118 0.5843];
cm = mkmap(cols,depth);
case('cbd_rd_gy')
cols = [0.4039 0 0.1216
1.0000 1.0000 1.0000
0.1020 0.1020 0.1020];
cm = mkmap(cols,depth);
case('cbd_rd_bu')
cols = [0.4039 0 0.1216
1 1 1
0.0196 0.1882 0.3804];
cm = mkmap(cols,depth);
case('cbd_pu_or')
cols = [0.4980 0.2314 0.0314
0.9686 0.9686 0.9686
0.1765 0 0.2941];
cm = mkmap(cols,depth);
case('cbd_pu_gn')
cols = [0.5569 0.0039 0.3216;
1 1 1 ;
0.1529 0.3922 0.0980];
cm = mkmap(cols,depth);
case('cbd_pi_yl_gn')
cols = [0.5569 0.0039 0.3216
0.9686 0.9686 0.9686
0.1529 0.3922 0.0980];
cm = mkmap(cols,depth);
case('cbd_br_bg')
cols = [0.3294 0.1882 0.0196
0.9608 0.9608 0.9608
0 0.2353 0.1882];
cm = mkmap(cols,depth);
case('cbs_yl_or_rd')
cols = [1.0000 1.0000 0.8000
0.9882 0.3059 0.1647
0.5020 0 0.1490];
cm = mkmap(cols,depth);
case('cbs_yl_or_br')
cols = [1.0000 1.0000 0.8980
0.9255 0.4392 0.0784
0.4000 0.1451 0.0235];
cm = mkmap(cols,depth);
case('cbs_yl_gn_bu')
cols = [1.0000 1.0000 0.8510
0.1137 0.5686 0.7529
0.0314 0.1137 0.3451];
cm = mkmap(cols,depth);
case('cbs_yl_gn')
cols = [1.0000 1.0000 0.8980
0.2549 0.6706 0.3647
0 0.2706 0.1608];
cm = mkmap(cols,depth);
case('cbs_rd_pu')
cols = [1.0000 0.9686 0.9529
0.8667 0.2039 0.5922
0.2863 0 0.4157];
cm = mkmap(cols,depth);
case('cbs_pu')
cols = [0.9882 0.9843 0.9922
0.5020 0.4902 0.7294
0.2471 0 0.4902];
cm = mkmap(cols,depth);
case('cbs_pu_rd')
cols = [0.9686 0.9569 0.9765
0.9059 0.1608 0.5412
0.4039 0 0.1216];
cm = mkmap(cols,depth);
case('cbs_pu_bu_gn')
cols = [1.0000 0.9686 0.9843
0.2118 0.5647 0.7529
0.0039 0.2745 0.2118];
cm = mkmap(cols,depth);
case('cbs_pu_bu')
cols = [1.0000 0.9686 0.9843
0.2118 0.5647 0.7529
0.0078 0.2196 0.3451];
cm = mkmap(cols,depth);
case('cbs_or_rd')
cols = [1.0000 0.9686 0.9255
0.9373 0.3961 0.2824
0.4980 0 0];
cm = mkmap(cols,depth);
case('cbs_or')
cols = [1.0000 0.9608 0.9216
0.9451 0.4118 0.0745
0.4980 0.1529 0.0157];
cm = mkmap(cols,depth);
case('cbs_gr')
cols = [1.0000 1.0000 1.0000
0.4510 0.4510 0.4510
0 0 0];
cm = mkmap(cols,depth);
case('cbs_gn')
cols = [0.9686 0.9882 0.9608
0.2549 0.6706 0.3647
0 0.2667 0.1059];
cm = mkmap(cols,depth);
case('cbs_gn_bu')
cols = [0.9686 0.9882 0.9412
0.3059 0.7020 0.8275
0.0314 0.2510 0.5059];
cm = mkmap(cols,depth);
case('cbs_bu_pu')
cols = [0.9686 0.9882 0.9922
0.5490 0.4196 0.6941
0.3020 0 0.2941];
cm = mkmap(cols,depth);
case('cbs_bn_gn')
cols = [0.9686 0.9882 0.9922
0.2549 0.6824 0.4627
0 0.2667 0.1059];
cm = mkmap(cols,depth);
case('cbs_bu')
cols = [0.9686 0.9843 1.0000
0.2588 0.5725 0.7765
0.0314 0.1882 0.4196];
cm = mkmap(cols,depth);
case('cbq_set1')
dat = [0.8941 0.1020 0.1098
0.2157 0.4941 0.7216
0.3020 0.6863 0.2902
0.5961 0.3059 0.6392
1.0000 0.4980 0
1.0000 1.0000 0.2000
0.6510 0.3373 0.1569
0.9686 0.5059 0.7490
0.6000 0.6000 0.6000];
cm = zeros(depth,3);
for ii = 1:size(dat,2);
nx = 1:8/(depth-1):9;
ny = interp1(1:9,dat(:,ii),nx,'PCHIP');
cm(:,ii) = ny;
end
case('cbq_paied')
dat = [0.6510 0.8078 0.8902
0.1216 0.4706 0.7059
0.6980 0.8745 0.5412
0.2000 0.6275 0.1725
0.9843 0.6039 0.6000
0.8902 0.1020 0.1098
0.9922 0.7490 0.4353
1.0000 0.4980 0
0.7922 0.6980 0.8392];
cm = zeros(depth,3);
for ii = 1:size(dat,2);
nx = 1:8/(depth-1):9;
ny = interp1(1:9,dat(:,ii),nx,'PCHIP');
cm(:,ii) = ny;
end
case('cbq_dark2')
dat = [0.1059 0.6196 0.4667
0.8510 0.3725 0.0078
0.4588 0.4392 0.7020
0.9059 0.1608 0.5412
0.6549 0.3961 0.3176
0.4000 0.6510 0.1176
0.9020 0.6706 0.0078
0.6510 0.4627 0.1137
0.4000 0.4000 0.4000];
cm = zeros(depth,3);
for ii = 1:size(dat,2);
nx = 1:8/(depth-1):9;
ny = interp1(1:9,dat(:,ii),nx,'PCHIP');
cm(:,ii) = ny;
end
case('cbq_accent')
dat = [0.4980 0.7882 0.4980
0.7451 0.6824 0.8314
0.9922 0.7529 0.5255
1.0000 1.0000 0.6000
0.6118 0.8000 0.6588
0.2196 0.4235 0.6902
0.9412 0.0078 0.4980
0.7490 0.3569 0.0902
0.4000 0.4000 0.4000];
cm = zeros(depth,3);
for ii = 1:size(dat,2);
nx = 1:8/(depth-1):9;
ny = interp1(1:9,dat(:,ii),nx,'PCHIP');
cm(:,ii) = ny;
end
case('cbq_pastel1')
dat = [0.9843 0.7059 0.6824
0.7020 0.8039 0.8902
0.8000 0.9216 0.7725
0.8706 0.7961 0.8941
0.9961 0.8510 0.6510
1.0000 1.0000 0.8000
0.8980 0.8471 0.7412
0.9922 0.8549 0.9255
0.9490 0.9490 0.9490];
cm = zeros(depth,3);
for ii = 1:size(dat,2);
nx = 1:8/(depth-1):9;
ny = interp1(1:9,dat(:,ii),nx,'PCHIP');
cm(:,ii) = ny;
end
case('cbq_pastel2')
dat = [0.7020 0.8863 0.8039
0.9922 0.8039 0.6745
0.7961 0.8353 0.9098
0.9569 0.7922 0.8941
0.9294 0.8784 0.8549
0.9020 0.9608 0.7882
1.0000 0.9490 0.6824
0.9451 0.8863 0.8000
0.8000 0.8000 0.8000];
cm = zeros(depth,3);
for ii = 1:size(dat,2);
nx = 1:8/(depth-1):9;
ny = interp1(1:9,dat(:,ii),nx,'PCHIP');
cm(:,ii) = ny;
end
case('cbq_set2')
dat = [0.4000 0.7608 0.6471
0.9882 0.5529 0.3843
0.5529 0.6275 0.7961
0.9059 0.5412 0.7647
0.7804 0.6941 0.5765
0.6510 0.8471 0.3294
1.0000 0.8510 0.1843
0.8980 0.7686 0.5804
0.7020 0.7020 0.7020];
cm = zeros(depth,3);
for ii = 1:size(dat,2);
nx = 1:8/(depth-1):9;
ny = interp1(1:9,dat(:,ii),nx,'PCHIP');
cm(:,ii) = ny;
end
case('cbq_set3')
dat = [0.5529 0.8275 0.7804
1.0000 1.0000 0.7020
0.7451 0.7294 0.8549
0.9843 0.5020 0.4471
0.5020 0.6941 0.8275
0.9922 0.7059 0.3843
0.7020 0.8706 0.4118
0.9882 0.8039 0.8980
0.8510 0.8510 0.8510];
cm = zeros(depth,3);
for ii = 1:size(dat,2);
nx = 1:8/(depth-1):9;
ny = interp1(1:9,dat(:,ii),nx,'PCHIP');
cm(:,ii) = ny;
end
case('test1')
%figure(10); clf; imagesc((1:255)'); set(gca,'ydir','normal'); colorbar; shg
xx = (1:depth)';
cols = [0 0 0; 1 0 0; 1 1 0; 0 1 1; 0 0 1; 1 0 1;];
%%cols = [0 0 0; 1 0 0; 0 1 0; 0 0 1; 1 1 1];
x = (1:(depth-1)/(size(cols,1)-1):depth)';
for ii = 1:size(cols,2)
cm(:,ii) = spline(x, cols(:,ii),xx);
end
cm(cm<0)=0; cm(cm>1)=1;
% for ii = 1:size(cm,2);
% if range(cm(:,ii))>1
% cm(:,1) = cm(:,ii)-min(cm(:,ii));
% cm(:,ii) = cm(:,ii)./max(cm(:,ii));
% end
% end
case('custom')
if isempty(custom)
fh = figure(777); clf; %reset(777);
pop(1) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .83 .9 .05],'String','Enter the colors you want (e.g. [1 0 0; 0 1 0; 0 0 1]','Fontsize',12);
pop(2) = uicontrol(fh,'style','edit','Units','Normalized','position',[.05 .75 .9 .08],'String','','Fontsize',12,'Callback','uiresume');
uiwait
eval(['custom = [' get(pop(2),'String') '];']);
close(gcf);
end
cm = mkmap(custom,depth);
otherwise
cm = jet(depth);
end
end
function cm = mkmap(cols,depth)
cm = zeros(depth,3);
if size(cols,1)==2;
cm(:,1) = linspace(cols(1,1),cols(2,1),depth)';
cm(:,2) = linspace(cols(1,2),cols(2,2),depth)';
cm(:,3) = linspace(cols(1,3),cols(2,3),depth)';
elseif size(cols,1)==3;
n = depth/2;
cm(1:n,1) = linspace(cols(1,1),cols(2,1),n)';
cm(1:n,2) = linspace(cols(1,2),cols(2,2),n)';
cm(1:n,3) = linspace(cols(1,3),cols(2,3),n)';
cm(n+1:end,1) = linspace(cols(2,1),cols(3,1),n)';
cm(n+1:end,2) = linspace(cols(2,2),cols(3,2),n)';
cm(n+1:end,3) = linspace(cols(2,3),cols(3,3),n)';
end
end
% figure(1); clf; scatter(1:256,1:256,[],cm);
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
original20150821_FIVE.m
|
.m
|
MRtools_Hoffman2-master/Visualization/original20150821_FIVE.m
| 170,340 |
utf_8
|
c25aab3735b43725afe314c25e5a0a5f
|
function [Obj VOI peak] = FIVE(inputImage,linkHands)
%%% This is an image viewing and plotting utility. Just launch it with
%%% "FIVE" at the command line. There are a great many features in
%%% this viewer, and you can learn all about them at:
%%% http://nmr.mgh.harvard.edu/harvardagingbrain/People/AaronSchultz/Aarons_Scripts.html
%%%
%%% For launching FIVE you can do one of the following:
%%% FIVE; %% Launch FIVE and then load images
%%% FIVE({'OverLay1.nii' 'Overlay2.img'}); %% This will launch FIVE with the specified overlays.
%%% FIVE({{'Underlay.nii'}}); %% this will launch FIVE with the specified underlay image
%%% FIVE({{'Underlay.nii'} {'OverLay1.nii' 'Overlay2.img'}}); %% This will launch FIVE with the specified underlay and load up the specified overlays.
%%%
%%% Ignore the linkHands input. This is for specialized call back functions.
%%%
%%% Some FIVE features require additinal packages, for instance get
%%% peaks requires Donald McLaren's peak_nii package, and the VOI plotting
%%% options will require that the analysis be done with GLM_Flex.
%%%
%%% Written by Aaron P. Schultz - [email protected]
%%%
%%% Copyright (C) 2011, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01-AG027435
%%%
%%% 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
%%% 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.
%%%
%%% system(['sh run_FIVE.sh /usr/pubsw/common/matlab/8.0/']);
% Update the colormaps, and colormapping system.
depth = 256;
[trash, cmaps] = colmap('jet',depth);
hand = [];
links = [];
origDat = [];
contrasts = [];
DM = [];
plotGo = 0;
Flist = [];
mniLims = [];
Des = [];
DataHeaders = [];
Outliers = [];
lastItem = [];
tabHand = [];
% global Obj;
Obj = [];
VOI = [];
peak = [];
modelType = [];
CachedClusterLoc = [];
ConExp = 0;
ConLayer = [];
ConHeader = [];
ssConExp = 0;
ssConLayer = [];
ssConHeader = [];
ssData = [];
clickFlag = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize the underlay
MH = spm_vol([fileparts(which('spm')) '/canonical/single_subj_T1.nii']); %% template underlay all image data is mapped to this orientation
if nargin > 0
try
if iscell(inputImage{1});
[a b c] = fileparts(inputImage{1}{1});
if strcmpi('.mgz',c)
m = MRIread(inputImage{1}{1});
m.descrip = [];
MRIwrite(m,[a b '.nii'],'float');
inputImage{1}{1} = [a b '.nii'];
%hh.fname = [m.fspec(1:end-3) 'nii'];
%hh.dim = m.volsize;
%hh.mat = m.vox2ras1;
%hh.pinfo = [1;0;352];
%hh.dt = [16 0];
%hh.n = [1 1];
%hh.descrip = ['MGZ Volume'];
%hh.private = [];
end
h = spm_vol(inputImage{1}{1});
[I mmm] = SliceAndDice3(h,MH,[],[],[3 NaN],[]);
h.dim = size(I);
h.mat = mmm;
else
[I h] = openIMG(which('defaultUnderlay.nii'));
end
catch
[I h] = openIMG(which('defaultUnderlay.nii'));
end
else
[I h] = openIMG(which('defaultUnderlay.nii'));
end
Obj = initializeUnderlay(I,h);
movego = 0;
loc = [0 0 0];
mc = round([loc 1] * inv(Obj(1).h.mat)');
Obj(1).point = round([loc 1] * inv(Obj(1).h.mat)');
Obj(1).lastpoint = [round(size(Obj(1).I)/2) 1]-1;
Obj(1).Range = [min(Obj(1).I(:)) max(Obj(1).I(:)) max(Obj(1).I(:))-min(Obj(1).I(:))];
Obj(1).FOV = sort([ [1 1 1 1]*Obj(1).h.mat'; [Obj(1).axLims 1]*Obj(1).h.mat']);
Obj(1).col = 1;
if any((size(Obj(1).I) - Obj(1).point(1:3))<0);
Obj(1).point = [round(size(Obj(1).I)/2) 1];
tmp = Obj(1).point*Obj(1).h.mat';
loc = tmp(1:3);
end
% if ~isempty(contains('aschultz',{UserTime})); keyboard; end
setupFrames(1,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create the figure window
height = []; width = []; rat = [];
ax1 = []; ax2 = []; ax3 = []; ax4 = [];
con = []; menu = []; hcmenu = []; item = [];
setupFigure;
Obj(1).con = con;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Setup the figure menus
paramenu1 = []; paramenu2 = []; paramenu3 = []; paramenu4 = []; S = [];
setupParamMenu;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read in a label atlas
RNH = spm_vol([which('aal_MNI_V4.img')]);
[RNI Rxyz] = spm_read_vols(RNH);
RNames = load('aal_MNI_V4_List.mat');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw Underlay
ch = [];
drawFresh(ax1,1);
drawFresh(ax2,2);
drawFresh(ax3,3);
Obj(1).hand = hand;
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot CrossHairs
[ch(1,1), ch(1,2)] = crossHairs(ax1,[0 0]);
[ch(2,1), ch(2,2)] = crossHairs(ax2,[0 0]);
[ch(3,1), ch(3,2)] = crossHairs(ax3,[0 0]);
Obj(1).ch = ch;
set(ch, 'uicontextmenu',hcmenu);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Link CrossHair Positions
hListener1 = addlistener(ch(1,1),'XData','PostSet',@AutoUpdate);
hListener2 = addlistener(ch(2,1),'XData','PostSet',@AutoUpdate);
hListener3 = addlistener(ch(1,2),'YData','PostSet',@AutoUpdate);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Synchronize Views if requested
if nargin>1 && ~isempty(linkHands)
links{end+1}=linkprop([ch(1,1),linkHands(1,1)],'XData');
links{end+1}=linkprop([ch(1,2),linkHands(1,2)],'YData');
links{end+1}=linkprop([ch(2,1),linkHands(2,1)],'XData');
links{end+1}=linkprop([ch(2,2),linkHands(2,2)],'YData');
links{end+1}=linkprop([ch(3,1),linkHands(3,1)],'XData');
links{end+1}=linkprop([ch(3,2),linkHands(3,2)],'YData');
set(gcf,'UserData',links);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Open Prespecified Overlays
Count = 2;
if nargin > 0;
try
if iscell(inputImage{1})
if length(inputImage)>1
openOverlay(inputImage{2});
end
else
openOverlay(inputImage);
end
catch
openOverlay(inputImage);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yy = Obj(1).clim(1):(Obj(1).clim(2)-Obj(1).clim(1))/255:Obj(1).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(1).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make Figure Visible
set(findobj(gcf,'Fontsize', 10),'fontsize',12); shg
set(findobj(gcf,'Fontsize', 12),'fontsize',13); shg
set(pane,'Visible','on');
%%
function AutoUpdate(varargin)
vn = get(con(21,1),'Value');
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
xyz = [x(1) y(1) z(1)];
xyz((mniLims(1,:)-xyz)>0) = mniLims(1,(mniLims(1,:)-xyz)>0);
xyz((mniLims(2,:)-xyz)<0) = mniLims(2,(mniLims(2,:)-xyz)<0);
x = xyz(1); y = xyz(2); z = xyz(3);
for ii = 1:length(Obj)
Obj(ii).point = ceil([x y z 1] * inv(Obj(ii).h.mat)');
Obj(ii).point(Obj(ii).point(1:3)<1) = 1;
ind = find((Obj(ii).axLims-Obj(ii).point(1:3))<0);
Obj(ii).point(ind) = Obj(ii).axLims(ind);
if ii == 1;
p = ceil([x y z 1] * inv(RNH.mat)');
try
nm = RNames.ROI(RNI(p(1),p(2),p(3)));
set(paramenu1(2),'Label',nm.Nom_L);
catch
set(paramenu1(2),'Label','undefined');
end
end
end
setupFrames(1:length(Obj),0);
updateGraphics([1 2 3],0);
set(con(15,1),'String',num2str(round([x y z])));
mc = round([x y z 1] * inv(Obj(get(con(21,1),'Value')).h.mat)');
vn = get(con(21,1),'Value');
try
set(con(22,1),'String',num2str(Obj(get(con(21,1),'Value')).I(mc(1),mc(2),mc(3))));
catch
set(con(22,1),'String','NaN');
end
shg
end
function goTo(varargin)
if varargin{1}==con(15,1);
cl = str2num(get(con(15,1),'String'));
set(ch(1,1), 'XData', [cl(2) cl(2)]);
set(ch(1,2), 'YData', [cl(3) cl(3)]);
set(ch(2,1), 'XData', [cl(1) cl(1)]);
set(ch(2,2), 'YData', [cl(3) cl(3)]);
set(ch(3,1), 'XData', [cl(1) cl(1)]);
set(ch(3,2), 'YData', [cl(2) cl(2)]);
end
end
function buttonUp(varargin)
movego = 0;
end
function buttonDown(varargin)
%get(gcf,'SelectionType')
if strcmpi(get(gcf,'SelectionType'),'normal') || clickFlag==1;
movego = 1;
co1 = gco;
co2 = gca;
switch co2
case ax1
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
y = cp(1);
z = cp(2);
set(ch(1,1), 'XData', [y y]);
set(ch(1,2), 'YData', [z z]);
set(ch(2,2), 'YData', [z z]);
set(ch(3,2), 'YData', [y y]);
case ax2
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
x = cp(1);
z = cp(2);
set(ch(2,1), 'XData', [x x]);
set(ch(2,2), 'YData', [z z]);
set(ch(1,2), 'YData', [z z]);
set(ch(3,1), 'XData', [x x]);
case ax3
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
y = cp(1);
x = cp(2);
set(ch(3,1), 'XData', [y y]);
set(ch(3,2), 'YData', [x x]);
set(ch(1,1), 'XData', [x x]);
set(ch(2,1), 'XData', [y y]);
otherwise
end
end
if strcmpi(get(gcf,'SelectionType'),'extend');
plotVOI(lastItem);
end
if strcmpi(get(gcf,'SelectionType'),'alt');
if ConExp ~=0
updateConnMap;
elseif ssConExp ~= 0;
ssUpdateConnMap;
end
end
end
function buttonMotion(varargin)
if movego == 1;
co1 = gco;
co2 = gca;
switch co2
case ax1
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
y = cp(1);
z = cp(2);
if Obj(1).FOV(1,2)>y; y=Obj(1).FOV(1,2); end;
if Obj(1).FOV(2,2)<y; y=Obj(1).FOV(2,2); end;
if Obj(1).FOV(1,3)>z; z=Obj(1).FOV(1,3); end;
if Obj(1).FOV(2,3)<z; z=Obj(1).FOV(2,3); end;
set(ch(1,1), 'XData', [y y]);
set(ch(1,2), 'YData', [z z]);
set(ch(2,2), 'YData', [z z]);
set(ch(3,2), 'YData', [y y]);
case ax2
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
x = cp(1);
z = cp(2);
if Obj(1).FOV(1,1)>x; x=Obj(1).FOV(1,1); end;
if Obj(1).FOV(2,1)<x; x=Obj(1).FOV(2,1); end;
if Obj(1).FOV(1,3)>z; z=Obj(1).FOV(1,3); end;
if Obj(1).FOV(2,3)<z; z=Obj(1).FOV(2,3); end;
set(ch(2,1), 'XData', [x x]);
set(ch(2,2), 'YData', [z z]);
set(ch(1,2), 'YData', [z z]);
set(ch(3,1), 'XData', [x x]);
case ax3
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
y = cp(1);
x = cp(2);
if Obj(1).FOV(1,1)>x; x=Obj(1).FOV(1,1); end;
if Obj(1).FOV(2,1)<x; x=Obj(1).FOV(2,1); end;
if Obj(1).FOV(1,2)>y; y=Obj(1).FOV(1,2); end;
if Obj(1).FOV(2,2)<y; y=Obj(1).FOV(2,2); end;
set(ch(3,1), 'XData', [y y]);
set(ch(3,2), 'YData', [x x]);
set(ch(1,1), 'XData', [x x]);
set(ch(2,1), 'XData', [y y]);
otherwise
end
end
end
function openOverlay(varargin)
if nargin == 0
nnn = spm_select(inf,'image');
else
if iscell(varargin{1})
nnn = char(varargin{1});
elseif ischar(varargin{1})
nnn = varargin{1};
else
nnn = spm_select(inf,'image');
end
for kk = 1:size(nnn,1)
n = strtrim(nnn(kk,:));
ind = find(n==filesep);
if isempty(ind);
nn = n;
n2 = n;
else
nn = n(ind(end)+1:end);
if numel(ind)>1
n2 = n(ind(end-1)+1:end);
else
n2 = n;
end
end
if mean(n==filesep)==0
n = [pwd filesep n];
end
hh = spm_vol(n);
set(con(21,1),'TooltipString',n)
a = world_bb(MH); b = world_bb(hh); tmp = a-b; tmp(1,:) = tmp(1,:)*-1;
if hh.dt(1)>=16
intOrd = 3;
else
intOrd = 0;
end
if all(tmp(:)>=0)
[m mmm] = SliceAndDice3(hh, MH, [], hh,[intOrd NaN],[]);
else
[m mmm] = SliceAndDice3(hh, MH, [], Obj(1).h,[intOrd NaN],[]);
end
%[m mmm] = SliceAndDice3(hh,MH,[],Obj(1).h,[0 NaN],[]);
hh.dim = size(m);
hh.mat = mmm;
Obj(Count).Name = n2;
Obj(Count).FullPath = n;
Obj(Count).DispName = n2;
set(gcf,'Name', ['FIVE: ' Obj(Count).DispName]);
Obj(Count).h = hh;
Obj(Count).I = double(m);
set(con(21,1),'String', [get(con(21,1),'String'); n2],'Value',Count);
if ~isempty(contains('{T_', {hh.descrip}));
tmp = hh.descrip;
i1 = find(tmp=='[');
i2 = find(tmp==']');
Obj(Count).DF = str2num(tmp(i1+1:i2-1));
th = spm_invTcdf(1-.001,Obj(Count).DF);
Obj(Count).Thresh = [th ceil(max(m(:))*1000)/1000];
Obj(Count).clim = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(Count).PVal = .001;
Obj(Count).col = 2;
Obj(Count).Trans = 1;
set(con(4),'String',[num2str(th) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(5),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(8),'String',num2str(Obj(Count).DF));
set(con(9),'String','++0.001');
elseif ~isempty(contains('{F_', {hh.descrip}))
tmp = hh.descrip;
i1 = find(tmp=='[');
i2 = find(tmp==']');
t1 = regexp(tmp(i1(1)+1:i2(1)-1),',','split');
df(1) = str2num(t1{1});
df(2) = str2num(t1{2});
Obj(Count).DF = df;
th = spm_invFcdf(1-.001,df(1), df(2));
Obj(Count).Thresh = [th ceil(max(m(:))*1000)/1000];
Obj(Count).clim = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(Count).PVal = .001;
Obj(Count).col = 2;
Obj(Count).Trans = 1;
set(con(4),'String',[num2str(th) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(5),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(8),'String',num2str(Obj(Count).DF));
set(con(9),'String','++0.001');
else
set(con(4),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(5),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(8),'String','NaN');
set(con(9),'String','NaN');
Obj(Count).DF = NaN;
Obj(Count).PVal = NaN;
Obj(Count).Thresh = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(Count).clim = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(Count).col = 2;
Obj(Count).Trans = 1;
end
set(con(23),'String','0');
Obj(Count).ClusterThresh = 0;
Obj(Count).Exclude = [];
Obj(Count).MaskInd = [];
Obj(Count).mask = ones(size(Obj(Count).I),'uint8');
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
loc = [x(1) y(1) z(1)];
Obj(Count).point = round([loc 1] * inv(Obj(Count).h.mat)');
Obj(Count).lastpoint = (round([loc 1] * inv(Obj(Count).h.mat)'))-1;
Obj(Count).axLims = size(Obj(Count).I);
setupFrames(Count,0);
Obj(Count).pos = axLim(Obj(Count).I,Obj(Count).h);
set(con(1,1),'Value',3);
drawFresh(ax1,1,Count);
drawFresh(ax2,2,Count);
drawFresh(ax3,3,Count);
uistack(ch(1,1),'top'); uistack(ch(1,2),'top');
uistack(ch(2,1),'top'); uistack(ch(2,2),'top');
uistack(ch(3,1),'top'); uistack(ch(3,2),'top');
Obj(Count).Range = [min(Obj(Count).I(:)) max(Obj(Count).I(:)) max(Obj(Count).I(:))-min(Obj(Count).I(:))];
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
yy = Obj(Count).clim(1):(Obj(Count).clim(2)-Obj(Count).clim(1))/255:Obj(Count).clim(2);
axes(ax4); cla
try
imagesc(yy,1,reshape(colmap(cmaps{Obj(Count).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
end
Count = Count+1;
end
end
end
function UpdateThreshold(varargin)
% Get the Volume Number.
vn = get(con(21,1),'Value');
% Get the ThresholdParamters
a = get(con(4),'String');
c = get(con(8),'String');
% d = get(con(9),'String');
% Parse the Threshold Parameters
if isempty(a);
a = [-inf inf];
else
if contains(',',{a})
ind = find(a==',');
a = [str2num(strtrim(a(1:ind-1))) str2num(strtrim(a(ind+1:end)))];
else
a = str2num(a);
end
end
if numel(a) == 2
% Correct the Threshold Parameter End Points
if a(1)==-inf
a(1) = floor(min(Obj(vn).I(:))*1000)/1000;
set(con(4),'string',[num2str(a(1)) ', ' num2str(a(2))])
end
if a(2)==inf
a(2) = ceil(max(Obj(vn).I(:))*1000)/1000;
set(con(4),'string',[num2str(a(1)) ', ' num2str(a(2))])
end
if a(1)>0 && a(2)>0
if numel(varargin)~=0 && varargin{1} ~= con(9,1)
if ~strcmpi(get(con(8,1),'String'),'NA')
df = str2num(get(con(8,1),'String'));
if isnan(df)
p = NaN;
else
if numel(df) == 1;
if isinf(df)
p = 1-spm_Ncdf(a(1),0,1);
else
p = 1-spm_Tcdf(a(1),df);
end
set(con(9,1),'String',['++' num2str(p)]);
end
if numel(df) == 2;
p = 1-spm_Fcdf(a(1),df(1),df(2));
set(con(9,1),'String',['++' num2str(p)]);
end
end
end
end
end
if a(1)<0 && a(2)<0
if numel(varargin)~=0 && varargin{1} ~= con(9,1)
if ~strcmpi(get(con(8,1),'String'),'NA')
df = str2num(get(con(8,1),'String'));
if isnan(df)
p = NaN;
else
if numel(df) == 1;
if isinf(df)
p = 1-spm_Ncdf(abs(a(2)),0,1);
else
p = 1-spm_Tcdf(abs(a(2)),df);
end
set(con(9,1),'String',['--' num2str(p)]);
end
if numel(df) == 2;
p = 1-spm_Fcdf(abs(a(2)),df(1),df(2));
set(con(9,1),'String',['--' num2str(p)]);
end
end
end
end
end
Obj(vn).Thresh = a;
elseif numel(a) == 4;
if a(1)==-inf
a(1) = floor(min(Obj(vn).I(:))*1000)/1000;
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
end
if a(4)==inf
a(4) = ceil(max(Obj(vn).I(:))*1000)/1000;
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
end
if numel(Obj(vn).Thresh)==numel(a);
check = Obj(vn).Thresh-a;
check = find(check~=0);
check = setdiff(check,[1 4]);
if numel(check)==1;
other = setdiff(2:3,check);
a(other) = -a(check);
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
end
if numel(varargin)>0 && varargin{1} ~= con(9,1)
if ~(strcmpi(get(con(8,1),'String'),'NA') || ~isempty(contains('nan', {lower(get(con(8,1),'String'))})))
df = str2num(get(con(8,1),'String'));
if numel(df) == 1;
if isinf(df)
p = (1-spm_Ncdf(abs(a(3)),0,1))*2;
else
p = (1-spm_Tcdf(abs(a(3)),df))*2;
end
set(con(9,1),'String',['+-' num2str(p)]);
end
if numel(df) == 2;
p = 1-spm_Fcdf(abs(a(3)),df(1),df(2));
set(con(9,1),'String',['+-' num2str(p)]);
end
end
end
else
if abs(a(2))~=abs(a(3))
ind1 = find(abs(a(2:3))==min(abs(a(2:3))));
ind2 = find(abs(a(2:3))==max(abs(a(2:3))));
a(ind1+1) = -a(ind2+1);
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
tmp = get(con(8,1),'String');
end
if numel(varargin)>0 && varargin{1} ~= con(9,1)
if ~strcmpi(get(con(8,1),'String'),'nan')
df = str2num(get(con(8,1),'String'));
if numel(df) == 1;
if isinf(df)
p = 1-spm_Ncdf(abs(a(2))/2,0,1);
else
p = 1-spm_Tcdf(abs(a(2))/2,df);
end
set(con(9,1),'String',['+-' num2str(p)]);
end
if numel(df) == 2;
p = 1-spm_Fcdf(abs(a(2)),df(1),df(2));
set(con(9,1),'String',['+-' num2str(p)]);
end
end
end
end
Obj(vn).Thresh = a;
end
loc = str2num(get(con(15),'String'));
Obj(vn).point = round([loc 1] * inv(Obj(vn).h.mat)');
if str2num(get(con(23),'String'))~=0
ExtentThresh;
end
setupFrames(vn,1);
updateGraphics({1:3 vn},1);
%Obj(vn).pos = axLim(Obj(vn).I,Obj(vn).h);
end
function UpdatePVal(varargin)
nv = get(con(21,1),'Value');
df = get(con(8,1),'String');
try
df = str2num(df);
if any(isnan(df));
return;
end
catch
set(con(8,1),'String','NA')
return
end
p = get(con(9,1),'String');
if mean(p(1:2)=='++')==1
direc = 1;
p = str2num(p(3:end));
elseif mean(p(1:2)=='--')==1
direc = -1;
p = str2num(p(3:end));
elseif mean(p(1:2)=='-+')==1 || mean(p(1:2)=='+-')==1
direc = 0;
p = str2num(p(3:end))/2;
else
p = str2num(p);
direc = 1;
end
Obj(nv).PVal = p;
Obj(nv).DF = df;
if numel(df)==1
if isinf(df)
T = spm_invNcdf(1-abs(p),0,1);
else
T = spm_invTcdf(1-abs(p),df);
end
elseif numel(df)==2
T = spm_invFcdf(1-abs(p),df(1),df(2));
end
curr = get(con(4),'String');
cur = regexp(curr,',','split');
if direc == 1
a = ceil(T*1000)/1000;
set(con(4),'String',[num2str(a) ', inf']);
%set(con(4),'String',[num2str(a) ',' cur{2}]);
UpdateThreshold;
elseif direc == -1
a = floor(-T*1000)/1000;
set(con(4),'String',['-inf ,' num2str(a)]);
%set(con(4),'String',[cur{1} ',' num2str(a)]);
UpdateThreshold;
elseif direc == 0
a = [];
%keyboard;
a(1) = floor(min(Obj(nv).I(:))*1000)/1000;
a(4) = ceil(max(Obj(nv).I(:))*1000)/1000;
a(2:3) = [floor(-T*1000)/1000 ceil(T*1000)/1000];
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
b = a([1 4]);
ind1 = find(abs(b)==min(abs(b)));
ind2 = find(abs(b)==max(abs(b)));
b(ind2) = -b(ind1);
UpdateThreshold;
end
end
function changeColorMap(varargin)
vn = get(con(21,1),'Value');
map = get(con(1,1),'Value');
if map == 1;
set(con(1,1),'Value',Obj(vn).col+1);
return;
end
Obj(vn).col = map-1;
setupFrames(vn,1);
updateGraphics({[1 2 3] vn},1);
%%% Update colorbar.
yy = Obj(vn).clim(1):(Obj(vn).clim(2)-Obj(vn).clim(1))/255:Obj(vn).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(vn).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
end
function adjustTrans(varargin)
vn = get(con(21,1),'Value');
if numel(hand{1})==1
return
end
const = get(varargin{1},'Value');
const = const+.0001;
if const>1; const = 1; end;
Obj(vn).Trans = const;
a = get(hand{1}(vn),'AlphaData');
a(a~=0)=const;
set(hand{1}(vn), 'AlphaData', a);
a = get(hand{2}(vn),'AlphaData');
a(a~=0)=const;
set(hand{2}(vn), 'AlphaData', a);
a = get(hand{3}(vn),'AlphaData');
a(a~=0)=const;
set(hand{3}(vn), 'AlphaData', a);
end
function resizeFig(varargin)
a = get(gcf,'Position');
hei = (height/width)*a(3);
wid = (width/height)*a(4);
if hei-a(4) > wid-a(3)
a(3) = wid;
elseif hei-a(4) < wid-a(3)
a(4) = hei;
end
set(gcf,'Position',a);
end
function switchObj(varargin)
if ~isempty(varargin)
if iscell(varargin{1})
nv = varargin{1}{1};
else
nv = get(con(21,1),'Value');
end
else
nv = get(con(21,1),'Value');
end
try
set(con(21,1),'TooltipString',Obj(nv).FullPath)
set(gcf,'Name', ['FIVE: ' Obj(nv).DispName]);
catch
end
set(con(2,1),'Value', Obj(nv).Trans);
set(con(23),'String', num2str(Obj(nv).ClusterThresh));
set(con(5,1),'String',[num2str(Obj(nv).clim(1)) ', ' num2str(Obj(nv).clim(2))]);
set(con(8,1), 'String',num2str(Obj(nv).DF));
if numel(Obj(nv).Thresh) == 4;
set(con(4,1),'String',[num2str(Obj(nv).Thresh(1)) ' ' num2str(Obj(nv).Thresh(2)) ', ' num2str(Obj(nv).Thresh(3)) ' ' num2str(Obj(nv).Thresh(4))]);
set(con(9,1), 'String',['+-' num2str(Obj(nv).PVal*2)]);
elseif sum(sign(Obj(nv).Thresh))>0
set(con(4,1),'String',[num2str(Obj(nv).Thresh(1)) ', ' num2str(Obj(nv).Thresh(2))]);
set(con(9,1), 'String',['++' num2str(Obj(nv).PVal)]);
elseif sum(sign(Obj(nv).Thresh))<0
set(con(4,1),'String',[num2str(Obj(nv).Thresh(1)) ', ' num2str(Obj(nv).Thresh(2))]);
set(con(9,1), 'String',['--' num2str(Obj(nv).PVal)]);
elseif sum(sign(Obj(nv).Thresh))==0
set(con(4,1),'String',[num2str(Obj(nv).Thresh(1)) ', ' num2str(Obj(nv).Thresh(2))]);
set(con(9,1), 'String',num2str(Obj(nv).PVal));
end
set(con(1,1),'Value', Obj(nv).col+1);
yy = Obj(nv).clim(1):(Obj(nv).clim(2)-Obj(nv).clim(1))/255:Obj(nv).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(nv).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
tmp1 = (Obj(nv).clim(2)-Obj(nv).Range(1))/Obj(nv).Range(3); if tmp1>1; tmp1=1; end; if tmp1<0; tmp1=0; end;
set(con(27),'Value', tmp1);
tmp1 = (Obj(nv).clim(1)-Obj(nv).Range(1))/Obj(nv).Range(3); if tmp1>1; tmp1=1; end; if tmp1<0; tmp1=0; end;
set(con(28),'Value', tmp1);
end
function removeVolume(varargin)
nv = get(con(21,1),'Value');
if nv == 1; return; end
ind = setdiff(1:length(Obj),nv);
tmp = get(con(21,1),'String');
set(con(21,1),'String',tmp(ind), 'Value',length(ind));
for ii = 1:length(hand)
delete(hand{ii}(nv));
end
Obj = Obj(ind);
hand{1} = hand{1}(ind);
hand{2} = hand{2}(ind);
hand{3} = hand{3}(ind);
Count = length(ind)+1;
switchObj;
end
function updateGraphics(HandInd,opt)
if iscell(HandInd);
HandInd2 = HandInd{2};
HandInd = HandInd{1};
else
HandInd2 = 1:length(Obj);
end
for ii = HandInd;
if Obj(1).point(ii)==Obj(1).lastpoint(ii) && opt~=1
continue
end
for jj = HandInd2
set(hand{ii}(jj),'CData',Obj(jj).frame{ii},'AlphaData',~isnan(Obj(jj).frame{ii}(:,:,1))*Obj(jj).Trans);
Obj(jj).lastpoint(ii) = Obj(jj).point(ii);
end
end
end
function drawFresh(axx,opt,opt2,opt3)
if nargin == 2;
opt2 = 1:length(Obj);
end
if nargin < 4
opt3 = 1;
end
axes(axx);
for ii = opt2;
if opt == 1;
tmp = image(Obj(ii).pos{2}, Obj(ii).pos{3}, Obj(ii).frame{opt});
if opt3; hand{opt}(ii) = tmp; end
set(tmp,'AlphaData', ~isnan(Obj(ii).frame{opt}(:,:,1))*Obj(ii).Trans);
set(axx, 'YDir','Normal'); set(gca, 'XDir','reverse'); axis equal;
end
if opt == 2;
tmp = image(Obj(ii).pos{1}, Obj(ii).pos{3}, Obj(ii).frame{opt});
if opt3; hand{opt}(ii) = tmp; end
set(tmp,'AlphaData', ~isnan(Obj(ii).frame{opt}(:,:,1))*Obj(ii).Trans);
set(axx, 'YDir','Normal'); set(gca, 'XDir','Normal');axis equal;
end
if opt == 3;
tmp = image(Obj(ii).pos{1}, Obj(ii).pos{2}, Obj(ii).frame{opt});
if opt3; hand{opt}(ii) = tmp; end
set(tmp,'AlphaData', ~isnan(Obj(ii).frame{opt}(:,:,1))*Obj(ii).Trans);
set(axx, 'YDir','Normal'); set(gca, 'XDir','Normal');axis equal;
end
end
set(axx,'XTick',[],'YTick',[]);
axis equal;
axis tight;
end
function out = axLim(dat,h)
t1 = [1 1 1 1; size(dat,1) 1 1 1]*h.mat';
out{1} = t1(1,1):(t1(2,1)-t1(1,1))/(size(dat,1)-1):t1(2,1);
t1 = [1 1 1 1; 1 size(dat,2) 1 1]*h.mat';
out{2} = t1(1,2):(t1(2,2)-t1(1,2))/(size(dat,2)-1):t1(2,2);
t1 = [1 1 1 1; 1 1 size(dat,3) 1]*h.mat';
out{3} = t1(1,3):(t1(2,3)-t1(1,3))/(size(dat,3)-1):t1(2,3);
out{1} = out{1}(end:-1:1);
end
function [h1 h2] = crossHairs(axx,loc)
axes(axx)
ax = axis;
h1 = plot([loc(1) loc(1)], ax(3:4),'b');
h2 = plot(ax(1:2),[loc(2) loc(2)],'b'); axis equal; axis tight;
end
function setupFrames(n,opt)
for ii = n;
ss = Obj(ii).axLims;
if Obj(ii).point(1)~=Obj(ii).lastpoint(1) || opt==1
tmp = Obj(ii).I(Obj(ii).point(1),:,:);
tmp(Obj(ii).mask(Obj(ii).point(1),:,:)==0)=NaN;
if numel(Obj(ii).Thresh)==2
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(2));
else
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(4) | (tmp>Obj(ii).Thresh(2) & tmp<Obj(ii).Thresh(3)));
end
tmp(ind) = NaN;
tmp(tmp==0)=NaN;
tmp = flipdim(rot90(squeeze(tmp),1),1);
[cols cm cc] = cmap(tmp, Obj(ii).clim, cmaps{Obj(ii).col});
Obj(ii).frame{1} = reshape(cols,[size(tmp) 3]);
end
if Obj(ii).point(2)~=Obj(ii).lastpoint(2) || opt==1
tmp = Obj(ii).I(:,Obj(ii).point(2),:);
tmp(Obj(ii).mask(:,Obj(ii).point(2),:)==0)=NaN;
if numel(Obj(ii).Thresh)==2
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(2));
else
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(4) | (tmp>Obj(ii).Thresh(2) & tmp<Obj(ii).Thresh(3)));
end
tmp(ind) = NaN;
tmp(tmp==0)=NaN;
tmp = flipdim(flipdim(rot90(squeeze(tmp),1),1),2);
[cols cm cc] = cmap(tmp, Obj(ii).clim, cmaps{Obj(ii).col});
Obj(ii).frame{2} = reshape(cols,[size(tmp) 3]);
end
if Obj(ii).point(3)~=Obj(ii).lastpoint(3) || opt==1
tmp = Obj(ii).I(:,:,Obj(ii).point(3));
tmp(Obj(ii).mask(:,:,Obj(ii).point(3))==0)=NaN;
if numel(Obj(ii).Thresh)==2
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(2));
else
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(4) | (tmp>Obj(ii).Thresh(2) & tmp<Obj(ii).Thresh(3)));
end
tmp(ind) = NaN;
tmp(tmp==0)=NaN;
tmp = flipdim(flipdim(rot90(squeeze(tmp),1),1),2);
[cols cm cc] = cmap(tmp, Obj(ii).clim, cmaps{Obj(ii).col});
Obj(ii).frame{3} = reshape(cols,[size(tmp) 3]);
end
end
end
function toggle(varargin)
state = get(varargin{1},'Checked');
if strcmpi(state,'on');
set(varargin{1},'Checked','off');
end
if strcmpi(state,'off');
set(varargin{1},'Checked','on');
end
end
function toggleCrossHairs(varargin)
state = get(varargin{1},'Checked');
if strcmpi(state,'on');
set(ch(:),'Visible','off')
set(varargin{1},'Checked','off');
end
if strcmpi(state,'off');
set(ch(:),'Visible','on')
set(varargin{1},'Checked','on');
end
end
function newFig(varargin)
tf = gcf;
vn = get(con(21,1),'Value');
if vn == 1
return;
end
NewObj = FIVE({Obj(vn).FullPath},ch);
tmp1 = get(pane,'Position');
tmp2 = tmp1;
tmp2(1) = tmp1(1)+tmp1(3);
set(gcf,'Position',tmp2);
% links{end+1}=linkprop([ch(1,1),NewObj(1).ch(1,1)],'XData');
% links{end+1}=linkprop([ch(1,2),NewObj(1).ch(1,2)],'YData');
% links{end+1}=linkprop([ch(2,1),NewObj(1).ch(2,1)],'XData');
% links{end+1}=linkprop([ch(2,2),NewObj(1).ch(2,2)],'YData');
% links{end+1}=linkprop([ch(3,1),NewObj(1).ch(3,1)],'XData');
% links{end+1}=linkprop([ch(3,2),NewObj(1).ch(3,2)],'YData');
%
% set(tf,'UserData',links);
set(menu(4),'Enable','on','Checked','on');
figure(tf);
removeVolume
end
function syncViews(varargin)
state = get(varargin{1},'Checked');
%%% Remove any existing links this figure has to other figures
for ii = 1:length(links);
set(links{ii},'Enabled','on');
removeprop(links{ii},'XData');
removeprop(links{ii},'YData');
end
links = [];
%%% Establish links between this figure and all other FIVE
%%% Figures
ind = findobj(0,'Type','Figure');
try
figs = ind(contains('FIVE',get(ind,'Name')));
catch
set(varargin{1},'Checked','off');
set(gcf,'WindowButtonMotionFcn',@buttonMotion);
return
end
figs = setdiff(figs,gcf);
for ii = 1:length(figs);
hhh = findobj(figs(ii),'Color','b','type','line');
if isempty(hhh)
hhh = findobj(figs(ii),'Color','y','type','line');
end
links{end+1}=linkprop([ch(1,1),hhh(6)],'XData');
links{end+1}=linkprop([ch(1,2),hhh(5)],'YData');
links{end+1}=linkprop([ch(2,1),hhh(4)],'XData');
links{end+1}=linkprop([ch(2,2),hhh(3)],'YData');
links{end+1}=linkprop([ch(3,1),hhh(2)],'XData');
links{end+1}=linkprop([ch(3,2),hhh(1)],'YData');
end
set(gcf,'UserData',links);
%%% Set the state of the links
if strcmpi(state,'on');
for ii = 1:length(links);
set(links{ii},'Enabled','off');
end
set(varargin{1},'Checked','off');
set(gcf,'WindowButtonMotionFcn',@buttonMotion);
end
if strcmpi(state,'off');
for ii = 1:length(links);
set(links{ii},'Enabled','on');
end
set(varargin{1},'Checked','on');
set(gcf,'WindowButtonMotionFcn',[]);
end
%%% Propogate changes to other Figure links if they exists.
for ii = 1:length(figs)
lnk = get(figs(ii),'UserData');
hh = findobj(figs(ii),'Label','Sync Views');
if strcmpi(state,'on');
for jj = 1:length(lnk);
set(lnk{jj},'Enabled','off');
end
set(hh,'Checked','off');
set(figs(ii),'WindowButtonMotionFcn',@buttonMotion);
end
if strcmpi(state,'off');
for jj = 1:length(lnk);
set(lnk{jj},'Enabled','on');
end
set(hh,'Checked','on');
set(figs(ii),'WindowButtonMotionFcn',[]);
end
end
end
function changeLayer(varargin)
vn = get(con(21,1),'Value');
if vn == 1
return
end
if varargin{1} == con(12,1)
for ii = 1:length(hand)
uistack(hand{ii}(vn),'top');
uistack(hand{ii}(vn),'down');
uistack(hand{ii}(vn),'down');
end
elseif varargin{1} == con(13,1)
for ii = 1:length(hand)
uistack(hand{ii}(vn),'bottom');
uistack(hand{ii}(vn),'up');
end
end
end
function axialView(varargin)
if numel(varargin{1})==1 || isempty(varargin)
out = popup('Which Slices (MNI coordinates)?');
else
out = varargin{1};
end
if isempty(out)
n = 25;
coords = min(Obj(2).pos{3}):6:max(Obj(2).pos{3});
c = 0;
while numel(coords)>n
c = c+1;
if mod(c,2)==1;
coords = coords(2:end);
else
coords = coords(1:end-1);
end
end
else
n = numel(out);
coords = out;
end
IN = [];
for jj = 1:numel(Obj);
IN.IM{jj} = Obj(jj).I.*double(Obj(jj).mask);
IN.H{jj} = Obj(jj).h;
IN.TH{jj} = Obj(jj).Thresh;
IN.LIMS{jj} = Obj(jj).clim;
IN.TRANS{jj} = Obj(jj).Trans;
IN.CM{jj} = cmaps{Obj(jj).col};
end
IN.Coords = coords;
IN.opt = 1;
SliceView(IN);
end
function coronalView(varargin)
if numel(varargin{1})==1 || isempty(varargin)
out = popup('Which Slices (MNI coordinates)?');
else
out = varargin{1};
end
if isempty(out)
n = 30;
coords = min(Obj(2).pos{2}):6:max(Obj(2).pos{2});
c = 0;
while numel(coords)>n
c = c+1;
if mod(c,2)==1;
coords = coords(2:end);
else
coords = coords(1:end-1);
end
end
else
n = numel(out);
coords = out;
end
IN = [];
for ii = 1:numel(Obj);
IN.IM{ii} = Obj(ii).I.*double(Obj(ii).mask);
IN.H{ii} = Obj(ii).h;
IN.TH{ii} = Obj(ii).Thresh;
IN.LIMS{ii} = Obj(ii).clim;
IN.TRANS{ii} = Obj(ii).Trans;
IN.CM{ii} = cmaps{Obj(ii).col};
end
IN.Coords = coords;
IN.opt = 3;
SliceView(IN);
end
function sagittalView(varargin)
if numel(varargin{1})==1 || isempty(varargin)
out = popup('Which Slices (MNI coordinates)?');
else
out = varargin{1};
end
if isempty(out)
n = 25;
coords = min(Obj(2).pos{1}):6:max(Obj(2).pos{1});
c = 0;
while numel(coords)>n
c = c+1;
if mod(c,2)==1;
coords = coords(2:end);
else
coords = coords(1:end-1);
end
end
else
n = numel(out);
coords = out;
end
IN = [];
for ii = 1:numel(Obj);
IN.IM{ii} = Obj(ii).I.*double(Obj(ii).mask);
IN.H{ii} = Obj(ii).h;
IN.TH{ii} = Obj(ii).Thresh;
IN.LIMS{ii} = Obj(ii).clim;
IN.TRANS{ii} = Obj(ii).Trans;
IN.CM{ii} = cmaps{Obj(ii).col};
end
IN.Coords = coords;
IN.opt = 2;
SliceView(IN);
end
function allSliceView(varargin)
axialView;
coronalView;
sagittalView;
end
function surfView(varargin)
if numel(Obj)==1
return
end
for jj = 2:numel(Obj)
vn = jj;
obj = [];
fs = get(findobj(paramenu3(12),'Checked','On'),'Label');
switch fs
case '642'
obj.fsaverage = 'fsaverage3';
case '2562'
obj.fsaverage = 'fsaverage4';
case '10242'
obj.fsaverage = 'fsaverage5';
case '40962'
obj.fsaverage = 'fsaverage6';
case '163842'
obj.fsaverage = 'fsaverage';
otherwise
end
obj.surface = lower(get(findobj(paramenu3(10),'Checked','On'),'Label'));
if strcmpi(get(paramenu3(19),'Checked'),'off')
obj.shading = lower(get(findobj(paramenu3(11),'Checked','On'),'Label'));
obj.shadingrange = [str2num(get(findobj(paramenu3(16),'Checked','On'),'Label')) str2num(get(findobj(paramenu3(17),'Checked','On'),'Label'))];
else
switch obj.surface
case 'white'
obj.shading = 'curv';
obj.shadingrange = [-2 2];
case 'pi'
obj.shading = 'mixed';
obj.shadingrange = [-2 2];
case 'inflated'
obj.shading = 'logcurv';
obj.shadingrange = [-.75 .75];
case 'pial'
obj.shading = 'curv';
obj.shadingrange = [-2 3];
otherwise
obj.shading = 'curv';
obj.shadingrange = [-2 3];
end
end
obj.input.m = Obj(vn).I.*double(Obj(vn).mask);
obj.input.he = Obj(vn).h;
if jj ==2
obj.figno = 0;
obj.newfig = 1;
else
obj.figno = gcf;
obj.newfig = 0;
end
obj.colorlims = Obj(vn).clim;
cm = get(con(1),'String');
cm = cm{Obj(vn).col+1};
obj.colomap = cm;
thresh = Obj(vn).Thresh;
if numel(thresh) == 2
[t,i] = min(abs(thresh));
sgn = sign(thresh(i));
t = t*sgn;
obj.overlaythresh = t;
if sgn==1
obj.direction = '+';
obj.reverse = 0;
else
obj.direction = '-';
obj.reverse = 0;
end
if sum(sign(thresh))==0
obj.direction='+';
end
else
obj.overlaythresh = Obj(vn).Thresh(2:3);
obj.reverse = 0;
obj.direction = '+';
end
obj.mappingfile = [];
nn = get(findobj(paramenu3(15),'Checked','On'),'Label');
if strcmpi(nn,'Yes')
obj.nearestneighbor=1;
else
obj.nearestneighbor=0;
end
%load(which('SperStandard_4p5prox_FS6_SM.mat'),'header')
%compH = Obj(vn).h.mat==header.mat;
%if mean(compH(:))==1
% obj.mappingfile = which('SperStandard_4p5prox_FS6_SM.mat');
%end
option = get(findobj(paramenu3(14),'Checked','On'),'Label');
switch option
case 'All'
obj.Nsurfs = 4;
case 'Both'
obj.Nsurfs = 2;
case 'Left 1'
obj.Nsurfs = -1;
case 'Left 2'
obj.Nsurfs = 1.9;
case 'Right 1'
obj.Nsurfs = 1;
case 'Right 2'
obj.Nsurfs = 2.1;
otherwise
end
[h1 hh1] = surfPlot(obj);
Obj(vn).SurfInfo.h1 = h1;
Obj(vn).SurfInfo.hh1 = hh1;
Obj(vn).SurfInfo.par = obj;
set(hh1,'FaceAlpha',Obj(vn).Trans);
end
end
function changeSign(varargin)
vn = get(con(21,1),'Value');
if vn == 1
return
end
Obj(vn).I = Obj(vn).I*-1;
t1 = num2str(sort(str2num(get(con(4),'String'))*-1));
for ii = 1:10; t1 = regexprep(t1,' ',' '); end
set(con(4),'String',t1);
t2 = num2str(sort(str2num(get(con(5),'String'))*-1));
for ii = 1:10; t2 = regexprep(t2,' ',' '); end
set(con(5),'String',t2)
Obj(vn).Range(1:2) = Obj(vn).Range([2 1])*-1;
UpdateThreshold;
%setupFrames(vn,1);
%updateGraphics({[1 2 3] vn},1);
end
function setupParamMenu
%%% Not Specified
% out: output prefix, default is to define using imagefile
% SPM: 0 or 1, see above for details
% mask: optional to mask your data
% df1: numerator degrees of freedom for T/F-test (if 0<thresh<1)
% df2: denominator degrees of freedom for F-test (if 0<thresh<1)
% thresh: T/F statistic or p-value to threshold the data or 0
paramenu1(1) = uimenu(pane,'Label','Parameters');
%paramenu2(1) = uimenu(paramenu1(1),'Label','Cluster Params');
paramenu3(1) = uimenu(paramenu1(1),'Label','Sign');
paramenu4(1) = uimenu(paramenu3(1),'Label','Pos','Checked','on','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(1),'Label','Neg','CallBack',@groupCheck);
paramenu3(2) = uimenu(paramenu1(1),'Label','Sphere Radius');
paramenu4(end+1) = uimenu(paramenu3(2),'Label','1mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','2mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','3mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','4mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','5mm','Checked','On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','6mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','7mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','8mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','9mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','10mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','11mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','12mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','13mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','14mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','15mm','CallBack',@groupCheck);
paramenu3(3) = uimenu(paramenu1(1), 'Label','Peak Number Limit');
paramenu4(end+1) = uimenu(paramenu3(3),'Label','100','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','200','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','500','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','750','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','1000','Checked','on','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','1500','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','2000','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','3000','CallBack',@groupCheck);
paramenu3(4) = uimenu(paramenu1(1),'Label','Peak Separation');
paramenu4(end+1) = uimenu(paramenu3(4),'Label','2mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','4mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','6mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','8mm','Checked', 'on','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','10mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','12mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','14mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','16mm','CallBack',@groupCheck);
paramenu3(5) = uimenu(paramenu1(1),'Label','Neighbor Def.');
paramenu4(end+1) = uimenu(paramenu3(5),'Label','6','Checked','on','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(5),'Label','18','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(5),'Label','26','CallBack',@groupCheck);
paramenu3(7) = uimenu(paramenu1(1),'Label','Labeling');
paramenu4(end+1) = uimenu(paramenu3(7),'Label','Use Nearest Label', 'Checked', 'On','CallBack',@groupCheck);
% paramenu3(8) = uimenu(paramenu1(1),'Label','Label Map');
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','aal_MNI_V4', 'Checked', 'On','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Nitschke_Lab','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','JHU_tracts','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','JHU_whitematter','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Talairach','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Thalamus','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','MNI','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','HarvardOxford_cortex','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Cerebellum-flirt','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Cerebellum-fnirt','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Juelich','CallBack',@changeLabelMap);
paramenu3(8) = uimenu(paramenu1(1),'Label','Label Map');
paramenu4(end+1) = uimenu(paramenu3(8),'Label','aal_MNI_V4', 'Checked', 'On','CallBack',@changeLabelMap);
try
[labellist]=getLabelMap();
for ll=2:numel(labellist)
paramenu4(end+1) = uimenu(paramenu3(8),'Label',labellist{ll},'CallBack',@changeLabelMap);
end
catch
paramenu4(end+1) = uimenu(paramenu3(8),'Label','aal_MNI_V4', 'Checked', 'On','CallBack',@changeLabelMap);
warning('Download Peak Nii to enable the use of other atlases');
end
paramenu3(18) = uimenu(paramenu1(1),'Label','Corrected Alpha');
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.100', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.050', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.025', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.010', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.001', 'Checked', 'Off','CallBack',@groupCheck);
paramenu1(2) = uimenu(pane,'Label','Region Name');
%menu(?) = uimenu(menu(1),'Label','Increase FontSize','CallBack',@increaseFont);
%menu(?) = uimenu(menu(1),'Label','Decrease FontSize','CallBack',@decreaseFont);
paramenu3(9) = uimenu(paramenu1(1),'Label','Surface Options');
paramenu3(19) = uimenu(paramenu3(9),'Label','Use Surface Shading Defaults','Checked', 'On','CallBack',@groupCheck);
paramenu3(10) = uimenu(paramenu3(9),'Label','Surface');
paramenu4(end+1) = uimenu(paramenu3(10),'Label','Inflated', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(10),'Label','Pial', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(10),'Label','White', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(10),'Label','PI', 'Checked', 'On','CallBack',@groupCheck);
paramenu3(11) = uimenu(paramenu3(9),'Label','Shading');
paramenu4(end+1) = uimenu(paramenu3(11),'Label','Curv', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(11),'Label','Sulc', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(11),'Label','Thk', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(11),'Label','LogCurv', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(11),'Label','Mixed', 'Checked', 'On','CallBack',@groupCheck);
paramenu3(12) = uimenu(paramenu3(9),'Label','N-verts');
paramenu4(end+1) = uimenu(paramenu3(12),'Label','642', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(12),'Label','2562', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(12),'Label','10242', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(12),'Label','40962', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(12),'Label','163842', 'Checked', 'Off','CallBack',@groupCheck);
% paramenu3(13) = uimenu(paramenu3(9),'Label','Reverse Map');
% paramenu4(end+1) = uimenu(paramenu3(13),'Label','No', 'Checked', 'On','CallBack',@groupCheck);
% paramenu4(end+1) = uimenu(paramenu3(13),'Label','Yes', 'Checked', 'Off','CallBack',@groupCheck);
paramenu3(14) = uimenu(paramenu3(9),'Label','N-Surfs');
paramenu4(end+1) = uimenu(paramenu3(14),'Label','All', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Both', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Left 1', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Left 2', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Right 1', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Right 2', 'Checked', 'Off','CallBack',@groupCheck);
paramenu3(15) = uimenu(paramenu3(9),'Label','Nearest Neighbor Only');
paramenu4(end+1) = uimenu(paramenu3(15),'Label','No', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(15),'Label','Yes', 'Checked', 'Off','CallBack',@groupCheck);
paramenu3(16) = uimenu(paramenu3(9),'Label','Underlay Min');
paramenu4(end+1) = uimenu(paramenu3(16),'Label',' 0.0', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-0.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-1.0', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-1.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-2.0', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-2.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-3.0', 'Checked', 'Off','CallBack',@groupCheck);
paramenu3(17) = uimenu(paramenu3(9),'Label','Underlay Max');
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+0.0', 'Checked','Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+0.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+1.0', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+1.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+2.0', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+2.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+3.0', 'Checked', 'Off','CallBack',@groupCheck);
end
function setupFigure
tss = Obj(1).axLims;
im = spm_imatrix(Obj(1).h.mat);
%tmp = [1 1 1];
tmp = abs(im(7:9));
tss = tss.*tmp;
height = tss(2)+tss(3);
width = tss(1)+tss(2);
rat = height/width;
ff = get(0,'ScreenSize');
if ff(4)>800
pro = 3.25;
else
pro = 2.5;
end
%[junk user] = UserTime; if strcmp(user,'aschultz'); keyboard; end
ss = get(0,'ScreenSize');
if (ss(3)/ss(4))>2
ss(3)=ss(3)/2;
end
op = floor([50 ss(4)-75-((ss(3)/pro)*rat) ss(3)/pro (ss(3)/pro)*rat]);
pane = figure;
set(gcf, 'Position', op,'toolbar','none', 'Name', 'FIVE','Visible','off');
set(gcf, 'WindowButtonUpFcn', @buttonUp);
set(gcf, 'WindowButtonDownFcn', @buttonDown);
set(gcf, 'WindowButtonMotionFcn', @buttonMotion);
set(gcf, 'ResizeFcn', @resizeFig);
hcmenu = uicontextmenu;
set(hcmenu,'CallBack','movego = 0;');
item = [];
wid(1) = tss(2)/width;
hei(1) = tss(3)/height;
wid(2) = tss(1)/width;
hei(2) = tss(3)/height;
wid(3) = tss(1)/width;
hei(3) = tss(2)/height;
ax1 = axes; set(ax1,'Color','k','Position',[wid(2) hei(3) wid(1) hei(1)],'XTick',[],'YTick',[],'YColor','k','XColor','k'); hold on; colormap(gray(256));
ax2 = axes; set(ax2,'Color','k','Position',[0 hei(3) wid(2) hei(2)],'XTick',[],'YTick',[],'YColor','k','XColor','k'); hold on; colormap(gray(256));
ax3 = axes; set(ax3,'Color','k','Position',[0 0 wid(3) hei(3)],'XTick',[],'YTick',[],'YColor','k','XColor','k'); hold on; colormap(gray(256));
ax4 = axes; set(ax4,'Color','w','Position',[wid(2) 0 .04 hei(3)*.99],'XTick',[],'YAxisLocation','right','YTick',[]); %,'YColor','k','XColor','k'
set(gcf,'WindowKeyPressFcn', @keyMove);
set(gcf,'WindowScrollWheelFcn',@scrollMove);
set(gcf,'WindowKeyReleaseFcn',@keyHandler);
%st = wid(2)+.01+.04+.03;
st = wid(2)+.125;
len1 = (1-st)-.01;
len2 = len1/2;
len3 = len1/3;
len4 = len1/4;
inc = (hei(3))/11;
inc2 = .75*inc;
% [wid(2)+.045 0 .025 hei(3)*.9]
% [wid(2)+.070 0 .025 hei(3)*.9]
% [wid(2)+.095 0 .025 hei(3)*.9]
val = (Obj(1).Range(2)-Obj(1).Range(1))/Obj(1).Range(3);
con(27,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.070 0 .025 hei(3)*.9],'Value',val,'CallBack', @adjustUnderlay);
val = (Obj(1).Range(1)-Obj(1).Range(1))/Obj(1).Range(3);
con(28,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.095 0 .025 hei(3)*.9],'Value',val,'CallBack', @adjustUnderlay);
%con(29,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.095 0 .025 hei(3)*.9],'Value',0,'CallBack', @adjustUnderlay);
con(30,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[wid(2)+.070 hei(3)*.9 .05 .05]); % wid(2)+.0450 hei(3)*.9 .075 .05]
% con(28,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[st-.1 (.01+(1*inc)+(0*inc2)) len1*.75 inc],'Value',1,'CallBack', @adjustTrans);
con(1,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(0*inc)+(0*inc2) len1 inc],'String',[{'Colormap'} cmaps(:)'],'CallBack', @changeColorMap); shg
%con(1,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(0*inc)+(0*inc2) len1 inc],'String',[{'Colormap' 'A' 'B' 'C' 'D'}],'CallBack', @changeColorMap); shg
con(2,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[st (.01+(1*inc)+(0*inc2)) len1*.75 inc],'Value',1,'CallBack', @adjustTrans);
con(23,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len1*.75 (.01+(1*inc)+(0*inc2)) len1*.25 inc],'String','All','CallBack', @applyToAll);
con(3,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(2*inc)+(0*inc2) len1 inc2],'String', 'Transparency','fontsize',12);
con(4,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(2*inc)+(1*inc2) len2 inc],'CallBack',@UpdateThreshold);
con(5,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len2 .01+(2*inc)+(1*inc2) len2 inc],'CallBack',@UpdateCLims);
con(6,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(3*inc)+(1*inc2) len2 inc2],'String', 'Thresh','fontsize',12);
con(7,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len2 .01+(3*inc)+(1*inc2) len2 inc2],'String', 'Color Limits','fontsize',12);
con(8,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@UpdatePVal);
con(9,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len3 .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@UpdatePVal);
con(23,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len3+len3 .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@ExtentThresh);
con(10,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(4*inc)+(2*inc2) len3 inc2],'String', 'DF','fontsize',12);
con(11,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len3 .01+(4*inc)+(2*inc2) len3 inc2],'String', 'P-Value','fontsize',12);
con(24,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len3+len3 .01+(4*inc)+(2*inc2) len3 inc2],'String', 'Extent','fontsize',12);
con(15,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(4*inc)+(3*inc2) len2 inc],'String',num2str(loc),'CallBack',@goTo);
%con(15,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(4*inc)+(3*inc2) len2 inc],'String',['0 0 0'],'CallBack',@goTo);
con(25,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len2 .01+(4*inc)+(3*inc2) len2/2 inc],'String','FDR','CallBack', @correctThresh);
con(26,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+(len2*1.5) .01+(4*inc)+(3*inc2) len2/2 inc],'String','FWE','CallBack', @correctThresh);
con(17,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(5*inc)+(3*inc2) len2 inc2],'String', 'MNI Coord', 'fontsize',12);
con(18,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len2 .01+(5*inc)+(3*inc2) len2 inc2],'String', 'MC Correct','fontsize',12);
con(12,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st .01+(5*inc)+(4*inc2) len2 inc],'String',{'Move Up'},'CallBack',@changeLayer);
con(13,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len2 .01+(5*inc)+(4*inc2) len2 inc],'String',{'Move Down'},'CallBack',@changeLayer);
con(21,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(5*inc)+(5*inc2) len1 inc],'String',{'Overlays'},'CallBack',@switchObj);
con(22,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[wid(2)-(len2/2) hei(3)-(inc*1.05) (len2/2) inc]);
con(19,1) = uicontrol(pane,'style','PushButton','Units','Normalized','Position',[st .01+(6*inc)+(5*inc2) len2 inc],'String','Open Overlay','FontWeight','Bold','CallBack',@openOverlay);
con(20,1) = uicontrol(pane,'style','PushButton','Units','Normalized','Position',[st+len2 .01+(6*inc)+(5*inc2) len2 inc],'String','Remove Volume', 'FontWeight','Bold','CallBack',@removeVolume);
menu(1) = uimenu(pane,'Label','Options');
menu(2) = uimenu(menu(1),'Label','CrossHair Toggle','Checked','on','CallBack', @toggleCrossHairs);
menu(43) = uimenu(menu(1),'Label','Reverse Image','CallBack', @changeSign);
menu(15) = uimenu(menu(1),'Label','Change Underlay','CallBack', @changeUnderlay);
menu(3) = uimenu(menu(1),'Label','Send Overlay To New Fig','CallBack',@newFig);
if nargin<2
menu(4) = uimenu(menu(1),'Label','Sync Views','Enable','on','CallBack',@syncViews);
else
menu(4) = uimenu(menu(1),'Label','Sync Views','Enable','on','Checked','on','CallBack',@syncViews);
end
menu(16) = uimenu(menu(1),'Label','SliceViews');
menu(6) = uimenu(menu(16),'Label','Axial Slice View','CallBack',@axialView);
menu(7) = uimenu(menu(16),'Label','Coronal Slice View','CallBack',@coronalView);
menu(8) = uimenu(menu(16),'Label','Sagittal Slice View','CallBack',@sagittalView);
menu(9) = uimenu(menu(16),'Label','All Slice View','CallBack',@allSliceView);
menu(17) = uimenu(menu(1),'Label','Ploting');
menu(10) = uimenu(menu(17),'Label','Load Plot Data','CallBack',@loadData);
menu(13) = uimenu(menu(17),'Label','JointPlot','CallBack',@JointPlot);
menu(12) = uimenu(menu(17),'Label','PaperPlot-Vert','CallBack',@PaperFigure_Vert);
menu(33) = uimenu(menu(17),'Label','PaperPlot-Horz','CallBack',@PaperFigure_Horz);
menu(23) = uimenu(menu(17),'Label','PaperPlot Overlay','Checked','off','CallBack', @toggle);
menu(41) = uimenu(menu(17),'Label','Surface Render','Checked','off','CallBack', @surfView);
menu(14) = uimenu(menu(1),'Label','Transparent Overlay','CallBack',@TestFunc);
menu(11) = uimenu(menu(1),'Label','Get Peak Info','CallBack',@getPeakInfo);
menu(25) = uimenu(menu(1),'Label','Resample');
menu(26) = uimenu(menu(25),'Label','.5x.5x.5', 'CallBack', @resampleIm);
menu(27) = uimenu(menu(25),'Label','1x1x1' , 'CallBack', @resampleIm);
menu(28) = uimenu(menu(25),'Label','2x2x2' , 'CallBack', @resampleIm);
menu(29) = uimenu(menu(25),'Label','3x3x3' , 'CallBack', @resampleIm);
menu(30) = uimenu(menu(25),'Label','4x4x4' , 'CallBack', @resampleIm);
menu(31) = uimenu(menu(25),'Label','5x5x5' , 'CallBack', @resampleIm);
menu(32) = uimenu(menu(25),'Label','6x6x6' , 'CallBack', @resampleIm);
menu(18) = uimenu(menu(1),'Label','Save Options');
menu(19) = uimenu(menu(18),'Label','Save Thresholded Image','Enable','on','CallBack',@saveImg);
menu(20) = uimenu(menu(18),'Label','Save Masked Image','Enable','on','CallBack',@saveImg);
menu(21) = uimenu(menu(18),'Label','Save Cluster Image','Enable','on','CallBack',@saveImg);
menu(22) = uimenu(menu(18),'Label','Save Cluster Mask','Enable','on','CallBack',@saveImg);
menu(34) = uimenu(menu(1),'Label','Mask');
menu(35) = uimenu(menu(34),'Label','Mask In','Enable','on','CallBack',@maskImage);
menu(36) = uimenu(menu(34),'Label','Mask Out','Enable','on','CallBack',@maskImage);
menu(37) = uimenu(menu(34),'Label','Un-Mask','Enable','on','CallBack',@maskImage);
menu(38) = uimenu(menu(1),'Label','Movie Mode','Enable','on','CallBack',@movieMode);
menu(39) = uimenu(menu(1),'Label','Conn Explore','Enable','on','CallBack',@initializeConnExplore);
menu(40) = uimenu(menu(1),'Label','SS Connectivity','Enable','on','CallBack',@ssConn);
item(1) = uimenu(hcmenu, 'Label', 'Go to local max', 'Callback', @gotoMinMax);
item(2) = uimenu(hcmenu, 'Label', 'Go to local min', 'Callback', @gotoMinMax);
item(3) = uimenu(hcmenu, 'Label', 'Go to global max', 'Callback', @gotoMinMax);
item(4) = uimenu(hcmenu, 'Label', 'Go to global min', 'Callback', @gotoMinMax);
item(5) = uimenu(hcmenu, 'Label', 'Plot Cluster', 'Callback', @plotVOI);
item(6) = uimenu(hcmenu, 'Label', 'Plot Sphere', 'Callback', @plotVOI);
item(7) = uimenu(hcmenu, 'Label', 'Plot Voxel', 'Callback', @plotVOI);
item(8) = uimenu(hcmenu, 'Label', 'Plot Cached Cluster', 'Callback', @plotVOI);
item(9) = uimenu(hcmenu, 'Label', 'Cache Cluster Index', 'Callback', @CachedPlot);
%item(8) = uimenu(hcmenu, 'Label', 'RegionName', 'Callback', @regionName);
menu(42) = uimenu(menu(1),'Label','Return Obj','Checked','off','CallBack', @returnInfo);
%menu(43) = uimenu(menu(1),'Label','Return Obj as Global','Checked','off','CallBack', @returnInfoGlob);
Obj(1).ax1 = ax1;
Obj(1).ax2 = ax2;
Obj(1).ax3 = ax3;
Obj(1).ax4 = ax4;
Obj(1).con = con;
Obj(1).menu = menu;
end
function returnInfo(varargin)
if isstruct(varargin{1})
Obj = varargin{1};
else
assignin('base','Obj',Obj);
end
end
function keyHandler(varargin)
d = varargin{2};
%disp([char(d.Modifier) ' - ' d.Key]);
if strcmpi('shift',d.Modifier)
switch d.Key
case 'o'
maskImage(menu(36));
case 'i'
maskImage(menu(35));
case 'u'
maskImage(menu(37));
end
else
switch d.Key
case 'u'
updateConnMap;
case 's'
ssUpdateConnMap;
otherwise
end
end
if contains('alt', {varargin{2}.Key})==1
clickFlag = 0;
end
end
function maskImage(varargin)
vn = get(con(21,1),'Value');
if varargin{1}==menu(37);
Obj(vn).MaskInd = [];
Obj(vn).mask(:) = 1;
Obj(vn).mask(Obj(vn).Exclude)=0;
setupFrames(vn,1);
updateGraphics({1:3 vn},1);
return
end
nnn = spm_select(inf,'image','Select a Mask Image:');
th = spm_vol(nnn);
for ii = 1:numel(th)
m = resizeVol(th(ii),Obj(vn).h);
if varargin{1}==menu(35)
Obj(vn).MaskInd = [Obj(vn).MaskInd; find(isnan(m))];
end
if varargin{1}==menu(36)
Obj(vn).MaskInd = [Obj(vn).MaskInd; find(~isnan(m))];
end
end
Obj(vn).MaskInd = unique(Obj(vn).MaskInd);
Obj(vn).mask(:) = 1;
Obj(vn).mask(Obj(vn).MaskInd)=0;
Obj(vn).mask(Obj(vn).Exclude)=0;
setupFrames(vn,1);
updateGraphics({1:3 vn},1);
end
function CachedPlot(varargin)
if varargin{1} == item(9)
CachedClusterLoc = [];
vn = get(con(21,1),'Value');
CM = str2num(get(findobj(paramenu3(5),'Checked','On'),'Label'));
lastItem = item(5);
adir = [fileparts(Obj(vn).FullPath) filesep];
%%% Using the diplayed image get the matrix vector indices
%%% for the selected cluster
mni = str2num(get(con(15),'string'));
if ~isempty(Obj(vn).mask);
tmpI = Obj(vn).I.*double(Obj(vn).mask);
else
tmpI = Obj(vn).I;
end
thresh = Obj(vn).Thresh;
if numel(thresh)==2
ind = find(tmpI<=thresh(2) & tmpI>=thresh(1));
L = [];
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',CM);
elseif numel(thresh)==4
ind1 = find(tmpI<=thresh(2) & tmpI>=thresh(1));
L1 = [];
[L1(:,1) L1(:,2) L1(:,3)] = ind2sub(Obj(vn).h.dim,ind1);
A1 = spm_clusters2(L1(:,1:3)',CM);
ind2 = find(tmpI<=thresh(4) & tmpI>=thresh(3));
L2 = [];
[L2(:,1) L2(:,2) L2(:,3)] = ind2sub(Obj(vn).h.dim,ind2);
A2 = spm_clusters2(L2(:,1:3)',CM);
L = [L1; L2];
A = [A1 A2+max(A1)];
ind = [ind1; ind2];
end
L(:,4) = 1;
L2 = L*Obj(vn).h.mat';
dist = sqrt(sum((L2(:,1:3)-repmat(mni, size(L,1),1)).^2,2));
if min(dist)>5
disp('No Cluster is selected');
end
ind1 = find(dist==min(dist));
ind2 = find(A==A(ind1(1)));
ind3 = ind(ind2);
CachedClusterLoc.index = ind3;
CachedClusterLoc.mat = Obj(vn).h.mat;
end
end
function PaperFigure_Vert(varargin)
%%% Figure width is off
ss2 = get(gcf,'position');
tss = size(Obj(1).I);
tmp = abs(matInfo(Obj(1).h.mat));
tss = tss.*tmp;
tot = tss(3)+tss(3)+tss(2);
wid(1) = tss(2)/width;
hei(1) = tss(3)/tot;
wid(2) = tss(1)/width;
hei(2) = tss(3)/tot;
wid(3) = tss(1)/width;
hei(3) = tss(2)/tot;
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
xyz = [x(1) y(1) z(1)];
fg = figure; clf; colormap(gray);
set(fg,'color','k')
n = numel(Obj)-1;
if n==0;
return;
end
if strcmpi(get(menu(23),'Checked'),'off')
ww = floor((max(wid)*ss2(3)) * n);
else
ww = floor((max(wid)*ss2(3)) * 1);
n = 1;
end
hh = floor((sum(tss([3 3 2])./height)*ss2(4))*1);
dims = [10 10 ww+((1/8)*ww) hh];
dims(3) = floor(dims(3));
set(fg,'Position',dims);
dd = [.1/n (((dims(3)-dims(1))/n)*.1)/((dims(4)-dims(2)))];
for zz = 2:length(Obj)
if (zz==2) || strcmpi(get(menu(23),'Checked'),'off')
aax1 = axes; set(aax1,'Color','k','Position',[(zz-2)/n sum(hei(1:2)) (1/n)-((1/8)/n) hei(3)],'Xcolor','k','Ycolor','k'); hold on;
aax2 = axes; set(aax2,'Color','k','Position',[(zz-2)/n sum(hei(2)) (1/n)-((1/8)/n) hei(1)],'Xcolor','k','Ycolor','k'); hold on;
aax3 = axes; set(aax3,'Color','k','Position',[(zz-2)/n 0 (1/n)-((1/8)/n) hei(2)],'Xcolor','k','Ycolor','k'); hold on;
aax4 = axes; set(aax4,'Color','k','Position',[((zz-2)/n)+((7/8)/n) 0 (1/8)/n 1],'Xcolor','k','Ycolor','k'); hold on;
tr(zz-1) = aax4;
drawFresh(aax1,3,1,0);
drawFresh(aax2,1,1,0);
drawFresh(aax3,2,1,0);
end
h_in = (zz-2)/(numel(Obj)-1);
drawFresh(aax1,3,zz,0);
drawFresh(aax2,1,zz,0);
drawFresh(aax3,2,zz,0);
if strcmpi(get(menu(23),'Checked'),'off')
an(zz-1,1) = annotation(gcf,'textbox',[h_in+.005 sum(hei(1:2))+(.88*hei(3)) dd],...
'Color','w', 'String',num2str(xyz(3)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
an(zz-1,2) = annotation(gcf,'textbox',[h_in+.005 sum(hei(2))+(.88*hei(2)) dd],...
'Color','w', 'String',num2str(xyz(1)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
an(zz-1,3) = annotation(gcf,'textbox',[h_in+.005 0+(.88*hei(2)) dd],...
'Color','w', 'String',num2str(xyz(2)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
vn = zz;
lim = [min(Obj(vn).clim) max(Obj(vn).clim)];
yy = lim(1):(lim(2)-lim(1))/255:lim(2);
axes(aax4); cla
cm = colmap(cmaps{Obj(vn).col},256);
imagesc(yy',1,reshape(cm,numel(yy),1,3)); axis tight
set(aax4,'YDir','Normal','YAxisLocation','left','YTick', unique([1 get(aax4,'YTick')]));
set(aax4,'YTickLabel',(round(((min(yy):spm_range(yy)/(numel(get(aax4,'YTick'))-1):max(yy)))*100)/100));
th = moveYaxLabs(aax4,'y');
set(th,'fontsize',get(con(2),'fontsize'),'fontweight','bold');
set(th,'BackgroundColor','k'); shg
else
if zz == 2
delete(aax4);
tr = [];
end
end
end
for zz = 1:length(tr)
uistack(tr(zz),'top');
end
if strcmpi(get(menu(23),'Checked'),'on')
h_in = 0;
an(1,1) = annotation(gcf,'textbox',[h_in+.005 sum(hei(1:2))+(.88*hei(3)) dd],...
'Color','w', 'String',num2str(xyz(3)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
an(1,2) = annotation(gcf,'textbox',[h_in+.005 sum(hei(2))+(.88*hei(2)) dd],...
'Color','w', 'String',num2str(xyz(1)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
an(1,3) = annotation(gcf,'textbox',[h_in+.005 0+(.88*hei(2)) dd],...
'Color','w', 'String',num2str(xyz(2)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
end
end
function PaperFigure_Horz(varargin)
scrn = get(0, 'ScreenSize');
tmp = get(Obj(1).ax1,'position');
wid(1) = tmp(3); hei(1) = tmp(4);
tmp = get(Obj(1).ax2,'position');
wid(2) = tmp(3); hei(2) = tmp(4);
tmp = get(Obj(1).ax3,'position');
wid(3) = tmp(3); hei(3) = tmp(4);
ss2 = get(gcf,'position');
wid = wid*ss2(3);
hei = hei*ss2(4);
n = numel(Obj)-1;
if n==0;
return;
end
%fg = figure(400+gcf); clf; colormap(gray)
fg = figure; clf; colormap(gray)
set(fg,'color','k')
tall = max(hei)./.9;
if strcmpi(get(menu(23),'Checked'),'off')
hh = tall*n;
else
hh = tall;
n = 1;
end
dims = [10 scrn(3)-75 sum(wid) hh];
dims = round(dims);
set(fg,'Position',dims);
wid = wid./sum(wid);
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
xyz = [x(1) y(1) z(1)];
dd = [.1/n .033];
for zz = 2:length(Obj)
if (zz==2) || strcmpi(get(menu(23),'Checked'),'off')
aax1 = axes; set(aax1,'Color','k','Position',[0 (( n-zz+1)/n)+(.1/n) wid(3) .9/n],'Xcolor','k','Ycolor','k'); hold on;
aax2 = axes; set(aax2,'Color','k','Position',[wid(3) (( n-zz+1)/n)+(.1/n) wid(2) .9/n],'Xcolor','k','Ycolor','k'); hold on;
aax3 = axes; set(aax3,'Color','k','Position',[sum(wid([2 3])) (( n-zz+1)/n)+(.1/n) wid(1) .9/n],'Xcolor','k','Ycolor','k'); hold on;
aax4 = axes; set(aax4,'Color','k','Position',[0 (( n-zz+1)/n) 1 .1/n],'Xcolor','k','Ycolor','k'); hold on;
tr(zz-1) = aax4;
drawFresh(aax1,3,1,0);
drawFresh(aax2,2,1,0);
drawFresh(aax3,1,1,0);
end
h_in = (zz-2)/(numel(Obj)-1);
drawFresh(aax1,3,zz,0);
drawFresh(aax2,2,zz,0);
drawFresh(aax3,1,zz,0);
if strcmpi(get(menu(23),'Checked'),'off')
an(zz-1,1) = annotation(gcf,'textbox',[0 ((n-zz+1)/n)+(.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(3)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
an(zz-1,2) = annotation(gcf,'textbox',[wid(2) ((n-zz+1)/n)+(.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(2)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
an(zz-1,3) = annotation(gcf,'textbox',[sum(wid([2 3]))+(.04) ((n-zz+1)/n)+(.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(1)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
vn = zz;
lim = [min(Obj(vn).clim) max(Obj(vn).clim)];
yy = lim(1):(lim(2)-lim(1))/255:lim(2);
axes(aax4); cla
cm = colmap(cmaps{Obj(vn).col},256);
imagesc(1,yy,reshape(cm,1,numel(yy),3)); axis tight
%imagesc(1,yy',reshape(cmap{Obj(vn).col,1},1,size(cmap{Obj(vn).col,1},1),3)); axis tight
set(aax4,'XDir','Normal','XAxisLocation','top','XTick', unique([1 get(aax4,'XTick')]));
set(aax4,'XTickLabel',(round(((min(yy):spm_range(yy)/(numel(get(aax4,'XTick'))-1):max(yy)))*100)/100));
set(aax4,'xcolor','w','fontsize',12,'fontweight','bold')
th = moveYaxLabs(aax4,'x');
%set(th,'fontsize',get(con(2),'fontsize'),'fontweight','bold');
set(th,'BackgroundColor','k'); shg
else
if zz == 2
delete(aax4);
tr = [];
end
end
end
for zz = 1:length(tr)
uistack(tr(zz),'top');
end
if strcmpi(get(menu(23),'Checked'),'on')
h_in = 0;
an(1,1) = annotation(gcf,'textbox',[0 (.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(3)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
an(1,2) = annotation(gcf,'textbox',[wid(2) (.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(2)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
an(1,3) = annotation(gcf,'textbox',[sum(wid([2 3]))+(.04) (.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(1)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
end
end
function JointPlot(varargin)
if length(Obj)>3
disp('This option only works if there are two and only two overlays');
return
end
% Obj(2).col = 16;
% set(con(21,1),'Value',2);
% switchObj({2});
% UpdateThreshold;
%
% Obj(3).col = 14;
% set(con(21,1),'Value',3);
% switchObj({3});
% UpdateThreshold;
%%%
tmp = Obj(2).I.*double(Obj(2).mask);
if numel(Obj(2).Thresh)==2
ind = find(tmp<Obj(2).Thresh(1) | tmp>Obj(2).Thresh(2));
else
ind = find(tmp<Obj(2).Thresh(1) | tmp>Obj(2).Thresh(4) | (tmp>Obj(2).Thresh(2) & tmp<Obj(2).Thresh(3)));
end
tmp(ind)=NaN;
ind1 = find(~isnan(tmp));
%%%
tmp = Obj(3).I.*double(Obj(3).mask);
if numel(Obj(3).Thresh)==2
ind = find(tmp<Obj(3).Thresh(1) | tmp>Obj(3).Thresh(2));
else
ind = find(tmp<Obj(3).Thresh(1) | tmp>Obj(3).Thresh(4) | (tmp>Obj(3).Thresh(2) & tmp<Obj(3).Thresh(3)));
end
tmp(ind)=NaN;
ind2 = find(~isnan(tmp));
both = intersect(ind1,ind2);
Obj(4) = Obj(3);
Obj(4).Name = 'Overlap.nii';
Obj(4).I(:) = 0;
Obj(4).I(both)=1;
Obj(4).Thresh = [.5 1];
Obj(4).clim = [.5 1.5];
Obj(4).col = 15;
Obj(4).mask = ones(size(Obj(4).I),'uint8');
set(con(21,1),'String', [get(con(21,1),'String'); Obj(4).Name],'Value',4);
setupFrames(4,1)
drawFresh(ax1,1,4);
drawFresh(ax2,2,4);
drawFresh(ax3,3,4);
uistack(ch(1,1),'top'); uistack(ch(1,2),'top');
uistack(ch(2,1),'top'); uistack(ch(2,2),'top');
uistack(ch(3,1),'top'); uistack(ch(3,2),'top');
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
switchObj;
end
function gotoMinMax(varargin)
movego = 0;
vn = get(con(21,1),'Value');
if vn==1
return
end
if ~isempty(Obj(vn).mask);
tmpI = Obj(vn).I.*double(Obj(vn).mask);
else
tmpI = Obj(vn).I;
end
if varargin{1} == item(1)
currloc = Obj(vn).point(1:3);
neigh = neighbors(currloc,Obj(vn).h.dim);
vi = sub2ind(Obj(vn).h.dim,neigh(:,1),neigh(:,2),neigh(:,3));
whvi = find(tmpI(vi)==max(tmpI(vi)));
whvi = vi(whvi(1));
currvi = vi(15);
while currvi ~= whvi
currvi = whvi;
[currloc(1) currloc(2) currloc(3)] = ind2sub(Obj(vn).h.dim,whvi);
neigh = neighbors(currloc,Obj(vn).h.dim);
vi = sub2ind(Obj(vn).h.dim,neigh(:,1),neigh(:,2),neigh(:,3));
whvi = find(tmpI(vi)==max(tmpI(vi)));
whvi = vi(whvi(1));
end
[currloc(1) currloc(2) currloc(3)] = ind2sub(Obj(vn).h.dim,whvi);
newloc = round([currloc 1]*Obj(vn).h.mat');
set(con(15),'String', num2str(newloc(1:3)));
goTo(con(15,1)); shg
elseif varargin{1} == item(2)
currloc = Obj(vn).point(1:3);
neigh = neighbors(currloc,Obj(vn).h.dim);
vi = sub2ind(Obj(vn).h.dim,neigh(:,1),neigh(:,2),neigh(:,3));
whvi = find(tmpI(vi)==min(tmpI(vi)));
whvi = vi(whvi(1));
currvi = vi(15);
while currvi ~= whvi
currvi = whvi;
[currloc(1) currloc(2) currloc(3)] = ind2sub(Obj(vn).h.dim,whvi);
neigh = neighbors(currloc,Obj(vn).h.dim);
vi = sub2ind(Obj(vn).h.dim,neigh(:,1),neigh(:,2),neigh(:,3));
whvi = find(tmpI(vi)==min(tmpI(vi)));
whvi = vi(whvi(1));
end
[currloc(1) currloc(2) currloc(3)] = ind2sub(Obj(vn).h.dim,whvi);
newloc = round([currloc 1]*Obj(vn).h.mat');
set(con(15),'String', num2str(newloc(1:3)));
goTo(con(15,1)); shg
elseif varargin{1} == item(3)
%keyboard;
i1 = find(tmpI==max(tmpI(:)));
[x y z] = ind2sub(Obj(vn).h.dim,i1);
if numel(x)>1
disp('There are multiple maxima!');
x = x(1); y = y(1); z = z(1);
end
newloc = round([x y z 1]*Obj(vn).h.mat');
set(con(15),'String', num2str(newloc(1:3)));
goTo(con(15,1)); shg
elseif varargin{1} == item(4)
i1 = find(tmpI==min(tmpI(:)));
[x y z] = ind2sub(Obj(vn).h.dim,i1);
if numel(x)>1
disp('There are multiple minima!');
x = x(1); y = y(1); z = z(1);
end
newloc = round([x y z 1]*Obj(vn).h.mat');
set(con(15),'String', num2str(newloc(1:3)));
goTo(con(15,1)); shg
end
movego = 0;
end
function scrollMove(varargin)
if isempty(gco);
return
end
switch gca%get(gco,'Parent')
case Obj(1).ax1
switch (varargin{2}.VerticalScrollCount>0)
case 1
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)+1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)-1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
end
case Obj(1).ax2
switch (varargin{2}.VerticalScrollCount>0)
case 1
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)+1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)-1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
end
case Obj(1).ax3
switch (varargin{2}.VerticalScrollCount>0)
case 1
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)+1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)-1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
end
otherwise
return
end
end
function keyMove(varargin)
if contains('alt', {varargin{2}.Key})==1
clickFlag = 1;
end
if strcmpi(varargin{2}.Modifier,'shift');
mult = 5;
else
mult = 1;
end
if char(get(gcf,'currentcharacter')) == 't'
vn = get(con(21,1),'Value');
state = get(hand{1}(vn),'visible');
if strcmpi(state,'on')
set(hand{1}(vn),'visible','off');
set(hand{2}(vn),'visible','off');
set(hand{3}(vn),'visible','off');
else
set(hand{1}(vn),'visible','on');
set(hand{2}(vn),'visible','on');
set(hand{3}(vn),'visible','on');
end
return
end
if ~isempty(gco)
return;
end
switch gca
case Obj(1).ax1
switch char(get(gcf,'currentcharacter'))
case char(28)
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(29)
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(30)
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(31)
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
return
end
case Obj(1).ax2
switch char(get(gcf,'currentcharacter'))
case char(28)
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(29)
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(30)
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(31)
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
return
end
case Obj(1).ax3
switch char(get(gcf,'currentcharacter'))
case char(28)
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(29)
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(30)
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(31)
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
return
end
otherwise
return
end
end
function getClusterParams
vn = get(con(21,1),'Value');
if vn<2
return
end
clear S;
S.mask = [];
S.SPM = 0;
if strcmpi(get(paramenu4(1),'Checked'),'on')
S.sign = 'pos';
elseif strcmpi(get(paramenu4(2),'Checked'),'on')
S.sign = 'neg';
end;
if numel(Obj(vn).DF)==1;
if any(isnan(Obj(vn).DF))
S.type = 'none';
S.df1 = [];
elseif any(isinf(Obj(vn).DF))
S.type = 'Z';
S.df1 = inf;
else
S.type = 'T';
S.df1 = Obj(vn).DF;
end
elseif numel(Obj(vn).DF)==2;
S.type = 'F';
S.df1 = Obj(vn).DF(1);
S.df2 = Obj(vn).DF(2);
end
if strcmpi(S.type,'none');
if numel(Obj(vn).Thresh)==4;
error('Threshold can only contain two terms (one-sided)');
end
i1 = find(abs(Obj(vn).Thresh)==min(abs(Obj(vn).Thresh)));
S.thresh = Obj(vn).Thresh(i1);
if strcmpi(S.sign,'pos'); l = 1; else l = -1;end
if sign(S.thresh)~=l
error('Direction of peaks (from Parameters-->Sign) does not match sign of the specified threshold.');
end
else
S.thresh = Obj(vn).PVal;
end
S.voxlimit = str2num(get(findobj(paramenu3(3),'Checked','on'),'Label'));
S.separation = str2num(strtok(get(findobj(paramenu3(4),'Checked','on'),'Label'),'m'));
S.conn = str2num(get(findobj(paramenu3(5),'Checked','on'),'Label'));
tmp = str2num(get(con(23),'String'));
if isempty(tmp); tmp = 0; end
S.cluster = tmp;
if strcmpi(get(findobj(paramenu3(7),'Label','Use Nearest Label'),'Checked'),'on')
S.nearest = 1;
else
S.nearest = 0;
end
S.label = get(findobj(paramenu3(8),'Checked','on'),'Label');
end
function groupCheck(varargin)
if varargin{1}==paramenu3(19)
state = get(varargin{1},'Checked');
if strcmpi(state,'on')
set(varargin{1},'Checked','off');
else
set(varargin{1},'Checked','on');
end
return
end
swh1 = findobj(get(varargin{1},'Parent'),'Checked','on');
swh2 = findobj(get(varargin{1},'Parent'),'Checked','off');
if swh1 == varargin{1}
if strcmpi(get(varargin{1},'Checked'),'on')
set(varargin{1},'Checked','off');
else
set(varargin{1},'Checked','on');
end
else
set(swh1,'Checked','off');
set(varargin{1},'Checked','on');
end
%if get(varargin{1},'Parent') == paramenu3(8)
% get(varargin{1},'Label')
% keyboard;
% RNH = spm_vol([which('aal_MNI_V4.img')]);
% [RNI Rxyz] = spm_read_vols(RNH);
% [RNI RNH] = openIMG([which('aal_MNI_V4.img')]);
% RNames = load('aal_MNI_V4_List.mat');
%end
end
function plotVOI(varargin)
movego = 0;
vn = get(con(21,1),'Value');
if isempty(contrasts) || isempty(DataHeaders);
try
loadData
catch
error('No go, no support file found.');
end
else
try
if ~strcmpi(fileparts(Obj(vn).FullPath),Des.OutputDir)
try
loadData
catch
error('No go, no support file found.');
end
end
catch
if ~strcmpi(fileparts(Obj(vn).FullPath),Des.swd)
try
loadData
catch
error('No go, no support file found.');
end
end
end
end
if ~isempty(Obj(vn).mask);
tmpI = Obj(vn).I.*double(Obj(vn).mask);
else
tmpI = Obj(vn).I;
end
if strcmpi(modelType,'SPM')
tmp = Obj(vn).DispName;
i1 = find(tmp=='_');
i2 = find(tmp=='.');
tmp = tmp(i1(end)+1:i2(end)-1);
spmCon = contrasts(str2num(tmp));
end
switch varargin{1}
case item(5) %% Cluster
CM = str2num(get(findobj(paramenu3(5),'Checked','On'),'Label'));
lastItem = item(5);
adir = [fileparts(Obj(vn).FullPath) filesep];
%%% Using the diplayed image get the matrix vector indices
%%% for the selected cluster
mni = str2num(get(con(15),'string'));
thresh = Obj(vn).Thresh;
if numel(thresh)==2
ind = find(tmpI<=thresh(2) & tmpI>=thresh(1));
L = [];
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',CM);
elseif numel(thresh)==4
ind1 = find(tmpI<=thresh(2) & tmpI>=thresh(1));
L1 = [];
[L1(:,1) L1(:,2) L1(:,3)] = ind2sub(Obj(vn).h.dim,ind1);
A1 = spm_clusters2(L1(:,1:3)',CM);
ind2 = find(tmpI<=thresh(4) & tmpI>=thresh(3));
L2 = [];
[L2(:,1) L2(:,2) L2(:,3)] = ind2sub(Obj(vn).h.dim,ind2);
A2 = spm_clusters2(L2(:,1:3)',CM);
L = [L1; L2];
A = [A1 A2+max(A1)];
ind = [ind1; ind2];
end
L(:,4) = 1;
L2 = L*Obj(vn).h.mat';
dist = sqrt(sum((L2(:,1:3)-repmat(mni, size(L,1),1)).^2,2));
if min(dist)>5
disp('No Cluster is selected');
end
ind1 = find(dist==min(dist));
ind2 = find(A==A(ind1(1)));
ind3 = ind(ind2);
%%% Read in an orignal volume
try
th = spm_vol(strtrim(Flist(1,:))); [trash,XYZ] = spm_read_vols(th(1)); clear trash
catch
th = spm_vol(Obj(vn).FullPath); [trash,XYZ] = spm_read_vols(th(1)); clear trash
end
th = th(1);
%try
matLoc = [mni 1]*inv(th(1).mat'); matLoc = matLoc(1:3);
%catch
% keyboard;
%end
%%% Covert the display index into the native volume index
Q = [];
[Q(:,1) Q(:,2) Q(:,3)] = ind2sub(Obj(vn).h.dim,ind3);
Q(:,4) = 1;
Q = (Q*Obj(vn).h.mat')*inv(th.mat');
Q = unique(round(Q),'rows');
i1 = unique([find(Q(:,1)<=0 | Q(:,1)>th.dim(1)); find(Q(:,2)<=0 | Q(:,2)>th.dim(2)); find(Q(:,3)<=0 | Q(:,3)>th.dim(3))]);
i2 = setdiff(1:size(Q,1),i1);
Q = Q(i2,:);
voxInd = sub2ind(th.dim,Q(:,1),Q(:,2),Q(:,3));
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
VOI = [];
VOI.mniLoc = mni;
VOI.matLoc = matLoc;
VOI.index = voxInd;
VOI.isCluster = 1;
try
[x y z] = ind2sub(th.dim,voxInd);
dat = zeros(numel(DataHeaders),numel(x));
for zz = 1:numel(DataHeaders);
dat(zz,:) = spm_sample_vol(DataHeaders(zz),x,y,z,0);
end
if isfield(Des,'ZeroDrop')
if Des.ZeroDrop == 1
dat(dat==0)=NaN;
end
end
if isfield(Des,'OL')
ti1 = intersect(voxInd,Des.OL{2}(:,2));
for zz = 1:numel(ti1);
ti2 = find(Des.OL{2}(:,2)==ti1(zz));
ti3 = find(voxInd == ti1(zz));
dat(ti3,Des.OL{2}(ti2,1))=NaN;
end
end
VOI.allData = dat;
VOI.data = nanmean(dat,2);
catch
VOI.allData = [];
end
case item(6) %% Sphere
lastItem = item(6);
adir = Obj(vn).FullPath;
ind = find(adir==filesep);
if isempty(ind);
adir = [];
else
adir = adir(1:ind(end));
end
try
th = spm_vol(strtrim(Flist(1,:))); [trash,XYZ] = spm_read_vols(th(1)); clear trash
catch
th = spm_vol(Obj(vn).FullPath); [trash,XYZ] = spm_read_vols(th(1)); clear trash
end
mniLoc = str2num(get(con(15),'string'));
matLoc = [mniLoc 1]*inv(th(1).mat'); matLoc = matLoc(1:3);
rad = get(findobj(paramenu3(2),'Checked','on'),'Label');
rad = str2num(rad(1:end-2));
voxInd = find(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))<rad);
if isempty(ind);
voxInd = find(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))==min(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))));
end
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
VOI = [];
VOI.mniLoc = mniLoc;
VOI.matLoc = matLoc;
VOI.index = voxInd;
VOI.rad = rad;
VOI.isCluster = 0;
try
[x y z] = ind2sub(th.dim,voxInd);
dat = zeros(numel(DataHeaders),numel(x));
for zz = 1:numel(DataHeaders);
dat(zz,:) = spm_sample_vol(DataHeaders(zz),x,y,z,0);
end
if isfield(Des,'ZeroDrop')
if Des.ZeroDrop == 1
dat(dat==0)=NaN;
end
end
if isfield(Des,'OL')
ti1 = intersect(voxInd,Des.OL{2}(:,2));
for zz = 1:numel(ti1);
ti2 = find(Des.OL{2}(:,2)==ti1(zz));
ti3 = find(voxInd == ti1(zz));
dat(ti3,Des.OL{2}(ti2,1))=NaN;
end
end
VOI.allData = dat;
VOI.data = nanmean(dat,2);
catch
VOI.allData = [];
end
case item(7) %% Voxel
lastItem = item(7);
adir = Obj(vn).FullPath;
ind = find(adir==filesep);
if isempty(ind);
adir = [];
else
adir = adir(1:ind(end));
end
try
th = spm_vol(strtrim(Flist(1,:))); [trash,XYZ] = spm_read_vols(th(1)); clear trash
catch
th = spm_vol(Obj(vn).FullPath); [trash,XYZ] = spm_read_vols(th(1)); clear trash
end
mniLoc = str2num(get(con(15),'string'));
matLoc = [mniLoc 1]*inv(th(1).mat'); matLoc = matLoc(1:3);
voxInd = find(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))==min(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))));
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
matLoc = round(matLoc);
VOI = [];
VOI.mniLoc = mniLoc;
VOI.matLoc = matLoc;
VOI.index = voxInd;
VOI.rad = 0;
VOI.isCluster = 0;
try
[x y z] = ind2sub(th.dim,voxInd);
dat = zeros(numel(DataHeaders),numel(x));
for zz = 1:numel(DataHeaders);
dat(zz,:) = spm_sample_vol(DataHeaders(zz),x,y,z,0);
end
if isfield(Des,'ZeroDrop')
if Des.ZeroDrop == 1
dat(dat==0)=NaN;
end
end
if isfield(Des,'OL')
ti1 = intersect(voxInd,Des.OL{2}(:,2));
for zz = 1:numel(ti1);
ti2 = find(Des.OL{2}(:,2)==ti1(zz));
ti3 = find(voxInd == ti1(zz));
dat(ti3,Des.OL{2}(ti2,1))=NaN;
end
end
VOI.allData = dat;
VOI.data = nanmean(dat,2);
catch
VOI.allData = [];
end
case item(8) %% Cached Location
if ~isfield(CachedClusterLoc,'index');
disp('No Cluster has been Cached');
return
end
if isempty(CachedClusterLoc.index)
disp('No Cluster has been Cached');
return
end
tmp = CachedClusterLoc.mat-Obj(vn).h.mat;
if sum(abs(tmp))>1e-10
disp('The Current Image is a different size than the one used to Cache the cluster. One image must be resized to the other for this to work');
return;
end
try
th = spm_vol(strtrim(Flist(1,:))); [trash,XYZ] = spm_read_vols(th(1)); clear trash
catch
th = spm_vol(Obj(vn).FullPath); [trash,XYZ] = spm_read_vols(th(1)); clear trash
end
ind3 = CachedClusterLoc.index;
%mni = [];
%matLoc = [] ;
%%% Covert the display index into the native volume index
Q = [];
[Q(:,1) Q(:,2) Q(:,3)] = ind2sub(Obj(vn).h.dim,ind3);
Q(:,4) = 1;
Q = (Q*Obj(vn).h.mat')*inv(th.mat');
Q = unique(round(Q),'rows');
i1 = unique([find(Q(:,1)<=0 | Q(:,1)>th.dim(1)); find(Q(:,2)<=0 | Q(:,2)>th.dim(2)); find(Q(:,3)<=0 | Q(:,3)>th.dim(3))]);
i2 = setdiff(1:size(Q,1),i1);
Q = Q(i2,:);
voxInd = sub2ind(th.dim,Q(:,1),Q(:,2),Q(:,3));
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
VOI = [];
VOI.mniLoc = 'From Cached Cluster';
VOI.matLoc = [];
VOI.index = voxInd;
VOI.isCluster = 1;
try
[x y z] = ind2sub(th.dim,voxInd);
dat = zeros(numel(DataHeaders),numel(x));
for zz = 1:numel(DataHeaders);
dat(zz,:) = spm_sample_vol(DataHeaders(zz),x,y,z,0);
end
if isfield(Des,'ZeroDrop')
if Des.ZeroDrop == 1
dat(dat==0)=NaN;
end
end
if isfield(Des,'OL')
ti1 = intersect(voxInd,Des.OL{2}(:,2));
for zz = 1:numel(ti1);
ti2 = find(Des.OL{2}(:,2)==ti1(zz));
ti3 = find(voxInd == ti1(zz));
dat(ti3,Des.OL{2}(ti2,1))=NaN;
end
end
VOI.allData = dat;
VOI.data = nanmean(dat,2);
catch
VOI.allData = [];
end
otherwise
end
if ~plotGo
assignin('base','VOI',VOI);
warning('Plotting options are not available for this contrast');
return;
end
switch modelType
case 'spm'
c = spmCon.c;
VOI.con = c;
VOI.DM = DM;
VOI.SPM = Des;
assignin('base','VOI',VOI);
GLM_Plot_spm(VOI,777+gcf);
case 'regular'
if isfield(contrasts,'c') && ~isempty(contrasts(wh).c)
c = contrasts(wh).c;
else
try
c = getContrastMat(contrasts(wh));
catch
assignin('base','VOI',VOI);
return
end
end
VOI.con = c;
VOI.DM = DM;
VOI.F = Des.F;
VOI.ConSpec = Des.Cons(wh);
assignin('base','VOI',VOI);
[yres xres] = GLM_Plot(VOI,777+gcf);
VOI.yres = yres;
VOI.xres = xres;
assignin('base','VOI',VOI);
case 'fast'
[pr1 pr2 pr3] = fileparts(Obj(vn).FullPath);
ind = find(pr2=='_');
effect = pr2(ind(2)+1:end);
%figure(555+gcf); clf;
figure; clf;
[yres xres part] = GLM_Plot_Fast(VOI.data,DM,effect);
VOI.effect = effect;
VOI.mod = DM;
VOI.part = part;
VOI.yres = yres;
VOI.xres = xres;
assignin('base','VOI',VOI);
otherwise
end
movego = 0;
end
function loadData(varargin)
vn = get(con(21,1),'Value');
adir = Obj(vn).FullPath;
ind = find(adir==filesep);
if isempty(ind);
adir = [];
else
adir = adir(1:ind(end));
end
if exist([adir 'I.mat'])>0;
%if ~isempty(contains('aschultz',{UserTime})) keyboard; end
HH = load([adir 'I.mat']);
if exist([adir 'FinalDataSet.nii'])
DataHeaders = spm_vol([adir 'FinalDataSet.nii']);
disp('Loading FinalDataSet.nii');
tmp = [(DataHeaders.n)];
Flist = [char(DataHeaders.fname) repmat(',',numel(DataHeaders),1) char(num2str(tmp(1:2:end)'))];
plotGo = 1;
elseif isfield(HH.I,'Scans');
disp('Reading in original input files');
Flist = char(HH.I.Scans);
DataHeaders = spm_vol(Flist);
plotGo = 1;
else
plotGo = 0;
end
if isfield(HH.I,'OL');
Outliers = HH.I.OL;
end
if isfield(HH.I,'Cons')
contrasts = HH.I.Cons;
DM = HH.I.F.XX;
modelType = 'regular';
else
modelType = 'fast';
DM = HH.I.MOD;
end
Des = HH.I;
nvox = prod(HH.I.v.dim);
ns = size(DM,1);
elseif exist([adir 'SPM.mat'])>0;
modelType = 'spm';
HH = load([adir 'SPM.mat']);
contrasts = HH.SPM.xCon;
tmp = spm_read_vols(HH.SPM.xY.VY);
ss = size(tmp);
Des = HH.SPM;
origDat = double(reshape(tmp, prod(ss(1:3)),ss(4))');
DM = HH.SPM.xX.X;
Flist = char(HH.SPM.xY.P);
DataHeaders = HH.SPM.xY.VY;
plotGo = 1;
else
disp('No stat support files were found');
return;
end
end
function applyToAll(varargin)
vn = get(con(21,1),'Value');
sett = setdiff(2:length(Obj),vn);
for ii = sett
%Obj(ii).Thresh = Obj(vn).Thresh;
Obj(ii).clim = Obj(vn).clim;
Obj(ii).PVal = Obj(vn).PVal;
%Obj(ii).DF = Obj(vn).DF;
Obj(ii).Trans = Obj(vn).Trans;
set(con(21,1),'Value',ii);
%AutoUpdate;
switchObj;
%UpdateThreshold;
end
set(con(21,1),'Value',vn);
switchObj;
end
function getPeakInfo(varargin)
vn = get(con(21,1),'Value');
S = [];
getClusterParams;
peak = [];
%S.FWHM = [15.4639 15.4037 15.3548];
%[voxels voxelstats clusterstats sigthresh regions mapparameters UID]
%keyboard;
[peak.voxels peak.voxelstats peak.clusterstats peak.sigthresh peak.regions] = peak_nii(Obj(vn).FullPath(1:end-2),S);
assignin('base','peak',peak);
figure(666); clf; %reset(666);
%%% Add in some sorting options for the table
[a b] = sortrows([cellstr(char(num2str(peak.voxels{1}(:,end)))) peak.regions(:,2)]);
tabHand = uitable('Parent',666,...
'ColumnName',{'Cluster Size' 'T/F-Stat' 'X' 'Y' 'Z' 'N_peaks' 'Cluster Num' 'Region Num' 'Region Name'},...
'data', [mat2cell(peak.voxels{1}(b,:),ones(size(peak.voxels{1},1),1), ones(size(peak.voxels{1},2),1)) peak.regions(b,:)],...
'Units','Normalized','Position', [0 0 1 1],...
'ColumnWidth', 'auto', 'RearrangeableColumns','on','CellSelectionCallback',@goToCluster);
%set(tabHand, 'uicontextmenu',tableMenu);
Out = cell(size(peak.voxels{1},1)+1 ,9);
Out(1,:) = {'Cluster Size' 'T/F-Stat' 'X' 'Y' 'Z' 'N_peaks' 'Cluster Num' 'Region Num' 'Region Name'};
Out(2:end,1:7) = num2cell(peak.voxels{1});
Out(2:end,8:9) = peak.regions;
[a b c] = fileparts(Obj(vn).FullPath);
WriteDataToText(Out,[a filesep 'peakinfo.csv'],'w',',');
end
function goToCluster(varargin)
data = get(tabHand,'Data');
row = varargin{2}.Indices(1);
mni = [data{row,3:5}];
set(con(15,1),'String',num2str(mni));
goTo(con(15,1));
end
function out = initializeUnderlay(M,HH)
out.Name = 'Structural Underlay';
out.I = double(M);
out.h = HH;
out.Thresh = [min(M(:)) max(M(:))];
if ~isempty(contains('defaultUnderlay.nii',{HH.fname}))
out.clim = [max(M(:))*.15 max(M(:))*.8];
else
out.clim = out.Thresh;
end
out.PVal = [];
out.col = 1;
out.pos = axLim(M,HH);
out.Exclude = [];
out.MaskInd = [];
out.mask = ones(size(M),'uint8');
out.Trans = 1;
out.mask = ones(size(M),'uint8');
out.Thresh = [min(M(:)) max(M(:))];
out.clim = [min(M(:)) max(M(:))];
out.Range = [out.Thresh(1) out.Thresh(2) diff(out.Thresh) ];
out.axLims = size(M);
mniLims = [[min(out.pos{1}) min(out.pos{2}) min(out.pos{3})]; ...
[max(out.pos{1}) max(out.pos{2}) max(out.pos{3})]];
end
function changeUnderlay(varargin)
ufn = spm_select(1,'image','Choose the new underlay');
h = spm_vol(ufn);
[I mmm] = SliceAndDice3(h,MH,[],[],[0 NaN],[]);
h.dim = size(I);
h.mat = mmm;
nv = 1;
for ii = 1:length(hand)
delete(hand{ii}(nv));
end
tmp = initializeUnderlay(I,h);
flds = fields(tmp);
for ii = 1:length(flds)
Obj(1).(flds{ii}) = tmp.(flds{ii});
end
Obj(1).point = round([loc 1] * inv(Obj(1).h.mat)');
setupFrames(1,1);
tss = Obj(1).axLims;
tmp = [1 1 1];
tss = tss.*tmp;
height = tss(2)+tss(3);
width = tss(1)+tss(2);
rat = height/width;
ff = get(0,'ScreenSize');
if ff(4)>800
pro = 3.25;
else
pro = 2.5;
end
ss = get(0,'ScreenSize');
if (ss(3)/ss(4))>2
ss(3)=ss(3)/2;
end
op = floor([50 ss(4)-75-((ss(3)/pro)*rat) ss(3)/pro (ss(3)/pro)*rat]);
set(gcf, 'Position', op);
wid(1) = tss(2)/width;
hei(1) = tss(3)/height;
wid(2) = tss(1)/width;
hei(2) = tss(3)/height;
wid(3) = tss(1)/width;
hei(3) = tss(2)/height;
set(ax1,'Color','k','Position',[wid(2) hei(3) wid(1) hei(1)]); hold on;
set(ax2,'Color','k','Position',[0 hei(3) wid(2) hei(2)]); hold on;
set(ax3,'Color','k','Position',[0 0 wid(3) hei(3)]); hold on;
set(ax4,'Color','w','Position',[wid(2) 0 .04 hei(3)]); axis tight;
%st = wid(2)+.01+.04+.03;
st = wid(2)+.125;
len1 = (1-st)-.01;
len2 = len1/2;
len3 = len1/3;
inc = (hei(3))/11;
inc2 = .75*inc;
val = (Obj(1).Range(2)-Obj(1).Range(1))/Obj(1).Range(3);
con(27,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.070 0 .025 hei(3)*.9],'Value',val,'CallBack', @adjustUnderlay);
val = (Obj(1).Range(1)-Obj(1).Range(1))/Obj(1).Range(3);
con(28,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.095 0 .025 hei(3)*.9],'Value',val,'CallBack', @adjustUnderlay);
%con(29,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.095 0 .025 hei(3)*.9],'Value',0,'CallBack', @adjustUnderlay);
con(30,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[wid(2)+.070 hei(3)*.9 .05 .05]); % wid(2)+.0450 hei(3)*.9 .075 .05]
% con(28,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[st-.1 (.01+(1*inc)+(0*inc2)) len1*.75 inc],'Value',1,'CallBack', @adjustTrans);
con(1,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(0*inc)+(0*inc2) len1 inc],'String',[{'Colormap'} cmaps(:)'],'CallBack', @changeColorMap); shg
%con(1,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(0*inc)+(0*inc2) len1 inc],'String',[{'Colormap' 'A' 'B' 'C' 'D'}],'CallBack', @changeColorMap); shg
con(2,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[st (.01+(1*inc)+(0*inc2)) len1*.75 inc],'Value',1,'CallBack', @adjustTrans);
con(23,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len1*.75 (.01+(1*inc)+(0*inc2)) len1*.25 inc],'String','All','CallBack', @applyToAll);
con(3,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(2*inc)+(0*inc2) len1 inc2],'String', 'Transparency','fontsize',12);
con(4,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(2*inc)+(1*inc2) len2 inc],'CallBack',@UpdateThreshold);
con(5,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len2 .01+(2*inc)+(1*inc2) len2 inc],'CallBack',@UpdateCLims);
con(6,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(3*inc)+(1*inc2) len2 inc2],'String', 'Thresh','fontsize',12);
con(7,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len2 .01+(3*inc)+(1*inc2) len2 inc2],'String', 'Color Limits','fontsize',12);
con(8,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@UpdatePVal);
con(9,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len3 .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@UpdatePVal);
con(23,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len3+len3 .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@ExtentThresh);
con(10,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(4*inc)+(2*inc2) len3 inc2],'String', 'DF','fontsize',12);
con(11,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len3 .01+(4*inc)+(2*inc2) len3 inc2],'String', 'P-Value','fontsize',12);
con(24,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len3+len3 .01+(4*inc)+(2*inc2) len3 inc2],'String', 'Extent','fontsize',12);
con(15,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(4*inc)+(3*inc2) len2 inc],'String',num2str(loc),'CallBack',@goTo);
%con(15,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(4*inc)+(3*inc2) len2 inc],'String',['0 0 0'],'CallBack',@goTo);
con(25,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len2 .01+(4*inc)+(3*inc2) len2/2 inc],'String','FDR','CallBack', @correctThresh);
con(26,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+(len2*1.5) .01+(4*inc)+(3*inc2) len2/2 inc],'String','FWE','CallBack', @correctThresh);
con(17,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(5*inc)+(3*inc2) len2 inc2],'String', 'MNI Coord', 'fontsize',12);
con(18,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len2 .01+(5*inc)+(3*inc2) len2 inc2],'String', 'MC Correct','fontsize',12);
con(12,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st .01+(5*inc)+(4*inc2) len2 inc],'String',{'Move Up'},'CallBack',@changeLayer);
con(13,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len2 .01+(5*inc)+(4*inc2) len2 inc],'String',{'Move Down'},'CallBack',@changeLayer);
con(21,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(5*inc)+(5*inc2) len1 inc],'String',{'Overlays'},'CallBack',@switchObj);
con(22,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[wid(2)-(len2/2) hei(3)-(inc*1.05) (len2/2) inc]);
con(19,1) = uicontrol(pane,'style','PushButton','Units','Normalized','Position',[st .01+(6*inc)+(5*inc2) len2 inc],'String','Open Overlay','FontWeight','Bold','CallBack',@openOverlay);
con(20,1) = uicontrol(pane,'style','PushButton','Units','Normalized','Position',[st+len2 .01+(6*inc)+(5*inc2) len2 inc],'String','Remove Volume', 'FontWeight','Bold','CallBack',@removeVolume);
drawFresh(ax1,1,1); axis equal;
drawFresh(ax2,2,1); axis equal;
drawFresh(ax3,3,1); axis equal;
set(ax1,'color','k')
set(ax2,'color','k')
set(ax3,'color','k')
axes(ax1); ax = axis;
set(ch(1,1),'YData',ax(3:4)); set(ch(1,2),'XData',ax(1:2));
axes(ax2); ax = axis;
set(ch(2,1),'YData',ax(3:4)); set(ch(2,2),'XData',ax(1:2));
axes(ax3); ax = axis;
set(ch(3,1),'YData',ax(3:4)); set(ch(3,2),'XData',ax(1:2));
uistack(hand{1}(1),'bottom');
uistack(hand{2}(1),'bottom');
uistack(hand{3}(1),'bottom');
set(con(27),'value',1);
set(con(28),'value',0);
if get(con(21,1),'Value') == 1
set(con(5),'String', sprintf('%0.3f %0.3f',Obj(1).Thresh(1),Obj(1).Thresh(2)));
end
end
function plotConfig
fh = figure(777); clf; reset(777);
pop(1) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .95 .9 .05],'String','Choose the plot Type','Fontsize',12);
bg = uibuttongroup(fh,'Units','Normalized','position',[.05 .9 .9 .05]);
pop(2) = uicontrol(bg,'style','radiobutton','Units','Normalized','position',[ 00 0 .33 1],'String','BoxPlot','Fontsize',12);
pop(3) = uicontrol(bg,'style','radiobutton','Units','Normalized','position',[.33 0 .33 1],'String','InteractionPlot','Fontsize',12);
pop(4) = uicontrol(bg,'style','radiobutton','Units','Normalized','position',[.66 0 .33 1], 'String', 'ScatterPlot','Fontsize',12);
pop(5) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .83 .9 .05],'String','Set the Data Groups','Fontsize',12);
pop(6) = uicontrol(fh,'style','edit','Units','Normalized','position',[.05 .75 .9 .08],'String','{{1:10} {11:20} {etc..}}','Fontsize',12);
pop(7) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .68 .9 .05],'String','Specify Design Matirx Columns','Fontsize',12);
pop(8) = uicontrol(fh,'style','edit','Units','Normalized','position',[.05 .60 .9 .08],'String','{{1:10} {11:20} {etc..}}','Fontsize',12);
end
function ExtentThresh(varargin)
CM = 18;%str2num(get(findobj(paramenu3(5),'Checked','On'),'Label'));
vn = get(con(21,1),'Value');
ClusterExtent = str2num(get(con(23),'String'));
if isempty(ClusterExtent) || ClusterExtent==0;
Obj(vn).mask = ones(size(Obj(vn).I),'uint8');
Obj(vn).Exclude = [];
Obj(vn).mask(Obj(vn).MaskInd)=0;
return
end
Obj(vn).ClusterThresh = ClusterExtent;
if numel(Obj(vn).Thresh)==2
ind = find(Obj(vn).I<Obj(vn).Thresh(1) | Obj(vn).I>Obj(vn).Thresh(2));
else
ind = find(Obj(vn).I<Obj(vn).Thresh(1) | Obj(vn).I>Obj(vn).Thresh(4) | (Obj(vn).I>Obj(vn).Thresh(2) & Obj(vn).I<Obj(vn).Thresh(3)));
end
%tmpI(ind) = NaN;
ind = setdiff(1:prod(Obj(vn).axLims),ind);
L = [];
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',CM);
Exclude = [];
list = unique(A);
for ii = list
i1 = find(A==ii);
if numel(i1)<ClusterExtent
Exclude = [Exclude ind(i1)];
end
end
Obj(vn).mask(:) = 1;
Obj(vn).Exclude = Exclude;
Obj(vn).mask(Exclude)=0;
Obj(vn).mask(Obj(vn).MaskInd)=0;
setupFrames(vn,1);
updateGraphics({1:3 vn},1);
end
function out = popup(Message)
%%% Fix this up later so that multiple messages mean multiple
%%% inputs
fh = figure(777); clf; %reset(777);
pop(1) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .83 .9 .05],'String',Message,'Fontsize',12);
pop(2) = uicontrol(fh,'style','edit','Units','Normalized','position',[.05 .75 .9 .08],'String','','Fontsize',12,'Callback','uiresume');
uiwait
eval(['out = [' get(pop(2),'String') '];']);
close(gcf);
end
function TestFunc(varargin)
vn = get(con(21,1),'Value');
wh = Count;
Obj(wh) = Obj(1);
tmpVol = SliceAndDice3(Obj(vn).FullPath,Obj(1).h,Obj(1).h,Obj(1).h,[1 NaN],[]);
ind = find(tmpVol>Obj(vn).Thresh(1) & tmpVol<Obj(vn).Thresh(2));
Obj(wh).I(setdiff(1:numel(Obj(wh).I),ind)) = NaN;
tmp = Obj(1).CM(:,:,:,1); tmp = round((tmp./max(tmp(:)))*(size(cmap{1,1},1)-1));
nn = zeros(numel(tmp),3)*NaN;
ind2 = find(~isnan(tmp));
nn(ind2,:) = cmap{2,1}(tmp(ind2)+1,:);
a = zeros(size(Obj(1).CM))*NaN;
b = zeros(size(Obj(1).CM))*NaN;
c = zeros(size(Obj(1).CM))*NaN;
a(ind) = nn(ind,1);
b(ind) = nn(ind,2);
c(ind) = nn(ind,3);
Obj(wh).CM = cat(4,a,b,c);
m = Obj(wh).I;
n2 = 'TmpImg';
set(con(21,1),'String', [get(con(21,1),'String'); n2],'Value',Count);
set(con(4),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(5),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(8),'String','NaN');
set(con(9),'String','NaN');
Obj(wh).DF = NaN;
Obj(wh).PVal = NaN;
Obj(wh).Thresh = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(wh).clim = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(wh).col = 2;
Obj(wh).Trans = 1;
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
loc = [x(1) y(1) z(1)];
Obj(wh).point = round([loc 1] * inv(Obj(wh).h.mat)');
setupFrames(wh,0);
Obj(wh).pos = axLim(Obj(wh).I,Obj(wh).h);
tmp = size(Obj(wh).CM);
Obj(wh).axLims = tmp(1:3);
set(con(1,1),'Value',wh+1);
drawFresh(ax1,1,wh);
drawFresh(ax2,2,wh);
drawFresh(ax3,3,wh);
uistack(ch(1,1),'top'); uistack(ch(1,2),'top');
uistack(ch(2,1),'top'); uistack(ch(2,2),'top');
uistack(ch(3,1),'top'); uistack(ch(3,2),'top');
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
Count = Count+1;
end
function c = getContrastMat(Con)
tx = Des.F.XX;
if ~isfield(Con,'c') || isempty(Con.c)
if iscell(Con.Groups)
tc = [];
for zz = 1:length(Con.Groups)
if size(Con.Groups{zz},1)>1
tmpX = Con.Groups{zz};
else
tmpX = tx(:,Con.Groups{zz});
end
cc = MakePreCons(tmpX,tx,Des.F.CovarCols);
tc(:,zz) = mean(cc,2);
end
levs = Con.Levs(end:-1:1);
if levs == 0
c = tc;
else
tmp = reshape(tc,[size(tc,1) levs]);
tmp = squeeze(tmp);
if size(tmp,2)==1
c = tmp;
else
c = differencer(tmp);
if numel(levs)==1
c = c*-1;
end
end
end
else
[r,c,cc] = MakeContrastMatrix('a',Con.Groups,Con.Levs,tx);
end
else
c = Con.c;
c0 = eye(size(txx,2))-(c*pinv(c));
x0 = txx*c0;
r = eye(size(x0,1))-(x0*pinv(x0));
end
end
function saveImg(varargin)
%%% Write something in the descip field to describe how the image
%%% was made
from = varargin{1};
vn = get(con(21,1),'Value');
CM = str2num(get(findobj(paramenu3(5),'Checked','On'),'Label'));
switch from
case menu(19)
disp('Save Thresholded Image');
dotI = find(Obj(vn).FullPath=='.');
fn = [Obj(vn).FullPath(1:dotI(end)-1) '_thresh.nii'];
th = spm_vol(Obj(vn).FullPath);
hh = Obj(vn).h;
hh.fname = fn;
if ~isempty(Obj(vn).mask);
tmp = Obj(vn).I.*double(Obj(vn).mask);
else
tmp = Obj(vn).I;
end
if numel(Obj(vn).Thresh)==2
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(2));
else
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(4) | (tmp>Obj(vn).Thresh(2) & tmp<Obj(vn).Thresh(3)));
end
tmp(ind)=NaN;
spm_write_vol(hh,tmp);
hh2 = spm_vol(fn);
N = resizeVol2(hh2,th);
th.fname = fn;
th.descrip = [];
spm_write_vol(th,N);
case menu(20)
disp('Save Masked Image');
dotI = find(Obj(vn).FullPath=='.');
fn = [Obj(vn).FullPath(1:dotI(end)-1) '_mask.nii'];
th = spm_vol(Obj(vn).FullPath);
hh = Obj(vn).h;
hh.fname = fn;
hh.dt = [2 0];
tmp = Obj(vn).I;
if numel(Obj(vn).Thresh)==2
ind = find(tmp>Obj(vn).Thresh(1) & tmp<Obj(vn).Thresh(2));
else
ind = find((tmp>Obj(vn).Thresh(1) & tmp<Obj(vn).Thresh(2)) | (tmp>Obj(vn).Thresh(3) & tmp<Obj(vn).Thresh(4)));
end
tmp(:)=0;
tmp(ind)=1;
spm_write_vol(hh,tmp);
hh2 = spm_vol(fn);
N = resizeVol(hh2,th);
th.fname = fn;
th.descrip = [];
th.dt = [2 0];
spm_write_vol(th,N);
case menu(21)
disp('Save Cluster Image');
mni = str2num(get(con(15),'string'));
tmp = Obj(vn).I;
if numel(Obj(vn).Thresh)==2
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(2));
else
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(4) | (tmp>Obj(vn).Thresh(2) & tmp<Obj(vn).Thresh(3)));
end
tmp(ind)=NaN;
ind = find(~isnan(tmp));
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',18);
L(:,4) = 1;
L2 = L*Obj(vn).h.mat';
dist = sqrt(sum((L2(:,1:3)-repmat(mni, size(L,1),1)).^2,2));
if min(dist)>5
disp('No Cluster is selected');
end
ind1 = find(dist==min(dist));
ind2 = find(A==A(ind1(1)));
ind3 = ind(ind2);
tmp(:) = NaN;
tmp(ind3) = Obj(vn).I(ind3);
dotI = find(Obj(vn).FullPath=='.');
fn = [Obj(vn).FullPath(1:dotI(end)-1) '_cluster.nii'];
th = spm_vol(Obj(vn).FullPath);
hh = Obj(vn).h;
hh.fname = fn;
spm_write_vol(hh,tmp);
hh2 = spm_vol(fn);
N = resizeVol2(hh2,th);
th.fname = fn;
th.descrip = [];
spm_write_vol(th,N);
case menu(22)
disp('Save Cluster Mask');
mni = str2num(get(con(15),'string'));
tmp = Obj(vn).I;
if numel(Obj(vn).Thresh)==2
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(2));
else
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(4) | (tmp>Obj(vn).Thresh(2) & tmp<Obj(vn).Thresh(3)));
end
tmp(ind)=NaN;
ind = find(~isnan(tmp));
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',18);
L(:,4) = 1;
L2 = L*Obj(vn).h.mat';
dist = sqrt(sum((L2(:,1:3)-repmat(mni, size(L,1),1)).^2,2));
if min(dist)>5
disp('No Cluster is selected');
end
ind1 = find(dist==min(dist));
ind2 = find(A==A(ind1(1)));
ind3 = ind(ind2);
tmp(:) = 0;
tmp(ind3) = 1;
dotI = find(Obj(vn).FullPath=='.');
fn = [Obj(vn).FullPath(1:dotI(end)-1) '_clusterMask.nii'];
th = spm_vol(Obj(vn).FullPath);
hh = Obj(vn).h;
hh.fname = fn;
spm_write_vol(hh,tmp);
hh2 = spm_vol(fn);
N = resizeVol(hh2,th);
th.fname = fn;
th.descrip = [];
th.dt = [2 0];
spm_write_vol(th,N);
otherwise
end
end
function resampleIm(varargin)
vn = get(con(21,1),'Value');
%keyboard;
voxdim = str2num(char(regexp(get(varargin{1},'Label'),'x','split')))';
nnn = Obj(vn).FullPath;
hh = spm_vol(nnn);
[mm mat] = SliceAndDice3(hh, MH, voxdim, [],[1 0],[]);
hh.dim = size(mm);
hh.mat = mat;
Obj(vn).h = hh;
Obj(vn).I = double(mm);
Obj(vn).mask = ones(size(mm),'uint8');
Obj(vn).pos = axLim(Obj(vn).I,Obj(vn).h);
Obj(vn).axLims = Obj(vn).h.dim;
loc = str2num(get(con(15),'String'));
Obj(vn).point = round([loc 1] * inv(Obj(vn).h.mat)');
setupFrames(vn,1);
for ii = 1:length(hand)
delete(hand{ii}(vn));
end
drawFresh(ax1,1,vn);
drawFresh(ax2,2,vn);
drawFresh(ax3,3,vn);
uistack(ch(1,1),'top'); uistack(ch(1,2),'top');
uistack(ch(2,1),'top'); uistack(ch(2,2),'top');
uistack(ch(3,1),'top'); uistack(ch(3,2),'top');
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
end
function correctThresh(varargin)
vn = get(con(21,1),'Value');
if numel(Obj(vn).DF)==1
stat = 'T';
df = [1 Obj(vn).DF];
elseif numel(Obj(vn).DF)==2
stat = 'F';
df = Obj(vn).DF;
end
if ~isempty(Obj(vn).mask);
tmpI = Obj(vn).I.*double(Obj(vn).mask);
else
tmpI = Obj(vn).I;
end
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
if varargin{1}==con(25) %FDR Correction
if numel(Obj(vn).Thresh) == 2
ind = find(abs(tmpI)>0);
div = 1;
if sum(sign(Obj(vn).Thresh))<0
%ind = find(Obj(vn).I<0);
t = abs(tmpI(ind));
elseif sum(sign(Obj(vn).Thresh))>0
%ind = find(Obj(vn).I>0);
t = abs(tmpI(ind));
end
elseif numel(Obj(vn).Thresh) == 4
ind = find(abs(tmpI)>0);
t = abs(tmpI(ind));
div = 2;
end
if strcmpi(stat,'f');
pp = 1-spm_Fcdf(t,df);
else
pp = (1-spm_Tcdf(t,df(2))).*div;
end
pp = sort(pp);
%keyboard;
alpha = str2num(get(findobj(paramenu3(18),'Checked','On'),'Label'));
p = pp';
rh = ((1:numel(p))./numel(p)).*alpha;
below = p<=rh;
in = (find(below==1));
if isempty(in)
warning('FDR Correction is not possible for this alpha');
return
end
%;
t = sort(t,'descend');
thresh = t(in(end));
pthresh = p(in(end));
%[FDR_alpha FDR_p FDR_t] = computeFDR('0003_T_TFO_Pos_Corr.nii',114,.05,0)
end
if varargin{1}==con(26) %% FWE correction using RFT
[a b c] = fileparts(Obj(vn).FullPath);
try
HH = load([a filesep 'I.mat']);
%R = HH.I.ReslInfo{HH.I.Cons(wh).ET};
if isfield(HH.I,'Cons')
FWHM = HH.I.FWHM{HH.I.Cons(wh).ET};
end
if isfield(HH.I,'MOD')
ind = find(b=='_');
effect = b(ind(2)+1:end);
for ii = 1:numel(HH.I.MOD.RFMs)
for jj = 1:numel(HH.I.MOD.RFMs(ii).Effect)
if strcmpi(effect,HH.I.MOD.RFMs(ii).Effect(jj).name)
ET = ii;
end
end
end
FWHM = HH.I.FWHM{ET};
end
catch
HH = load([a filesep 'SPM.mat']);
%R = HH.SPM.xVol.R;
FWHM = HH.SPM.xVol.FWHM;
end
p = str2num(get(findobj(paramenu3(18),'Checked','On'),'Label'));
try
[msk mh] = openIMG([a filesep 'mask.img']);
catch
try
[msk mh] = openIMG([a filesep 'mask.nii']);
catch
[msk mh] = openIMG([a filesep 'NN.nii']);
mh.fname = 'mask.nii';
spm_write_vol(mh,msk>0);
[msk mh] = openIMG([a filesep 'mask.nii']);
end
end
if ~isempty(Obj(vn).mask);
msk = Obj(vn).I.*double(Obj(vn).mask);
end
reselinfo = spm_resels_vol(mh,FWHM)';
if strcmpi(stat,'f');
thresh = spm_uc(p,df,stat,reselinfo,1,numel(find(msk>0)));
pthresh = 1-spm_Fcdf(thresh,df);
else
if numel(Obj(vn).Thresh) == 4
thresh = spm_uc(p/2,df,stat,reselinfo,1,numel(find(msk>0)));
pthresh = (1-spm_Tcdf(thresh,df(2)));
else
thresh = spm_uc(p,df,stat,reselinfo,1,numel(find(msk>0)));
pthresh = (1-spm_Tcdf(thresh,df(2)));
end
end
end
thresh = round(thresh*1000)/1000;
if numel(Obj(vn).Thresh) == 2
if sum(sign(Obj(vn).Thresh))<0
if thresh<Obj(vn).Thresh(1)
warning(['No voxels beyond the corrected threshold of ' num2str(-thresh)]);
return
end
Obj(vn).Thresh = [Obj(vn).Thresh(1) -thresh];
Obj(vn).PVal = pthresh;
else
if thresh>Obj(vn).Thresh(2)
warning(['No voxels beyond the corrected threshold of ' num2str(thresh)]);
return
end
Obj(vn).Thresh = [thresh Obj(vn).Thresh(2)];
Obj(vn).PVal = pthresh;
end
elseif numel(Obj(vn).Thresh) == 4
up = ~(thresh>Obj(vn).Thresh(4));
down = ~(thresh<Obj(vn).Thresh(1));
if ~up && ~down
warning(['Nothing Left at this Threshold. Exiting Correction.']);
return;
end
if up && down
Obj(vn).Thresh = [Obj(vn).Thresh(1) -thresh thresh Obj(vn).Thresh(4)];
Obj(vn).PVal = pthresh;
end
if up && ~down
warning(['No voxels below the corrected threshold of ' num2str(-thresh)]);
Obj(vn).Thresh = [thresh Obj(vn).Thresh(4)];
Obj(vn).PVal = pthresh;
end
if down && ~up
warning(['No voxels above the corrected threshold of ' num2str(thresh)]);
Obj(vn).Thresh = [Obj(vn).Thresh(1) -thresh];
Obj(vn).PVal = pthresh;
end
end
ll = []; for zz = 1:numel(Obj(vn).Thresh); ll = [ll num2str(Obj(vn).Thresh(zz)) ' ']; end;
ll = ll(1:end-1);
set(con(4,1),'String',num2str(ll));
UpdateThreshold(con(4,1));
end
function changeLabelMap(varargin)
groupCheck(varargin{1})
% fn1 = which([get(varargin{1},'Label') '.img']);
% fn2 = which([get(varargin{1},'Label') '.mat']);
try
[fn1,fn2]=getLabelMap(get(varargin{1},'Label'));
catch
fn1=[];fn2=[];
end
if isempty(fn1) && isempty(fn2)
warning(['Label Map ' get(varargin{1},'Label') ' cannot be found. Reverting to aal_MNI_V4']);
set(varargin{1},'Checked','off');
set(findobj(gcf,'Label','aal_MNI_V4'),'Checked','on');
return
end
RNH = spm_vol(fn1);
[RNI Rxyz] = spm_read_vols(RNH);
RNames = load(fn2);
end
function h = moveYaxLabs(currAx,wh)
if nargin==0 || isempty(currAx)
currAx = gca;
end
if wh == 'y'
ax = axis(currAx);
y = get(currAx,'YTick');
lab = cellstr(get(currAx,'YTickLabel'));
for ii = 1:numel(lab)
if lab{ii}(1) ~= '-'
lab{ii} = ['+' lab{ii}];
end
end
adj = range(y)*.015;
adj2 = range(ax(1:2))*.5;
for ii = 1:numel(lab)
if ii==1
h(ii) = text(ax(1)+adj2,y(ii)+adj,lab{ii},'FontName', get(currAx,'FontName'), 'FontSize',get(currAx,'FontSize'),'color','w','HorizontalAlignment','Center'); shg
elseif ii==numel(lab)
h(ii) = text(ax(1)+adj2,y(ii)-adj,lab{ii},'FontName', get(currAx,'FontName'), 'FontSize',get(currAx,'FontSize'),'color','w','HorizontalAlignment','Center'); shg
else
h(ii) = text(ax(1)+adj2,y(ii), lab{ii},'FontName', get(currAx,'FontName'), 'FontSize',get(currAx,'FontSize'),'color','w','fontweight','bold','HorizontalAlignment','Center'); shg
%p = get(h(ii),'Position'); p(3) = 15; set(h(ii),'Position',p);
end
end
set(gca,'XTick', [],'YTick',[]);
elseif wh == 'x'
ax = axis(currAx);
x = get(currAx,'XTick');
lab = cellstr(get(currAx,'XTickLabel'));
for ii = 1:numel(lab)
if lab{ii}(1) ~= '-'
lab{ii} = ['+' lab{ii}];
end
end
adj2 = range(ax(3:4))*.5;
for ii = 1:numel(lab)
if ii==1
h(ii) = text(ax(1)+(.005*adj2), ax(3)+adj2, lab{ii},'FontName', get(gca,'FontName'), 'FontSize',get(gca,'FontSize'),'color','w','HorizontalAlignment','Left'); shg
elseif ii==numel(lab)
h(ii) = text(ax(2)-(.005*adj2), ax(3)+adj2, lab{ii},'FontName', get(gca,'FontName'), 'FontSize',get(gca,'FontSize'),'color','w','HorizontalAlignment','Right'); shg
else
h(ii) = text(x(ii)-(.005*adj2), ax(3)+adj2, lab{ii},'FontName', get(gca,'FontName'), 'FontSize',get(gca,'FontSize'),'color','w','fontweight','bold','HorizontalAlignment','Center'); shg
end
end
set(gca,'XTick', [],'YTick',[]);
end
end
function initializeConnExplore(varargin)
vn = get(con(21,1),'Value');
if ConExp==1
switchObj(ConLayer)
return
end
fn = ['/autofs/space/schopenhauer_004/users/ConnectivityAtlas/Maps/blank.nii'];
openOverlay(fn);
ConExp = 1;
ConHeader = spm_vol(fn);
vn = get(con(21,1),'Value');
ConLayer = vn;
%Obj(2).h.mat
Obj(vn).Thresh = [-1 1];
Obj(vn).clim = [-1 1];
set(con(4),'String','-1 1');
set(con(5),'String','-1 1');
end
function updateConnMap(varargin)
if ConExp==0
return
end
vn = get(con(21,1),'Value');
if vn ~= ConLayer;
return
end
MNI = Obj(1).point*Obj(1).h.mat';
matLoc = round(MNI*inv(ConHeader.mat)');
thisLoc = sub2ind(ConHeader.dim,matLoc(1),matLoc(2),matLoc(3));
fn = ['/autofs/space/schopenhauer_004/users/ConnectivityAtlas/Maps/Vox_' sprintf('%0.6d',thisLoc) '.nii'];
if exist(fn)>0
Obj(vn).I = openIMG(fn);
%Obj(vn).I = resizeVol2(spm_vol(fn),Obj(vn).h);
else
Obj(vn).I(:) = NaN;
end
UpdateThreshold;
end
function ssConn(varargin)
vn = get(con(21,1),'Value');
if ssConExp==1
switchObj(ssConLayer)
return
end
ff = spm_select(inf,'image');
fn = [];
for zz = 1:size(ff,1)
fn{zz} = (ff(zz,1:end-2));
end
openOverlay(ff(1,:));
ssConExp = 1;
vn = get(con(21,1),'Value');
ssConHeader = Obj(vn).h;
ssConLayer = vn;
ssData = [];
for zz = 1:numel(fn);
pth = fileparts(fn{zz});
% R = [];
% fl = [pth '/ExtraRegressors.mat'];
% if exist(fl,'file')>0
% load(fl);
% [rows,cols] = find(R==1);
% else
% rows = [];
% end
th = spm_vol(fn{zz});
% wh = setdiff(1:numel(th), rows);
% th = th(wh);
dat = zeros(numel(th),prod(Obj(vn).h.dim));
for qq = 1:numel(th)
dd = resizeVol2(th(qq),Obj(vn).h);
dat(qq,:) = dd(:);
end
ssData = [ssData; zscore(dat)];
end
ssData = zscore(ssData);
Obj(vn).I(:) = 0;
Obj(vn).Thresh = [-1 1];
Obj(vn).clim = [-1 1];
set(con(4),'String','-1 1');
set(con(5),'String','-1 1');
UpdateThreshold;
end
function ssUpdateConnMap(varargin)
if ssConExp==0
return
end
vn = get(con(21,1),'Value');
if vn ~= ssConLayer;
return
end
MNI = Obj(1).point*Obj(1).h.mat';
matLoc = round(MNI*inv(ssConHeader.mat)');
thisLoc = sub2ind(ssConHeader.dim,matLoc(1),matLoc(2),matLoc(3));
rad = get(findobj(paramenu3(2),'Checked','on'),'Label');
rad = str2num(rad(1:end-2));
[ml vi] = getMatCoord(ssConHeader,MNI(1:3),rad*2);
seed = zscore(nanmean(ssData(:,vi),2));
beta = pinv(seed)*ssData;
% keyboard;
Obj(vn).I(:) = beta;
UpdateThreshold;
end
function movieMode(varargin)
nnn = spm_select(inf,'image');
if size(nnn,1)==1
ind = find(nnn==',');
nnn = nnn(1:ind-1);
end
dh = spm_vol(nnn);
for ii = 1:numel(dh)
[t1 t2] = SliceAndDice3(dh(ii),MH,[],Obj(1).h,[0 NaN],[]);
if ii == 1
dd = nan([size(t1) numel(dh)]);
end
dd(:,:,:,ii) = t1;
end
rang = [min(dd(:)) min(dd(:))];
xyz = [20 20 20]; jj = 1;
tmp = [];
tmp{1} = flipdim(rot90(squeeze(dd(xyz(1),:,:,jj)),1),1);
tmp{2} = flipdim(flipdim(rot90(squeeze(dd(:,xyz(2),:,jj)),1),1),2);
tmp{3} = flipdim(flipdim(rot90(squeeze(dd(:,:,xyz(3),jj)),1),1),2);
% tmp = pcolor(Obj(ii).pos{2}, Obj(ii).pos{3}, Obj(ii).frame{opt});
% if opt3; hand{opt}(ii) = tmp; end
% colormap(gray(256)); shading interp; hold on;
keyboard;
end
function adjustUnderlay(varargin)
if varargin{1}==con(29)
return
end
vn = get(con(21,1),'Value');
if isempty(Obj(vn).Thresh)
Obj(vn).Thresh = [min(Obj(vn).I(:)) max(Obj(vn).I(:))];
Obj(vn).clim = [min(Obj(vn).I(:)) max(Obj(vn).I(:))];
end
if ~isfield(Obj(vn),'Range') || isempty(Obj(vn).Range)
Obj(vn).Range = [min(Obj(vn).I(:)) max(Obj(vn).I(:)) max(Obj(vn).I(:))-min(Obj(vn).I(:)) ];
end
val = get(varargin{1},'Value');
if varargin{1}==con(27)
Obj(vn).clim(2) = (val*Obj(vn).Range(3))+Obj(vn).Range(1);
%Obj(vn).clim(2) = val*Obj(vn).Thresh(2);
end
if varargin{1}==con(28)
Obj(vn).clim(1) = (val*Obj(vn).Range(3))+Obj(vn).Range(1);
%Obj(vn).clim(1) = val*Obj(vn).Thresh(2);
end
set(con(5),'String',[sprintf('%0.3f %0.3f',Obj(vn).clim(1),Obj(vn).clim(2))]);
setupFrames(vn,1);
updateGraphics([1 2 3],1);
%%%%%
yy = Obj(vn).clim(1):(Obj(vn).clim(2)-Obj(vn).clim(1))/255:Obj(vn).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(vn).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
end
function UpdateCLims(varargin)
vn = get(con(21,1),'Value');
b = get(con(5),'String');
if contains(',',{b})
ind = find(b==',');
b = [str2num(strtrim(b(1:ind-1))) str2num(strtrim(b(ind+1:end)))];
else
b = str2num(b);
end
if b(1)==-inf
b(1) = Obj(vn).Range(1);
end
if b(2)==inf
b(2) = Obj(vn).Range(2);
end
Obj(vn).clim = b;
tmp1 = (Obj(vn).clim(2)-Obj(vn).Range(1))/Obj(vn).Range(3); if tmp1>1; tmp1=1; end; if tmp1<0; tmp1=0; end;
set(con(27),'Value', tmp1);
tmp1 = (Obj(vn).clim(1)-Obj(vn).Range(1))/Obj(vn).Range(3); if tmp1>1; tmp1=1; end; if tmp1<0; tmp1=0; end;
set(con(28),'Value', tmp1);
setupFrames(vn,1);
updateGraphics([1 2 3],1);
set(con(5),'String', sprintf('%0.3f %0.3f',b(1),b(2)));
%%%%%%%%%%%%%
yy = Obj(vn).clim(1):(Obj(vn).clim(2)-Obj(vn).clim(1))/255:Obj(vn).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(vn).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
end
end
function out = differencer(tmp,count)
if nargin == 1;
count = numel(size(tmp));
end
out = diff(tmp,1,count);
if count ~= 2;
out = differencer(out,count-1);
else
if numel(size(out))>2
ss = size(out);
out = reshape(out,size(out,1),prod(ss(2:end)));
end
return
end
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
GLM_Plot_Fast.m
|
.m
|
MRtools_Hoffman2-master/Visualization/GLM_Plot_Fast.m
| 8,807 |
utf_8
|
ac475e6853ae5de5eadc31da4bfe68b3
|
function [yres xres part] = GLM_Plot_Fast2(y,mod,effect)
%%% Written by Aaron Schultz ([email protected])
%%%
%%% Copyright (C) 2012, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01-AG027435
%%%
%%% 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
%%% 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.
%if contains('aschultz', {UserTime}); keyboard; end
yres = [];
xres = [];
part = [];
flag = 0;
effect = regexprep(effect,'\*',':');
effect = regexprep(effect,'_x_',':');
br = 0;
for ii = 1:numel(mod.RFMs)
if br==1; break; end
for jj = 1:numel(mod.RFMs(ii).Effect)
if strcmpi(effect, mod.RFMs(ii).Effect(jj).name)
which = [ii jj];
part = mod.RFMs(ii).Effect(jj);
br = 1;
break;
end
end
end
if strcmpi('FullModel',effect)
type1 = 'Continuous';
type2 = 'Prediction';
else
if isempty(part.dif) %isfield(part,'pieces') && ~isempty(part.pieces)
type1 = 'Continuous';
type2 = 'Prediction';
flag = 1;
else
terms = regexp(effect,'[\*\:]','split');
type1 = 'Categorical'; iscat = [];
for ii = 1:numel(terms)
if isnumeric(mod.data.(terms{ii}));
type1 = 'Continuous';
iscat(ii) = 0;
else
iscat(ii) = 1;
end
end
type2 = [];
if isempty(regexp(effect,'[\*\:]'))
type2 = 'MainEffect';
else
type2 = 'Interaction';
end
end
end
if strcmpi(type1,'Categorical') && strcmpi(type2,'MainEffect');
figure(gcf); clf; set(gcf,'Name','Raw Data Plot');
ScatterGroups2(y,mod.data.(effect));
% if exist('part','var');
% yres = crtlFor(y,part.tx2);%+mean(y);
% figure(gcf+1); clf; set(gcf,'Name','Type III Residualized Plot');
% ScatterGroups2(yres,mod.data.(effect));
% end
end
if strcmpi(type1,'Categorical') && strcmpi(type2,'Interaction');
figure(gcf); clf; set(gcf,'Name','Raw Data Plot');
F = {};
for ii = 1:numel(terms)
tmp = mod.data.(terms{ii});
if isobject(tmp)
F(:,ii) = cellstr(tmp);
else
F(:,ii) = tmp;
end
end
InterPlot2(y,F);
% if exist('part','var');
% figure(gcf+1); clf; set(gcf,'Name','Type III Residualized Plot');
% yres = crtlFor(y,part.tx2);%+mean(y);
% InterPlot2(yres,F);
% end
end
if strcmpi(type1,'Continuous') && strcmpi(type2,'MainEffect');
figure(gcf); clf; set(gcf,'Name','Raw Data Plot');
ScatterPlot2(mod.data.(effect),y,ones(size(y)),{part.name 'Y'});
% if exist('part','var');
% figure(gcf+1); clf; set(gcf,'Name','Type III Residualized Plot');
% yres = crtlFor(y,part.tx2);%+mean(y);
% xres = crtlFor(mod.data.(effect),part.tx2);%+mean(y);
% ScatterPlot2(xres,yres,ones(size(y)),{part.name 'Y'});
% end
end
if strcmpi(type1,'Continuous') && strcmpi(type2,'Interaction');
eff = effect;
i1 = find(iscat==1);
F = []; Levs = [];
for ii = 1:numel(i1);
F{ii} = makedummy(mod.data.(terms{i1(ii)}),0);
tmp = unique(mod.data.(terms{i1(ii)}),'stable');
if isobject(tmp); tmp = cellstr(tmp); end
Levs{ii} = tmp;
eff = regexprep(eff,[terms{i1(ii)} ':'],'');
end
if ~isempty(F)
F = FactorCross(F);
L = LabelCross(Levs);
G = cell(size(F,1),1);
for ii = 1:size(F,2);
G(find(F(:,ii)==1)) = L(ii);
end
else
G = ones(size(y));
end
i1 = find(iscat==0);
x = 1; xlab = [];
for ii = 1:numel(i1);
x = x.*demean(mod.data.(terms{i1(ii)}));
xlab = [xlab terms{i1(ii)} '*'];
end
xlab = xlab(1:end-1);
figure(gcf); clf; set(gcf,'Name','Raw Data Plot');
ScatterPlot2(x,y,G,{xlab 'Y'});
% if exist('part','var') && ~isempty(part);
% figure(gcf+1); clf; set(gcf,'Name','Type III Residualized Plot');
% yres = crtlFor(y,part.tx2);
% xres = crtlFor(x,part.tx2);
% ScatterPlot2(xres,yres,G,{xlab 'Y'});
% end
end
%%% Always plot the predicted data, this will always work and will always
%%% be accurate
% if strcmpi(type1,'Continuous') && strcmpi(type2,'Prediction');
% if ~isempty(contains('aschultz',{UserTime})); keyboard; end
tx1 = part.tx1;
tx2 = part.tx2;
if isempty(tx2);
tx2 = eye(size(tx1,1));
end
warning off
nm = tx1-(tx2*(tx2\tx1));
nm(nm>-1e-12 & nm<1e-12)=0;
warning on
yy = crtlFor(y,tx2);
xx = nm*(pinv(nm)*yy);
i1 = find(xx~=0);
%i1 = 1:size(xx,1);
if std(xx)~=0
figure; clf; set(gcf,'Name','Predicted vs. Observed');
ScatterPlot2(xx(i1),yy(i1),ones(numel(i1),1),{part.name 'Y'});
xlabel('Predicted');
ylabel('Observed');
end
% end
if flag %% Try plotting the post-hoc contrast
if numel(regexp(effect,'&','split'))>1
warning('Not sure how to display a raw data plot for this contrast');
return
end
[con ind tr] = ParseEffect(effect,mod.X,mod.data);
if all(all(con~=0))
groups = regexp(effect,'#','split');
xx = []; yy = []; gg = [];
g = cell(numel(ind),1);
for ii = 1:size(con,2);
yy = [yy; y(ind)];
xx = [xx; con(ind,ii)];
g(:) = groups(ii);
gg = [gg; g];
end
figure(gcf+1); clf; set(gcf,'Name','Post-Hoc Raw Data');
ScatterPlot2(xx,yy,gg,{'' ''});
return
else
groups = regexp(effect,'#','split');
if numel(groups)<size(con,2);
groups = cellstr(unique(ds.(effect)));
end
yy = y(ind);
tc = (con(ind,:)~=0)*(1:size(con,2))';
gg = cell(numel(tc),1);
for ii = unique(tc)'
gg(tc==ii)=groups(ii);
end
end
figure(gcf+1); clf; set(gcf,'Name','Post-Hoc Raw Data');
if all(all(con==0 | con==1))
ScatterGroups(yy,tc,groups);
else
ScatterPlot2(sum(con(ind,:),2),yy,gg,{'' ''});
end
end
end
function [con, indices, track1] = ParseEffect(contrast,X,data)
cond4 = [];
extra = [];
indices = [];
flag = [];
step1 = regexprep(contrast,' ', '');
step2 = regexp(step1,'&','split');
for mm = 1:numel(step2);
step3 = regexp(step2{mm},'#','split');
cond3 = [];
track1 = {}; track2 = {};
for jj = 1:numel(step3)
cond2 = []; XD = [];
step5 = regexp(step3{jj},'\|','split');
cond = [];
for kk = 1:numel(step5)
step6 = regexp(step5{kk},'\$','split');
track1(end+1,1:2) = step6;
track2{end+1,1} = step5{kk};
var = data.(step6{1});
if isnumeric(var)
cond = [cond demean(var)];
flag(kk) = 0;
XD{end+1}=1:numel(var);
else
flag(kk) = 1;
if iscell(var)
tmp = zeros(numel(var),1);
i1 = strmatch(var,step6{2});
tmp(i1)=1;
else
if numel(step6)==1
tmp = makedummy(data.(step6{1}));
XD{end+1}=1:size(tmp,1);
else
tmp = data.(step6{1})==step6{2};
XD{end+1} = find(data.(step6{1})==step6{2});
end
end
cond = [cond tmp];
end
end
if any(flag)
if numel(step5)==1
cond2 = [cond2 cond];
else
cond2 = [cond2 prod(cond,2)];
end
else
cond2 = [cond2 cond];
end
indices{end+1} = intersections(XD);
if all(flag)
if numel(step5)==1
cond3 = [cond3 cond2];
else
cond3 = [cond3 sum(cond2,2)>0];
end
else
cond3 = [cond3 cond2];
end
end
cond4 = [cond4 cond3];
if ~isempty(contains('#',step2(mm)))
extra = [extra mean(cond3,2)];
end
indices = unions(indices);
end
con = cond4;
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
FIVE.m
|
.m
|
MRtools_Hoffman2-master/Visualization/FIVE.m
| 173,424 |
utf_8
|
8e55f8351b753a9d7d75312cc66a9de9
|
function [Obj VOI peak] = FIVE(inputImage,linkHands)
%%% This is an image viewing and plotting utility. Just launch it with
%%% "FIVE" at the command line. There are a great many features in
%%% this viewer, and you can learn all about them at:
%%% http://nmr.mgh.harvard.edu/harvardagingbrain/People/AaronSchultz/Aarons_Scripts.html
%%%
%%% For launching FIVE you can do one of the following:
%%% FIVE; %% Launch FIVE and then load images
%%% FIVE({'OverLay1.nii' 'Overlay2.img'}); %% This will launch FIVE with the specified overlays.
%%% FIVE({{'Underlay.nii'}}); %% this will launch FIVE with the specified underlay image
%%% FIVE({{'Underlay.nii'} {'OverLay1.nii' 'Overlay2.img'}}); %% This will launch FIVE with the specified underlay and load up the specified overlays.
%%%
%%% Ignore the linkHands input. This is for specialized call back functions.
%%%
%%% Some FIVE features require additinal packages, for instance get
%%% peaks requires Donald McLaren's peak_nii package, and the VOI plotting
%%% options will require that the analysis be done with GLM_Flex.
%%%
%%% Written by Aaron P. Schultz - [email protected]
%%%
%%% Copyright (C) 2011, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01-AG027435
%%%
%%% 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
%%% 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.
%%%
%%% system(['sh run_FIVE.sh /usr/pubsw/common/matlab/8.0/']);
% Update the colormaps, and colormapping system.
depth = 256;
[trash, cmaps] = colmap('jet',depth);
hand = [];
links = [];
origDat = [];
contrasts = [];
DM = [];
plotGo = 0;
Flist = [];
mniLims = [];
Des = [];
DataHeaders = [];
Outliers = [];
lastItem = [];
tabHand = [];
% global Obj;
Obj = [];
VOI = [];
peak = [];
modelType = [];
CachedClusterLoc = [];
ConExp = 0;
ConLayer = [];
ConHeader = [];
ssConExp = 0;
ssConLayer = [];
ssConHeader = [];
ssData = [];
clickFlag = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initialize the underlay
MH = spm_vol([fileparts(which('spm')) '/canonical/single_subj_T1.nii']); %% template underlay all image data is mapped to this orientation
if nargin > 0
try
if iscell(inputImage{1});
[a b c] = fileparts(inputImage{1}{1});
if strcmpi('.mgz',c)
m = MRIread(inputImage{1}{1});
m.descrip = [];
MRIwrite(m,[a b '.nii'],'float');
inputImage{1}{1} = [a b '.nii'];
%hh.fname = [m.fspec(1:end-3) 'nii'];
%hh.dim = m.volsize;
%hh.mat = m.vox2ras1;
%hh.pinfo = [1;0;352];
%hh.dt = [16 0];
%hh.n = [1 1];
%hh.descrip = ['MGZ Volume'];
%hh.private = [];
end
h = spm_vol(inputImage{1}{1});
[I mmm] = SliceAndDice3(h,MH,[],[],[3 NaN],[]);
h.dim = size(I);
h.mat = mmm;
else
[I h] = openIMG(which('defaultUnderlay.nii'));
end
catch
[I h] = openIMG(which('defaultUnderlay.nii'));
end
else
[I h] = openIMG(which('defaultUnderlay.nii'));
end
Obj = initializeUnderlay(I,h);
movego = 0;
loc = [0 0 0];
mc = round([loc 1] * inv(Obj(1).h.mat)');
Obj(1).point = round([loc 1] * inv(Obj(1).h.mat)');
Obj(1).lastpoint = [round(size(Obj(1).I)/2) 1]-1;
Obj(1).Range = [min(Obj(1).I(:)) max(Obj(1).I(:)) max(Obj(1).I(:))-min(Obj(1).I(:))];
Obj(1).FOV = sort([ [1 1 1 1]*Obj(1).h.mat'; [Obj(1).axLims 1]*Obj(1).h.mat']);
Obj(1).col = 1;
if any((size(Obj(1).I) - Obj(1).point(1:3))<0);
Obj(1).point = [round(size(Obj(1).I)/2) 1];
tmp = Obj(1).point*Obj(1).h.mat';
loc = tmp(1:3);
end
% if ~isempty(contains('aschultz',{UserTime})); keyboard; end
setupFrames(1,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create the figure window
height = []; width = []; rat = [];
ax1 = []; ax2 = []; ax3 = []; ax4 = [];
con = []; menu = []; hcmenu = []; item = [];
setupFigure;
Obj(1).con = con;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Setup the figure menus
paramenu1 = []; paramenu2 = []; paramenu3 = []; paramenu4 = []; S = [];
setupParamMenu;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read in a label atlas
RNH = spm_vol([which('aal_MNI_V4.img')]);
[RNI Rxyz] = spm_read_vols(RNH);
RNames = load('aal_MNI_V4_List.mat');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Draw Underlay
ch = [];
drawFresh(ax1,1);
drawFresh(ax2,2);
drawFresh(ax3,3);
Obj(1).hand = hand;
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot CrossHairs
[ch(1,1), ch(1,2)] = crossHairs(ax1,[0 0]);
[ch(2,1), ch(2,2)] = crossHairs(ax2,[0 0]);
[ch(3,1), ch(3,2)] = crossHairs(ax3,[0 0]);
Obj(1).ch = ch;
set(ch, 'uicontextmenu',hcmenu);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Link CrossHair Positions
hListener1 = addlistener(ch(1,1),'XData','PostSet',@AutoUpdate);
hListener2 = addlistener(ch(2,1),'XData','PostSet',@AutoUpdate);
hListener3 = addlistener(ch(1,2),'YData','PostSet',@AutoUpdate);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Synchronize Views if requested
if nargin>1 && ~isempty(linkHands)
links{end+1}=linkprop([ch(1,1),linkHands(1,1)],'XData');
links{end+1}=linkprop([ch(1,2),linkHands(1,2)],'YData');
links{end+1}=linkprop([ch(2,1),linkHands(2,1)],'XData');
links{end+1}=linkprop([ch(2,2),linkHands(2,2)],'YData');
links{end+1}=linkprop([ch(3,1),linkHands(3,1)],'XData');
links{end+1}=linkprop([ch(3,2),linkHands(3,2)],'YData');
set(gcf,'UserData',links);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Open Prespecified Overlays
Count = 2;
if nargin > 0;
% if isa(inputImage,'uint8')
% [stuff ras] = ReadFileFromBlob(bin);
% else
try
if iscell(inputImage{1})
if length(inputImage)>1
openOverlay(inputImage{2});
end
else
openOverlay(inputImage);
end
catch
openOverlay(inputImage);
end
% end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yy = Obj(1).clim(1):(Obj(1).clim(2)-Obj(1).clim(1))/255:Obj(1).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(1).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Make Figure Visible
set(findobj(gcf,'Fontsize', 10),'fontsize',12); shg
set(findobj(gcf,'Fontsize', 12),'fontsize',13); shg
set(pane,'Visible','on');
%%
function AutoUpdate(varargin)
vn = get(con(21,1),'Value');
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
xyz = [x(1) y(1) z(1)];
xyz((mniLims(1,:)-xyz)>0) = mniLims(1,(mniLims(1,:)-xyz)>0);
xyz((mniLims(2,:)-xyz)<0) = mniLims(2,(mniLims(2,:)-xyz)<0);
x = xyz(1); y = xyz(2); z = xyz(3);
for ii = 1:length(Obj)
Obj(ii).point = ceil([x y z 1] * inv(Obj(ii).h.mat)');
Obj(ii).point(Obj(ii).point(1:3)<1) = 1;
ind = find((Obj(ii).axLims-Obj(ii).point(1:3))<0);
Obj(ii).point(ind) = Obj(ii).axLims(ind);
if ii == 1;
p = ceil([x y z 1] * inv(RNH.mat)');
try
nm = RNames.ROI(RNI(p(1),p(2),p(3)));
set(paramenu1(2),'Label',nm.Nom_L);
catch
set(paramenu1(2),'Label','undefined');
end
end
end
setupFrames(1:length(Obj),0);
updateGraphics([1 2 3],0);
set(con(15,1),'String',num2str(round([x y z])));
mc = round([x y z 1] * inv(Obj(get(con(21,1),'Value')).h.mat)');
vn = get(con(21,1),'Value');
try
set(con(22,1),'String',num2str(Obj(get(con(21,1),'Value')).I(mc(1),mc(2),mc(3))));
catch
set(con(22,1),'String','NaN');
end
shg
end
function goTo(varargin)
if varargin{1}==con(15,1);
cl = str2num(get(con(15,1),'String'));
set(ch(1,1), 'XData', [cl(2) cl(2)]);
set(ch(1,2), 'YData', [cl(3) cl(3)]);
set(ch(2,1), 'XData', [cl(1) cl(1)]);
set(ch(2,2), 'YData', [cl(3) cl(3)]);
set(ch(3,1), 'XData', [cl(1) cl(1)]);
set(ch(3,2), 'YData', [cl(2) cl(2)]);
end
end
function buttonUp(varargin)
movego = 0;
end
function buttonDown(varargin)
%get(gcf,'SelectionType')
if strcmpi(get(gcf,'SelectionType'),'normal') || clickFlag==1;
movego = 1;
co1 = gco;
co2 = gca;
switch co2
case ax1
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
y = cp(1);
z = cp(2);
set(ch(1,1), 'XData', [y y]);
set(ch(1,2), 'YData', [z z]);
set(ch(2,2), 'YData', [z z]);
set(ch(3,2), 'YData', [y y]);
case ax2
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
x = cp(1);
z = cp(2);
set(ch(2,1), 'XData', [x x]);
set(ch(2,2), 'YData', [z z]);
set(ch(1,2), 'YData', [z z]);
set(ch(3,1), 'XData', [x x]);
case ax3
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
y = cp(1);
x = cp(2);
set(ch(3,1), 'XData', [y y]);
set(ch(3,2), 'YData', [x x]);
set(ch(1,1), 'XData', [x x]);
set(ch(2,1), 'XData', [y y]);
otherwise
end
end
if strcmpi(get(gcf,'SelectionType'),'extend');
plotVOI(lastItem);
end
if strcmpi(get(gcf,'SelectionType'),'alt');
if ConExp ~=0
updateConnMap;
elseif ssConExp ~= 0;
ssUpdateConnMap;
end
end
end
function buttonMotion(varargin)
if movego == 1;
co1 = gco;
co2 = gca;
switch co2
case ax1
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
y = cp(1);
z = cp(2);
if Obj(1).FOV(1,2)>y; y=Obj(1).FOV(1,2); end;
if Obj(1).FOV(2,2)<y; y=Obj(1).FOV(2,2); end;
if Obj(1).FOV(1,3)>z; z=Obj(1).FOV(1,3); end;
if Obj(1).FOV(2,3)<z; z=Obj(1).FOV(2,3); end;
set(ch(1,1), 'XData', [y y]);
set(ch(1,2), 'YData', [z z]);
set(ch(2,2), 'YData', [z z]);
set(ch(3,2), 'YData', [y y]);
case ax2
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
x = cp(1);
z = cp(2);
if Obj(1).FOV(1,1)>x; x=Obj(1).FOV(1,1); end;
if Obj(1).FOV(2,1)<x; x=Obj(1).FOV(2,1); end;
if Obj(1).FOV(1,3)>z; z=Obj(1).FOV(1,3); end;
if Obj(1).FOV(2,3)<z; z=Obj(1).FOV(2,3); end;
set(ch(2,1), 'XData', [x x]);
set(ch(2,2), 'YData', [z z]);
set(ch(1,2), 'YData', [z z]);
set(ch(3,1), 'XData', [x x]);
case ax3
cp = get(co2, 'CurrentPoint');
cp = round(cp(1,1:2));
y = cp(1);
x = cp(2);
if Obj(1).FOV(1,1)>x; x=Obj(1).FOV(1,1); end;
if Obj(1).FOV(2,1)<x; x=Obj(1).FOV(2,1); end;
if Obj(1).FOV(1,2)>y; y=Obj(1).FOV(1,2); end;
if Obj(1).FOV(2,2)<y; y=Obj(1).FOV(2,2); end;
set(ch(3,1), 'XData', [y y]);
set(ch(3,2), 'YData', [x x]);
set(ch(1,1), 'XData', [x x]);
set(ch(2,1), 'XData', [y y]);
otherwise
end
end
end
function openOverlay(varargin)
if nargin == 0
nnn = spm_select(inf,'image');
else
if iscell(varargin{1})
if ~isa(varargin{1}{1},'uint8')
nnn = char(varargin{1});
else
nnn = {};
for ii = 1:numel(varargin{1})
[mm hh] = ReadFileFromBlob(varargin{1}{ii});
hh.n = [ii 1];
spm_write_vol(hh,mm);
nnn{ii,1} = [hh.fname ',' num2str(ii)];
end
nnn = char(nnn);
end
elseif ischar(varargin{1})
nnn = varargin{1};
elseif isa(varargin{1},'uint8')
[mm hh] = ReadFileFromBlob(varargin{1});
spm_write_vol(hh,mm);
nnn = hh.fname;
else
nnn = spm_select(inf,'image');
end
for kk = 1:size(nnn,1)
% if isa(nnn,'uint8')
% fid = fopen([pwd '/tmp.nii']);
% fwrite(fid,nnn,'uint8');
% fclose(fid);
% n = [pwd '/tmp.nii'];
% % elseif isa(nnn{kk},'uint8')
% % fid = fopen(['/tmp' '/tmp.nii'],'w');
% % fwrite(fid,nnn{kk},'uint8');
% % fclose(fid);
% % n = ['/tmp' '/tmp.nii'];
% else
% n = strtrim(nnn(kk,:));
% end
n = strtrim(nnn(kk,:));
ind = find(n==filesep);
if isempty(ind);
nn = n;
n2 = n;
else
nn = n(ind(end)+1:end);
if numel(ind)>1
n2 = n(ind(end-1)+1:end);
else
n2 = n;
end
end
if mean(n==filesep)==0
n = [pwd filesep n];
end
hh = spm_vol(n);
set(con(21,1),'TooltipString',n)
a = world_bb(MH); b = world_bb(hh); tmp = a-b; tmp(1,:) = tmp(1,:)*-1;
if hh.dt(1)>=16
intOrd = 3;
else
intOrd = 0;
end
if all(tmp(:)>=0)
[m mmm] = SliceAndDice3(hh, MH, [], hh,[intOrd NaN],[]);
else
[m mmm] = SliceAndDice3(hh, MH, [], Obj(1).h,[intOrd NaN],[]);
end
%[m mmm] = SliceAndDice3(hh,MH,[],Obj(1).h,[0 NaN],[]);
hh.dim = size(m);
hh.mat = mmm;
Obj(Count).Name = n2;
Obj(Count).FullPath = n;
Obj(Count).DispName = n2;
set(gcf,'Name', ['FIVE: ' Obj(Count).DispName]);
Obj(Count).h = hh;
Obj(Count).I = double(m);
set(con(21,1),'String', [get(con(21,1),'String'); n2],'Value',Count);
if ~isempty(contains('{T_', {hh.descrip}));
tmp = hh.descrip;
i1 = find(tmp=='[');
i2 = find(tmp==']');
Obj(Count).DF = str2num(tmp(i1+1:i2-1));
th = spm_invTcdf(1-.001,Obj(Count).DF);
Obj(Count).Thresh = [th ceil(max(m(:))*1000)/1000];
Obj(Count).clim = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(Count).PVal = .001;
Obj(Count).col = 2;
Obj(Count).Trans = 1;
set(con(4),'String',[num2str(th) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(5),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(8),'String',num2str(Obj(Count).DF));
set(con(9),'String','++0.001');
elseif ~isempty(contains('{F_', {hh.descrip}))
tmp = hh.descrip;
i1 = find(tmp=='[');
i2 = find(tmp==']');
t1 = regexp(tmp(i1(1)+1:i2(1)-1),',','split');
df(1) = str2num(t1{1});
df(2) = str2num(t1{2});
Obj(Count).DF = df;
th = spm_invFcdf(1-.001,df(1), df(2));
Obj(Count).Thresh = [th ceil(max(m(:))*1000)/1000];
Obj(Count).clim = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(Count).PVal = .001;
Obj(Count).col = 2;
Obj(Count).Trans = 1;
set(con(4),'String',[num2str(th) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(5),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(8),'String',num2str(Obj(Count).DF));
set(con(9),'String','++0.001');
else
set(con(4),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(5),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(8),'String','NaN');
set(con(9),'String','NaN');
Obj(Count).DF = NaN;
Obj(Count).PVal = NaN;
Obj(Count).Thresh = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(Count).clim = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(Count).col = 2;
Obj(Count).Trans = 1;
end
set(con(23),'String','0');
Obj(Count).ClusterThresh = 0;
Obj(Count).Exclude = [];
Obj(Count).MaskInd = [];
Obj(Count).mask = ones(size(Obj(Count).I),'uint8');
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
loc = [x(1) y(1) z(1)];
Obj(Count).point = round([loc 1] * inv(Obj(Count).h.mat)');
Obj(Count).lastpoint = (round([loc 1] * inv(Obj(Count).h.mat)'))-1;
Obj(Count).axLims = size(Obj(Count).I);
setupFrames(Count,0);
Obj(Count).pos = axLim(Obj(Count).I,Obj(Count).h);
set(con(1,1),'Value',3);
drawFresh(ax1,1,Count);
drawFresh(ax2,2,Count);
drawFresh(ax3,3,Count);
uistack(ch(1,1),'top'); uistack(ch(1,2),'top');
uistack(ch(2,1),'top'); uistack(ch(2,2),'top');
uistack(ch(3,1),'top'); uistack(ch(3,2),'top');
Obj(Count).Range = [min(Obj(Count).I(:)) max(Obj(Count).I(:)) max(Obj(Count).I(:))-min(Obj(Count).I(:))];
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
yy = Obj(Count).clim(1):(Obj(Count).clim(2)-Obj(Count).clim(1))/255:Obj(Count).clim(2);
axes(ax4); cla
try
imagesc(yy,1,reshape(colmap(cmaps{Obj(Count).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
end
Count = Count+1;
end
end
end
function UpdateThreshold(varargin)
% Get the Volume Number.
vn = get(con(21,1),'Value');
% Get the ThresholdParamters
a = get(con(4),'String');
c = get(con(8),'String');
% d = get(con(9),'String');
% Parse the Threshold Parameters
if isempty(a);
a = [-inf inf];
else
if contains(',',{a})
ind = find(a==',');
a = [str2num(strtrim(a(1:ind-1))) str2num(strtrim(a(ind+1:end)))];
else
a = str2num(a);
end
end
if numel(a) == 2
% Correct the Threshold Parameter End Points
if a(1)==-inf
a(1) = floor(min(Obj(vn).I(:))*1000)/1000;
set(con(4),'string',[num2str(a(1)) ', ' num2str(a(2))])
end
if a(2)==inf
a(2) = ceil(max(Obj(vn).I(:))*1000)/1000;
set(con(4),'string',[num2str(a(1)) ', ' num2str(a(2))])
end
if a(1)>0 && a(2)>0
if numel(varargin)~=0 && varargin{1} ~= con(9,1)
if ~strcmpi(get(con(8,1),'String'),'NA')
df = str2num(get(con(8,1),'String'));
if isnan(df)
p = NaN;
else
if numel(df) == 1;
if isinf(df)
p = 1-spm_Ncdf(a(1),0,1);
else
p = 1-spm_Tcdf(a(1),df);
end
set(con(9,1),'String',['++' num2str(p)]);
end
if numel(df) == 2;
p = 1-spm_Fcdf(a(1),df(1),df(2));
set(con(9,1),'String',['++' num2str(p)]);
end
end
end
end
end
if a(1)<0 && a(2)<0
if numel(varargin)~=0 && varargin{1} ~= con(9,1)
if ~strcmpi(get(con(8,1),'String'),'NA')
df = str2num(get(con(8,1),'String'));
if isnan(df)
p = NaN;
else
if numel(df) == 1;
if isinf(df)
p = 1-spm_Ncdf(abs(a(2)),0,1);
else
p = 1-spm_Tcdf(abs(a(2)),df);
end
set(con(9,1),'String',['--' num2str(p)]);
end
if numel(df) == 2;
p = 1-spm_Fcdf(abs(a(2)),df(1),df(2));
set(con(9,1),'String',['--' num2str(p)]);
end
end
end
end
end
Obj(vn).Thresh = a;
elseif numel(a) == 4;
if a(1)==-inf
a(1) = floor(min(Obj(vn).I(:))*1000)/1000;
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
end
if a(4)==inf
a(4) = ceil(max(Obj(vn).I(:))*1000)/1000;
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
end
if numel(Obj(vn).Thresh)==numel(a);
check = Obj(vn).Thresh-a;
check = find(check~=0);
check = setdiff(check,[1 4]);
if numel(check)==1;
other = setdiff(2:3,check);
a(other) = -a(check);
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
end
if numel(varargin)>0 && varargin{1} ~= con(9,1)
if ~(strcmpi(get(con(8,1),'String'),'NA') || ~isempty(contains('nan', {lower(get(con(8,1),'String'))})))
df = str2num(get(con(8,1),'String'));
if numel(df) == 1;
if isinf(df)
p = (1-spm_Ncdf(abs(a(3)),0,1))*2;
else
p = (1-spm_Tcdf(abs(a(3)),df))*2;
end
set(con(9,1),'String',['+-' num2str(p)]);
end
if numel(df) == 2;
p = 1-spm_Fcdf(abs(a(3)),df(1),df(2));
set(con(9,1),'String',['+-' num2str(p)]);
end
end
end
else
if abs(a(2))~=abs(a(3))
ind1 = find(abs(a(2:3))==min(abs(a(2:3))));
ind2 = find(abs(a(2:3))==max(abs(a(2:3))));
a(ind1+1) = -a(ind2+1);
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
tmp = get(con(8,1),'String');
end
if numel(varargin)>0 && varargin{1} ~= con(9,1)
if ~strcmpi(get(con(8,1),'String'),'nan')
df = str2num(get(con(8,1),'String'));
if numel(df) == 1;
if isinf(df)
p = 1-spm_Ncdf(abs(a(2))/2,0,1);
else
p = 1-spm_Tcdf(abs(a(2))/2,df);
end
set(con(9,1),'String',['+-' num2str(p)]);
end
if numel(df) == 2;
p = 1-spm_Fcdf(abs(a(2)),df(1),df(2));
set(con(9,1),'String',['+-' num2str(p)]);
end
end
end
end
Obj(vn).Thresh = a;
end
loc = str2num(get(con(15),'String'));
Obj(vn).point = round([loc 1] * inv(Obj(vn).h.mat)');
if str2num(get(con(23),'String'))~=0
ExtentThresh;
end
setupFrames(vn,1);
updateGraphics({1:3 vn},1);
%Obj(vn).pos = axLim(Obj(vn).I,Obj(vn).h);
end
function UpdatePVal(varargin)
nv = get(con(21,1),'Value');
df = get(con(8,1),'String');
try
df = str2num(df);
if any(isnan(df));
return;
end
catch
set(con(8,1),'String','NA')
return
end
p = get(con(9,1),'String');
if mean(p(1:2)=='++')==1
direc = 1;
p = str2num(p(3:end));
elseif mean(p(1:2)=='--')==1
direc = -1;
p = str2num(p(3:end));
elseif mean(p(1:2)=='-+')==1 || mean(p(1:2)=='+-')==1
direc = 0;
p = str2num(p(3:end))/2;
else
p = str2num(p);
direc = 1;
end
Obj(nv).PVal = p;
Obj(nv).DF = df;
if numel(df)==1
if isinf(df)
T = spm_invNcdf(1-abs(p),0,1);
else
T = spm_invTcdf(1-abs(p),df);
end
elseif numel(df)==2
T = spm_invFcdf(1-abs(p),df(1),df(2));
end
curr = get(con(4),'String');
cur = regexp(curr,',','split');
if direc == 1
a = ceil(T*1000)/1000;
set(con(4),'String',[num2str(a) ', inf']);
%set(con(4),'String',[num2str(a) ',' cur{2}]);
UpdateThreshold;
elseif direc == -1
a = floor(-T*1000)/1000;
set(con(4),'String',['-inf ,' num2str(a)]);
%set(con(4),'String',[cur{1} ',' num2str(a)]);
UpdateThreshold;
elseif direc == 0
a = [];
%keyboard;
a(1) = floor(min(Obj(nv).I(:))*1000)/1000;
a(4) = ceil(max(Obj(nv).I(:))*1000)/1000;
a(2:3) = [floor(-T*1000)/1000 ceil(T*1000)/1000];
set(con(4),'String',[num2str(a(1)) ' ' num2str(a(2)) ', ' num2str(a(3)) ' ' num2str(a(4))]);
b = a([1 4]);
ind1 = find(abs(b)==min(abs(b)));
ind2 = find(abs(b)==max(abs(b)));
b(ind2) = -b(ind1);
UpdateThreshold;
end
end
function changeColorMap(varargin)
vn = get(con(21,1),'Value');
map = get(con(1,1),'Value');
if map == 1;
set(con(1,1),'Value',Obj(vn).col+1);
return;
end
Obj(vn).col = map-1;
setupFrames(vn,1);
updateGraphics({[1 2 3] vn},1);
%%% Update colorbar.
yy = Obj(vn).clim(1):(Obj(vn).clim(2)-Obj(vn).clim(1))/255:Obj(vn).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(vn).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
end
function adjustTrans(varargin)
vn = get(con(21,1),'Value');
if numel(hand{1})==1
return
end
const = get(varargin{1},'Value');
const = const+.0001;
if const>1; const = 1; end;
Obj(vn).Trans = const;
a = get(hand{1}(vn),'AlphaData');
a(a~=0)=const;
set(hand{1}(vn), 'AlphaData', a);
a = get(hand{2}(vn),'AlphaData');
a(a~=0)=const;
set(hand{2}(vn), 'AlphaData', a);
a = get(hand{3}(vn),'AlphaData');
a(a~=0)=const;
set(hand{3}(vn), 'AlphaData', a);
end
function resizeFig(varargin)
a = get(gcf,'Position');
hei = (height/width)*a(3);
wid = (width/height)*a(4);
if hei-a(4) > wid-a(3)
a(3) = wid;
elseif hei-a(4) < wid-a(3)
a(4) = hei;
end
set(gcf,'Position',a);
end
function switchObj(varargin)
if ~isempty(varargin)
if iscell(varargin{1})
nv = varargin{1}{1};
else
nv = get(con(21,1),'Value');
end
else
nv = get(con(21,1),'Value');
end
try
set(con(21,1),'TooltipString',Obj(nv).FullPath)
set(gcf,'Name', ['FIVE: ' Obj(nv).DispName]);
catch
end
set(con(2,1),'Value', Obj(nv).Trans);
set(con(23),'String', num2str(Obj(nv).ClusterThresh));
set(con(5,1),'String',[num2str(Obj(nv).clim(1)) ', ' num2str(Obj(nv).clim(2))]);
set(con(8,1), 'String',num2str(Obj(nv).DF));
if numel(Obj(nv).Thresh) == 4;
set(con(4,1),'String',[num2str(Obj(nv).Thresh(1)) ' ' num2str(Obj(nv).Thresh(2)) ', ' num2str(Obj(nv).Thresh(3)) ' ' num2str(Obj(nv).Thresh(4))]);
set(con(9,1), 'String',['+-' num2str(Obj(nv).PVal*2)]);
elseif sum(sign(Obj(nv).Thresh))>0
set(con(4,1),'String',[num2str(Obj(nv).Thresh(1)) ', ' num2str(Obj(nv).Thresh(2))]);
set(con(9,1), 'String',['++' num2str(Obj(nv).PVal)]);
elseif sum(sign(Obj(nv).Thresh))<0
set(con(4,1),'String',[num2str(Obj(nv).Thresh(1)) ', ' num2str(Obj(nv).Thresh(2))]);
set(con(9,1), 'String',['--' num2str(Obj(nv).PVal)]);
elseif sum(sign(Obj(nv).Thresh))==0
set(con(4,1),'String',[num2str(Obj(nv).Thresh(1)) ', ' num2str(Obj(nv).Thresh(2))]);
set(con(9,1), 'String',num2str(Obj(nv).PVal));
end
set(con(1,1),'Value', Obj(nv).col+1);
yy = Obj(nv).clim(1):(Obj(nv).clim(2)-Obj(nv).clim(1))/255:Obj(nv).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(nv).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
tmp1 = (Obj(nv).clim(2)-Obj(nv).Range(1))/Obj(nv).Range(3); if tmp1>1; tmp1=1; end; if tmp1<0; tmp1=0; end;
set(con(27),'Value', tmp1);
tmp1 = (Obj(nv).clim(1)-Obj(nv).Range(1))/Obj(nv).Range(3); if tmp1>1; tmp1=1; end; if tmp1<0; tmp1=0; end;
set(con(28),'Value', tmp1);
end
function removeVolume(varargin)
nv = get(con(21,1),'Value');
if nv == 1; return; end
ind = setdiff(1:length(Obj),nv);
tmp = get(con(21,1),'String');
set(con(21,1),'String',tmp(ind), 'Value',length(ind));
for ii = 1:length(hand)
delete(hand{ii}(nv));
end
Obj = Obj(ind);
hand{1} = hand{1}(ind);
hand{2} = hand{2}(ind);
hand{3} = hand{3}(ind);
Count = length(ind)+1;
switchObj;
end
function updateGraphics(HandInd,opt)
if iscell(HandInd);
HandInd2 = HandInd{2};
HandInd = HandInd{1};
else
HandInd2 = 1:length(Obj);
end
for ii = HandInd;
if Obj(1).point(ii)==Obj(1).lastpoint(ii) && opt~=1
continue
end
for jj = HandInd2
set(hand{ii}(jj),'CData',Obj(jj).frame{ii},'AlphaData',~isnan(Obj(jj).frame{ii}(:,:,1))*Obj(jj).Trans);
Obj(jj).lastpoint(ii) = Obj(jj).point(ii);
end
end
end
function drawFresh(axx,opt,opt2,opt3)
if nargin == 2;
opt2 = 1:length(Obj);
end
if nargin < 4
opt3 = 1;
end
axes(axx);
for ii = opt2;
if opt == 1;
tmp = image(Obj(ii).pos{2}, Obj(ii).pos{3}, Obj(ii).frame{opt});
if opt3; hand{opt}(ii) = tmp; end
set(tmp,'AlphaData', ~isnan(Obj(ii).frame{opt}(:,:,1))*Obj(ii).Trans);
set(axx, 'YDir','Normal'); set(gca, 'XDir','reverse'); axis equal;
end
if opt == 2;
tmp = image(Obj(ii).pos{1}, Obj(ii).pos{3}, Obj(ii).frame{opt});
if opt3; hand{opt}(ii) = tmp; end
set(tmp,'AlphaData', ~isnan(Obj(ii).frame{opt}(:,:,1))*Obj(ii).Trans);
set(axx, 'YDir','Normal'); set(gca, 'XDir','Normal');axis equal;
end
if opt == 3;
tmp = image(Obj(ii).pos{1}, Obj(ii).pos{2}, Obj(ii).frame{opt});
if opt3; hand{opt}(ii) = tmp; end
set(tmp,'AlphaData', ~isnan(Obj(ii).frame{opt}(:,:,1))*Obj(ii).Trans);
set(axx, 'YDir','Normal'); set(gca, 'XDir','Normal');axis equal;
end
end
set(axx,'XTick',[],'YTick',[]);
axis equal;
axis tight;
end
function out = axLim(dat,h)
t1 = [1 1 1 1; size(dat,1) 1 1 1]*h.mat';
out{1} = t1(1,1):(t1(2,1)-t1(1,1))/(size(dat,1)-1):t1(2,1);
t1 = [1 1 1 1; 1 size(dat,2) 1 1]*h.mat';
out{2} = t1(1,2):(t1(2,2)-t1(1,2))/(size(dat,2)-1):t1(2,2);
t1 = [1 1 1 1; 1 1 size(dat,3) 1]*h.mat';
out{3} = t1(1,3):(t1(2,3)-t1(1,3))/(size(dat,3)-1):t1(2,3);
out{1} = out{1}(end:-1:1);
end
function [h1 h2] = crossHairs(axx,loc)
axes(axx)
ax = axis;
h1 = plot([loc(1) loc(1)], ax(3:4),'b');
h2 = plot(ax(1:2),[loc(2) loc(2)],'b'); axis equal; axis tight;
end
function setupFrames(n,opt)
for ii = n;
ss = Obj(ii).axLims;
if Obj(ii).point(1)~=Obj(ii).lastpoint(1) || opt==1
tmp = Obj(ii).I(Obj(ii).point(1),:,:);
tmp(Obj(ii).mask(Obj(ii).point(1),:,:)==0)=NaN;
if numel(Obj(ii).Thresh)==2
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(2));
else
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(4) | (tmp>Obj(ii).Thresh(2) & tmp<Obj(ii).Thresh(3)));
end
tmp(ind) = NaN;
tmp(tmp==0)=NaN;
tmp = flipdim(rot90(squeeze(tmp),1),1);
[cols cm cc] = cmap(tmp, Obj(ii).clim, cmaps{Obj(ii).col});
Obj(ii).frame{1} = reshape(cols,[size(tmp) 3]);
end
if Obj(ii).point(2)~=Obj(ii).lastpoint(2) || opt==1
tmp = Obj(ii).I(:,Obj(ii).point(2),:);
tmp(Obj(ii).mask(:,Obj(ii).point(2),:)==0)=NaN;
if numel(Obj(ii).Thresh)==2
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(2));
else
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(4) | (tmp>Obj(ii).Thresh(2) & tmp<Obj(ii).Thresh(3)));
end
tmp(ind) = NaN;
tmp(tmp==0)=NaN;
tmp = flipdim(flipdim(rot90(squeeze(tmp),1),1),2);
[cols cm cc] = cmap(tmp, Obj(ii).clim, cmaps{Obj(ii).col});
Obj(ii).frame{2} = reshape(cols,[size(tmp) 3]);
end
if Obj(ii).point(3)~=Obj(ii).lastpoint(3) || opt==1
tmp = Obj(ii).I(:,:,Obj(ii).point(3));
tmp(Obj(ii).mask(:,:,Obj(ii).point(3))==0)=NaN;
if numel(Obj(ii).Thresh)==2
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(2));
else
ind = find(tmp<Obj(ii).Thresh(1) | tmp>Obj(ii).Thresh(4) | (tmp>Obj(ii).Thresh(2) & tmp<Obj(ii).Thresh(3)));
end
tmp(ind) = NaN;
tmp(tmp==0)=NaN;
tmp = flipdim(flipdim(rot90(squeeze(tmp),1),1),2);
[cols cm cc] = cmap(tmp, Obj(ii).clim, cmaps{Obj(ii).col});
Obj(ii).frame{3} = reshape(cols,[size(tmp) 3]);
end
end
end
function toggle(varargin)
state = get(varargin{1},'Checked');
if strcmpi(state,'on');
set(varargin{1},'Checked','off');
end
if strcmpi(state,'off');
set(varargin{1},'Checked','on');
end
end
function toggleCrossHairs(varargin)
state = get(varargin{1},'Checked');
if strcmpi(state,'on');
set(ch(:),'Visible','off')
set(varargin{1},'Checked','off');
end
if strcmpi(state,'off');
set(ch(:),'Visible','on')
set(varargin{1},'Checked','on');
end
end
function newFig(varargin)
tf = gcf;
vn = get(con(21,1),'Value');
if vn == 1
return;
end
NewObj = FIVE({Obj(vn).FullPath},ch);
tmp1 = get(pane,'Position');
tmp2 = tmp1;
tmp2(1) = tmp1(1)+tmp1(3);
set(gcf,'Position',tmp2);
% links{end+1}=linkprop([ch(1,1),NewObj(1).ch(1,1)],'XData');
% links{end+1}=linkprop([ch(1,2),NewObj(1).ch(1,2)],'YData');
% links{end+1}=linkprop([ch(2,1),NewObj(1).ch(2,1)],'XData');
% links{end+1}=linkprop([ch(2,2),NewObj(1).ch(2,2)],'YData');
% links{end+1}=linkprop([ch(3,1),NewObj(1).ch(3,1)],'XData');
% links{end+1}=linkprop([ch(3,2),NewObj(1).ch(3,2)],'YData');
%
% set(tf,'UserData',links);
set(menu(4),'Enable','on','Checked','on');
figure(tf);
removeVolume
end
function syncViews(varargin)
state = get(varargin{1},'Checked');
%%% Remove any existing links this figure has to other figures
for ii = 1:length(links);
set(links{ii},'Enabled','on');
removeprop(links{ii},'XData');
removeprop(links{ii},'YData');
end
links = [];
%%% Establish links between this figure and all other FIVE
%%% Figures
ind = findobj(0,'Type','Figure');
try
figs = ind(contains('FIVE',get(ind,'Name')));
catch
set(varargin{1},'Checked','off');
set(gcf,'WindowButtonMotionFcn',@buttonMotion);
return
end
figs = setdiff(figs,gcf);
for ii = 1:length(figs);
hhh = findobj(figs(ii),'Color','b','type','line');
if isempty(hhh)
hhh = findobj(figs(ii),'Color','y','type','line');
end
links{end+1}=linkprop([ch(1,1),hhh(6)],'XData');
links{end+1}=linkprop([ch(1,2),hhh(5)],'YData');
links{end+1}=linkprop([ch(2,1),hhh(4)],'XData');
links{end+1}=linkprop([ch(2,2),hhh(3)],'YData');
links{end+1}=linkprop([ch(3,1),hhh(2)],'XData');
links{end+1}=linkprop([ch(3,2),hhh(1)],'YData');
end
set(gcf,'UserData',links);
%%% Set the state of the links
if strcmpi(state,'on');
for ii = 1:length(links);
set(links{ii},'Enabled','off');
end
set(varargin{1},'Checked','off');
set(gcf,'WindowButtonMotionFcn',@buttonMotion);
end
if strcmpi(state,'off');
for ii = 1:length(links);
set(links{ii},'Enabled','on');
end
set(varargin{1},'Checked','on');
set(gcf,'WindowButtonMotionFcn',[]);
end
%%% Propogate changes to other Figure links if they exists.
for ii = 1:length(figs)
lnk = get(figs(ii),'UserData');
hh = findobj(figs(ii),'Label','Sync Views');
if strcmpi(state,'on');
for jj = 1:length(lnk);
set(lnk{jj},'Enabled','off');
end
set(hh,'Checked','off');
set(figs(ii),'WindowButtonMotionFcn',@buttonMotion);
end
if strcmpi(state,'off');
for jj = 1:length(lnk);
set(lnk{jj},'Enabled','on');
end
set(hh,'Checked','on');
set(figs(ii),'WindowButtonMotionFcn',[]);
end
end
end
function changeLayer(varargin)
vn = get(con(21,1),'Value');
if vn == 1
return
end
if varargin{1} == con(12,1)
for ii = 1:length(hand)
uistack(hand{ii}(vn),'top');
uistack(hand{ii}(vn),'down');
uistack(hand{ii}(vn),'down');
end
elseif varargin{1} == con(13,1)
for ii = 1:length(hand)
uistack(hand{ii}(vn),'bottom');
uistack(hand{ii}(vn),'up');
end
end
end
function axialView(varargin)
if numel(varargin{1})==1 || isempty(varargin)
out = popup('Which Slices (MNI coordinates)?');
else
out = varargin{1};
end
if isempty(out)
n = 25;
coords = min(Obj(2).pos{3}):6:max(Obj(2).pos{3});
c = 0;
while numel(coords)>n
c = c+1;
if mod(c,2)==1;
coords = coords(2:end);
else
coords = coords(1:end-1);
end
end
else
n = numel(out);
coords = out;
end
IN = [];
for jj = 1:numel(Obj);
IN.IM{jj} = Obj(jj).I.*double(Obj(jj).mask);
IN.H{jj} = Obj(jj).h;
IN.TH{jj} = Obj(jj).Thresh;
IN.LIMS{jj} = Obj(jj).clim;
IN.TRANS{jj} = Obj(jj).Trans;
IN.CM{jj} = cmaps{Obj(jj).col};
end
IN.Coords = coords;
IN.opt = 1;
SliceView(IN);
end
function coronalView(varargin)
if numel(varargin{1})==1 || isempty(varargin)
out = popup('Which Slices (MNI coordinates)?');
else
out = varargin{1};
end
if isempty(out)
n = 30;
coords = min(Obj(2).pos{2}):6:max(Obj(2).pos{2});
c = 0;
while numel(coords)>n
c = c+1;
if mod(c,2)==1;
coords = coords(2:end);
else
coords = coords(1:end-1);
end
end
else
n = numel(out);
coords = out;
end
IN = [];
for ii = 1:numel(Obj);
IN.IM{ii} = Obj(ii).I.*double(Obj(ii).mask);
IN.H{ii} = Obj(ii).h;
IN.TH{ii} = Obj(ii).Thresh;
IN.LIMS{ii} = Obj(ii).clim;
IN.TRANS{ii} = Obj(ii).Trans;
IN.CM{ii} = cmaps{Obj(ii).col};
end
IN.Coords = coords;
IN.opt = 3;
SliceView(IN);
end
function sagittalView(varargin)
if numel(varargin{1})==1 || isempty(varargin)
out = popup('Which Slices (MNI coordinates)?');
else
out = varargin{1};
end
if isempty(out)
n = 25;
coords = min(Obj(2).pos{1}):6:max(Obj(2).pos{1});
c = 0;
while numel(coords)>n
c = c+1;
if mod(c,2)==1;
coords = coords(2:end);
else
coords = coords(1:end-1);
end
end
else
n = numel(out);
coords = out;
end
IN = [];
for ii = 1:numel(Obj);
IN.IM{ii} = Obj(ii).I.*double(Obj(ii).mask);
IN.H{ii} = Obj(ii).h;
IN.TH{ii} = Obj(ii).Thresh;
IN.LIMS{ii} = Obj(ii).clim;
IN.TRANS{ii} = Obj(ii).Trans;
IN.CM{ii} = cmaps{Obj(ii).col};
end
IN.Coords = coords;
IN.opt = 2;
SliceView(IN);
end
function allSliceView(varargin)
axialView;
coronalView;
sagittalView;
end
function surfView(varargin)
if numel(Obj)==1
return
end
for jj = 2:numel(Obj)
vn = jj;
obj = [];
fs = get(findobj(paramenu3(12),'Checked','On'),'Label');
switch fs
case '642'
obj.fsaverage = 'fsaverage3';
case '2562'
obj.fsaverage = 'fsaverage4';
case '10242'
obj.fsaverage = 'fsaverage5';
case '40962'
obj.fsaverage = 'fsaverage6';
case '163842'
obj.fsaverage = 'fsaverage';
otherwise
end
obj.surface = lower(get(findobj(paramenu3(10),'Checked','On'),'Label'));
if strcmpi(get(paramenu3(19),'Checked'),'off')
obj.shading = lower(get(findobj(paramenu3(11),'Checked','On'),'Label'));
obj.shadingrange = [str2num(get(findobj(paramenu3(16),'Checked','On'),'Label')) str2num(get(findobj(paramenu3(17),'Checked','On'),'Label'))];
else
switch obj.surface
case 'white'
obj.shading = 'curv';
obj.shadingrange = [-2 2];
case 'pi'
obj.shading = 'mixed';
obj.shadingrange = [-2 2];
case 'inflated'
obj.shading = 'logcurv';
obj.shadingrange = [-.75 .75];
case 'pial'
obj.shading = 'curv';
obj.shadingrange = [-2 3];
otherwise
obj.shading = 'curv';
obj.shadingrange = [-2 3];
end
end
obj.input.m = Obj(vn).I.*double(Obj(vn).mask);
obj.input.he = Obj(vn).h;
if jj ==2
obj.figno = 0;
obj.newfig = 1;
else
obj.figno = gcf;
obj.newfig = 0;
end
obj.colorlims = Obj(vn).clim;
cm = get(con(1),'String');
cm = cm{Obj(vn).col+1};
obj.colomap = cm;
thresh = Obj(vn).Thresh;
if numel(thresh) == 2
[t,i] = min(abs(thresh));
sgn = sign(thresh(i));
t = t*sgn;
obj.overlaythresh = t;
if sgn==1
obj.direction = '+';
obj.reverse = 0;
else
obj.direction = '-';
obj.reverse = 0;
end
if sum(sign(thresh))==0
obj.direction='+';
end
else
obj.overlaythresh = Obj(vn).Thresh(2:3);
obj.reverse = 0;
obj.direction = '+';
end
obj.mappingfile = [];
nn = get(findobj(paramenu3(15),'Checked','On'),'Label');
if strcmpi(nn,'Yes')
obj.nearestneighbor=1;
else
obj.nearestneighbor=0;
end
%load(which('SperStandard_4p5prox_FS6_SM.mat'),'header')
%compH = Obj(vn).h.mat==header.mat;
%if mean(compH(:))==1
% obj.mappingfile = which('SperStandard_4p5prox_FS6_SM.mat');
%end
option = get(findobj(paramenu3(14),'Checked','On'),'Label');
switch option
case 'All'
obj.Nsurfs = 4;
case 'Both'
obj.Nsurfs = 2;
case 'Left 1'
obj.Nsurfs = -1;
case 'Left 2'
obj.Nsurfs = 1.9;
case 'Right 1'
obj.Nsurfs = 1;
case 'Right 2'
obj.Nsurfs = 2.1;
otherwise
end
[h1 hh1] = surfPlot(obj);
Obj(vn).SurfInfo.h1 = h1;
Obj(vn).SurfInfo.hh1 = hh1;
Obj(vn).SurfInfo.par = obj;
set(hh1,'FaceAlpha',Obj(vn).Trans);
end
end
function changeSign(varargin)
vn = get(con(21,1),'Value');
if vn == 1
return
end
Obj(vn).I = Obj(vn).I*-1;
t1 = num2str(sort(str2num(get(con(4),'String'))*-1));
for ii = 1:10; t1 = regexprep(t1,' ',' '); end
set(con(4),'String',t1);
t2 = num2str(sort(str2num(get(con(5),'String'))*-1));
for ii = 1:10; t2 = regexprep(t2,' ',' '); end
set(con(5),'String',t2)
Obj(vn).Range(1:2) = Obj(vn).Range([2 1])*-1;
UpdateThreshold;
%setupFrames(vn,1);
%updateGraphics({[1 2 3] vn},1);
end
function setupParamMenu
%%% Not Specified
% out: output prefix, default is to define using imagefile
% SPM: 0 or 1, see above for details
% mask: optional to mask your data
% df1: numerator degrees of freedom for T/F-test (if 0<thresh<1)
% df2: denominator degrees of freedom for F-test (if 0<thresh<1)
% thresh: T/F statistic or p-value to threshold the data or 0
paramenu1(1) = uimenu(pane,'Label','Parameters');
%paramenu2(1) = uimenu(paramenu1(1),'Label','Cluster Params');
paramenu3(1) = uimenu(paramenu1(1),'Label','Sign');
paramenu4(1) = uimenu(paramenu3(1),'Label','Pos','Checked','on','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(1),'Label','Neg','CallBack',@groupCheck);
paramenu3(2) = uimenu(paramenu1(1),'Label','Sphere Radius');
paramenu4(end+1) = uimenu(paramenu3(2),'Label','1mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','2mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','3mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','4mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','5mm','Checked','On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','6mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','7mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','8mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','9mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','10mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','11mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','12mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','13mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','14mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(2),'Label','15mm','CallBack',@groupCheck);
paramenu3(3) = uimenu(paramenu1(1), 'Label','Peak Number Limit');
paramenu4(end+1) = uimenu(paramenu3(3),'Label','100','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','200','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','500','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','750','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','1000','Checked','on','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','1500','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','2000','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(3),'Label','3000','CallBack',@groupCheck);
paramenu3(4) = uimenu(paramenu1(1),'Label','Peak Separation');
paramenu4(end+1) = uimenu(paramenu3(4),'Label','2mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','4mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','6mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','8mm','Checked', 'on','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','10mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','12mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','14mm','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(4),'Label','16mm','CallBack',@groupCheck);
paramenu3(5) = uimenu(paramenu1(1),'Label','Neighbor Def.');
paramenu4(end+1) = uimenu(paramenu3(5),'Label','6','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(5),'Label','18','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(5),'Label','26','Checked','on','CallBack',@groupCheck);
paramenu3(7) = uimenu(paramenu1(1),'Label','Labeling');
paramenu4(end+1) = uimenu(paramenu3(7),'Label','Use Nearest Label', 'Checked', 'On','CallBack',@groupCheck);
% paramenu3(8) = uimenu(paramenu1(1),'Label','Label Map');
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','aal_MNI_V4', 'Checked', 'On','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Nitschke_Lab','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','JHU_tracts','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','JHU_whitematter','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Talairach','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Thalamus','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','MNI','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','HarvardOxford_cortex','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Cerebellum-flirt','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Cerebellum-fnirt','CallBack',@changeLabelMap);
% paramenu4(end+1) = uimenu(paramenu3(8),'Label','Juelich','CallBack',@changeLabelMap);
paramenu3(8) = uimenu(paramenu1(1),'Label','Label Map');
paramenu4(end+1) = uimenu(paramenu3(8),'Label','aal_MNI_V4', 'Checked', 'On','CallBack',@changeLabelMap);
try
[labellist]=getLabelMap();
for ll=2:numel(labellist)
paramenu4(end+1) = uimenu(paramenu3(8),'Label',labellist{ll},'CallBack',@changeLabelMap);
end
catch
paramenu4(end+1) = uimenu(paramenu3(8),'Label','aal_MNI_V4', 'Checked', 'On','CallBack',@changeLabelMap);
warning('Download Peak Nii to enable the use of other atlases');
end
paramenu3(18) = uimenu(paramenu1(1),'Label','Corrected Alpha');
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.100', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.050', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.025', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.010', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(18),'Label','0.001', 'Checked', 'Off','CallBack',@groupCheck);
paramenu1(2) = uimenu(pane,'Label','Region Name');
%menu(?) = uimenu(menu(1),'Label','Increase FontSize','CallBack',@increaseFont);
%menu(?) = uimenu(menu(1),'Label','Decrease FontSize','CallBack',@decreaseFont);
paramenu3(9) = uimenu(paramenu1(1),'Label','Surface Options');
paramenu3(19) = uimenu(paramenu3(9),'Label','Use Surface Shading Defaults','Checked', 'On','CallBack',@groupCheck);
paramenu3(10) = uimenu(paramenu3(9),'Label','Surface');
paramenu4(end+1) = uimenu(paramenu3(10),'Label','Inflated', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(10),'Label','Pial', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(10),'Label','White', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(10),'Label','PI', 'Checked', 'On','CallBack',@groupCheck);
paramenu3(11) = uimenu(paramenu3(9),'Label','Shading');
paramenu4(end+1) = uimenu(paramenu3(11),'Label','Curv', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(11),'Label','Sulc', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(11),'Label','Thk', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(11),'Label','LogCurv', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(11),'Label','Mixed', 'Checked', 'On','CallBack',@groupCheck);
paramenu3(12) = uimenu(paramenu3(9),'Label','N-verts');
paramenu4(end+1) = uimenu(paramenu3(12),'Label','642', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(12),'Label','2562', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(12),'Label','10242', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(12),'Label','40962', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(12),'Label','163842', 'Checked', 'Off','CallBack',@groupCheck);
% paramenu3(13) = uimenu(paramenu3(9),'Label','Reverse Map');
% paramenu4(end+1) = uimenu(paramenu3(13),'Label','No', 'Checked', 'On','CallBack',@groupCheck);
% paramenu4(end+1) = uimenu(paramenu3(13),'Label','Yes', 'Checked', 'Off','CallBack',@groupCheck);
paramenu3(14) = uimenu(paramenu3(9),'Label','N-Surfs');
paramenu4(end+1) = uimenu(paramenu3(14),'Label','All', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Both', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Left 1', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Left 2', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Right 1', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(14),'Label','Right 2', 'Checked', 'Off','CallBack',@groupCheck);
paramenu3(15) = uimenu(paramenu3(9),'Label','Nearest Neighbor Only');
paramenu4(end+1) = uimenu(paramenu3(15),'Label','No', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(15),'Label','Yes', 'Checked', 'Off','CallBack',@groupCheck);
paramenu3(16) = uimenu(paramenu3(9),'Label','Underlay Min');
paramenu4(end+1) = uimenu(paramenu3(16),'Label',' 0.0', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-0.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-1.0', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-1.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-2.0', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-2.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(16),'Label','-3.0', 'Checked', 'Off','CallBack',@groupCheck);
paramenu3(17) = uimenu(paramenu3(9),'Label','Underlay Max');
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+0.0', 'Checked','Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+0.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+1.0', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+1.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+2.0', 'Checked', 'On','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+2.5', 'Checked', 'Off','CallBack',@groupCheck);
paramenu4(end+1) = uimenu(paramenu3(17),'Label','+3.0', 'Checked', 'Off','CallBack',@groupCheck);
end
function setupFigure
tss = Obj(1).axLims;
im = spm_imatrix(Obj(1).h.mat);
%tmp = [1 1 1];
tmp = abs(im(7:9));
tss = tss.*tmp;
height = tss(2)+tss(3);
width = tss(1)+tss(2);
rat = height/width;
ff = get(0,'ScreenSize');
if ff(4)>800
pro = 3.25;
else
pro = 2.5;
end
%[junk user] = UserTime; if strcmp(user,'aschultz'); keyboard; end
ss = get(0,'ScreenSize');
if (ss(3)/ss(4))>2
ss(3)=ss(3)/2;
end
op = floor([50 ss(4)-75-((ss(3)/pro)*rat) ss(3)/pro (ss(3)/pro)*rat]);
pane = figure('Visible','off');
set(gcf, 'Position', op,'toolbar','none', 'Name', 'FIVE','Visible','off');
set(gcf, 'WindowButtonUpFcn', @buttonUp);
set(gcf, 'WindowButtonDownFcn', @buttonDown);
set(gcf, 'WindowButtonMotionFcn', @buttonMotion);
set(gcf, 'ResizeFcn', @resizeFig);
hcmenu = uicontextmenu;
set(hcmenu,'CallBack','movego = 0;');
item = [];
wid(1) = tss(2)/width;
hei(1) = tss(3)/height;
wid(2) = tss(1)/width;
hei(2) = tss(3)/height;
wid(3) = tss(1)/width;
hei(3) = tss(2)/height;
ax1 = axes; set(ax1,'Color','k','Position',[wid(2) hei(3) wid(1) hei(1)],'XTick',[],'YTick',[],'YColor','k','XColor','k'); hold on; colormap(gray(256));
ax2 = axes; set(ax2,'Color','k','Position',[0 hei(3) wid(2) hei(2)],'XTick',[],'YTick',[],'YColor','k','XColor','k'); hold on; colormap(gray(256));
ax3 = axes; set(ax3,'Color','k','Position',[0 0 wid(3) hei(3)],'XTick',[],'YTick',[],'YColor','k','XColor','k'); hold on; colormap(gray(256));
ax4 = axes; set(ax4,'Color','w','Position',[wid(2) 0 .04 hei(3)*.99],'XTick',[],'YAxisLocation','right','YTick',[]); %,'YColor','k','XColor','k'
set(gcf,'WindowKeyPressFcn', @keyMove);
set(gcf,'WindowScrollWheelFcn',@scrollMove);
set(gcf,'WindowKeyReleaseFcn',@keyHandler);
%st = wid(2)+.01+.04+.03;
st = wid(2)+.125;
len1 = (1-st)-.01;
len2 = len1/2;
len3 = len1/3;
len4 = len1/4;
inc = (hei(3))/11;
inc2 = .75*inc;
% [wid(2)+.045 0 .025 hei(3)*.9]
% [wid(2)+.070 0 .025 hei(3)*.9]
% [wid(2)+.095 0 .025 hei(3)*.9]
val = (Obj(1).Range(2)-Obj(1).Range(1))/Obj(1).Range(3);
con(27,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.070 0 .025 hei(3)*.9],'Value',val,'CallBack', @adjustUnderlay);
val = (Obj(1).Range(1)-Obj(1).Range(1))/Obj(1).Range(3);
con(28,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.095 0 .025 hei(3)*.9],'Value',val,'CallBack', @adjustUnderlay);
%con(29,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.095 0 .025 hei(3)*.9],'Value',0,'CallBack', @adjustUnderlay);
con(30,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[wid(2)+.070 hei(3)*.9 .05 .05]); % wid(2)+.0450 hei(3)*.9 .075 .05]
% con(28,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[st-.1 (.01+(1*inc)+(0*inc2)) len1*.75 inc],'Value',1,'CallBack', @adjustTrans);
con(1,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(0*inc)+(0*inc2) len1 inc],'String',[{'Colormap'} cmaps(:)'],'CallBack', @changeColorMap); shg
%con(1,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(0*inc)+(0*inc2) len1 inc],'String',[{'Colormap' 'A' 'B' 'C' 'D'}],'CallBack', @changeColorMap); shg
con(2,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[st (.01+(1*inc)+(0*inc2)) len1*.75 inc],'Value',1,'CallBack', @adjustTrans);
con(23,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len1*.75 (.01+(1*inc)+(0*inc2)) len1*.25 inc],'String','All','CallBack', @applyToAll);
con(3,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(2*inc)+(0*inc2) len1 inc2],'String', 'Transparency','fontsize',12);
con(4,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(2*inc)+(1*inc2) len2 inc],'CallBack',@UpdateThreshold);
con(5,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len2 .01+(2*inc)+(1*inc2) len2 inc],'CallBack',@UpdateCLims);
con(6,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(3*inc)+(1*inc2) len2 inc2],'String', 'Thresh','fontsize',12);
con(7,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len2 .01+(3*inc)+(1*inc2) len2 inc2],'String', 'Color Limits','fontsize',12);
con(8,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@UpdatePVal);
con(9,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len3 .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@UpdatePVal);
con(23,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len3+len3 .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@ExtentThresh);
con(10,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(4*inc)+(2*inc2) len3 inc2],'String', 'DF','fontsize',12);
con(11,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len3 .01+(4*inc)+(2*inc2) len3 inc2],'String', 'P-Value','fontsize',12);
con(24,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len3+len3 .01+(4*inc)+(2*inc2) len3 inc2],'String', 'Extent','fontsize',12);
con(15,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(4*inc)+(3*inc2) len2 inc],'String',num2str(loc),'CallBack',@goTo);
%con(15,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(4*inc)+(3*inc2) len2 inc],'String',['0 0 0'],'CallBack',@goTo);
con(25,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len2 .01+(4*inc)+(3*inc2) len2/2 inc],'String','FDR','CallBack', @correctThresh);
con(26,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+(len2*1.5) .01+(4*inc)+(3*inc2) len2/2 inc],'String','FWE','CallBack', @correctThresh);
con(17,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(5*inc)+(3*inc2) len2 inc2],'String', 'MNI Coord', 'fontsize',12);
con(18,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len2 .01+(5*inc)+(3*inc2) len2 inc2],'String', 'MC Correct','fontsize',12);
con(12,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st .01+(5*inc)+(4*inc2) len2 inc],'String',{'Move Up'},'CallBack',@changeLayer);
con(13,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len2 .01+(5*inc)+(4*inc2) len2 inc],'String',{'Move Down'},'CallBack',@changeLayer);
con(21,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(5*inc)+(5*inc2) len1 inc],'String',{'Overlays'},'CallBack',@switchObj);
con(22,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[wid(2)-(len2/2) hei(3)-(inc*1.05) (len2/2) inc]);
con(19,1) = uicontrol(pane,'style','PushButton','Units','Normalized','Position',[st .01+(6*inc)+(5*inc2) len2 inc],'String','Open Overlay','FontWeight','Bold','CallBack',@openOverlay);
con(20,1) = uicontrol(pane,'style','PushButton','Units','Normalized','Position',[st+len2 .01+(6*inc)+(5*inc2) len2 inc],'String','Remove Volume', 'FontWeight','Bold','CallBack',@removeVolume);
menu(1) = uimenu(pane,'Label','Options');
menu(2) = uimenu(menu(1),'Label','CrossHair Toggle','Checked','on','CallBack', @toggleCrossHairs);
menu(43) = uimenu(menu(1),'Label','Reverse Image','CallBack', @changeSign);
menu(15) = uimenu(menu(1),'Label','Change Underlay','CallBack', @changeUnderlay);
menu(3) = uimenu(menu(1),'Label','Send Overlay To New Fig','CallBack',@newFig);
if nargin<2
menu(4) = uimenu(menu(1),'Label','Sync Views','Enable','on','CallBack',@syncViews);
else
menu(4) = uimenu(menu(1),'Label','Sync Views','Enable','on','Checked','on','CallBack',@syncViews);
end
menu(16) = uimenu(menu(1),'Label','SliceViews');
menu(6) = uimenu(menu(16),'Label','Axial Slice View','CallBack',@axialView);
menu(7) = uimenu(menu(16),'Label','Coronal Slice View','CallBack',@coronalView);
menu(8) = uimenu(menu(16),'Label','Sagittal Slice View','CallBack',@sagittalView);
menu(9) = uimenu(menu(16),'Label','All Slice View','CallBack',@allSliceView);
menu(17) = uimenu(menu(1),'Label','Ploting');
menu(10) = uimenu(menu(17),'Label','Load Plot Data','CallBack',@loadData);
menu(13) = uimenu(menu(17),'Label','JointPlot','CallBack',@JointPlot);
menu(12) = uimenu(menu(17),'Label','PaperPlot-Vert','CallBack',@PaperFigure_Vert);
menu(33) = uimenu(menu(17),'Label','PaperPlot-Horz','CallBack',@PaperFigure_Horz);
menu(23) = uimenu(menu(17),'Label','PaperPlot Overlay','Checked','off','CallBack', @toggle);
menu(41) = uimenu(menu(17),'Label','Surface Render','Checked','off','CallBack', @surfView);
menu(14) = uimenu(menu(1),'Label','Transparent Overlay','CallBack',@TestFunc);
menu(11) = uimenu(menu(1),'Label','Get Peak Info','CallBack',@getPeakInfo);
menu(25) = uimenu(menu(1),'Label','Resample');
menu(26) = uimenu(menu(25),'Label','.5x.5x.5', 'CallBack', @resampleIm);
menu(27) = uimenu(menu(25),'Label','1x1x1' , 'CallBack', @resampleIm);
menu(28) = uimenu(menu(25),'Label','2x2x2' , 'CallBack', @resampleIm);
menu(29) = uimenu(menu(25),'Label','3x3x3' , 'CallBack', @resampleIm);
menu(30) = uimenu(menu(25),'Label','4x4x4' , 'CallBack', @resampleIm);
menu(31) = uimenu(menu(25),'Label','5x5x5' , 'CallBack', @resampleIm);
menu(32) = uimenu(menu(25),'Label','6x6x6' , 'CallBack', @resampleIm);
menu(18) = uimenu(menu(1),'Label','Save Options');
menu(19) = uimenu(menu(18),'Label','Save Thresholded Image','Enable','on','CallBack',@saveImg);
menu(20) = uimenu(menu(18),'Label','Save Masked Image','Enable','on','CallBack',@saveImg);
menu(21) = uimenu(menu(18),'Label','Save Cluster Image','Enable','on','CallBack',@saveImg);
menu(22) = uimenu(menu(18),'Label','Save Cluster Mask','Enable','on','CallBack',@saveImg);
menu(34) = uimenu(menu(1),'Label','Mask');
menu(35) = uimenu(menu(34),'Label','Mask In','Enable','on','CallBack',@maskImage);
menu(36) = uimenu(menu(34),'Label','Mask Out','Enable','on','CallBack',@maskImage);
menu(37) = uimenu(menu(34),'Label','Un-Mask','Enable','on','CallBack',@maskImage);
menu(38) = uimenu(menu(1),'Label','Movie Mode','Enable','on','CallBack',@movieMode);
menu(39) = uimenu(menu(1),'Label','Conn Explore','Enable','on','CallBack',@initializeConnExplore);
menu(40) = uimenu(menu(1),'Label','SS Connectivity','Enable','on','CallBack',@ssConn);
item(1) = uimenu(hcmenu, 'Label', 'Go to local max', 'Callback', @gotoMinMax);
item(2) = uimenu(hcmenu, 'Label', 'Go to local min', 'Callback', @gotoMinMax);
item(3) = uimenu(hcmenu, 'Label', 'Go to global max', 'Callback', @gotoMinMax);
item(4) = uimenu(hcmenu, 'Label', 'Go to global min', 'Callback', @gotoMinMax);
item(5) = uimenu(hcmenu, 'Label', 'Plot Cluster', 'Callback', @plotVOI);
item(6) = uimenu(hcmenu, 'Label', 'Plot Sphere', 'Callback', @plotVOI);
item(7) = uimenu(hcmenu, 'Label', 'Plot Voxel', 'Callback', @plotVOI);
item(8) = uimenu(hcmenu, 'Label', 'Plot Cached Cluster', 'Callback', @plotVOI);
item(9) = uimenu(hcmenu, 'Label', 'Cache Cluster Index', 'Callback', @CachedPlot);
%item(8) = uimenu(hcmenu, 'Label', 'RegionName', 'Callback', @regionName);
menu(42) = uimenu(menu(1),'Label','Return Obj','Checked','off','CallBack', @returnInfo);
%menu(43) = uimenu(menu(1),'Label','Return Obj as Global','Checked','off','CallBack', @returnInfoGlob);
Obj(1).ax1 = ax1;
Obj(1).ax2 = ax2;
Obj(1).ax3 = ax3;
Obj(1).ax4 = ax4;
Obj(1).con = con;
Obj(1).menu = menu;
end
function returnInfo(varargin)
if isstruct(varargin{1})
Obj = varargin{1};
else
assignin('base','Obj',Obj);
end
end
function keyHandler(varargin)
d = varargin{2};
%disp([char(d.Modifier) ' - ' d.Key]);
if strcmpi('shift',d.Modifier)
switch d.Key
case 'o'
maskImage(menu(36));
case 'i'
maskImage(menu(35));
case 'u'
maskImage(menu(37));
end
else
switch d.Key
case 'u'
updateConnMap;
case 's'
ssUpdateConnMap;
otherwise
end
end
if contains('alt', {varargin{2}.Key})==1
clickFlag = 0;
end
end
function maskImage(varargin)
vn = get(con(21,1),'Value');
if varargin{1}==menu(37);
Obj(vn).MaskInd = [];
Obj(vn).mask(:) = 1;
Obj(vn).mask(Obj(vn).Exclude)=0;
setupFrames(vn,1);
updateGraphics({1:3 vn},1);
return
end
nnn = spm_select(inf,'image','Select a Mask Image:');
th = spm_vol(nnn);
for ii = 1:numel(th)
m = resizeVol(th(ii),Obj(vn).h);
if varargin{1}==menu(35)
Obj(vn).MaskInd = [Obj(vn).MaskInd; find(isnan(m))];
end
if varargin{1}==menu(36)
Obj(vn).MaskInd = [Obj(vn).MaskInd; find(~isnan(m))];
end
end
Obj(vn).MaskInd = unique(Obj(vn).MaskInd);
Obj(vn).mask(:) = 1;
Obj(vn).mask(Obj(vn).MaskInd)=0;
Obj(vn).mask(Obj(vn).Exclude)=0;
setupFrames(vn,1);
updateGraphics({1:3 vn},1);
end
function CachedPlot(varargin)
if varargin{1} == item(9)
CachedClusterLoc = [];
vn = get(con(21,1),'Value');
CM = str2num(get(findobj(paramenu3(5),'Checked','On'),'Label'));
lastItem = item(5);
adir = [fileparts(Obj(vn).FullPath) filesep];
%%% Using the diplayed image get the matrix vector indices
%%% for the selected cluster
mni = str2num(get(con(15),'string'));
if ~isempty(Obj(vn).mask);
tmpI = Obj(vn).I.*double(Obj(vn).mask);
else
tmpI = Obj(vn).I;
end
thresh = Obj(vn).Thresh;
if numel(thresh)==2
ind = find(tmpI<=thresh(2) & tmpI>=thresh(1));
L = [];
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',CM);
elseif numel(thresh)==4
ind1 = find(tmpI<=thresh(2) & tmpI>=thresh(1));
L1 = [];
[L1(:,1) L1(:,2) L1(:,3)] = ind2sub(Obj(vn).h.dim,ind1);
A1 = spm_clusters2(L1(:,1:3)',CM);
ind2 = find(tmpI<=thresh(4) & tmpI>=thresh(3));
L2 = [];
[L2(:,1) L2(:,2) L2(:,3)] = ind2sub(Obj(vn).h.dim,ind2);
A2 = spm_clusters2(L2(:,1:3)',CM);
L = [L1; L2];
A = [A1 A2+max(A1)];
ind = [ind1; ind2];
end
L(:,4) = 1;
L2 = L*Obj(vn).h.mat';
dist = sqrt(sum((L2(:,1:3)-repmat(mni, size(L,1),1)).^2,2));
if min(dist)>5
disp('No Cluster is selected');
end
ind1 = find(dist==min(dist));
ind2 = find(A==A(ind1(1)));
ind3 = ind(ind2);
CachedClusterLoc.index = ind3;
CachedClusterLoc.mat = Obj(vn).h.mat;
end
end
function PaperFigure_Vert(varargin)
%%% Figure width is off
ss2 = get(gcf,'position');
tss = size(Obj(1).I);
tmp = abs(matInfo(Obj(1).h.mat));
tss = tss.*tmp;
tot = tss(3)+tss(3)+tss(2);
wid(1) = tss(2)/width;
hei(1) = tss(3)/tot;
wid(2) = tss(1)/width;
hei(2) = tss(3)/tot;
wid(3) = tss(1)/width;
hei(3) = tss(2)/tot;
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
xyz = [x(1) y(1) z(1)];
fg = figure; clf; colormap(gray);
set(fg,'color','k')
n = numel(Obj)-1;
if n==0;
return;
end
if strcmpi(get(menu(23),'Checked'),'off')
ww = floor((max(wid)*ss2(3)) * n);
else
ww = floor((max(wid)*ss2(3)) * 1);
n = 1;
end
hh = floor((sum(tss([3 3 2])./height)*ss2(4))*1);
dims = [10 10 ww+((1/8)*ww) hh];
dims(3) = floor(dims(3));
set(fg,'Position',dims);
dd = [.1/n (((dims(3)-dims(1))/n)*.1)/((dims(4)-dims(2)))];
for zz = 2:length(Obj)
if (zz==2) || strcmpi(get(menu(23),'Checked'),'off')
aax1 = axes; set(aax1,'Color','k','Position',[(zz-2)/n sum(hei(1:2)) (1/n)-((1/8)/n) hei(3)],'Xcolor','k','Ycolor','k'); hold on;
aax2 = axes; set(aax2,'Color','k','Position',[(zz-2)/n sum(hei(2)) (1/n)-((1/8)/n) hei(1)],'Xcolor','k','Ycolor','k'); hold on;
aax3 = axes; set(aax3,'Color','k','Position',[(zz-2)/n 0 (1/n)-((1/8)/n) hei(2)],'Xcolor','k','Ycolor','k'); hold on;
aax4 = axes; set(aax4,'Color','k','Position',[((zz-2)/n)+((7/8)/n) 0 (1/8)/n 1],'Xcolor','k','Ycolor','k'); hold on;
tr(zz-1) = aax4;
drawFresh(aax1,3,1,0);
drawFresh(aax2,1,1,0);
drawFresh(aax3,2,1,0);
end
h_in = (zz-2)/(numel(Obj)-1);
drawFresh(aax1,3,zz,0);
drawFresh(aax2,1,zz,0);
drawFresh(aax3,2,zz,0);
if strcmpi(get(menu(23),'Checked'),'off')
an(zz-1,1) = annotation(gcf,'textbox',[h_in+.005 sum(hei(1:2))+(.88*hei(3)) dd],...
'Color','w', 'String',num2str(xyz(3)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
an(zz-1,2) = annotation(gcf,'textbox',[h_in+.005 sum(hei(2))+(.88*hei(2)) dd],...
'Color','w', 'String',num2str(xyz(1)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
an(zz-1,3) = annotation(gcf,'textbox',[h_in+.005 0+(.88*hei(2)) dd],...
'Color','w', 'String',num2str(xyz(2)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
vn = zz;
lim = [min(Obj(vn).clim) max(Obj(vn).clim)];
yy = lim(1):(lim(2)-lim(1))/255:lim(2);
axes(aax4); cla
cm = colmap(cmaps{Obj(vn).col},256);
imagesc(yy',1,reshape(cm,numel(yy),1,3)); axis tight
set(aax4,'YDir','Normal','YAxisLocation','left','YTick', unique([1 get(aax4,'YTick')]));
set(aax4,'YTickLabel',(round(((min(yy):spm_range(yy)/(numel(get(aax4,'YTick'))-1):max(yy)))*100)/100));
th = moveYaxLabs(aax4,'y');
set(th,'fontsize',get(con(2),'fontsize'),'fontweight','bold');
set(th,'BackgroundColor','k'); shg
else
if zz == 2
delete(aax4);
tr = [];
end
end
end
for zz = 1:length(tr)
uistack(tr(zz),'top');
end
if strcmpi(get(menu(23),'Checked'),'on')
h_in = 0;
an(1,1) = annotation(gcf,'textbox',[h_in+.005 sum(hei(1:2))+(.88*hei(3)) dd],...
'Color','w', 'String',num2str(xyz(3)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
an(1,2) = annotation(gcf,'textbox',[h_in+.005 sum(hei(2))+(.88*hei(2)) dd],...
'Color','w', 'String',num2str(xyz(1)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
an(1,3) = annotation(gcf,'textbox',[h_in+.005 0+(.88*hei(2)) dd],...
'Color','w', 'String',num2str(xyz(2)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle','EdgeColor','none');
end
end
function PaperFigure_Horz(varargin)
scrn = get(0, 'ScreenSize');
tmp = get(Obj(1).ax1,'position');
wid(1) = tmp(3); hei(1) = tmp(4);
tmp = get(Obj(1).ax2,'position');
wid(2) = tmp(3); hei(2) = tmp(4);
tmp = get(Obj(1).ax3,'position');
wid(3) = tmp(3); hei(3) = tmp(4);
ss2 = get(gcf,'position');
wid = wid*ss2(3);
hei = hei*ss2(4);
n = numel(Obj)-1;
if n==0;
return;
end
%fg = figure(400+gcf); clf; colormap(gray)
fg = figure; clf; colormap(gray)
set(fg,'color','k')
tall = max(hei)./.9;
if strcmpi(get(menu(23),'Checked'),'off')
hh = tall*n;
else
hh = tall;
n = 1;
end
dims = [10 scrn(3)-75 sum(wid) hh];
dims = round(dims);
set(fg,'Position',dims);
wid = wid./sum(wid);
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
xyz = [x(1) y(1) z(1)];
dd = [.1/n .033];
for zz = 2:length(Obj)
if (zz==2) || strcmpi(get(menu(23),'Checked'),'off')
aax1 = axes; set(aax1,'Color','k','Position',[0 (( n-zz+1)/n)+(.1/n) wid(3) .9/n],'Xcolor','k','Ycolor','k'); hold on;
aax2 = axes; set(aax2,'Color','k','Position',[wid(3) (( n-zz+1)/n)+(.1/n) wid(2) .9/n],'Xcolor','k','Ycolor','k'); hold on;
aax3 = axes; set(aax3,'Color','k','Position',[sum(wid([2 3])) (( n-zz+1)/n)+(.1/n) wid(1) .9/n],'Xcolor','k','Ycolor','k'); hold on;
aax4 = axes; set(aax4,'Color','k','Position',[0 (( n-zz+1)/n) 1 .1/n],'Xcolor','k','Ycolor','k'); hold on;
tr(zz-1) = aax4;
drawFresh(aax1,3,1,0);
drawFresh(aax2,2,1,0);
drawFresh(aax3,1,1,0);
end
h_in = (zz-2)/(numel(Obj)-1);
drawFresh(aax1,3,zz,0);
drawFresh(aax2,2,zz,0);
drawFresh(aax3,1,zz,0);
if strcmpi(get(menu(23),'Checked'),'off')
an(zz-1,1) = annotation(gcf,'textbox',[0 ((n-zz+1)/n)+(.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(3)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
an(zz-1,2) = annotation(gcf,'textbox',[wid(2) ((n-zz+1)/n)+(.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(2)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
an(zz-1,3) = annotation(gcf,'textbox',[sum(wid([2 3]))+(.04) ((n-zz+1)/n)+(.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(1)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
vn = zz;
lim = [min(Obj(vn).clim) max(Obj(vn).clim)];
yy = lim(1):(lim(2)-lim(1))/255:lim(2);
axes(aax4); cla
cm = colmap(cmaps{Obj(vn).col},256);
imagesc(1,yy,reshape(cm,1,numel(yy),3)); axis tight
%imagesc(1,yy',reshape(cmap{Obj(vn).col,1},1,size(cmap{Obj(vn).col,1},1),3)); axis tight
set(aax4,'XDir','Normal','XAxisLocation','top','XTick', unique([1 get(aax4,'XTick')]));
set(aax4,'XTickLabel',(round(((min(yy):spm_range(yy)/(numel(get(aax4,'XTick'))-1):max(yy)))*100)/100));
set(aax4,'xcolor','w','fontsize',12,'fontweight','bold')
th = moveYaxLabs(aax4,'x');
%set(th,'fontsize',get(con(2),'fontsize'),'fontweight','bold');
set(th,'BackgroundColor','k'); shg
else
if zz == 2
delete(aax4);
tr = [];
end
end
end
for zz = 1:length(tr)
uistack(tr(zz),'top');
end
if strcmpi(get(menu(23),'Checked'),'on')
h_in = 0;
an(1,1) = annotation(gcf,'textbox',[0 (.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(3)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
an(1,2) = annotation(gcf,'textbox',[wid(2) (.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(2)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
an(1,3) = annotation(gcf,'textbox',[sum(wid([2 3]))+(.04) (.1/n)+(.8/n) .02 .033],...
'Color','w', 'String',num2str(xyz(1)),'fontsize',18,'fontweight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle');
end
end
function JointPlot(varargin)
if length(Obj)>3
disp('This option only works if there are two and only two overlays');
return
end
% Obj(2).col = 16;
% set(con(21,1),'Value',2);
% switchObj({2});
% UpdateThreshold;
%
% Obj(3).col = 14;
% set(con(21,1),'Value',3);
% switchObj({3});
% UpdateThreshold;
%%%
tmp = Obj(2).I.*double(Obj(2).mask);
if numel(Obj(2).Thresh)==2
ind = find(tmp<Obj(2).Thresh(1) | tmp>Obj(2).Thresh(2));
else
ind = find(tmp<Obj(2).Thresh(1) | tmp>Obj(2).Thresh(4) | (tmp>Obj(2).Thresh(2) & tmp<Obj(2).Thresh(3)));
end
tmp(ind)=NaN;
ind1 = find(~isnan(tmp));
%%%
tmp = Obj(3).I.*double(Obj(3).mask);
if numel(Obj(3).Thresh)==2
ind = find(tmp<Obj(3).Thresh(1) | tmp>Obj(3).Thresh(2));
else
ind = find(tmp<Obj(3).Thresh(1) | tmp>Obj(3).Thresh(4) | (tmp>Obj(3).Thresh(2) & tmp<Obj(3).Thresh(3)));
end
tmp(ind)=NaN;
ind2 = find(~isnan(tmp));
both = intersect(ind1,ind2);
Obj(4) = Obj(3);
Obj(4).Name = 'Overlap.nii';
Obj(4).I(:) = 0;
Obj(4).I(both)=1;
Obj(4).Thresh = [.5 1];
Obj(4).clim = [.5 1.5];
Obj(4).col = 15;
Obj(4).mask = ones(size(Obj(4).I),'uint8');
set(con(21,1),'String', [get(con(21,1),'String'); Obj(4).Name],'Value',4);
setupFrames(4,1)
drawFresh(ax1,1,4);
drawFresh(ax2,2,4);
drawFresh(ax3,3,4);
uistack(ch(1,1),'top'); uistack(ch(1,2),'top');
uistack(ch(2,1),'top'); uistack(ch(2,2),'top');
uistack(ch(3,1),'top'); uistack(ch(3,2),'top');
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
switchObj;
end
function gotoMinMax(varargin)
movego = 0;
vn = get(con(21,1),'Value');
if vn==1
return
end
if ~isempty(Obj(vn).mask);
tmpI = Obj(vn).I.*double(Obj(vn).mask);
else
tmpI = Obj(vn).I;
end
if varargin{1} == item(1)
currloc = Obj(vn).point(1:3);
neigh = neighbors(currloc,Obj(vn).h.dim);
vi = sub2ind(Obj(vn).h.dim,neigh(:,1),neigh(:,2),neigh(:,3));
whvi = find(tmpI(vi)==max(tmpI(vi)));
whvi = vi(whvi(1));
currvi = vi(15);
while currvi ~= whvi
currvi = whvi;
[currloc(1) currloc(2) currloc(3)] = ind2sub(Obj(vn).h.dim,whvi);
neigh = neighbors(currloc,Obj(vn).h.dim);
vi = sub2ind(Obj(vn).h.dim,neigh(:,1),neigh(:,2),neigh(:,3));
whvi = find(tmpI(vi)==max(tmpI(vi)));
whvi = vi(whvi(1));
end
[currloc(1) currloc(2) currloc(3)] = ind2sub(Obj(vn).h.dim,whvi);
newloc = round([currloc 1]*Obj(vn).h.mat');
set(con(15),'String', num2str(newloc(1:3)));
goTo(con(15,1)); shg
elseif varargin{1} == item(2)
currloc = Obj(vn).point(1:3);
neigh = neighbors(currloc,Obj(vn).h.dim);
vi = sub2ind(Obj(vn).h.dim,neigh(:,1),neigh(:,2),neigh(:,3));
whvi = find(tmpI(vi)==min(tmpI(vi)));
whvi = vi(whvi(1));
currvi = vi(15);
while currvi ~= whvi
currvi = whvi;
[currloc(1) currloc(2) currloc(3)] = ind2sub(Obj(vn).h.dim,whvi);
neigh = neighbors(currloc,Obj(vn).h.dim);
vi = sub2ind(Obj(vn).h.dim,neigh(:,1),neigh(:,2),neigh(:,3));
whvi = find(tmpI(vi)==min(tmpI(vi)));
whvi = vi(whvi(1));
end
[currloc(1) currloc(2) currloc(3)] = ind2sub(Obj(vn).h.dim,whvi);
newloc = round([currloc 1]*Obj(vn).h.mat');
set(con(15),'String', num2str(newloc(1:3)));
goTo(con(15,1)); shg
elseif varargin{1} == item(3)
%keyboard;
i1 = find(tmpI==max(tmpI(:)));
[x y z] = ind2sub(Obj(vn).h.dim,i1);
if numel(x)>1
disp('There are multiple maxima!');
x = x(1); y = y(1); z = z(1);
end
newloc = round([x y z 1]*Obj(vn).h.mat');
set(con(15),'String', num2str(newloc(1:3)));
goTo(con(15,1)); shg
elseif varargin{1} == item(4)
i1 = find(tmpI==min(tmpI(:)));
[x y z] = ind2sub(Obj(vn).h.dim,i1);
if numel(x)>1
disp('There are multiple minima!');
x = x(1); y = y(1); z = z(1);
end
newloc = round([x y z 1]*Obj(vn).h.mat');
set(con(15),'String', num2str(newloc(1:3)));
goTo(con(15,1)); shg
end
movego = 0;
end
function scrollMove(varargin)
if isempty(gco);
return
end
switch gca%get(gco,'Parent')
case Obj(1).ax1
switch (varargin{2}.VerticalScrollCount>0)
case 1
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)+1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)-1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
end
case Obj(1).ax2
switch (varargin{2}.VerticalScrollCount>0)
case 1
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)+1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)-1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
end
case Obj(1).ax3
switch (varargin{2}.VerticalScrollCount>0)
case 1
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)+1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)-1;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
end
otherwise
return
end
end
function keyMove(varargin)
if contains('alt', {varargin{2}.Key})==1
clickFlag = 1;
end
if strcmpi(varargin{2}.Modifier,'shift');
mult = 5;
else
mult = 1;
end
if char(get(gcf,'currentcharacter')) == 't'
vn = get(con(21,1),'Value');
state = get(hand{1}(vn),'visible');
if strcmpi(state,'on')
set(hand{1}(vn),'visible','off');
set(hand{2}(vn),'visible','off');
set(hand{3}(vn),'visible','off');
else
set(hand{1}(vn),'visible','on');
set(hand{2}(vn),'visible','on');
set(hand{3}(vn),'visible','on');
end
return
end
if ~isempty(gco)
return;
end
switch gca
case Obj(1).ax1
switch char(get(gcf,'currentcharacter'))
case char(28)
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(29)
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(30)
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(31)
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
return
end
case Obj(1).ax2
switch char(get(gcf,'currentcharacter'))
case char(28)
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(29)
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(30)
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(31)
cl = str2num(get(con(15,1),'String'));
cl(3) = cl(3)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
return
end
case Obj(1).ax3
switch char(get(gcf,'currentcharacter'))
case char(28)
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(29)
cl = str2num(get(con(15,1),'String'));
cl(1) = cl(1)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(30)
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)+mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
case char(31)
cl = str2num(get(con(15,1),'String'));
cl(2) = cl(2)-mult;
set(con(15,1),'string',num2str(cl))
goTo(con(15,1))
otherwise
return
end
otherwise
return
end
end
function groupCheck(varargin)
if varargin{1}==paramenu3(19)
state = get(varargin{1},'Checked');
if strcmpi(state,'on')
set(varargin{1},'Checked','off');
else
set(varargin{1},'Checked','on');
end
return
end
swh1 = findobj(get(varargin{1},'Parent'),'Checked','on');
swh2 = findobj(get(varargin{1},'Parent'),'Checked','off');
if swh1 == varargin{1}
if strcmpi(get(varargin{1},'Checked'),'on')
set(varargin{1},'Checked','off');
else
set(varargin{1},'Checked','on');
end
else
set(swh1,'Checked','off');
set(varargin{1},'Checked','on');
end
%if get(varargin{1},'Parent') == paramenu3(8)
% get(varargin{1},'Label')
% keyboard;
% RNH = spm_vol([which('aal_MNI_V4.img')]);
% [RNI Rxyz] = spm_read_vols(RNH);
% [RNI RNH] = openIMG([which('aal_MNI_V4.img')]);
% RNames = load('aal_MNI_V4_List.mat');
%end
end
function plotVOI(varargin)
movego = 0;
vn = get(con(21,1),'Value');
if isempty(contrasts) || isempty(DataHeaders);
try
loadData
catch
error('No go, no support file found.');
end
else
try
if ~strcmpi(fileparts(Obj(vn).FullPath),Des.OutputDir)
try
loadData
catch
error('No go, no support file found.');
end
end
catch
if ~strcmpi(fileparts(Obj(vn).FullPath),Des.swd)
try
loadData
catch
error('No go, no support file found.');
end
end
end
end
if ~isempty(Obj(vn).mask);
tmpI = Obj(vn).I.*double(Obj(vn).mask);
else
tmpI = Obj(vn).I;
end
if strcmpi(modelType,'SPM')
tmp = Obj(vn).DispName;
i1 = find(tmp=='_');
i2 = find(tmp=='.');
tmp = tmp(i1(end)+1:i2(end)-1);
spmCon = contrasts(str2num(tmp));
end
switch varargin{1}
case item(5) %% Cluster
CM = str2num(get(findobj(paramenu3(5),'Checked','On'),'Label'));
lastItem = item(5);
adir = [fileparts(Obj(vn).FullPath) filesep];
%%% Using the diplayed image get the matrix vector indices
%%% for the selected cluster
mni = str2num(get(con(15),'string'));
thresh = Obj(vn).Thresh;
if numel(thresh)==2
ind = find(tmpI<=thresh(2) & tmpI>=thresh(1));
L = [];
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',CM);
elseif numel(thresh)==4
ind1 = find(tmpI<=thresh(2) & tmpI>=thresh(1));
L1 = [];
[L1(:,1) L1(:,2) L1(:,3)] = ind2sub(Obj(vn).h.dim,ind1);
A1 = spm_clusters2(L1(:,1:3)',CM);
ind2 = find(tmpI<=thresh(4) & tmpI>=thresh(3));
L2 = [];
[L2(:,1) L2(:,2) L2(:,3)] = ind2sub(Obj(vn).h.dim,ind2);
A2 = spm_clusters2(L2(:,1:3)',CM);
L = [L1; L2];
A = [A1 A2+max(A1)];
ind = [ind1; ind2];
end
L(:,4) = 1;
L2 = L*Obj(vn).h.mat';
dist = sqrt(sum((L2(:,1:3)-repmat(mni, size(L,1),1)).^2,2));
if min(dist)>5
disp('No Cluster is selected');
end
ind1 = find(dist==min(dist));
ind2 = find(A==A(ind1(1)));
ind3 = ind(ind2);
%%% Read in an orignal volume
try
th = spm_vol(strtrim(Flist(1,:))); [trash,XYZ] = spm_read_vols(th(1)); clear trash
catch
th = spm_vol(Obj(vn).FullPath); [trash,XYZ] = spm_read_vols(th(1)); clear trash
end
th = th(1);
%try
matLoc = [mni 1]*inv(th(1).mat'); matLoc = matLoc(1:3);
%catch
% keyboard;
%end
%%% Covert the display index into the native volume index
Q = [];
[Q(:,1) Q(:,2) Q(:,3)] = ind2sub(Obj(vn).h.dim,ind3);
Q(:,4) = 1;
Q = (Q*Obj(vn).h.mat')*inv(th.mat');
Q = unique(round(Q),'rows');
i1 = unique([find(Q(:,1)<=0 | Q(:,1)>th.dim(1)); find(Q(:,2)<=0 | Q(:,2)>th.dim(2)); find(Q(:,3)<=0 | Q(:,3)>th.dim(3))]);
i2 = setdiff(1:size(Q,1),i1);
Q = Q(i2,:);
voxInd = sub2ind(th.dim,Q(:,1),Q(:,2),Q(:,3));
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
VOI = [];
VOI.mniLoc = mni;
VOI.matLoc = matLoc;
VOI.index = voxInd;
VOI.isCluster = 1;
try
[x y z] = ind2sub(th.dim,voxInd);
dat = zeros(numel(DataHeaders),numel(x));
for zz = 1:numel(DataHeaders);
dat(zz,:) = spm_sample_vol(DataHeaders(zz),x,y,z,0);
end
if isfield(Des,'ZeroDrop')
if Des.ZeroDrop == 1
dat(dat==0)=NaN;
end
end
if isfield(Des,'OL')
ti1 = intersect(voxInd,Des.OL{2}(:,2));
for zz = 1:numel(ti1);
ti2 = find(Des.OL{2}(:,2)==ti1(zz));
ti3 = find(voxInd == ti1(zz));
dat(ti3,Des.OL{2}(ti2,1))=NaN;
end
end
VOI.allData = dat;
VOI.data = nanmean(dat,2);
catch
VOI.allData = [];
end
case item(6) %% Sphere
lastItem = item(6);
adir = Obj(vn).FullPath;
ind = find(adir==filesep);
if isempty(ind);
adir = [];
else
adir = adir(1:ind(end));
end
try
th = spm_vol(strtrim(Flist(1,:))); [trash,XYZ] = spm_read_vols(th(1)); clear trash
catch
th = spm_vol(Obj(vn).FullPath); [trash,XYZ] = spm_read_vols(th(1)); clear trash
end
mniLoc = str2num(get(con(15),'string'));
matLoc = [mniLoc 1]*inv(th(1).mat'); matLoc = matLoc(1:3);
rad = get(findobj(paramenu3(2),'Checked','on'),'Label');
rad = str2num(rad(1:end-2));
voxInd = find(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))<rad);
if isempty(ind);
voxInd = find(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))==min(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))));
end
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
VOI = [];
VOI.mniLoc = mniLoc;
VOI.matLoc = matLoc;
VOI.index = voxInd;
VOI.rad = rad;
VOI.isCluster = 0;
try
[x y z] = ind2sub(th.dim,voxInd);
dat = zeros(numel(DataHeaders),numel(x));
for zz = 1:numel(DataHeaders);
dat(zz,:) = spm_sample_vol(DataHeaders(zz),x,y,z,0);
end
if isfield(Des,'ZeroDrop')
if Des.ZeroDrop == 1
dat(dat==0)=NaN;
end
end
if isfield(Des,'OL')
ti1 = intersect(voxInd,Des.OL{2}(:,2));
for zz = 1:numel(ti1);
ti2 = find(Des.OL{2}(:,2)==ti1(zz));
ti3 = find(voxInd == ti1(zz));
dat(ti3,Des.OL{2}(ti2,1))=NaN;
end
end
VOI.allData = dat;
VOI.data = nanmean(dat,2);
catch
VOI.allData = [];
end
case item(7) %% Voxel
lastItem = item(7);
adir = Obj(vn).FullPath;
ind = find(adir==filesep);
if isempty(ind);
adir = [];
else
adir = adir(1:ind(end));
end
try
th = spm_vol(strtrim(Flist(1,:))); [trash,XYZ] = spm_read_vols(th(1)); clear trash
catch
th = spm_vol(Obj(vn).FullPath); [trash,XYZ] = spm_read_vols(th(1)); clear trash
end
mniLoc = str2num(get(con(15),'string'));
matLoc = [mniLoc 1]*inv(th(1).mat'); matLoc = matLoc(1:3);
voxInd = find(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))==min(sqrt(sum((XYZ'-repmat(mniLoc,size(XYZ,2),1)).^2,2))));
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
matLoc = round(matLoc);
VOI = [];
VOI.mniLoc = mniLoc;
VOI.matLoc = matLoc;
VOI.index = voxInd;
VOI.rad = 0;
VOI.isCluster = 0;
try
[x y z] = ind2sub(th.dim,voxInd);
dat = zeros(numel(DataHeaders),numel(x));
for zz = 1:numel(DataHeaders);
dat(zz,:) = spm_sample_vol(DataHeaders(zz),x,y,z,0);
end
if isfield(Des,'ZeroDrop')
if Des.ZeroDrop == 1
dat(dat==0)=NaN;
end
end
if isfield(Des,'OL')
ti1 = intersect(voxInd,Des.OL{2}(:,2));
for zz = 1:numel(ti1);
ti2 = find(Des.OL{2}(:,2)==ti1(zz));
ti3 = find(voxInd == ti1(zz));
dat(ti3,Des.OL{2}(ti2,1))=NaN;
end
end
VOI.allData = dat;
VOI.data = nanmean(dat,2);
catch
VOI.allData = [];
end
case item(8) %% Cached Location
if ~isfield(CachedClusterLoc,'index');
disp('No Cluster has been Cached');
return
end
if isempty(CachedClusterLoc.index)
disp('No Cluster has been Cached');
return
end
tmp = CachedClusterLoc.mat-Obj(vn).h.mat;
if sum(abs(tmp))>1e-10
disp('The Current Image is a different size than the one used to Cache the cluster. One image must be resized to the other for this to work');
return;
end
try
th = spm_vol(strtrim(Flist(1,:))); [trash,XYZ] = spm_read_vols(th(1)); clear trash
catch
th = spm_vol(Obj(vn).FullPath); [trash,XYZ] = spm_read_vols(th(1)); clear trash
end
ind3 = CachedClusterLoc.index;
%mni = [];
%matLoc = [] ;
%%% Covert the display index into the native volume index
Q = [];
[Q(:,1) Q(:,2) Q(:,3)] = ind2sub(Obj(vn).h.dim,ind3);
Q(:,4) = 1;
Q = (Q*Obj(vn).h.mat')*inv(th.mat');
Q = unique(round(Q),'rows');
i1 = unique([find(Q(:,1)<=0 | Q(:,1)>th.dim(1)); find(Q(:,2)<=0 | Q(:,2)>th.dim(2)); find(Q(:,3)<=0 | Q(:,3)>th.dim(3))]);
i2 = setdiff(1:size(Q,1),i1);
Q = Q(i2,:);
voxInd = sub2ind(th.dim,Q(:,1),Q(:,2),Q(:,3));
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
VOI = [];
VOI.mniLoc = 'From Cached Cluster';
VOI.matLoc = [];
VOI.index = voxInd;
VOI.isCluster = 1;
try
[x y z] = ind2sub(th.dim,voxInd);
dat = zeros(numel(DataHeaders),numel(x));
for zz = 1:numel(DataHeaders);
dat(zz,:) = spm_sample_vol(DataHeaders(zz),x,y,z,0);
end
if isfield(Des,'ZeroDrop')
if Des.ZeroDrop == 1
dat(dat==0)=NaN;
end
end
if isfield(Des,'OL')
ti1 = intersect(voxInd,Des.OL{2}(:,2));
for zz = 1:numel(ti1);
ti2 = find(Des.OL{2}(:,2)==ti1(zz));
ti3 = find(voxInd == ti1(zz));
dat(ti3,Des.OL{2}(ti2,1))=NaN;
end
end
VOI.allData = dat;
VOI.data = nanmean(dat,2);
catch
VOI.allData = [];
end
otherwise
end
if ~plotGo
assignin('base','VOI',VOI);
warning('Plotting options are not available for this contrast');
return;
end
switch modelType
case 'spm'
c = spmCon.c;
VOI.con = c;
VOI.DM = DM;
VOI.SPM = Des;
assignin('base','VOI',VOI);
GLM_Plot_spm(VOI,777+gcf);
case 'regular'
if isfield(contrasts,'c') && ~isempty(contrasts(wh).c)
c = contrasts(wh).c;
else
try
c = getContrastMat(contrasts(wh));
catch
assignin('base','VOI',VOI);
return
end
end
VOI.con = c;
VOI.DM = DM;
VOI.F = Des.F;
VOI.ConSpec = Des.Cons(wh);
assignin('base','VOI',VOI);
[yres xres] = GLM_Plot(VOI,777+gcf);
VOI.yres = yres;
VOI.xres = xres;
assignin('base','VOI',VOI);
case 'fast'
[pr1 pr2 pr3] = fileparts(Obj(vn).FullPath);
ind = find(pr2=='_');
effect = pr2(ind(2)+1:end);
%figure(555+gcf); clf;
figure; clf;
[yres xres part] = GLM_Plot_Fast(VOI.data,DM,effect);
VOI.effect = effect;
VOI.mod = DM;
VOI.part = part;
VOI.yres = yres;
VOI.xres = xres;
assignin('base','VOI',VOI);
otherwise
end
movego = 0;
end
function loadData(varargin)
vn = get(con(21,1),'Value');
adir = Obj(vn).FullPath;
ind = find(adir==filesep);
if isempty(ind);
adir = [];
else
adir = adir(1:ind(end));
end
if exist([adir 'I.mat'])>0;
%if ~isempty(contains('aschultz',{UserTime})) keyboard; end
HH = load([adir 'I.mat']);
if exist([adir 'FinalDataSet.nii'])
DataHeaders = spm_vol([adir 'FinalDataSet.nii']);
disp('Loading FinalDataSet.nii');
tmp = [(DataHeaders.n)];
Flist = [char(DataHeaders.fname) repmat(',',numel(DataHeaders),1) char(num2str(tmp(1:2:end)'))];
plotGo = 1;
elseif isfield(HH.I,'Scans');
disp('Reading in original input files');
Flist = char(HH.I.Scans);
DataHeaders = spm_vol(Flist);
plotGo = 1;
else
plotGo = 0;
end
if isfield(HH.I,'OL');
Outliers = HH.I.OL;
end
if isfield(HH.I,'Cons')
contrasts = HH.I.Cons;
DM = HH.I.F.XX;
modelType = 'regular';
else
modelType = 'fast';
DM = HH.I.MOD;
end
Des = HH.I;
nvox = prod(HH.I.v.dim);
ns = size(DM,1);
elseif exist([adir 'SPM.mat'])>0;
modelType = 'spm';
HH = load([adir 'SPM.mat']);
contrasts = HH.SPM.xCon;
tmp = spm_read_vols(HH.SPM.xY.VY);
ss = size(tmp);
Des = HH.SPM;
origDat = double(reshape(tmp, prod(ss(1:3)),ss(4))');
DM = HH.SPM.xX.X;
Flist = char(HH.SPM.xY.P);
DataHeaders = HH.SPM.xY.VY;
plotGo = 1;
else
disp('No stat support files were found');
return;
end
end
function applyToAll(varargin)
vn = get(con(21,1),'Value');
sett = setdiff(2:length(Obj),vn);
for ii = sett
%Obj(ii).Thresh = Obj(vn).Thresh;
Obj(ii).clim = Obj(vn).clim;
Obj(ii).PVal = Obj(vn).PVal;
%Obj(ii).DF = Obj(vn).DF;
Obj(ii).Trans = Obj(vn).Trans;
set(con(21,1),'Value',ii);
%AutoUpdate;
switchObj;
%UpdateThreshold;
end
set(con(21,1),'Value',vn);
switchObj;
end
function getClusterParams
vn = get(con(21,1),'Value');
if vn<2
return
end
clear S;
S.mask = [];
S.SPM = 0;
if strcmpi(get(paramenu4(1),'Checked'),'on')
S.sign = 'pos';
elseif strcmpi(get(paramenu4(2),'Checked'),'on')
S.sign = 'neg';
end;
if numel(Obj(vn).DF)==1;
if any(isnan(Obj(vn).DF))
S.type = 'none';
S.df1 = [];
elseif any(isinf(Obj(vn).DF))
S.type = 'Z';
S.df1 = inf;
else
S.type = 'T';
S.df1 = Obj(vn).DF;
end
elseif numel(Obj(vn).DF)==2;
S.type = 'F';
S.df1 = Obj(vn).DF(1);
S.df2 = Obj(vn).DF(2);
end
if strcmpi(S.type,'none');
if numel(Obj(vn).Thresh)==4;
error('Threshold can only contain two terms (one-sided)');
end
i1 = find(abs(Obj(vn).Thresh)==min(abs(Obj(vn).Thresh)));
S.thresh = Obj(vn).Thresh(i1);
if strcmpi(S.sign,'pos'); l = 1; else l = -1;end
if sign(S.thresh)~=l
error('Direction of peaks (from Parameters-->Sign) does not match sign of the specified threshold.');
end
else
S.thresh = Obj(vn).PVal;
end
S.voxlimit = str2num(get(findobj(paramenu3(3),'Checked','on'),'Label'));
S.separation = str2num(strtok(get(findobj(paramenu3(4),'Checked','on'),'Label'),'m'));
S.conn = str2num(get(findobj(paramenu3(5),'Checked','on'),'Label'));
tmp = str2num(get(con(23),'String'));
if isempty(tmp); tmp = 0; end
S.cluster = tmp;
if strcmpi(get(findobj(paramenu3(7),'Label','Use Nearest Label'),'Checked'),'on')
S.nearest = 1;
else
S.nearest = 0;
end
S.label = get(findobj(paramenu3(8),'Checked','on'),'Label');
%%% New Params
% S.UID = [];
% S.out = [];
% S.df2 = ?
th = Obj(vn).h;
[a b c] = fileparts(th.fname);
%%% Create a mask based on the current masking field.
% th.pinfo = [1 0 352]';
% th.dt = [2 0];
% th.fname = [a filesep 'tmpPeakMask.nii'];
% spm_write_vol(th,Obj(vn).mask);
% S.mask = th.fname;
S.exact = 0;
% S.sphere = 0;
% S.clustersphere=0;
S.SV=0;
A = load([a filesep 'I.mat']);
% S.RESELS = [];
%%% Will need to double check this with a repeated measures design.
tmp = regexp(b,'_','split');
effect = tmp{3};
et = [];
for ii = 1:numel(A.I.MOD.RFMs)
for jj = 1:numel(A.I.MOD.RFMs(ii).Effect)
if strcmpi(A.I.MOD.RFMs(ii).Effect(jj).name,effect)
et = ii;
break
end
end
end
try
if ~isempty(et)
S.FWHM = A.I.FWHM{et};
% S.RESELS = spm_resels_vol(Obj(vn).h,S.FWHM)';
end
catch
end
S.threshc = str2num(get(findobj(paramenu3(18),'Checked','on'),'Label'));
% S.exactvoxel = [];
% S.FIVE = [];`
% S.savecorrected.do = 1;
% S.savecorrected.type = {'cFWE' 'vFWE' 'vFDR' 'cFDR'};
end
function getPeakInfo(varargin)
vn = get(con(21,1),'Value');
S = [];
getClusterParams;
peak = [];
% save S.mat S;
[peak.voxels, peak.voxelstats, peak.clusterstats, peak.sigthresh, peak.regions, peak.mapparameters, peak.UID] = peak_nii(Obj(vn).FullPath(1:end-2),S);
assignin('base','peak',peak);
figure(666); clf; %reset(666);
%%% Add in some sorting options for the table
[a b] = sortrows([cellstr(char(num2str(peak.voxels{1}(:,end)))) peak.regions(:,2)]);
tabHand = uitable('Parent',666,...
'ColumnName',{'Cluster Size' 'T/F-Stat' 'X' 'Y' 'Z' 'N_peaks' 'Cluster Num' 'Region Num' 'Region Name'},...
'data', [mat2cell(peak.voxels{1}(b,:),ones(size(peak.voxels{1},1),1), ones(size(peak.voxels{1},2),1)) peak.regions(b,:)],...
'Units','Normalized','Position', [0 0 1 1],...
'ColumnWidth', 'auto', 'RearrangeableColumns','on','CellSelectionCallback',@goToCluster);
%set(tabHand, 'uicontextmenu',tableMenu);
Out = cell(size(peak.voxels{1},1)+1 ,9);
Out(1,:) = {'Cluster Size' 'T/F-Stat' 'X' 'Y' 'Z' 'N_peaks' 'Cluster Num' 'Region Num' 'Region Name'};
% 'Other1' 'Other2' 'Other3' 'Other4'
Out(2:end,1:7) = num2cell(peak.voxels{1}(:,1:7));
Out(2:end,8:9) = peak.regions;
[a b c] = fileparts(Obj(vn).FullPath);
WriteDataToText(Out,[a filesep 'peakinfo.csv'],'w',',');
%delete(th.fname);
end
function goToCluster(varargin)
data = get(tabHand,'Data');
row = varargin{2}.Indices(1);
mni = [data{row,3:5}];
set(con(15,1),'String',num2str(mni));
goTo(con(15,1));
end
function out = initializeUnderlay(M,HH)
out.Name = 'Structural Underlay';
out.I = double(M);
out.h = HH;
out.Thresh = [min(M(:)) max(M(:))];
if ~isempty(contains('defaultUnderlay.nii',{HH.fname}))
out.clim = [max(M(:))*.15 max(M(:))*.8];
else
out.clim = out.Thresh;
end
out.PVal = [];
out.col = 1;
out.pos = axLim(M,HH);
out.Exclude = [];
out.MaskInd = [];
out.mask = ones(size(M),'uint8');
out.Trans = 1;
out.mask = ones(size(M),'uint8');
out.Thresh = [min(M(:)) max(M(:))];
out.clim = [min(M(:)) max(M(:))];
out.Range = [out.Thresh(1) out.Thresh(2) diff(out.Thresh) ];
out.axLims = size(M);
mniLims = [[min(out.pos{1}) min(out.pos{2}) min(out.pos{3})]; ...
[max(out.pos{1}) max(out.pos{2}) max(out.pos{3})]];
end
function changeUnderlay(varargin)
ufn = spm_select(1,'image','Choose the new underlay');
h = spm_vol(ufn);
[I mmm] = SliceAndDice3(h,MH,[],[],[0 NaN],[]);
h.dim = size(I);
h.mat = mmm;
nv = 1;
for ii = 1:length(hand)
delete(hand{ii}(nv));
end
tmp = initializeUnderlay(I,h);
flds = fields(tmp);
for ii = 1:length(flds)
Obj(1).(flds{ii}) = tmp.(flds{ii});
end
Obj(1).point = round([loc 1] * inv(Obj(1).h.mat)');
setupFrames(1,1);
tss = Obj(1).axLims;
tmp = [1 1 1];
tss = tss.*tmp;
height = tss(2)+tss(3);
width = tss(1)+tss(2);
rat = height/width;
ff = get(0,'ScreenSize');
if ff(4)>800
pro = 3.25;
else
pro = 2.5;
end
ss = get(0,'ScreenSize');
if (ss(3)/ss(4))>2
ss(3)=ss(3)/2;
end
op = floor([50 ss(4)-75-((ss(3)/pro)*rat) ss(3)/pro (ss(3)/pro)*rat]);
set(gcf, 'Position', op);
wid(1) = tss(2)/width;
hei(1) = tss(3)/height;
wid(2) = tss(1)/width;
hei(2) = tss(3)/height;
wid(3) = tss(1)/width;
hei(3) = tss(2)/height;
set(ax1,'Color','k','Position',[wid(2) hei(3) wid(1) hei(1)]); hold on;
set(ax2,'Color','k','Position',[0 hei(3) wid(2) hei(2)]); hold on;
set(ax3,'Color','k','Position',[0 0 wid(3) hei(3)]); hold on;
set(ax4,'Color','w','Position',[wid(2) 0 .04 hei(3)]); axis tight;
%st = wid(2)+.01+.04+.03;
st = wid(2)+.125;
len1 = (1-st)-.01;
len2 = len1/2;
len3 = len1/3;
inc = (hei(3))/11;
inc2 = .75*inc;
val = (Obj(1).Range(2)-Obj(1).Range(1))/Obj(1).Range(3);
con(27,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.070 0 .025 hei(3)*.9],'Value',val,'CallBack', @adjustUnderlay);
val = (Obj(1).Range(1)-Obj(1).Range(1))/Obj(1).Range(3);
con(28,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.095 0 .025 hei(3)*.9],'Value',val,'CallBack', @adjustUnderlay);
%con(29,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[wid(2)+.095 0 .025 hei(3)*.9],'Value',0,'CallBack', @adjustUnderlay);
con(30,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[wid(2)+.070 hei(3)*.9 .05 .05]); % wid(2)+.0450 hei(3)*.9 .075 .05]
% con(28,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[st-.1 (.01+(1*inc)+(0*inc2)) len1*.75 inc],'Value',1,'CallBack', @adjustTrans);
con(1,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(0*inc)+(0*inc2) len1 inc],'String',[{'Colormap'} cmaps(:)'],'CallBack', @changeColorMap); shg
%con(1,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(0*inc)+(0*inc2) len1 inc],'String',[{'Colormap' 'A' 'B' 'C' 'D'}],'CallBack', @changeColorMap); shg
con(2,1) = uicontrol(pane,'style','slider', 'Units','Normalized','Position',[st (.01+(1*inc)+(0*inc2)) len1*.75 inc],'Value',1,'CallBack', @adjustTrans);
con(23,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len1*.75 (.01+(1*inc)+(0*inc2)) len1*.25 inc],'String','All','CallBack', @applyToAll);
con(3,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(2*inc)+(0*inc2) len1 inc2],'String', 'Transparency','fontsize',12);
con(4,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(2*inc)+(1*inc2) len2 inc],'CallBack',@UpdateThreshold);
con(5,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len2 .01+(2*inc)+(1*inc2) len2 inc],'CallBack',@UpdateCLims);
con(6,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(3*inc)+(1*inc2) len2 inc2],'String', 'Thresh','fontsize',12);
con(7,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len2 .01+(3*inc)+(1*inc2) len2 inc2],'String', 'Color Limits','fontsize',12);
con(8,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@UpdatePVal);
con(9,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len3 .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@UpdatePVal);
con(23,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st+len3+len3 .01+(3*inc)+(2*inc2) len3 inc],'CallBack',@ExtentThresh);
con(10,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(4*inc)+(2*inc2) len3 inc2],'String', 'DF','fontsize',12);
con(11,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len3 .01+(4*inc)+(2*inc2) len3 inc2],'String', 'P-Value','fontsize',12);
con(24,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len3+len3 .01+(4*inc)+(2*inc2) len3 inc2],'String', 'Extent','fontsize',12);
con(15,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(4*inc)+(3*inc2) len2 inc],'String',num2str(loc),'CallBack',@goTo);
%con(15,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[st .01+(4*inc)+(3*inc2) len2 inc],'String',['0 0 0'],'CallBack',@goTo);
con(25,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len2 .01+(4*inc)+(3*inc2) len2/2 inc],'String','FDR','CallBack', @correctThresh);
con(26,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+(len2*1.5) .01+(4*inc)+(3*inc2) len2/2 inc],'String','FWE','CallBack', @correctThresh);
con(17,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st .01+(5*inc)+(3*inc2) len2 inc2],'String', 'MNI Coord', 'fontsize',12);
con(18,1) = uicontrol(pane,'style','text', 'Units','Normalized','Position',[st+len2 .01+(5*inc)+(3*inc2) len2 inc2],'String', 'MC Correct','fontsize',12);
con(12,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st .01+(5*inc)+(4*inc2) len2 inc],'String',{'Move Up'},'CallBack',@changeLayer);
con(13,1) = uicontrol(pane,'style','pushbutton','Units','Normalized','Position',[st+len2 .01+(5*inc)+(4*inc2) len2 inc],'String',{'Move Down'},'CallBack',@changeLayer);
con(21,1) = uicontrol(pane,'style','popupmenu', 'Units','Normalized','Position',[st .01+(5*inc)+(5*inc2) len1 inc],'String',{'Overlays'},'CallBack',@switchObj);
con(22,1) = uicontrol(pane,'style','edit', 'Units','Normalized','Position',[wid(2)-(len2/2) hei(3)-(inc*1.05) (len2/2) inc]);
con(19,1) = uicontrol(pane,'style','PushButton','Units','Normalized','Position',[st .01+(6*inc)+(5*inc2) len2 inc],'String','Open Overlay','FontWeight','Bold','CallBack',@openOverlay);
con(20,1) = uicontrol(pane,'style','PushButton','Units','Normalized','Position',[st+len2 .01+(6*inc)+(5*inc2) len2 inc],'String','Remove Volume', 'FontWeight','Bold','CallBack',@removeVolume);
drawFresh(ax1,1,1); axis equal;
drawFresh(ax2,2,1); axis equal;
drawFresh(ax3,3,1); axis equal;
set(ax1,'color','k')
set(ax2,'color','k')
set(ax3,'color','k')
axes(ax1); ax = axis;
set(ch(1,1),'YData',ax(3:4)); set(ch(1,2),'XData',ax(1:2));
axes(ax2); ax = axis;
set(ch(2,1),'YData',ax(3:4)); set(ch(2,2),'XData',ax(1:2));
axes(ax3); ax = axis;
set(ch(3,1),'YData',ax(3:4)); set(ch(3,2),'XData',ax(1:2));
uistack(hand{1}(1),'bottom');
uistack(hand{2}(1),'bottom');
uistack(hand{3}(1),'bottom');
set(con(27),'value',1);
set(con(28),'value',0);
if get(con(21,1),'Value') == 1
set(con(5),'String', sprintf('%0.3f %0.3f',Obj(1).Thresh(1),Obj(1).Thresh(2)));
end
end
function plotConfig
fh = figure(777); clf; reset(777);
pop(1) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .95 .9 .05],'String','Choose the plot Type','Fontsize',12);
bg = uibuttongroup(fh,'Units','Normalized','position',[.05 .9 .9 .05]);
pop(2) = uicontrol(bg,'style','radiobutton','Units','Normalized','position',[ 00 0 .33 1],'String','BoxPlot','Fontsize',12);
pop(3) = uicontrol(bg,'style','radiobutton','Units','Normalized','position',[.33 0 .33 1],'String','InteractionPlot','Fontsize',12);
pop(4) = uicontrol(bg,'style','radiobutton','Units','Normalized','position',[.66 0 .33 1], 'String', 'ScatterPlot','Fontsize',12);
pop(5) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .83 .9 .05],'String','Set the Data Groups','Fontsize',12);
pop(6) = uicontrol(fh,'style','edit','Units','Normalized','position',[.05 .75 .9 .08],'String','{{1:10} {11:20} {etc..}}','Fontsize',12);
pop(7) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .68 .9 .05],'String','Specify Design Matirx Columns','Fontsize',12);
pop(8) = uicontrol(fh,'style','edit','Units','Normalized','position',[.05 .60 .9 .08],'String','{{1:10} {11:20} {etc..}}','Fontsize',12);
end
function ExtentThresh(varargin)
%keyboard;
%CM = 18;%
CM = str2num(get(findobj(paramenu3(5),'Checked','On'),'Label'));
vn = get(con(21,1),'Value');
ClusterExtent = str2num(get(con(23),'String'));
if isempty(ClusterExtent) || ClusterExtent==0;
Obj(vn).mask = ones(size(Obj(vn).I),'uint8');
Obj(vn).Exclude = [];
Obj(vn).mask(Obj(vn).MaskInd)=0;
return
end
Obj(vn).ClusterThresh = ClusterExtent;
if numel(Obj(vn).Thresh)==2
% ind = find(Obj(vn).I<Obj(vn).Thresh(1) | Obj(vn).I>Obj(vn).Thresh(2));
ind = find(Obj(vn).I>Obj(vn).Thresh(1) & Obj(vn).I<Obj(vn).Thresh(2));
else
% ind = find(Obj(vn).I<Obj(vn).Thresh(1) | Obj(vn).I>Obj(vn).Thresh(4) | (Obj(vn).I>Obj(vn).Thresh(2) & Obj(vn).I<Obj(vn).Thresh(3)));
ind = find( (Obj(vn).I>Obj(vn).Thresh(1) & Obj(vn).I<Obj(vn).Thresh(2)) | (Obj(vn).I>Obj(vn).Thresh(3) & Obj(vn).I<Obj(vn).Thresh(4)));
end
% ind = setdiff(1:prod(Obj(vn).axLims),ind);
ind = ind(:)';
L = [];
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',CM);
Exclude = [];
list = unique(A);
for ii = list
i1 = find(A==ii);
if numel(i1)<ClusterExtent
Exclude = [Exclude ind(i1)];
end
end
Obj(vn).mask(:) = 1;
Obj(vn).Exclude = Exclude;
Obj(vn).mask(Exclude)=0;
Obj(vn).mask(Obj(vn).MaskInd)=0;
setupFrames(vn,1);
updateGraphics({1:3 vn},1);
end
function out = popup(Message)
%%% Fix this up later so that multiple messages mean multiple
%%% inputs
fh = figure(777); clf; %reset(777);
pop(1) = uicontrol(fh,'style','text','Units','Normalized','position',[.05 .83 .9 .05],'String',Message,'Fontsize',12);
pop(2) = uicontrol(fh,'style','edit','Units','Normalized','position',[.05 .75 .9 .08],'String','','Fontsize',12,'Callback','uiresume');
uiwait
eval(['out = [' get(pop(2),'String') '];']);
close(gcf);
end
function TestFunc(varargin)
vn = get(con(21,1),'Value');
wh = Count;
Obj(wh) = Obj(1);
tmpVol = SliceAndDice3(Obj(vn).FullPath,Obj(1).h,Obj(1).h,Obj(1).h,[1 NaN],[]);
ind = find(tmpVol>Obj(vn).Thresh(1) & tmpVol<Obj(vn).Thresh(2));
Obj(wh).I(setdiff(1:numel(Obj(wh).I),ind)) = NaN;
tmp = Obj(1).CM(:,:,:,1); tmp = round((tmp./max(tmp(:)))*(size(cmap{1,1},1)-1));
nn = zeros(numel(tmp),3)*NaN;
ind2 = find(~isnan(tmp));
nn(ind2,:) = cmap{2,1}(tmp(ind2)+1,:);
a = zeros(size(Obj(1).CM))*NaN;
b = zeros(size(Obj(1).CM))*NaN;
c = zeros(size(Obj(1).CM))*NaN;
a(ind) = nn(ind,1);
b(ind) = nn(ind,2);
c(ind) = nn(ind,3);
Obj(wh).CM = cat(4,a,b,c);
m = Obj(wh).I;
n2 = 'TmpImg';
set(con(21,1),'String', [get(con(21,1),'String'); n2],'Value',Count);
set(con(4),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(5),'String',[num2str(floor(min(m(:))*1000)/1000) ', ' num2str(ceil(max(m(:))*1000)/1000)]);
set(con(8),'String','NaN');
set(con(9),'String','NaN');
Obj(wh).DF = NaN;
Obj(wh).PVal = NaN;
Obj(wh).Thresh = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(wh).clim = [floor(min(m(:))*1000)/1000 ceil(max(m(:))*1000)/1000];
Obj(wh).col = 2;
Obj(wh).Trans = 1;
y = get(ch(1,1),'XData');
x = get(ch(2,1),'XData');
z = get(ch(1,2),'YData');
loc = [x(1) y(1) z(1)];
Obj(wh).point = round([loc 1] * inv(Obj(wh).h.mat)');
setupFrames(wh,0);
Obj(wh).pos = axLim(Obj(wh).I,Obj(wh).h);
tmp = size(Obj(wh).CM);
Obj(wh).axLims = tmp(1:3);
set(con(1,1),'Value',wh+1);
drawFresh(ax1,1,wh);
drawFresh(ax2,2,wh);
drawFresh(ax3,3,wh);
uistack(ch(1,1),'top'); uistack(ch(1,2),'top');
uistack(ch(2,1),'top'); uistack(ch(2,2),'top');
uistack(ch(3,1),'top'); uistack(ch(3,2),'top');
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
Count = Count+1;
end
function c = getContrastMat(Con)
tx = Des.F.XX;
if ~isfield(Con,'c') || isempty(Con.c)
if iscell(Con.Groups)
tc = [];
for zz = 1:length(Con.Groups)
if size(Con.Groups{zz},1)>1
tmpX = Con.Groups{zz};
else
tmpX = tx(:,Con.Groups{zz});
end
cc = MakePreCons(tmpX,tx,Des.F.CovarCols);
tc(:,zz) = mean(cc,2);
end
levs = Con.Levs(end:-1:1);
if levs == 0
c = tc;
else
tmp = reshape(tc,[size(tc,1) levs]);
tmp = squeeze(tmp);
if size(tmp,2)==1
c = tmp;
else
c = differencer(tmp);
if numel(levs)==1
c = c*-1;
end
end
end
else
[r,c,cc] = MakeContrastMatrix('a',Con.Groups,Con.Levs,tx);
end
else
c = Con.c;
c0 = eye(size(txx,2))-(c*pinv(c));
x0 = txx*c0;
r = eye(size(x0,1))-(x0*pinv(x0));
end
end
function saveImg(varargin)
%%% Write something in the descip field to describe how the image
%%% was made
from = varargin{1};
vn = get(con(21,1),'Value');
CM = str2num(get(findobj(paramenu3(5),'Checked','On'),'Label'));
switch from
case menu(19)
disp('Save Thresholded Image');
dotI = find(Obj(vn).FullPath=='.');
fn = [Obj(vn).FullPath(1:dotI(end)-1) '_thresh.nii'];
th = spm_vol(Obj(vn).FullPath);
hh = Obj(vn).h;
hh.fname = fn;
if ~isempty(Obj(vn).mask);
tmp = Obj(vn).I.*double(Obj(vn).mask);
else
tmp = Obj(vn).I;
end
if numel(Obj(vn).Thresh)==2
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(2));
else
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(4) | (tmp>Obj(vn).Thresh(2) & tmp<Obj(vn).Thresh(3)));
end
tmp(ind)=NaN;
spm_write_vol(hh,tmp);
hh2 = spm_vol(fn);
N = resizeVol2(hh2,th);
th.fname = fn;
th.descrip = [];
spm_write_vol(th,N);
case menu(20)
disp('Save Masked Image');
dotI = find(Obj(vn).FullPath=='.');
fn = [Obj(vn).FullPath(1:dotI(end)-1) '_mask.nii'];
th = spm_vol(Obj(vn).FullPath);
hh = Obj(vn).h;
hh.fname = fn;
hh.dt = [2 0];
tmp = Obj(vn).I;
if numel(Obj(vn).Thresh)==2
ind = find(tmp>Obj(vn).Thresh(1) & tmp<Obj(vn).Thresh(2));
else
ind = find((tmp>Obj(vn).Thresh(1) & tmp<Obj(vn).Thresh(2)) | (tmp>Obj(vn).Thresh(3) & tmp<Obj(vn).Thresh(4)));
end
tmp(:)=0;
tmp(ind)=1;
spm_write_vol(hh,tmp);
hh2 = spm_vol(fn);
N = resizeVol(hh2,th);
th.fname = fn;
th.descrip = [];
th.dt = [2 0];
spm_write_vol(th,N);
case menu(21)
disp('Save Cluster Image');
mni = str2num(get(con(15),'string'));
tmp = Obj(vn).I;
if numel(Obj(vn).Thresh)==2
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(2));
else
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(4) | (tmp>Obj(vn).Thresh(2) & tmp<Obj(vn).Thresh(3)));
end
tmp(ind)=NaN;
ind = find(~isnan(tmp));
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',18);
L(:,4) = 1;
L2 = L*Obj(vn).h.mat';
dist = sqrt(sum((L2(:,1:3)-repmat(mni, size(L,1),1)).^2,2));
if min(dist)>5
disp('No Cluster is selected');
end
ind1 = find(dist==min(dist));
ind2 = find(A==A(ind1(1)));
ind3 = ind(ind2);
tmp(:) = NaN;
tmp(ind3) = Obj(vn).I(ind3);
dotI = find(Obj(vn).FullPath=='.');
fn = [Obj(vn).FullPath(1:dotI(end)-1) '_cluster.nii'];
th = spm_vol(Obj(vn).FullPath);
hh = Obj(vn).h;
hh.fname = fn;
spm_write_vol(hh,tmp);
hh2 = spm_vol(fn);
N = resizeVol2(hh2,th);
th.fname = fn;
th.descrip = [];
spm_write_vol(th,N);
case menu(22)
disp('Save Cluster Mask');
mni = str2num(get(con(15),'string'));
tmp = Obj(vn).I;
if numel(Obj(vn).Thresh)==2
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(2));
else
ind = find(tmp<Obj(vn).Thresh(1) | tmp>Obj(vn).Thresh(4) | (tmp>Obj(vn).Thresh(2) & tmp<Obj(vn).Thresh(3)));
end
tmp(ind)=NaN;
ind = find(~isnan(tmp));
[L(:,1) L(:,2) L(:,3)] = ind2sub(Obj(vn).h.dim,ind);
A = spm_clusters2(L(:,1:3)',18);
L(:,4) = 1;
L2 = L*Obj(vn).h.mat';
dist = sqrt(sum((L2(:,1:3)-repmat(mni, size(L,1),1)).^2,2));
if min(dist)>5
disp('No Cluster is selected');
end
ind1 = find(dist==min(dist));
ind2 = find(A==A(ind1(1)));
ind3 = ind(ind2);
tmp(:) = 0;
tmp(ind3) = 1;
dotI = find(Obj(vn).FullPath=='.');
fn = [Obj(vn).FullPath(1:dotI(end)-1) '_clusterMask.nii'];
th = spm_vol(Obj(vn).FullPath);
hh = Obj(vn).h;
hh.fname = fn;
spm_write_vol(hh,tmp);
hh2 = spm_vol(fn);
N = resizeVol(hh2,th);
th.fname = fn;
th.descrip = [];
th.dt = [2 0];
spm_write_vol(th,N);
otherwise
end
end
function resampleIm(varargin)
vn = get(con(21,1),'Value');
%keyboard;
voxdim = str2num(char(regexp(get(varargin{1},'Label'),'x','split')))';
nnn = Obj(vn).FullPath;
hh = spm_vol(nnn);
[mm mat] = SliceAndDice3(hh, MH, voxdim, [],[1 0],[]);
hh.dim = size(mm);
hh.mat = mat;
Obj(vn).h = hh;
Obj(vn).I = double(mm);
Obj(vn).mask = ones(size(mm),'uint8');
Obj(vn).pos = axLim(Obj(vn).I,Obj(vn).h);
Obj(vn).axLims = Obj(vn).h.dim;
loc = str2num(get(con(15),'String'));
Obj(vn).point = round([loc 1] * inv(Obj(vn).h.mat)');
setupFrames(vn,1);
for ii = 1:length(hand)
delete(hand{ii}(vn));
end
drawFresh(ax1,1,vn);
drawFresh(ax2,2,vn);
drawFresh(ax3,3,vn);
uistack(ch(1,1),'top'); uistack(ch(1,2),'top');
uistack(ch(2,1),'top'); uistack(ch(2,2),'top');
uistack(ch(3,1),'top'); uistack(ch(3,2),'top');
for ii = 1:length(hand);
set(hand{ii}, 'uicontextmenu',hcmenu);
end
end
function correctThresh(varargin)
vn = get(con(21,1),'Value');
if numel(Obj(vn).DF)==1
stat = 'T';
df = [1 Obj(vn).DF];
elseif numel(Obj(vn).DF)==2
stat = 'F';
df = Obj(vn).DF;
end
if ~isempty(Obj(vn).mask);
tmpI = Obj(vn).I.*double(Obj(vn).mask);
else
tmpI = Obj(vn).I;
end
ind = find(Obj(vn).Name == '.');
indfilesep = find(Obj(vn).Name == filesep); %DGM Added
wind=find(ind>indfilesep); %DGM Added
ind=ind(wind);%DGM Added
wh = str2num(Obj(vn).Name(ind-4:ind-1));
if isempty(wh);
ind = find(Obj(vn).Name==filesep);
if isempty(ind); ind=0; end
wh = str2num(Obj(vn).Name(ind+1:ind+4));
end
if varargin{1}==con(25) %FDR Correction
if numel(Obj(vn).Thresh) == 2
ind = find(abs(tmpI)>0);
div = 1;
if sum(sign(Obj(vn).Thresh))<0
%ind = find(Obj(vn).I<0);
t = abs(tmpI(ind));
elseif sum(sign(Obj(vn).Thresh))>0
%ind = find(Obj(vn).I>0);
t = abs(tmpI(ind));
end
elseif numel(Obj(vn).Thresh) == 4
ind = find(abs(tmpI)>0);
t = abs(tmpI(ind));
div = 2;
end
if strcmpi(stat,'f');
pp = 1-spm_Fcdf(t,df);
else
pp = (1-spm_Tcdf(t,df(2))).*div;
end
pp = sort(pp);
%keyboard;
alpha = str2num(get(findobj(paramenu3(18),'Checked','On'),'Label'));
p = pp';
rh = ((1:numel(p))./numel(p)).*alpha;
below = p<=rh;
in = (find(below==1));
if isempty(in)
warning('FDR Correction is not possible for this alpha');
return
end
%;
t = sort(t,'descend');
thresh = t(in(end));
pthresh = p(in(end));
%[FDR_alpha FDR_p FDR_t] = computeFDR('0003_T_TFO_Pos_Corr.nii',114,.05,0)
end
if varargin{1}==con(26) %% FWE correction using RFT
[a b c] = fileparts(Obj(vn).FullPath);
try
HH = load([a filesep 'I.mat']);
%R = HH.I.ReslInfo{HH.I.Cons(wh).ET};
if isfield(HH.I,'Cons')
FWHM = HH.I.FWHM{HH.I.Cons(wh).ET};
end
if isfield(HH.I,'MOD')
ind = find(b=='_');
effect = b(ind(2)+1:end);
for ii = 1:numel(HH.I.MOD.RFMs)
for jj = 1:numel(HH.I.MOD.RFMs(ii).Effect)
if strcmpi(effect,HH.I.MOD.RFMs(ii).Effect(jj).name)
ET = ii;
end
end
end
FWHM = HH.I.FWHM{ET};
end
catch
HH = load([a filesep 'SPM.mat']);
%R = HH.SPM.xVol.R;
FWHM = HH.SPM.xVol.FWHM;
end
p = str2num(get(findobj(paramenu3(18),'Checked','On'),'Label'));
try
[msk mh] = openIMG([a filesep 'mask.img']);
catch
try
[msk mh] = openIMG([a filesep 'mask.nii']);
catch
[msk mh] = openIMG([a filesep 'NN.nii']);
mh.fname = 'mask.nii';
spm_write_vol(mh,msk>0);
[msk mh] = openIMG([a filesep 'mask.nii']);
end
end
if ~isempty(Obj(vn).mask);
msk = Obj(vn).I.*double(Obj(vn).mask);
end
reselinfo = spm_resels_vol(mh,FWHM)';
if strcmpi(stat,'f');
thresh = spm_uc(p,df,stat,reselinfo,1,numel(find(msk>0)));
pthresh = 1-spm_Fcdf(thresh,df);
else
if numel(Obj(vn).Thresh) == 4
thresh = spm_uc(p/2,df,stat,reselinfo,1,numel(find(msk>0)));
pthresh = (1-spm_Tcdf(thresh,df(2)));
else
thresh = spm_uc(p,df,stat,reselinfo,1,numel(find(msk>0)));
pthresh = (1-spm_Tcdf(thresh,df(2)));
end
end
end
thresh = round(thresh*1000)/1000;
if numel(Obj(vn).Thresh) == 2
if sum(sign(Obj(vn).Thresh))<0
if thresh<Obj(vn).Thresh(1)
warning(['No voxels beyond the corrected threshold of ' num2str(-thresh)]);
return
end
Obj(vn).Thresh = [Obj(vn).Thresh(1) -thresh];
Obj(vn).PVal = pthresh;
else
if thresh>Obj(vn).Thresh(2)
warning(['No voxels beyond the corrected threshold of ' num2str(thresh)]);
return
end
Obj(vn).Thresh = [thresh Obj(vn).Thresh(2)];
Obj(vn).PVal = pthresh;
end
elseif numel(Obj(vn).Thresh) == 4
up = ~(thresh>Obj(vn).Thresh(4));
down = ~(thresh<Obj(vn).Thresh(1));
if ~up && ~down
warning(['Nothing Left at this Threshold. Exiting Correction.']);
return;
end
if up && down
Obj(vn).Thresh = [Obj(vn).Thresh(1) -thresh thresh Obj(vn).Thresh(4)];
Obj(vn).PVal = pthresh;
end
if up && ~down
warning(['No voxels below the corrected threshold of ' num2str(-thresh)]);
Obj(vn).Thresh = [thresh Obj(vn).Thresh(4)];
Obj(vn).PVal = pthresh;
end
if down && ~up
warning(['No voxels above the corrected threshold of ' num2str(thresh)]);
Obj(vn).Thresh = [Obj(vn).Thresh(1) -thresh];
Obj(vn).PVal = pthresh;
end
end
ll = []; for zz = 1:numel(Obj(vn).Thresh); ll = [ll num2str(Obj(vn).Thresh(zz)) ' ']; end;
ll = ll(1:end-1);
set(con(4,1),'String',num2str(ll));
UpdateThreshold(con(4,1));
end
function changeLabelMap(varargin)
groupCheck(varargin{1})
% fn1 = which([get(varargin{1},'Label') '.img']);
% fn2 = which([get(varargin{1},'Label') '.mat']);
try
[fn1,fn2]=getLabelMap(get(varargin{1},'Label'));
catch
fn1=[];fn2=[];
end
if isempty(fn1) && isempty(fn2)
warning(['Label Map ' get(varargin{1},'Label') ' cannot be found. Reverting to aal_MNI_V4']);
set(varargin{1},'Checked','off');
set(findobj(gcf,'Label','aal_MNI_V4'),'Checked','on');
return
end
RNH = spm_vol(fn1);
[RNI Rxyz] = spm_read_vols(RNH);
RNames = load(fn2);
end
function h = moveYaxLabs(currAx,wh)
if nargin==0 || isempty(currAx)
currAx = gca;
end
if wh == 'y'
ax = axis(currAx);
y = get(currAx,'YTick');
lab = cellstr(get(currAx,'YTickLabel'));
for ii = 1:numel(lab)
if lab{ii}(1) ~= '-'
lab{ii} = ['+' lab{ii}];
end
end
adj = range(y)*.015;
adj2 = range(ax(1:2))*.5;
for ii = 1:numel(lab)
if ii==1
h(ii) = text(ax(1)+adj2,y(ii)+adj,lab{ii},'FontName', get(currAx,'FontName'), 'FontSize',get(currAx,'FontSize'),'color','w','HorizontalAlignment','Center'); shg
elseif ii==numel(lab)
h(ii) = text(ax(1)+adj2,y(ii)-adj,lab{ii},'FontName', get(currAx,'FontName'), 'FontSize',get(currAx,'FontSize'),'color','w','HorizontalAlignment','Center'); shg
else
h(ii) = text(ax(1)+adj2,y(ii), lab{ii},'FontName', get(currAx,'FontName'), 'FontSize',get(currAx,'FontSize'),'color','w','fontweight','bold','HorizontalAlignment','Center'); shg
%p = get(h(ii),'Position'); p(3) = 15; set(h(ii),'Position',p);
end
end
set(gca,'XTick', [],'YTick',[]);
elseif wh == 'x'
ax = axis(currAx);
x = get(currAx,'XTick');
lab = cellstr(get(currAx,'XTickLabel'));
for ii = 1:numel(lab)
if lab{ii}(1) ~= '-'
lab{ii} = ['+' lab{ii}];
end
end
adj2 = range(ax(3:4))*.5;
for ii = 1:numel(lab)
if ii==1
h(ii) = text(ax(1)+(.005*adj2), ax(3)+adj2, lab{ii},'FontName', get(gca,'FontName'), 'FontSize',get(gca,'FontSize'),'color','w','HorizontalAlignment','Left'); shg
elseif ii==numel(lab)
h(ii) = text(ax(2)-(.005*adj2), ax(3)+adj2, lab{ii},'FontName', get(gca,'FontName'), 'FontSize',get(gca,'FontSize'),'color','w','HorizontalAlignment','Right'); shg
else
h(ii) = text(x(ii)-(.005*adj2), ax(3)+adj2, lab{ii},'FontName', get(gca,'FontName'), 'FontSize',get(gca,'FontSize'),'color','w','fontweight','bold','HorizontalAlignment','Center'); shg
end
end
set(gca,'XTick', [],'YTick',[]);
end
end
function initializeConnExplore(varargin)
vn = get(con(21,1),'Value');
if ConExp==1
switchObj(ConLayer)
return
end
fn = ['/autofs/space/schopenhauer_004/users/ConnectivityAtlas/Maps/blank.nii'];
openOverlay(fn);
ConExp = 1;
ConHeader = spm_vol(fn);
vn = get(con(21,1),'Value');
ConLayer = vn;
%Obj(2).h.mat
Obj(vn).Thresh = [-1 1];
Obj(vn).clim = [-1 1];
set(con(4),'String','-1 1');
set(con(5),'String','-1 1');
end
function updateConnMap(varargin)
if ConExp==0
return
end
vn = get(con(21,1),'Value');
if vn ~= ConLayer;
return
end
MNI = Obj(1).point*Obj(1).h.mat';
matLoc = round(MNI*inv(ConHeader.mat)');
thisLoc = sub2ind(ConHeader.dim,matLoc(1),matLoc(2),matLoc(3));
fn = ['/autofs/space/schopenhauer_004/users/ConnectivityAtlas/Maps/Vox_' sprintf('%0.6d',thisLoc) '.nii'];
if exist(fn)>0
Obj(vn).I = openIMG(fn);
%Obj(vn).I = resizeVol2(spm_vol(fn),Obj(vn).h);
else
Obj(vn).I(:) = NaN;
end
UpdateThreshold;
end
function ssConn(varargin)
vn = get(con(21,1),'Value');
if ssConExp==1
switchObj(ssConLayer)
return
end
ff = spm_select(inf,'image');
fn = [];
for zz = 1:size(ff,1)
fn{zz} = (ff(zz,1:end-2));
end
openOverlay(ff(1,:));
ssConExp = 1;
vn = get(con(21,1),'Value');
ssConHeader = Obj(vn).h;
ssConLayer = vn;
ssData = [];
for zz = 1:numel(fn);
pth = fileparts(fn{zz});
% R = [];
% fl = [pth '/ExtraRegressors.mat'];
% if exist(fl,'file')>0
% load(fl);
% [rows,cols] = find(R==1);
% else
% rows = [];
% end
th = spm_vol(fn{zz});
% wh = setdiff(1:numel(th), rows);
% th = th(wh);
dat = zeros(numel(th),prod(Obj(vn).h.dim));
for qq = 1:numel(th)
dd = resizeVol2(th(qq),Obj(vn).h);
dat(qq,:) = dd(:);
end
ssData = [ssData; zscore(dat)];
end
ssData = zscore(ssData);
Obj(vn).I(:) = 0;
Obj(vn).Thresh = [-1 1];
Obj(vn).clim = [-1 1];
set(con(4),'String','-1 1');
set(con(5),'String','-1 1');
UpdateThreshold;
end
function ssUpdateConnMap(varargin)
if ssConExp==0
return
end
vn = get(con(21,1),'Value');
if vn ~= ssConLayer;
return
end
MNI = Obj(1).point*Obj(1).h.mat';
matLoc = round(MNI*inv(ssConHeader.mat)');
thisLoc = sub2ind(ssConHeader.dim,matLoc(1),matLoc(2),matLoc(3));
rad = get(findobj(paramenu3(2),'Checked','on'),'Label');
rad = str2num(rad(1:end-2));
[ml vi] = getMatCoord(ssConHeader,MNI(1:3),rad*2);
seed = zscore(nanmean(ssData(:,vi),2));
beta = pinv(seed)*ssData;
% keyboard;
Obj(vn).I(:) = beta;
UpdateThreshold;
end
function movieMode(varargin)
nnn = spm_select(inf,'image');
if size(nnn,1)==1
ind = find(nnn==',');
nnn = nnn(1:ind-1);
end
dh = spm_vol(nnn);
for ii = 1:numel(dh)
[t1 t2] = SliceAndDice3(dh(ii),MH,[],Obj(1).h,[0 NaN],[]);
if ii == 1
dd = nan([size(t1) numel(dh)]);
end
dd(:,:,:,ii) = t1;
end
rang = [min(dd(:)) min(dd(:))];
xyz = [20 20 20]; jj = 1;
tmp = [];
tmp{1} = flipdim(rot90(squeeze(dd(xyz(1),:,:,jj)),1),1);
tmp{2} = flipdim(flipdim(rot90(squeeze(dd(:,xyz(2),:,jj)),1),1),2);
tmp{3} = flipdim(flipdim(rot90(squeeze(dd(:,:,xyz(3),jj)),1),1),2);
% tmp = pcolor(Obj(ii).pos{2}, Obj(ii).pos{3}, Obj(ii).frame{opt});
% if opt3; hand{opt}(ii) = tmp; end
% colormap(gray(256)); shading interp; hold on;
keyboard;
end
function adjustUnderlay(varargin)
if varargin{1}==con(29)
return
end
vn = get(con(21,1),'Value');
if isempty(Obj(vn).Thresh)
Obj(vn).Thresh = [min(Obj(vn).I(:)) max(Obj(vn).I(:))];
Obj(vn).clim = [min(Obj(vn).I(:)) max(Obj(vn).I(:))];
end
if ~isfield(Obj(vn),'Range') || isempty(Obj(vn).Range)
Obj(vn).Range = [min(Obj(vn).I(:)) max(Obj(vn).I(:)) max(Obj(vn).I(:))-min(Obj(vn).I(:)) ];
end
val = get(varargin{1},'Value');
if varargin{1}==con(27)
Obj(vn).clim(2) = (val*Obj(vn).Range(3))+Obj(vn).Range(1);
%Obj(vn).clim(2) = val*Obj(vn).Thresh(2);
end
if varargin{1}==con(28)
Obj(vn).clim(1) = (val*Obj(vn).Range(3))+Obj(vn).Range(1);
%Obj(vn).clim(1) = val*Obj(vn).Thresh(2);
end
set(con(5),'String',[sprintf('%0.3f %0.3f',Obj(vn).clim(1),Obj(vn).clim(2))]);
setupFrames(vn,1);
updateGraphics([1 2 3],1);
%%%%%
yy = Obj(vn).clim(1):(Obj(vn).clim(2)-Obj(vn).clim(1))/255:Obj(vn).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(vn).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
end
function UpdateCLims(varargin)
vn = get(con(21,1),'Value');
b = get(con(5),'String');
if contains(',',{b})
ind = find(b==',');
b = [str2num(strtrim(b(1:ind-1))) str2num(strtrim(b(ind+1:end)))];
else
b = str2num(b);
end
if b(1)==-inf
b(1) = Obj(vn).Range(1);
end
if b(2)==inf
b(2) = Obj(vn).Range(2);
end
Obj(vn).clim = b;
tmp1 = (Obj(vn).clim(2)-Obj(vn).Range(1))/Obj(vn).Range(3); if tmp1>1; tmp1=1; end; if tmp1<0; tmp1=0; end;
set(con(27),'Value', tmp1);
tmp1 = (Obj(vn).clim(1)-Obj(vn).Range(1))/Obj(vn).Range(3); if tmp1>1; tmp1=1; end; if tmp1<0; tmp1=0; end;
set(con(28),'Value', tmp1);
setupFrames(vn,1);
updateGraphics([1 2 3],1);
set(con(5),'String', sprintf('%0.3f %0.3f',b(1),b(2)));
%%%%%%%%%%%%%
yy = Obj(vn).clim(1):(Obj(vn).clim(2)-Obj(vn).clim(1))/255:Obj(vn).clim(2);
axes(ax4); cla
imagesc(yy,1,reshape(colmap(cmaps{Obj(vn).col},256),256,1,3));
axis tight;
set(ax4,'YDir','Normal','YAxisLocation','right','YTick', unique([1 get(ax4,'YTick')]));
set(ax4,'YTickLabel',round(min(yy):spm_range(yy)/(numel(get(ax4,'YTick'))-1):max(yy)));
set(ax4,'fontsize',6);
end
end
function out = differencer(tmp,count)
if nargin == 1;
count = numel(size(tmp));
end
out = diff(tmp,1,count);
if count ~= 2;
out = differencer(out,count-1);
else
if numel(size(out))>2
ss = size(out);
out = reshape(out,size(out,1),prod(ss(2:end)));
end
return
end
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
ScatterGroups2.m
|
.m
|
MRtools_Hoffman2-master/Visualization/ScatterGroups2.m
| 4,891 |
utf_8
|
c9e1840b483ee024bcc9e7c122333157
|
function [h X] = ScatterGroups2(dat,Groups,altLabs)
%%% Written by Aaron Schultz ([email protected])
%%%
%%% Copyright (C) 2012, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01-AG027435
%%%
%%% 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
%%% 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.
IND = {};
if isobject(Groups);
Groups = cellstr(Groups);
end
tt = unique(Groups,'stable');
for ii = 1:numel(tt)
if iscell(Groups)
ind = strmatch(tt{ii}, Groups,'exact');
Labs{ii} = tt{ii};
elseif isnumeric(Groups)
ind = find(Groups==tt(ii));
Labs{ii} = num2str(ii);
end
IND{ii} = ind;
mm(ii) = mean(dat(ind));
sd(ii) = std(dat(ind));
se(ii) = (std(dat(ind))./sqrt(numel(ind)))*1.96;
end
% keyboard;
if nargin>2
Labs = altLabs;
end
% errorbar(1:length(mm),mm,2*sd,'.k','linewidth',1.5)
eh = errorbar((1:length(mm)),mm,se,'o','color',[.65 .65 .65],'linewidth',4,'markersize',10,'markerfacecolor',[.65 .65 .65]); hold on;
% keyboard;
% errorbar_tick(eh,10); hold on
h = [];
for ii = 1:numel(IND)
ind = IND{ii};
X{ii} = ii+(.35*(rand(numel(ind),1)-.5));
h(ii) = plot(X{ii},dat(ind),'b.','markersize',20); hold on;
end
bp = [];
if exist('boxplot.m')>0
%keyboard;
bp = boxplot(dat,Groups);
set(findobj(gcf,'color', 'k'),'linewidth',3)
set(findobj(gcf,'color', 'r'),'linewidth',3,'color','k')
set(findobj(gcf,'color', 'b'),'linewidth',3,'color','k')
end
if numel(h)==1
cols = [0 0 1];
else
cols = zeros(numel(h),3);
cols(:,3) = 1:-1/(numel(h)-1):0;
cols(:,1) = 0:1/(numel(h)-1):1;
end
for ii = 1:numel(h)
set(h(ii),'Color',cols(ii,:));
end
set(gca,'XTick', 1:length(Labs), 'XTickLabel',Labs,'FontSize',14,'FontWeight','bold');
uistack(eh,'bottom');
if ~isempty(bp)
uistack(bp,'bottom');
end
ax = axis;
ax(1:2) = [.5 numel(tt)+.5];
axis(ax);
plot(ax(1:2),[0 0],'m--','linewidth',2);
function errorbar_tick(h,w,xtype)
%ERRORBAR_TICK Adjust the width of errorbars
% ERRORBAR_TICK(H) adjust the width of error bars with handle H.
% Error bars width is given as a ratio of X axis length (1/80).
% ERRORBAR_TICK(H,W) adjust the width of error bars with handle H.
% The input W is given as a ratio of X axis length (1/W). The result
% is independent of the x-axis units. A ratio between 20 and 80 is usually fine.
% ERRORBAR_TICK(H,W,'UNITS') adjust the width of error bars with handle H.
% The input W is given in the units of the current x-axis.
%
% See also ERRORBAR
%
% Author: Arnaud Laurent
% Creation : Jan 29th 2009
% MATLAB version: R2007a
%
% Notes: This function was created from a post on the french forum :
% http://www.developpez.net/forums/f148/environnements-developpement/matlab/
% Author : Jerome Briot (Dut)
% http://www.mathworks.com/matlabcentral/newsreader/author/94805
% http://www.developpez.net/forums/u125006/dut/
% It was further modified by Arnaud Laurent and Jerome Briot.
% Check numbers of arguments
error(nargchk(1,3,nargin))
% Check for the use of V6 flag ( even if it is depreciated ;) )
flagtype = get(h,'type');
% Check number of arguments and provide missing values
if nargin==1
w = 80;
end
if nargin<3
xtype = 'ratio';
end
% Calculate width of error bars
if ~strcmpi(xtype,'units')
dx = diff(get(gca,'XLim')); % Retrieve x limits from current axis
w = dx/w; % Errorbar width
end
% Plot error bars
if strcmpi(flagtype,'hggroup') % ERRORBAR(...)
hh=get(h,'children'); % Retrieve info from errorbar plot
x = get(hh(2),'xdata'); % Get xdata from errorbar plot
x(4:9:end) = x(1:9:end)-w/2; % Change xdata with respect to ratio
x(7:9:end) = x(1:9:end)-w/2;
x(5:9:end) = x(1:9:end)+w/2;
x(8:9:end) = x(1:9:end)+w/2;
set(hh(2),'xdata',x(:)) % Change error bars on the figure
else % ERRORBAR('V6',...)
x = get(h(1),'xdata'); % Get xdata from errorbar plot
x(4:9:end) = x(1:9:end)-w/2; % Change xdata with respect to the chosen ratio
x(7:9:end) = x(1:9:end)-w/2;
x(5:9:end) = x(1:9:end)+w/2;
x(8:9:end) = x(1:9:end)+w/2;
set(h(1),'xdata',x(:)) % Change error bars on the figure
end
end
end
% return
% %%
% dat = rand(200,1);
% groups = ones(200,1);
% groups(51:100)=2; groups(101:150) = 3; groups(151:200)=4;
%
% figure(20); clf;
% ll = {'Group1' 'Group2' 'Group3' 'Group4'};
% clf; ScatterGroups(dat,groups,ll)
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
Groupbar.m
|
.m
|
MRtools_Hoffman2-master/Visualization/Groupbar.m
| 3,949 |
utf_8
|
3b1b120022e2c8fc48f734d0b04610b9
|
function Groupbar(dat,Groups,Labs)
%%% Written by Aaron Schultz ([email protected])
%%%
%%% Copyright (C) 2012, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01-AG027435
%%%
%%% 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
%%% 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.
tt = unique(Groups);
for ii = tt(:)'
ind = find(Groups==ii);
mm(ii) = mean(dat(ind));
sd(ii) = std(dat(ind));
se(ii) = (std(dat(ind))./sqrt(numel(ind)))*1.96;
end
cols = jet(numel(mm));
% if mod(numel(mm),2)==1
% cols = colmap('cbd_pu_gn',numel(mm));
% %cols=cols(setdiff(1:numel(mm),ceil((numel(mm)/2))),:);
% else
% cols = colmap('cbd_pu_gn',numel(mm)+2);
% cols=cols(setdiff(1:size(cols,1),(numel(mm)/2)+1:(numel(mm)/2)+2),:);
% end
for ii = 1:length(mm)
bar(ii,mm(ii),'FaceColor',cols(ii,:)); hold on
end
% bar((1:length(mm)),mm); hold on
% errorbar(1:length(mm),mm,2*sd,'.k','linewidth',1.5)
h=errorbar((1:length(mm)),mm,se,'k.','linewidth',3); hold on;
% errorbar_tick(h,10); hold on
set(gca,'XTick', 1:length(Labs), 'XTickLabel',Labs,'FontSize',14);
ax = axis;
ax(1:2) = [.5 numel(tt)+.5];
axis(ax);
if ax(3)~=0 && ax(4)~=0
plot(ax(1:2),[0 0],'m--','linewidth',2);
end
end
function errorbar_tick(h,w,xtype)
%ERRORBAR_TICK Adjust the width of errorbars
% ERRORBAR_TICK(H) adjust the width of error bars with handle H.
% Error bars width is given as a ratio of X axis length (1/80).
% ERRORBAR_TICK(H,W) adjust the width of error bars with handle H.
% The input W is given as a ratio of X axis length (1/W). The result
% is independent of the x-axis units. A ratio between 20 and 80 is usually fine.
% ERRORBAR_TICK(H,W,'UNITS') adjust the width of error bars with handle H.
% The input W is given in the units of the current x-axis.
%
% See also ERRORBAR
%
% Author: Arnaud Laurent
% Creation : Jan 29th 2009
% MATLAB version: R2007a
%
% Notes: This function was created from a post on the french forum :
% http://www.developpez.net/forums/f148/environnements-developpement/matlab/
% Author : Jerome Briot (Dut)
% http://www.mathworks.com/matlabcentral/newsreader/author/94805
% http://www.developpez.net/forums/u125006/dut/
% It was further modified by Arnaud Laurent and Jerome Briot.
% Check numbers of arguments
error(nargchk(1,3,nargin))
% Check for the use of V6 flag ( even if it is depreciated ;) )
flagtype = get(h,'type');
% Check number of arguments and provide missing values
if nargin==1
w = 80;
end
if nargin<3
xtype = 'ratio';
end
% Calculate width of error bars
if ~strcmpi(xtype,'units')
dx = diff(get(gca,'XLim')); % Retrieve x limits from current axis
w = dx/w; % Errorbar width
end
% Plot error bars
if strcmpi(flagtype,'hggroup') % ERRORBAR(...)
hh=get(h,'children'); % Retrieve info from errorbar plot
x = get(hh(2),'xdata'); % Get xdata from errorbar plot
x(4:9:end) = x(1:9:end)-w/2; % Change xdata with respect to ratio
x(7:9:end) = x(1:9:end)-w/2;
x(5:9:end) = x(1:9:end)+w/2;
x(8:9:end) = x(1:9:end)+w/2;
set(hh(2),'xdata',x(:)) % Change error bars on the figure
else % ERRORBAR('V6',...)
x = get(h(1),'xdata'); % Get xdata from errorbar plot
x(4:9:end) = x(1:9:end)-w/2; % Change xdata with respect to the chosen ratio
x(7:9:end) = x(1:9:end)-w/2;
x(5:9:end) = x(1:9:end)+w/2;
x(8:9:end) = x(1:9:end)+w/2;
set(h(1),'xdata',x(:)) % Change error bars on the figure
end
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
ScatterGroups.m
|
.m
|
MRtools_Hoffman2-master/Visualization/ScatterGroups.m
| 4,772 |
utf_8
|
f1ebbaf74bc7dd673ebc53d25a2a4d5a
|
function [h X] = ScatterGroups(dat,Groups,Labs)
%%% Written by Aaron Schultz ([email protected])
%%%
%%% Copyright (C) 2012, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01-AG027435
%%%
%%% 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
%%% 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.
tt = unique(Groups);
c = 0;
for ii = tt(:)'
c = c+1;
ind = find(Groups==ii);
%plot(ii,dat(ind),'bd','markersize',10); hold on;
mm(c) = mean(dat(ind));
sd(c) = std(dat(ind));
se(c) = (std(dat(ind))./sqrt(numel(ind)))*1.96;
end
disp(mm)
disp(se)
% errorbar(1:length(mm),mm,2*sd,'.k','linewidth',1.5)
eh = errorbar((1:length(mm)),mm,se,'o','color',[.65 .65 .65],'linewidth',4,'markersize',10,'markerfacecolor',[.65 .65 .65]); hold on;
errorbar_tick(eh,10); hold on
h = [];
c = 0;
for ii = tt(:)'
c = c+1;
ind = find(Groups==ii);
X{c} = c+(.2*(rand(numel(ind),1)-.5));
h(c) = plot(X{c},dat(ind),'b.','markersize',20); hold on;
end
bp = [];
if exist('boxplot.m')>0
% [junk user] = UserTime;
% if strcmp(user,'aschultz');
% bp = boxplot(dat,Groups,'notch','on');
% else
bp = boxplot(dat,Groups);
% end
set(findobj(gcf,'color', 'k'),'linewidth',3)
set(findobj(gcf,'color', 'r'),'linewidth',3,'color','k')
set(findobj(gcf,'color', 'b'),'linewidth',3,'color','k')
end
if numel(h)==1
cols = [0 0 1];
else
cols = zeros(numel(h),3);
cols(:,3) = 1:-1/(numel(h)-1):0;
cols(:,1) = 0:1/(numel(h)-1):1;
end
for ii = 1:numel(h)
set(h(ii),'Color',cols(ii,:));
end
set(gca,'XTick', 1:length(Labs), 'XTickLabel',Labs,'FontSize',14,'FontWeight','bold');
uistack(eh,'bottom');
if ~isempty(bp)
uistack(bp,'bottom');
end
ax = axis;
ax(1:2) = [.5 numel(tt)+.5];
axis(ax);
plot(ax(1:2),[0 0],'m--','linewidth',2);
function errorbar_tick(h,w,xtype)
%ERRORBAR_TICK Adjust the width of errorbars
% ERRORBAR_TICK(H) adjust the width of error bars with handle H.
% Error bars width is given as a ratio of X axis length (1/80).
% ERRORBAR_TICK(H,W) adjust the width of error bars with handle H.
% The input W is given as a ratio of X axis length (1/W). The result
% is independent of the x-axis units. A ratio between 20 and 80 is usually fine.
% ERRORBAR_TICK(H,W,'UNITS') adjust the width of error bars with handle H.
% The input W is given in the units of the current x-axis.
%
% See also ERRORBAR
%
% Author: Arnaud Laurent
% Creation : Jan 29th 2009
% MATLAB version: R2007a
%
% Notes: This function was created from a post on the french forum :
% http://www.developpez.net/forums/f148/environnements-developpement/matlab/
% Author : Jerome Briot (Dut)
% http://www.mathworks.com/matlabcentral/newsreader/author/94805
% http://www.developpez.net/forums/u125006/dut/
% It was further modified by Arnaud Laurent and Jerome Briot.
% Check numbers of arguments
error(nargchk(1,3,nargin))
% Check for the use of V6 flag ( even if it is depreciated ;) )
flagtype = get(h,'type');
% Check number of arguments and provide missing values
if nargin==1
w = 80;
end
if nargin<3
xtype = 'ratio';
end
% Calculate width of error bars
if ~strcmpi(xtype,'units')
dx = diff(get(gca,'XLim')); % Retrieve x limits from current axis
w = dx/w; % Errorbar width
end
% Plot error bars
if strcmpi(flagtype,'hggroup') % ERRORBAR(...)
hh=get(h,'children'); % Retrieve info from errorbar plot
x = get(hh(2),'xdata'); % Get xdata from errorbar plot
x(4:9:end) = x(1:9:end)-w/2; % Change xdata with respect to ratio
x(7:9:end) = x(1:9:end)-w/2;
x(5:9:end) = x(1:9:end)+w/2;
x(8:9:end) = x(1:9:end)+w/2;
set(hh(2),'xdata',x(:)) % Change error bars on the figure
else % ERRORBAR('V6',...)
x = get(h(1),'xdata'); % Get xdata from errorbar plot
x(4:9:end) = x(1:9:end)-w/2; % Change xdata with respect to the chosen ratio
x(7:9:end) = x(1:9:end)-w/2;
x(5:9:end) = x(1:9:end)+w/2;
x(8:9:end) = x(1:9:end)+w/2;
set(h(1),'xdata',x(:)) % Change error bars on the figure
end
end
end
% return
% %%
% dat = rand(200,1);
% groups = ones(200,1);
% groups(51:100)=2; groups(101:150) = 3; groups(151:200)=4;
%
% figure(20); clf;
% ll = {'Group1' 'Group2' 'Group3' 'Group4'};
% clf; ScatterGroups(dat,groups,ll)
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
ANOVA_APS.m
|
.m
|
MRtools_Hoffman2-master/GLM_Flex/ANOVA_APS.m
| 16,479 |
utf_8
|
593cd3020dc55da7f1846da9aafa91f0
|
function OUTPUT = ANOVA_APS(dat,mod,posthocs,runModel,dm,asEffects)
%%% Written by Aaron Schultz ([email protected])
%%%
%%% Copyright (C) 2012, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01-AG027435
%%%
%%% 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
%%% 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.
%%% SEB stuff.
% % X = mod.X;
% % rr = eye(size(X,1))-(X*pinv(X));
% % MSE = LoopEstimate(y,1,rr)./mod.RFMs(1).EDF;
% % b = pinv(X)*y;
% % cv = MSE*inv(X'*X);
% % seb = sqrt(diag(cv));
% % t = b./seb;
OUTPUT.data = dat;
iscontinuous = [];
isconstant = 0;
supress = 0;
if nargin<3
posthocs = [];
else
if any(size(posthocs)==1) && any(size(posthocs)>2)
posthocs = posthocs(:);
end
end
if nargin<4 || isempty(runModel)
runModel = 1;
end
if runModel==3
runModel=1;
supress = 1;
end
if nargin<5 || isempty(dm)
dm = 1;
% disp('All covariates will be demeaned');
end
if nargin<6 || isempty(asEffects) || runModel==1
asEffects = 1;
end
%%% Split the model into sets of additive terms
ind = find(mod=='~');
if numel(ind)>1
error('Only 1 ~ should be present in model specification');
end
if ~isempty(ind)
varname = strtrim(mod(1:ind(1)-1));
Nobs = size(dat.(varname),1);
else
runModel = 0;
ind = 0;
end
mod2 = mod(ind(1)+1:end);
mod3 = regexp(mod2,'+','split');
for ii = 1:numel(mod3);
mod3{ii} = strtrim(mod3{ii});
end
%%% Get a list of the unique terms in the model : Not inclusing error specification
terms = [];
for ii = 1:numel(mod3)
if ~isempty(strfind(mod3{ii},'random'))
continue
end
if ~isempty(regexp(mod3{ii},'*')) && ~isempty(regexp(mod3{ii},':'))
error('You cannot specify both * and : within the same term');
end
tmp = regexp(mod3{ii},'[*:]','split');
for jj = 1:numel(tmp);
terms{end+1} = strtrim(tmp{jj});
end
end
terms= unique(terms,'stable');
if exist('varname','var')==0
Nobs = size(dat.(terms{1}),1);
end
%%% now create the dummy coded main effect terms
Effects = [];
for ii = 1:numel(terms);
if isnumeric(dat.(terms{ii}))
iscontinuous(ii) = 1;
if dm == 1
Nobs = numel(dat.(terms{ii}));
Effects{ii} = demean(dat.(terms{ii})); % + ((rand(Nobs,1)-.5)*1e-16); % Real values covariates should never have a value of 0 will mess up contrast later on.
else
Effects{ii} = dat.(terms{ii});
end
else
iscontinuous(ii) = 0;
Effects{ii} = makedummy(dat.(terms{ii}),asEffects);
if size(Effects{ii},2)==1 && all(Effects{ii}==1)
isconstant = 1;
end
end
end
%%% Now create the interaction terms
for ii = 1:numel(mod3);
if ~isempty(strfind(lower(mod3{ii}),'random'));
continue
end
tt = regexp(mod3{ii},'[*:]' ,'split');
tt = strtrim(tt);
for jj = 2:numel(tt);
sets = combnk(1:numel(tt),jj);
for kk = 1:size(sets,1)
which = sets(kk,:);
if any(iscontinuous(which))
iscontinuous(end+1) = 1;
else
iscontinuous(end+1) = 0;
end
[i1 i2] = matchAll(tt(which),terms);
Effects{end+1} = FactorCross(Effects(i2));
name = [];
for ll = 1:numel(which);
name = [name tt{which(ll)} ':'];
end
terms{end+1} = name(1:end-1);
end
end
end
%%% Now it's time to setup the error terms.
ErrorTerms = []; eTerms = [];
if isempty(contains('random',{mod}))
eTerms{1} = 'Observations';
ErrorTerms{1} = makedummy(1:Nobs,asEffects);
random = 'Observations';
else
tmp = regexp(mod2,'random','split');
if numel(tmp)>2
error('Only 1 random effect may be specified. If you need more look to an LME model');
end
err = strtrim(tmp{2});
err = strtrim(regexprep(err,'[()]',''));
tmp = regexp(err,'\|','split');
random = strtrim(tmp{1});
nesting = strtrim(tmp{2});
np = regexp(nesting,'*','split');
eTerms{end+1} = tmp{1};
ErrorTerms{end+1} = makedummy(dat.(tmp{1}),asEffects);
for ii = 1:numel(np)
sets = combnk(1:numel(np),ii);
for jj = 1:size(sets,1)
[a b] = matchAll(np(sets(jj,:)), terms);
ErrorTerms{end+1} = FactorCross([ErrorTerms{1} Effects(b)]);
%%% Random effects with : specification?
name = [random ':'];
for kk = 1:size(sets(jj,:),2)
name = [name np{sets(jj,kk)} ':'];
end
eTerms{end+1} = name(1:end-1);
end
end
end
%%% If there is a random effect, make sure that there are no missing
%%% observations.
if numel(eTerms)>1
RF = dat.(eTerms{1});
S1 = regexp(eTerms{end},[eTerms{1} ':'],'split');
S2 = regexp(S1{end},':','split');
ps = {};
%keyboard;
for ii = 1:numel(S2);
if isnumeric(dat.(S2{ii}))
continue
end
ps{ii} = makedummy(dat.(S2{ii}),0);
end
if ~isempty(ps);
combo = FactorCross(ps);
missing = {}; %drop = [];
list = unique(RF);
for ii = 1:numel(list);
try
i2 = find(nominal(RF)==list(ii));
catch
i2 = strmatch(list{ii},RF,'exact');
end
if ~all(sum(combo(i2,:)))
missing{end+1,1} = list{ii};
end
end
if ~isempty(missing)
disp(missing)
error('At least one observation is missing for each level of the random factor listed above');
end
else
disp('Assuming that everything is ok');
end
end
%%% Which terms should go into the model?
ModelTerms = []; whichTerms = [];
for ii = 1:numel(mod3)
if ~isempty(regexp(mod3{ii},'random'));
continue
end
if isempty(regexp(mod3{ii},'*'))
ModelTerms{end+1} = mod3{ii};
whichTerms(end+1) = strmatch(ModelTerms{end},terms,'exact');
else
tt = regexp(mod3{ii},'*','split');
for jj = 1:numel(tt);
sets = combnk(1:numel(tt),jj);
for kk = 1:size(sets,1)
which = sets(kk,:);
name = [];
for ll = 1:numel(which);
name = [name tt{which(ll)} ':'];
end
ModelTerms{end+1} = regexprep(name(1:end-1),' ','');
tmp = strmatch(ModelTerms{end},terms,'exact');
whichTerms(end+1) = tmp(1);
end
end
end
end
[ModelTerms idx] = unique(ModelTerms,'stable');
whichTerms = whichTerms(idx);
Effects = Effects(whichTerms);
iscontinuous = iscontinuous(whichTerms);
%%% Now partition the effects and put them with the proper error term
ti = 1:numel(ModelTerms);
DesignParts = [];
for ii = numel(eTerms):-1:1
tmp = eTerms{ii};
tmp = regexp(tmp,[random ':'],'split');
if numel(tmp)==1
if ~isempty(ti)
DesignParts{ii,1} = ti;
continue
else
continue
end
end
tmp = tmp{2};
i1 = contains(tmp,ModelTerms(ti));
% %%% New and Experimental
% for jj = 1:numel(Effects)
% if iscontinuous(jj);
% i1 = [i1(:); jj];
% end
% end
% i1 = unique(i1,'stable');
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DesignParts{ii,1} = ti(i1);
ti = setdiff(ti,ti(i1));
end
%%% Now Run/Setup the Model
RFMs = [];
if nargin>2 && ~isempty(posthocs)
spacer = size(char([ModelTerms 'Error' posthocs(:,1)']),2)+4;
else
spacer = size(char([ModelTerms 'Error' ]),2)+4;
end
if isconstant
C = [];
else
C = ones(Nobs,1);
end
effectResults = [];
for ii = 1:size(DesignParts,1);
if isempty(DesignParts{ii});
continue
end
if runModel && ~supress
fprintf(['\n%-' num2str(spacer) 's%s\t%s\t%s\t%s\t%s\n'],'','df','Sum Sq', 'Mean Sq','F-value', 'P-value');
end
%%% Compute the error
tx1 = [C Effects{DesignParts{ii}} ErrorTerms{ii}];
tx2 = [C Effects{DesignParts{ii}}];
r1 = eye(size(tx1,1))-(tx1*pinv(tx1));
r2 = eye(size(tx2,1))-(tx2*pinv(tx2));
edf = ResidualDFs(tx1)-ResidualDFs(tx2);
RFMs(ii).EDF = edf;
RFMs(ii).name = eTerms{ii};
RFMs(ii).tx1 = tx1;
RFMs(ii).tx2 = tx2;
if runModel
RSS = LoopEstimate(dat.(varname),1,r2-r1);
end
All = DesignParts{ii};
for jj = 1:numel(DesignParts{ii})
in = DesignParts{ii}(jj);
out = setdiff(DesignParts{ii},in);
tx1 = [C Effects{All}];
tx2 = [C Effects{out}];
dif = [Effects{in}];
%if ~isempty(contains('aschultz',{UserTime})); keyboard; end
r1 = eye(size(tx1,1))-(tx1*pinv(tx1));
r2 = eye(size(tx2,1))-(tx2*pinv(tx2));
if isempty(r2)
r2 = eye(Nobs);
end
df = ResidualDFs(tx1)-ResidualDFs(tx2);
RFMs(ii).Effect(jj).df = df;
RFMs(ii).Effect(jj).name = ModelTerms{DesignParts{ii}(jj)};
RFMs(ii).Effect(jj).tx1 = tx1;
RFMs(ii).Effect(jj).tx2 = tx2;
RFMs(ii).Effect(jj).dif = dif;
if runModel
RFMs(ii).MSE =RSS/edf;
SS = LoopEstimate(dat.(varname),1,r2-r1);
F = (SS/df)/(RSS/edf);
p = 1-spm_Fcdf(F,df,edf);
effectResults{end+1,1} = {ModelTerms{in},df,SS,SS/df,F,p};
if ~supress
fprintf(['%-' num2str(spacer) 's%0.0f\t%6.3f\t%6.3f\t%6.3f\t%1.6f\n'],ModelTerms{in},df,SS,SS/df,F,p);
end
end
end
if runModel && ~supress
fprintf(['%-' num2str(spacer) 's%0.0f\t%6.3f\t%6.3f\n'],'Error',edf,RSS,RSS/edf);
end
end
if nargin>2 && ~isempty(posthocs)
if runModel && ~supress
fprintf('\nPost Hocs:');
fprintf(['\n%-' num2str(spacer) 's%s\t%s\t%s\t%s\t%s\n'],'','df','Sum Sq', 'Mean Sq','F-value', 'P-value');
end
for ii = 1:size(posthocs,1)
[ttx1 ttx2 ET df track] = posthoc(posthocs{ii,1},[C Effects{:}],dat,eTerms);
tx1 = RFMs(ET).tx1;
tx2 = RFMs(ET).tx2;
r1 = eye(size(tx1,1))-(tx1*pinv(tx1));
r2 = eye(size(tx2,1))-(tx2*pinv(tx2));
edf = ResidualDFs(tx1)-ResidualDFs(tx2);
if runModel
RSS = LoopEstimate(dat.(varname),1,r2-r1);
end
tx1 = ttx1;
tx2 = ttx2;
r1 = eye(size(tx1,1))-(tx1*pinv(tx1));
r2 = eye(size(tx2,1))-(tx2*pinv(tx2));
if isempty(r2)
r2 = eye(Nobs);
end
df = ResidualDFs(tx1)-ResidualDFs(tx2);
if size(posthocs,2)>1 && ~isempty(posthocs{ii,2});
name = [posthocs{ii,2} ];
else
name = [posthocs{ii,1} ];
end
RFMs(ET).Effect(end+1).df = df;
RFMs(ET).Effect(end).name = name;
RFMs(ET).Effect(end).tx1 = tx1;
RFMs(ET).Effect(end).tx2 = tx2;
RFMs(ET).Effect(end).dif = [];
RFMs(ET).Effect(end).pieces = track;
if runModel
SS = LoopEstimate(dat.(varname),1,r2-r1);
F = (SS/df)/(RSS/edf);
p = 1-spm_Fcdf(F,df,edf);
effectResults{end+1,1} = {name,df,SS,SS/df,F,p};
if ~supress
fprintf(['%-' num2str(spacer) 's%0.0f\t%6.3f\t%6.3f\t%6.3f\t%1.6f\n'],name,df,SS,SS/df,F,p);
end
end
if runModel && ~supress
fprintf(['%-' num2str(spacer) 's%0.0f\t%6.3f\t%6.3f\n'],['ET #' num2str(ET)],edf,RSS,RSS/edf);
end
end
end
OUTPUT.EffTerms = ModelTerms;
OUTPUT.ErrTerms = eTerms;
OUTPUT.EffParts = Effects;
OUTPUT.ErrParts = ErrorTerms;
OUTPUT.X = [C Effects{:} ErrorTerms{1:end-1}];
OUTPUT.EffMod = [C Effects{:}];
OUTPUT.ErrMod = [C ErrorTerms{:}];
OUTPUT.DesignParts = DesignParts;
OUTPUT.RFMs = RFMs;
OUTPUT.const = isconstant;
OUTPUT.Results = effectResults;
% warning off
% OUTPUT.Beta = OUTPUT.X\dat.(varname);
% warning on
try
OUTPUT.Y = dat.(varname);
end
if runModel && ~supress
TSS = SumOfSquares(dat.(varname));
pred = PredictedData(dat.(varname),OUTPUT.X);
ESS = SumOfSquares(pred);
RSS = TSS-ESS;
%if ~isempty(contains('aschultz',{UserTime})); keyboard; end
mdf = ResidualDFs(OUTPUT.X)-1;
rdf = size(pred,1)-mdf-1;
R2 = ESS/TSS;
aR2 = R2 - ( (1-R2) * ( (mdf-1)/rdf) );
F = (ESS/mdf)/(RSS/rdf);
%F = (R2/mdf)/((1-R2)/rdf);
if isinf(F)
p=0;
else
p = 1-spm_Fcdf(F,mdf,rdf);
end
OUTPUT.ModelSummary.Y = dat.(varname);
OUTPUT.ModelSummary.TSS = TSS;
OUTPUT.ModelSummary.ESS = ESS;
OUTPUT.ModelSummary.RSS = RSS;
OUTPUT.ModelSummary.R2 = R2;
OUTPUT.ModelSummary.aR2 = aR2;
OUTPUT.ModelSummary.df = [mdf edf];
OUTPUT.ModelSummary.F = F;
OUTPUT.ModelSummary.p = p;
s1 = ['Model R^2 = ' sprintf('%0.3f',R2) '; Adjusted R^2 = ' sprintf('%0.3f',aR2)];
s2 = ['Model Stats: F(' num2str(mdf) ',' num2str(rdf) ') = ' sprintf('%0.3f',F) '; p = ' sprintf('%0.5d',p)];
fprintf('\n%s\n%s\n\n',s1,s2)
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [tx1 tx2 ET df track] = posthoc(contrast,X,data,ErrTerms)
cond4 = [];
extra = [];
flag = [];
step1 = regexprep(contrast,' ', '');
step2 = regexp(step1,'&','split');
for mm = 1:numel(step2);
step3 = regexp(step2{mm},'#','split');
cond3 = [];
track1 = {}; track2 = {};
for jj = 1:numel(step3)
cond2 = [];
step5 = regexp(step3{jj},'\|','split');
cond = [];
for kk = 1:numel(step5)
step6 = regexp(step5{kk},'\$','split');
track1(end+1,1:2) = step6;
track2{end+1,1} = step5{kk};
var = data.(step6{1});
if isnumeric(var)
cond = [cond demean(var)];
flag(kk) = 0;
else
flag(kk) = 1;
if iscell(var)
tmp = zeros(numel(var),1);
i1 = strmatch(step6{2},var,'exact');
tmp(i1)=1;
else
tmp = data.(step6{1})==step6{2};
end
cond = [cond tmp];
end
end
if any(flag)
cond2 = [cond2 prod(cond,2)];
else
cond2 = [cond2 cond];
end
if all(flag)
cond3 = [cond3 sum(cond2,2)>0];
else
cond3 = [cond3 cond2];
end
end
cond4 = [cond4 cond3];
if ~isempty(contains('#',step2(mm)))
extra = [extra mean(cond3,2)];
end
end
con = cond4;
tx1 = X;
tx2 = X;
tmp = [];
tr = [];
for ii = 1:size(con,2);
ind = find(con(:,ii)~=0);
tmp{ii} = ind;
in = [find(mean(X(ind,:)==repmat(con(ind,ii),1,size(X,2)))==1) find(mean(-X(ind,:)==repmat(con(ind,ii),1,size(X,2)))==1)];
tr = [tr in];
tx2(ind,in)=0;
end
tr = unique(tr);
if isempty(tr)
error('Invalid Contrast')
end
tx2 = [tx2 extra];
%%%
[a i] = unique(track2);
track = track1(i,:);
list = unique(track(:,1));
wh = [];
for ii = 1:numel(list)
cc = numel(strmatch(list{ii},track1(:,1),'exact'));
if cc>1
if ~isempty(contains(list{ii},ErrTerms))
wh{end+1} = contains(list{ii},ErrTerms);
end
end
end
if isempty(wh) || isempty(wh{1})
ET = 1;
else
ET = intersections(wh);
ET = ET(1);
end
df = ResidualDFs(tx1)-ResidualDFs(tx2);
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
GLM_Flex_Fast4.m
|
.m
|
MRtools_Hoffman2-master/GLM_Flex/GLM_Flex_Fast4.m
| 32,993 |
utf_8
|
665480c5b8fe81966f67d6063cd16455
|
function I = GLM_Flex_Fast4(I,DD)
%%% This is the main analysis script.
%%% Go to: http://nmr.mgh.harvard.edu/harvardagingbrain/People/AaronSchultz/Aarons_Scripts.html
%%% for more information on this script and how to use it.
%%%
%%% Inputs: This is the I structure that is passed to GLM_Flex to run the
%%% analyses.
%%%
%%%
%%% I.Model = 'the model'
%%% I.Data = dat;
%%% I.Posthocs = [];
%%% I.OutputDir = pwd;
%%% I.F = [];
%%% I.Scans = [];
%%% I.Mask = [];
%%% I.RemoveOutliers = 0;
%%% I.DoOnlyAll = 0;
%%% I.minN = 2;
%%% I.minRat = 0;
%%% I.Thresh = [];
%%% I.writeI = 1;
%%% I.writeT = 1;
%%% I.writeFin = 0;
%%% I.KeepResiduals = 0;
%%% I.estSmooth = 1;
%%% I.Transform.FisherZ = 0;
%%% I.Transform.AdjustR2 = 0;
%%% I.Transform.ZScore = 0;
%%% I.Reslice = 0;
%%% I.covCorrect = 0;
%%%
%%% Written by Aaron Schultz ([email protected])
%%%
%%% Copyright (C) 2011, Aaron P. Schultz
%%%
%%% Supported in part by the NIH funded Harvard Aging Brain Study (P01AG036694) and NIH R01AG027435
%%%
%%% 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
%%% 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.
%if ~contains('aschultz', {UserTime}); error('Aaron is currently reworking this script. Check with him to see when it will be functional again.'); end
if isfield(I,'PostHocs') && ~isempty(I.PostHocs)
MOD = ANOVA_APS(I.Data,I.Model,I.PostHocs,0,1,1);
else
MOD = ANOVA_APS(I.Data,I.Model,[],0,1,1);
end
tx1 = [MOD.X];
tx2 = ones(size(tx1,1),1);
df = ResidualDFs(tx1)-ResidualDFs(tx2);
dif = tx1;
if ~all([numel(MOD.RFMs) numel(MOD.RFMs(1).Effect)])
MOD.RFMs(end).Effect(end+1).df = df;
MOD.RFMs(end).Effect(end).name = 'FullModel';
MOD.RFMs(end).Effect(end).tx1 = tx1;
MOD.RFMs(end).Effect(end).tx2 = tx2;
MOD.RFMs(end).Effect(end).dif = dif;
end
I.MOD = MOD;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Setup/Check the I Structure
%%
fprintf('\nSetup/Check the I Structure:\n');
if ~isfield(I,'DoOnlyAll')
I.DoOnlyAll = 0;
end
if ~isfield(I,'ZeroDrop')
I.ZeroDrop = 1;
end
if ~isfield(I,'OutputDir')
I.OutputDir = pwd;
else
if exist(I.OutputDir)==0
mkdir(I.OutputDir);
end
cd(I.OutputDir);
end
if ~isfield(I,'writeT')
I.writeT = 1;
end
if ~isfield(I,'minN')
I.minN = 2;
end
if ~isfield(I,'minRAT')
I.minRAT = 0;
end
if ~isfield(I,'RemoveOutliers');
I.RemoveOutliers = 0;
end
if ~isfield(I,'Thresh');
I.Thresh = [];
end
if ~isfield(I,'writeFin');
I.writeFin = 0;
end
if ~isfield(I,'writeI');
I.writeI = 1;
end
if ~isfield(I,'KeepResiduals');
I.KeepResiduals = 0;
end
if ~isfield(I,'Reslice');
I.Reslice = 0;
end
if ~isfield(I,'estSmooth');
I.estSmooth = 1;
end
if ~isfield(I,'covCorrect');
I.covCorrect = 0;
end
if I.DoOnlyAll==1;
I.minN=0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Read In The Data
%%
if isfield(I,'Scans');
fprintf('\nReading In Data:\n');
h = spm_vol(char(I.Scans));
if ~any(h(1).dim==1)
if mean(mean(std(reshape([h.mat],4,4,numel(h)),[],3)))~=0
error('Images are not all the same orientation');
end
end
I.v = h(1);
FullIndex = 1:prod(I.v.dim);
mskInd = 1:prod(I.v.dim);
mskOut = [];
if isfield(I,'Mask');
if ~isempty(I.Mask)
mh = spm_vol(I.Mask);
msk = resizeVol(mh,I.v);
mskInd = find(msk==1);
mskOut = find(msk~=1);
end
end
if nargin == 1
% if isstruct(I.Reslice)
% else
[x y z] = ind2sub(I.v.dim,mskInd);
OD = zeros(numel(h),numel(x));
for ii = 1:numel(h);
OD(ii,:) = spm_sample_vol(h(ii),x,y,z,0);
end
% end
else
OD = DD(:,mskInd);
end
if I.ZeroDrop == 1
OD(OD==0)=NaN;
end
% %%% Add in some missing values.
% tmp = randperm(numel(OD));
% OD(tmp(1:10000))=NaN;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Screen Missing Data for Within Subject Factors;
if numel(MOD.ErrParts)>1
Subs = I.Data.(MOD.ErrTerms{1});
list = unique(Subs);
for ii = 1:numel(list);
if iscell(Subs)
try
i2 = find(nominal(Subs)==list{ii});
catch
i2 = contains(['^' list{ii} '$'],Subs);
end
else
i2 = find(Subs==list(ii));
end
i3 = find(isnan(sum(OD(i2,:))));
OD(i2,i3)=NaN;
end
end
counts = sum(~isnan(OD));
ind = (find(counts>=I.minN));
MasterInd = mskInd(ind);
OD = OD(:,ind);
counts = counts(ind);
else
error('No images were specified.');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Perform Specified Transformations
%%
fprintf('\nPerform Specified Transformations:\n');
if isfield(I,'Transform')
if isfield(I.Transform,'FisherZ')
if I.Transform.FisherZ == 1;
OD = atanh(OD);
disp('FisherZ transform worked!');
end
end
if isfield(I.Transform,'AdjustR2')
if I.Transform.AdjustR2 == 1;
OD = atanh(sqrt(OD));
disp('R2 adjust worked!');
end
end
if isfield(I.Transform,'ZScore')
if I.Transform.ZScore == 1;
OD = zscore(OD,0,1);
disp('Normalization worked!');
end
end
if isfield(I.Transform,'Scale')
if numel(I.Transform.Scale) == numel(I.Scans);
for ii = 1:size(OD,1);
OD(ii,:) = (OD(ii,:)+1).*(I.Transform.Scale(ii));
end
disp('Scaling worked!');
end
end
if isfield(I.Transform,'crtlFor')
I.writeFin = 1;
OD = crtlFor(OD,[ones(size(I.Transform.crtlFor,1),1) I.Transform.crtlFor]);
disp('residualizing worked!');
end
if isfield(I.Transform,'log')
I.writeFin = 1;
OD = log(OD);
disp('data has been log-transformed!');
end
if isfield(I.Transform,'Power')
I.writeFin = 1;
OD = (OD.^I.Power);
disp('data has been log-transformed!');
end
if isfield(I.Transform,'MapNorm')
if I.Transform.MapNorm == 1;
I.writeFin = 1;
OD = OD';
OD = (OD-repmat(nanmean(OD),size(OD,1),1))./repmat(nanstd(OD),size(OD,1),1);
OD = OD';
%OD = zscore(OD',0,1)';
disp('MapNorm worked!');
end
end
if isfield(I.Transform,'Smooth')
if numel(I.Transform.Smooth) == 3;
I.writeFin = 1;
tmp = spm_imatrix(I.v.mat);
tmp = abs(tmp(7:9));
k = smoothing_kernel(I.Transform.Smooth,tmp);
%keyboard;
OD(isnan(OD))=0;
vol = zeros(I.v.dim);
for ii = 1:size(OD,1);
vol(:) = OD(ii,:);
nm = convn(vol,k,'same');
OD(ii,:) = nm(:)';
end
OD(OD==0)=NaN;
disp('Smoothing worked!');
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Initialize Variables
%%
fprintf('\nIntialize Variable and Output Structures\n');
BMdim = [numel(h) prod(I.v.dim)];
maxLL = numel(h);
Indices = {};
Ls = [];
Outliers = {[]};
oCy = repmat({zeros(maxLL,maxLL)},numel(I.MOD.RFMs),1);
oN = repmat({zeros(maxLL,maxLL)},numel(I.MOD.RFMs),1);
First = 0;
BigCount = 0; %% was 1 before. make sure this isn't a problem.
%%% Get the Design Matrix
X = MOD.X;
I.X = X;
I.Vi = eye(size(X,1));
%%% Setup Objects for Output Images
ss = I.v.dim;
NN = nan(ss);
ResMS = cell(1,numel(MOD.RFMs));
ResMS(:) = {NN};
nn = 0;
for ii = 1:numel(MOD.RFMs)
nn = nn+numel(MOD.RFMs(ii).Effect);
end
Con = cell(1,nn);
Con(:) = {NN};
Stat = cell(1,nn);
Stat(:) = {NN};
if size(I.X,1)~=maxLL
error('Design Matrix does not match input volumes');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q = 1 %% Calculate Possible Grouptings
%%
if ~MOD.const
AllColNames = {'Constant'};
else
AllColNames = {};
end
Groupings = [];
for jj = 1:numel(MOD.EffTerms)
EffList = regexp(MOD.EffTerms{jj},'[\*\:]','split');
AllColNames(end+1:end+size(MOD.EffParts{jj},2)) = {MOD.EffTerms{jj}};
if numel(EffList)>1
continue
end
tmp = {}; tmp{1} = [];
for ii = 1:numel(EffList)
tDat = I.Data.(EffList{ii});
if isnumeric(tDat)
continue
end
tmp{ii} = makedummy(tDat);
end
if numel(tmp)>1
Groupings = [Groupings FactorCross(tmp)];
else
Groupings = [Groupings tmp{1}];
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if I.covCorrect == 1
I.VV = getVI(I.MOD);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Perform initial pass to evaluate for missing data, outliers, and computation of the covariance matrix.
%%
nOut = 0;
persisText
for ll = size(X,1):-1:I.minN
%%% Find the indices where the number of observations matches the current loop.
CurrIndex = find(counts==ll);
if isempty(CurrIndex)
continue
end
BigCount = BigCount+1;
Ls(BigCount) = ll;
%%% This Section computes different combinations of N size ll across
%%% the groups specified in the design matrix.
ss = size(OD(:,CurrIndex));
if I.DoOnlyAll ~= 1
if ll == maxLL
ch = [1 numel(CurrIndex)];
uni = 1:numel(h);
II = 1:ss(2);
else
rr = ~isnan(OD(:,CurrIndex)).*repmat((1:size(X,1))',1,ss(2));
rr = rr';
[rr II] = sortrows(rr,(1:size(rr,2))*-1);
tt = sum(abs(diff(rr~=0)),2)>0;
ind = find(tt==1);
ch = [[1; ind+1] [ind; numel(II)]];
ch = ch((diff(ch,1,2)>=0),:);
uni = rr(ch(:,1),:);
CurrIndex = CurrIndex(II);
end
else
ch = [1 numel(CurrIndex)];
uni = 1:numel(h);
II = 1:ss(2);
end
Outliers{BigCount}=[];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Loop through specific designs for ll observations
for ii = 1:size(ch,1)
persisText(['Examining Set #' num2str(ll) ': SubModel ' num2str(ii) ' of ' num2str(size(ch,1)) '; Nvox = ' num2str(numel(ch(ii,1):ch(ii,2)))]);
%%% Get the observation index for the current design
Xind = uni(ii,:);
Xind = Xind(Xind>0);
%%% Subset the design matrix
xx = X(Xind,:);
%%% Make sure there is enough data across conditions.
Ns = sum(Groupings(Xind,:));
if ~all(Ns>=I.minN)
continue;
end
if min(Ns)/max(Ns) < I.minRAT;
continue;
end
%%% get the global index of the voxels being analyzed
vec = CurrIndex((ch(ii,1):ch(ii,2)));
%%% Get the correponding data to be analyzed
Y = OD(Xind,vec);
%%% Outlier Detection Compute Cook's D
for q =1
if I.RemoveOutliers == 1;
df1 = ResidualDFs(xx);
df2 = MOD.RFMs(end).EDF;
%%% Run a basic GLM
pv = pinv(xx);
pv(abs(pv)<eps*(size(xx,1)))=0;
beta = pv*Y;
pred = xx*beta;
res = Y-pred;
ResSS = sum(res.^2);
MSE = ResSS./df2;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
e2 = res.^2;
p = size(xx,2);
bc = pinv(xx'*xx);
bc(abs(bc)<eps*(size(xx,1)))=0;
tmp = diag(xx*bc*xx');
CD = (e2./(p*repmat(MSE,size(e2,1),1))) .* (repmat(tmp./((1-tmp).^2),1,size(e2,2)));
if ~isempty(I.Thresh)
thresh = spm_invFcdf(I.Thresh,[df1 df2-1]);
else
thresh = spm_invFcdf(.5,[df1 df2-1]);
end
[mm,ith] = max(CD);
a = find(mm>thresh);
nOut = nOut+numel(a);
persisText(['Examining Set #' num2str(ll) ': SubModel ' num2str(ii) ' of ' num2str(size(ch,1)) '; Nvox = ' num2str(numel(ch(ii,1):ch(ii,2))) '; Found ' num2str(nOut) ' outliers so far:']);
if ~isempty(a)
rows = Xind(ith(a));
cols = vec(a);
Outliers{BigCount} = [Outliers{BigCount} sub2ind(BMdim,rows,MasterInd(cols))];
OD(sub2ind(size(OD),rows,cols))=NaN;
if numel(MOD.ErrParts)>1
for jj = 1:numel(rows);
if iscell(I.Data.(MOD.ErrTerms{1}));
i1 = contains(['^' I.Data.(MOD.ErrTerms{1}){rows(jj)} '$'],I.Data.(MOD.ErrTerms{1}));
else
i1 = find(I.Data.(MOD.ErrTerms{1}) == I.Data.(MOD.ErrTerms{1})(rows(jj)));
end
OD(i1,cols(jj)) = NaN;
end
counts(cols)=sum(~isnan(OD(:,cols)));
else
counts(cols)=counts(cols)-1;
end
end
a = find(mm<thresh);
else
a = 1:numel(vec);
end
end
%%% If there are no voxels free of outliers, continue
if isempty(a)
continue;
end
First = First+1;
if First == 1;
hh = I.v;
tmp = nan(hh.dim);
tmp(MasterInd(vec(a)))=1;
hh.dt = [2 0];
writeIMG(hh,tmp,'AllMask.nii');
end
%%% Subset data to only those voxels without outliers
Y = Y(:,a);
Indices{First,1} = vec(a);
Indices{First,2} = Xind;
if I.covCorrect==1
for jj = 1:numel(I.MOD.RFMs)
if isempty(I.MOD.RFMs(jj).tx1)
continue
end
tx1 = I.MOD.RFMs(jj).tx1(Xind,:);
tx2 = I.MOD.RFMs(jj).tx2(Xind,:);
if size(tx1,2)==1
df2=1;
else
[z1 z2 z3] = svd(tx1);
tol = max(size(tx1))*max(abs(diag(z2)))*eps;
df2 = sum(diag(z2)>tol);
end
df2 = df2-1;
if size(tx2,2)==1
df1=1;
else
[z1 z2 z3] = svd(tx2);
tol = max(size(tx2))*max(abs(diag(z2)))*eps;
df1 = sum(diag(z2)>tol);
end
df1 = df1-1;
df2 = df2-df1;
SSm = makeSSmat(tx2,ones(size(tx2,1)));
SS1 = LoopEstimate(Y,1,SSm);
SSm = makeSSmat(tx1,ones(size(tx1,1)));
SS2 = LoopEstimate(Y,1,SSm);
SS2 = SS2-SS1;
FF = (SS1/df1)./(SS2/df2);
UF = spm_invFcdf(1-.001,[df1 df2]);
%%% Get the index of voxels where the full model p is less than 0.001
mv = find(FF>UF);
cn = numel(mv);
%%% Pool variance across voxels
if ~isempty(mv)
q = spdiags(sqrt(df2./SS2(mv)'),0,cn,cn);
YY = Y(:,mv)*q;
Cy = (YY*YY');
oCy{jj}(Xind,Xind) = oCy{jj}(Xind,Xind)+Cy;
oN{jj}(Xind,Xind) = oN{jj}(Xind,Xind)+cn;
else
Cy = [];
end
end
else
V = eye(size(xx,1));
end
end
if I.DoOnlyAll==1
break;
end
end
for ii = 1:numel(oCy);
oCy{ii} = oCy{ii}./oN{ii};
end
I.oCy = oCy;
I.oN = oN;
persisText;
fprintf('\n\n');
if First==0
error('Nothing ws analyzed, make sure that I.minN is not set too high');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Write out mask images
%%
v = I.v;
v.dt = [64 0];
writeIMG(v,NN,'NN.nii');
writeIMG(v,NN>0,'mask.nii');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Perform unitary variance/covariance reml correction to be sub-indexed below
% keyboard;
rX = getREMLdm(I.MOD);
for ii = 1:numel(I.MOD.RFMs);
if I.covCorrect==1
Vi = I.VV{ii};
if isempty(Vi)
I.W{ii} = eye(size(OD,1));
continue
end
%%% Possible reduced correction due to use of overspecified
%%% model. Might need to see about altering the error term in
%%% the model.
xxW = rX{ii};
[V h] = spm_reml(oCy{ii},xxW,Vi);
I.V{ii}=V;
V = V*size(xxW,1)/trace(V);
W = full(spm_sqrtm(spm_inv(V)));
W = W.*(abs(W) > 1e-6);
I.W{ii} = W;
clear V W;
else
I.W{ii} = eye(size(OD,1));
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Compute Statistics
%%
fileNames = []; conDFs = []; type = {};
persisText;
for ll = 1:size(Indices,1);
persisText(['Analysing Sub-Model #' num2str(ll) ' of ' num2str(size(Indices,1)) '; ' num2str(numel(Indices{ll,2})) ' Observations, across ' num2str(numel(Indices{ll,1})) ' Voxels.' ]);
Xind = Indices{ll,2};
vec = Indices{ll,1};
counter = 0;
%%% Compute Error
for ii = 1:numel(MOD.RFMs);
if isempty( MOD.RFMs(ii).tx1)
continue
end
%%%%%%%% Var/Covar correct %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Y = I.W{ii}*OD(Xind,vec);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
tx1 = I.W{ii}*MOD.RFMs(ii).tx1(Xind,:);
tx2 = I.W{ii}*MOD.RFMs(ii).tx2(Xind,:);
edf = ResidualDFs(tx1)-ResidualDFs(tx2);
if ll==1; masterDF(ii) = edf; end
[SSm] = makeSSmat(tx1,tx2);
if I.estSmooth == 1 && ll == 1
[RSS Res] = LoopEstimate(Y,1,SSm);
Res = Res./repmat(sqrt(RSS/edf)',1,size(Res,2));
tm = [pwd '/ResAll_' sprintf('%0.2d',ii)];
warning off;
delete([tm '.nii']); delete([tm '.mat']);
warning on;
v = I.v;
v.fname = [tm '.nii'];
vol = nan(v.dim);
for jj = 1:size(Res,2);
vol(MasterInd(vec)) = Res(:,jj);
v.n = [jj 1];
spm_write_vol(v,vol);
end
fprintf('\n');
h = spm_vol(v.fname);
[FWHM,VRpv,R] = spm_est_smoothness(h,spm_vol('AllMask.nii'),[numel(h) edf]);
I.FWHM{ii} = FWHM;
try
[tmpM tmpH] = openIMG('RPV.img');
catch
[tmpM tmpH] = openIMG('RPV.nii');
end
tmpH.fname = ['RPV' tm(end-2:end) '.nii'];
spm_write_vol(tmpH,tmpM);
delete('RPV.*')
if I.KeepResiduals==0
delete ResAll_*.nii;
delete ResAll_*.mat;
end
clear Res;
persisText();
persisText(['Analysing Sub-Model #' num2str(ll) ' of ' num2str(size(Indices,1)) '; ' num2str(numel(Indices{ll,2})) ' Observations, across ' num2str(numel(Indices{ll,1})) ' Voxels.' ]);
else
RSS = LoopEstimate(Y,1,SSm);
end
ResMS{ii}(MasterInd(vec)) = RSS./edf;
for jj = 1:numel(MOD.RFMs(ii).Effect)
counter = counter+1;
tx1 = I.W{ii}*MOD.RFMs(ii).Effect(jj).tx1(Xind,:);
if isempty(MOD.RFMs(ii).Effect(jj).tx2)
tx2 = zeros(size(tx1,1),1);
df = ResidualDFs(tx1);
SSm = makeSSmat(tx1,tx2);
else
tx2 = I.W{ii}*MOD.RFMs(ii).Effect(jj).tx2(Xind,:);
df = ResidualDFs(tx1)-ResidualDFs(tx2);
SSm = makeSSmat(tx1,tx2);
end
ESS = LoopEstimate(Y,1,SSm);
Fstat = (ESS./df) ./ (RSS./edf);
conDFs(end+1,1:2) = [df edf];
name = MOD.RFMs(ii).Effect(jj).name;
fileNames{end+1} = name;
if I.writeT == 1 && df==1 && isempty(contains('[\*|\:]',{name})) && ~strcmpi('FullModel',name);
test = 'T';
tol = max(size(tx2)) * eps(norm(tx2));
[U,sigma,R] = svd(tx2);
atx2 = tx2*R;
atx2 = atx2(:,find(diag(sigma)>tol));
nm = tx1-(atx2*(atx2\tx1));
[U,sigma,R] = svd(nm);
tmp = abs([max(R); min(R)]);
[trash,i1] = max(tmp); i1(i1==2)=-1;
for kk = 1:size(R,2); R(:,kk) = R(:,kk)*i1(kk); end
nm = nm*R;
nm = nm(:,find(diag(sigma)>tol));
b = pinv(nm)*Y;
con = sum(b,1);
else
test = 'F';
con = ESS./df;
end
type{end+1} = test;
if edf~=masterDF(ii)
p = spm_Fcdf(Fstat,df,edf);
Fstat2 = spm_invFcdf(p,df,masterDF(ii));
Fstat2(isinf(Fstat2))=Fstat(isinf(Fstat2));
Fstat = Fstat2;
end
if strcmpi(test,'T')
Stat{counter}(MasterInd(vec)) = sqrt(Fstat).*sign(con);
Con{counter}(MasterInd(vec)) = con;
else
Stat{counter}(MasterInd(vec)) = Fstat;
Con{counter}(MasterInd(vec)) = con;
end
end
end
end
fprintf('\n\n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Write Out Mat-Files
%%
fprintf('\n\nWriting out mat files...\n');
c = 0;
for ii = 1:numel(Outliers);
c = c+numel(Outliers{ii});
end
if c>0
OL{1} = zeros(c,1);
OL{2} = zeros(c,2);
st = 0;
for ii = 1:numel(Outliers)
tmp = Outliers{ii};
if ~isempty(tmp)
OL{1}(st+1:st+numel(tmp))=tmp;
[row col] = ind2sub(BMdim,tmp);
OL{2}(st+1:st+numel(tmp),:)=[row(:),col(:)];
st = st+numel(tmp);
end
end
I.OL = OL;
end
if I.writeI == 1;
save I.mat I -v7.3;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for q=1 %% Write Out Image Files
%%
fprintf('\n\nWriting out image files...\n');
v = I.v;
v.dt = [64 0];
for ll = 1:length(ResMS);
tm = ['ResMS_' sprintf('%0.2d',ll)];
writeIMG(v,ResMS{ll},[tm '.nii']);
end
for jj = 1:numel(Con)
delete(['*' sprintf('%0.4d',jj) '*.nii'])
fileNames{jj} = regexprep(fileNames{jj},':','_x_');
if strcmpi(type{jj},'T')
tm = [sprintf('%0.4d',jj) '_T_' fileNames{jj} '.nii'];
hold = v.descrip;
v.descrip = ['SPM{T_' '[' num2str(conDFs(jj,2)) ']} - created with GLM_Flex_Fast'];
writeIMG(v,Stat{jj},tm);
v.descrip = hold;
tm = ['con_' sprintf('%0.4d',jj) '.nii'];
writeIMG(v,Con{jj},tm);
end
if strcmpi(type{jj},'F')
tm = [sprintf('%0.4d',jj) '_F_' fileNames{jj} '.nii'];
hold = v.descrip;
v.descrip = ['SPM{F_' '[' num2str(conDFs(jj,1)) ',' num2str(conDFs(jj,2)) ']} - created with GLM_Flex_Fast'];
writeIMG(v,Stat{jj},tm);
v.descrip = hold;
tm = ['ess_' sprintf('%0.4d',jj) '.nii'];
writeIMG(v,Con{jj},tm);
end
end
if I.writeFin == 1;
fprintf('\nWriting out finalized data set ...\n');
v.descrip = 'Original data set with outliers removed.';
vol = nan(v.dim);
v.n = [1 1];
v.fname = 'FinalDataSet.nii';
for ii = 1:size(OD,1)
vol(MasterInd) = OD(ii,:);
v.n = [ii 1];
spm_write_vol(v,vol);
end
end
fprintf('\nAll Done!\n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end %% End of Main Function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function VV = getVI(mod)
P = [];
i1 = numel(mod.RFMs);
VV = [];
%%%
for ii = 1:i1
factor = [];
FM = ones(size(mod.X,1),1);
c = 0;
part = mod.RFMs(ii);
for jj = 1:numel(part.Effect)
Eff = part.Effect(jj);
if any(Eff.name==':') && jj==1
terms = regexp(Eff.name,':', 'split');
% factor = F1;
% FM = F2;
c = numel(factor);
for kk = 1:numel(terms)
a = makedummy(mod.data.(terms{kk}))*(1:numel(unique(mod.data.(terms{kk}))))';
FM(:,end+1) = a;
c = c+1;
factor(c).name = terms{kk};
factor(c).levels = numel(unique(mod.data.(terms{kk})));
factor(c).gmsca = 0;
factor(c).ancova = 0;
factor(c).variance = 1;
factor(c).dept = 1;
end
else
if any(Eff.name==':')
continue
end
if strcmpi(Eff.name,'FullModel')
continue
end
if isnumeric(mod.data.(Eff.name))
continue
end
a = makedummy(mod.data.(Eff.name))*(1:numel(unique(mod.data.(Eff.name))))';
FM(:,end+1) = a;
c = c+1;
factor(c).name = Eff.name;
factor(c).levels = numel(unique(mod.data.(Eff.name)));
factor(c).gmsca = 0;
factor(c).ancova = 0;
factor(c).variance = 1;
if ii==1
FM = [ones(size(FM,1),1) FM];
factor(c).dept = 0;
F1 = factor;
F2 = FM;
else
factor(c).dept = 1;
end
end
P(ii).factor = factor;
P(ii).FM = FM;
end
if isempty(factor);
continue
end
if strfind(lower(spm('version')),'spm8')
clear SPM;
SPM.factor = factor;
SPM.xVi.I = FM;
SPM = spm_get_vc(SPM);
try
VV{ii} = SPM.xVi.Vi;
catch
VV{ii} = {SPM.xVi.V};
end
end
if strfind(lower(spm('version')),'spm12')
Vi = spm_get_vc(FM,factor);
VV{ii} = Vi;
end
end
save tmp.mat P;
end
function X = getREMLdm(mod)
X = [];
L = mod.RFMs;
for ii = 1:numel(L);
if isempty(L(ii).name)
X{ii} = [];
continue
end
parts = regexp(L(ii).name,':','split');
n = numel(parts);
sets = combnk(1:n,n-1);
tmp = L(ii).tx2;
if ~isempty(sets)
for jj = 1:size(sets,1)
in = [];
if any(sets(jj,:)==1)
for kk = 1:size(sets,2)
in{end+1} = makedummy(mod.data.(parts{sets(jj,kk)}),1);
end
else
continue
end
tmp = [tmp FactorCross(in)];
end
end
X{ii} = tmp;
end
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
inria_realign.m
|
.m
|
MRtools_Hoffman2-master/fcMRI_scripts/inria_realign.m
| 24,047 |
utf_8
|
a6b6c891554c9808aa903c6f4f947d63
|
function inria_realign(P,flags)
% Robust rigid motion compensation in time series.
% FORMAT inria_realign(P,flags)
%
% Similar to spm_realign.m.
%
% P - matrix of filenames {one string per row}
% All operations are performed relative to the first image.
% ie. Coregistration is to the first image, and resampling
% of images is into the space of the first image.
% For multiple sessions, P should be a cell array, where each
% cell should be a matrix of filenames.
%
% flags - a structure containing various options. The fields are:
%
% rho_func - A string indicating the cost function that
% will be used to caracterize intensity errors.
% Possible choices are :
%
% 'quadratic' - fast, but not robust...
% 'absolute' - quite slow, not very robust
% 'huber' - Huber function
% 'cauchy' - Cauchy function
% 'geman' - Geman-McClure function
% 'leclerc' - Leclerc-Welsch function
% 'tukey' - Tukey's biweight function
%
% DEFAULT: 'geman', usually a good trade-off
% between robustness and speed.
%
% cutoff - Most of the rho functions listed above require
% an extra-parameter called the cut-off distance
% (exceptions are 'quadratic' and 'absolute'). The
% cut-off value is set proportionally to the
% standard deviation of the noise (which is
% estimated in course of registration using the
% median of absolute deviations). The
% proportionality factor, however, may be set by the
% user according to the considered rho-function.
%
% DEFAULT: 2.5.
%
% The remaining flags are the same as in spm_realign:
%
% quality - Quality versus speed trade-off. Highest quality
% (1) gives most precise results, whereas lower
% qualities gives faster realignment.
% The idea is that some voxels contribute little to
% the estimation of the realignment parameters.
% This parameter is involved in selecting the number
% of voxels that are used.
%
% fwhm - The FWHM of the Gaussian smoothing kernel (mm)
% applied to the images before estimating the
% realignment parameters.
%
% sep - the default separation (mm) to sample the images.
%
% rtm - Register to mean. If field exists then a two pass
% procedure is to be used in order to register the
% images to the mean of the images after the first
% realignment.
%
% PW - a filename of a weighting image (reciprocal of
% standard deviation). If field does not exist, then
% no weighting is done.
%
% hold - hold for interpolation (see spm_slice_vol and
% spm_sample_vol).
%
%__________________________________________________________________________
%
% Inputs
% A series of *.img conforming to SPM data format (see 'Data Format').
%
% Outputs
% The parameter estimation part writes out ".mat" files for each of the
% input images. The details of the transformation are displayed in the
% results window as plots of translation and rotation.
% A set of realignment parameters are saved for each session, named:
% realignment_params_*.txt.
%__________________________________________________________________________
%
% The `.mat' files.
%
% This simply contains a 4x4 affine transformation matrix in a variable `M'.
% These files are normally generated by the `realignment' and
% `coregistration' modules. What these matrixes contain is a mapping from
% the voxel coordinates (x0,y0,z0) (where the first voxel is at coordinate
% (1,1,1)), to coordinates in millimeters (x1,y1,z1). By default, the
% the new coordinate system is derived from the `origin' and `vox' fields
% of the image header.
%
% x1 = M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4)
% y1 = M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4)
% z1 = M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4)
%
% Assuming that image1 has a transformation matrix M1, and image2 has a
% transformation matrix M2, the mapping from image1 to image2 is: M2\M1
% (ie. from the coordinate system of image1 into millimeters, followed
% by a mapping from millimeters into the space of image2).
%
% These `.mat' files allow several realignment or coregistration steps to be
% combined into a single operation (without the necessity of resampling the
% images several times). The `.mat' files are also used by the spatial
% normalisation module.
%__________________________________________________________________________
% @(#)inria_realign.m 1.01 Alexis Roche 01/03/08
% based on spm_realign.m 2.27 John Ashburner 99/10/26
if nargin==0, inria_realign_ui; return; end;
def_flags = struct('quality',1,'fwhm',6,'sep',4.5,'hold',-8,...
'rho_func','geman','cutoff',2.5);
if nargin < 2,
flags = def_flags;
else,
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags = setfield(flags,fnms{i},getfield(def_flags,fnms{i}));
end;
end;
end;
linfun = inline('fprintf('' %-60s%s'', x,sprintf(''\b'')*ones(1,60))');
% if ~isstruct(P)
if isempty(P), warning('Nothing to do'); return; end;
if ~iscell(P), tmp = cell(1); tmp{1} = P; P = tmp; end;
P = spm_vol(P);
if isfield(flags,'PW'), flags.PW = spm_vol(flags.PW); end;
% end
if length(P)==1,
linfun('Registering images..');
P{1} = realign_series(P{1},flags);
save_parameters(P{1});
else,
linfun('Registering together the first image of each session..');
%%% I might be able to tweak something here.
Ptmp = P{1}(1);
for s=2:prod(size(P)),
Ptmp = [Ptmp ; P{s}(1)];
end;
Ptmp = realign_series(Ptmp,flags);
for s=1:prod(size(P)),
M = Ptmp(s).mat*inv(P{s}(1).mat);
for i=1:prod(size(P{s})),
P{s}(i).mat = M*P{s}(i).mat;
end;
end;
for s=1:prod(size(P)),
linfun(['Registering together images from session ' num2str(s) '..']);
P{s} = realign_series(P{s},flags);
save_parameters(P{s});
end;
end;
% Save Realignment Parameters
%---------------------------------------------------------------------------
linfun('Saving parameters..');
for s=1:prod(size(P)),
for i=1:prod(size(P{s})),
if strmatch(P{s}(i).fname(end-2:end), 'nii')
%%% Alright, so this is all it took to get it straightend out.
spm_get_space([P{s}(i).fname ',' num2str(i)], P{s}(i).mat);
else
spm_get_space(P{s}(i).fname, P{s}(i).mat);
end
end;
end;
plot_parameters(P,flags);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function P = realign_series(P,flags)
% Realign a time series of 3D images to the first of the series.
% FORMAT P = realign_series(P,flags)
% P - a vector of volumes (see spm_vol)
%-----------------------------------------------------------------------
% P(i).mat is modified to reflect the modified position of the image i.
% The scaling (and offset) parameters are also set to contain the
% optimum scaling required to match the images.
%_______________________________________________________________________
if prod(size(P))<2, return; end;
lkp = [1 2 3 4 5 6];
if P(1).dim(3) < 3, lkp = [1 2 6]; end;
% Robust estimation flags
%-----------------------------------------------------------------------
flagSSD = (flags.cutoff == Inf | strcmp(lower(flags.rho_func), 'quadratic'));
flagSAD = strcmp(lower(flags.rho_func), 'absolute');
% Points to sample in reference image
%-----------------------------------------------------------------------
skip = sqrt(sum(P(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
d = P(1).dim(1:3);
[x1,x2,x3]=ndgrid(1:skip(1):d(1),1:skip(2):d(2),1:skip(3):d(3));
x1 = x1(:);
x2 = x2(:);
x3 = x3(:);
% Possibly mask an area of the sample volume.
%-----------------------------------------------------------------------
if isfield(flags,'PW'),
[y1,y2,y3]=coords([0 0 0 0 0 0],P(1).mat,flags.PW.mat,x1,x2,x3);
wt = spm_sample_vol(flags.PW,y1,y2,y3,1);
msk = find(wt>0.01);
x1 = x1(msk);
x2 = x2(msk);
x3 = x3(msk);
wt = wt(msk);
else,
wt = [];
end;
n = prod(size(x1));
% Compute rate of change of (robust) chi2 w.r.t changes in parameters (matrix A)
%--------------------------------------------------------------------------------
V = smooth_vol(P(1),flags.fwhm);
[G,dG1,dG2,dG3] = spm_sample_vol(V,x1,x2,x3,flags.hold);
clear V
A0 = make_A(P(1).mat,x1,x2,x3,dG1,dG2,dG3,lkp);
%----------------------------------------------------------------------
% Depending on flags.quality, remove a certain percentage of voxels
% that contribute little to the final estimate. It basically
% involves removing the voxels that contribute least to the
% determinant of the inverse covariance matrix.
if flags.quality < 1,
% spm_chi2_plot('Init','Eliminating Unimportant Voxels',...
% 'Fractional loss of quality','Iteration');
spm_plot_convergence('Init','Eliminating Unimportant Voxels','Fractional loss of quality','Iteration');
if isempty(wt),
%det0 = det(spm_atranspa([A0 -G]));
det0 = det([A0 -G]'*[A0 -G]); %APS_Edit
else,
det0 = det(spm_atranspa(diagW_A(sqrt(wt),[A0 -G])));
det0 = (det0^2)/det(spm_atranspa(diagW_A(wt,[A0 -G])));
end,
% We will reject the voxels having the least gradient norm. Although
% essentially heuristic, this choice allows to speed up the
% selection while achieving compression rates that are not worse
% than in the original SPM implementation.
normG = dG1.^2 + dG2.^2 + dG3.^2;
Nvox = length(normG);
if ~isempty(wt),
normG = (wt.^2).*normG;
end,
% Initial fraction of points.
prop = 0.5*flags.quality;
[junk,mmsk] = sort(normG); % junk == normG(msk)
step = 0.1;
det1=det0;
stop = 0;
isdet_large = 1;
while stop == 0 & prop > 1e-2,
msk = mmsk( round((1-prop)*Nvox):Nvox );
Adim = [A0(msk,:), -G(msk,:)];
if isempty(wt),
% det1 = det(spm_atranspa(Adim));
det1 = det(Adim'*Adim); %% aps edit
else,
det1 = det(spm_atranspa(diagW_A(sqrt(wt(msk)),Adim)));
det1 = (det1^2)/det(spm_atranspa(diagW_A(wt(msk),Adim)));
end,
stop = ( abs(det1/det0 - flags.quality) < 1e-2 );
aux = (det1/det0 > flags.quality);
if aux ~= isdet_large,
isdet_large = aux;
step = step/2;
end,
if isdet_large,
prop = prop - step;
else,
prop = prop + step;
end,
spm_plot_convergence('Set',det1/det0);
end,
clear Adim,
clear normG,
msk = mmsk(1:ceil((1-prop)*Nvox));
A0(msk,:) = []; G(msk,:) = [];
x1(msk,:) = []; x2(msk,:) = []; x3(msk,:) = [];
dG1(msk,:) = []; dG2(msk,:) = []; dG3(msk,:) = [];
if ~isempty(wt), wt(msk,:) = []; end;
spm_plot_convergence('Clear');
end,
%-----------------------------------------------------------------------
if isfield(flags,'rtm'),
count = ones(size(G));
ave = G;
grad1 = dG1;
grad2 = dG2;
grad3 = dG3;
end;
spm_progress_bar('Init',length(P)-1,'Registering Images');
% Loop over images
%-----------------------------------------------------------------------
for i=2:length(P),
V=smooth_vol(P(i),flags.fwhm);
countdown = -1;
Hold = 1; % Begin with tri-linear interpolation.
for iter=1:64,
% Initial multiplicative factor to be applied to image P(i)
slope = 1.0;
% Voxel coordinates in the P(i) coordinate system of the
% points yi that match the points xi
[y1,y2,y3] = coords([0 0 0 0 0 0],P(1).mat,P(i).mat,x1,x2,x3);
% Test partial overlap
msk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3)));
msk = msk(find(msk<numel(G)));
if length(msk)<32, error_message(P(i)); end;
% Interpolates image P(i)
F = spm_sample_vol(V, y1(msk),y2(msk),y3(msk),Hold);
% Matrix A (7xn) and vector b (nx1)
A = [A0(msk,:), -F];
try
b = slope*F - G(msk);
catch
keyboard;
end
if flagSSD & isempty(wt),
Alpha = spm_atranspa(A);
Beta = A'*b;
else,
% Computes adaptive weights
if flagSSD,
cutoff = Inf;
elseif flagSAD,
cutoff = 0;
else,
cutoff = flags.cutoff * 1.4826 * median(abs(b)); % Adaptive cut-off distance
end,
ad_wt = Mweight(b, cutoff, flags.rho_func);
% Possibly takes into account prior weights
if ~isempty(wt), ad_wt = ad_wt.*wt(msk); end,
% Computes A'*diag(ad_wt)
AtW = diagW_A(ad_wt,A)';
% Computes Alpha (Hessian) and Beta (-0.5* gradient)
Alpha = AtW*A;
Beta = AtW*b;
end,
% Update parameters
soln = Alpha\Beta;
slope = slope + soln(end);
p = [0 0 0 0 0 0 1 1 1 0 0 0];
p(lkp) = soln(1:(end-1));
% Update P(i).mat
dP = spm_matrix(p);
P(i).mat = dP*P(i).mat;
% Stopping criterion
% Test the variation of parameters rather than the variation of
% the criterion
[epst,epsr] = rigid_errors(eye(4),dP);
if epst < 1e-2 & epsr < 1e-4 & countdown == -1, % Stopped converging.
% Switch to a better (slower) interpolation
% and do two final iterations
Hold = flags.hold;
countdown = 2;
end;
if countdown ~= -1,
if countdown==0, break; end;
countdown = countdown -1;
end;
end;
if isfield(flags,'rtm'),
% Generate mean and derivatives of mean
tiny = 5e-2; % From spm_vol_utils.c
msk = find((y1>=(1-tiny) & y1<=(d(1)+tiny) &...
y2>=(1-tiny) & y2<=(d(2)+tiny) &...
y3>=(1-tiny) & y3<=(d(3)+tiny)));
count(msk) = count(msk) + 1;
[G,dG1,dG2,dG3] = spm_sample_vol(V,y1(msk),y2(msk),y3(msk),flags.hold);
ave(msk) = ave(msk) + G.*soln(end);
grad1(msk) = grad1(msk) + dG1.*soln(end);
grad2(msk) = grad2(msk) + dG2.*soln(end);
grad3(msk) = grad3(msk) + dG3.*soln(end);
end;
spm_progress_bar('Set',i-1);
end;
spm_progress_bar('Clear');
for i=1:prod(size(P)),
aux = spm_imatrix(P(i).mat/P(1).mat);
Params(i,:) = aux(1:6);
end
%%% Bidouille
save SPMtmp Params flags,
if ~isfield(flags,'rtm'), return; end;
%_______________________________________________________________________
M=P(1).mat;
A0 = make_A(M,x1,x2,x3,grad1./count,grad2./count,grad3./count,lkp);
G = ave;
clear ave grad1 grad2 grad3,
% Loop over images
%-----------------------------------------------------------------------
spm_progress_bar('Init',length(P),'Registering Images to Mean');
for i=1:length(P),
V=smooth_vol(P(i),flags.fwhm);
for iter=1:64,
slope = 1.0;
[y1,y2,y3] = coords([0 0 0 0 0 0],M,P(i).mat,x1,x2,x3);
msk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3)));
if length(msk)<32, error_message(P(i)); end;
F = spm_sample_vol(V, y1(msk),y2(msk),y3(msk),flags.hold);
A = [A0(msk,:), -F];
b = slope*F - G(msk);
if flagSSD & isempty(wt),
Alpha = spm_atranspa(A);
Beta = A'*b;
else,
if flagSSD,
cutoff = Inf;
elseif flagSAD,
cutoff = 0;
else,
cutoff = flags.cutoff * 1.4826 * median(abs(b)); % Adaptive cut-off distance
end,
ad_wt = Mweight(b, cutoff, flags.rho_func);
if ~isempty(wt), ad_wt = ad_wt.*wt(msk); end,
AtW = diagW_A(ad_wt,A)';
Alpha = AtW*A;
Beta = AtW*b;
end,
% Update parameters
soln = Alpha\Beta;
slope = slope + soln(end);
p = [0 0 0 0 0 0 1 1 1 0 0 0];
p(lkp) = soln(1:(end-1));
% Update P(i).mat
dP = spm_matrix(p);
P(i).mat = dP*P(i).mat;
% Stopping criterion
[epst,epsr] = rigid_errors(eye(4),dP);
if epst < 1e-2 & epsr < 1e-4, % Stopped converging
break;
end,
end;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
% Since we are supposed to be aligning everything to the first
% image, then we had better do so
%-----------------------------------------------------------------------
M = M/P(1).mat;
for i=1:length(P)
P(i).mat = M*P(i).mat;
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [y1,y2,y3]=coords(p,M1,M2,x1,x2,x3)
% Rigid body transformation of a set of coordinates.
M = (inv(M2)*spm_matrix(p(1:6))*M1);
y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4);
y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4);
y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function V = smooth_vol(P,fwhm)
% Test wehter smoothing should really be applied...
if fwhm == 0, V = spm_read_vols(P); return; end,
% Convolve the volume in memory.
s = sqrt(sum(P.mat(1:3,1:3).^2)).^(-1)*(fwhm/sqrt(8*log(2)));
x = round(6*s(1)); x = [-x:x];
y = round(6*s(2)); y = [-y:y];
z = round(6*s(3)); z = [-z:z];
x = exp(-(x).^2/(2*(s(1)).^2));
y = exp(-(y).^2/(2*(s(2)).^2));
z = exp(-(z).^2/(2*(s(3)).^2));
x = x/sum(x);
y = y/sum(y);
z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
V = zeros(P.dim(1:3));
spm_conv_vol(P,V,x,y,z,-[i j k]);
return;
%_______________________________________________________________________
function A = make_A(M,x1,x2,x3,dG1,dG2,dG3,lkp)
% Matrix of rate of change of weighted difference w.r.t. parameter changes
p0 = [0 0 0 0 0 0 1 1 1 0 0 0];
A = zeros(prod(size(x1)),length(lkp));
for i=1:length(lkp)
pt = p0;
pt(lkp(i)) = pt(lkp(i))+1e-6;
[y1,y2,y3] = coords(pt,M,M,x1,x2,x3);
A(:,i) = sum([y1-x1 y2-x2 y3-x3].*[dG1 dG2 dG3],2)*(1e+6);
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function error_message(P)
str = { 'There is not enough overlap in the images',...
'to obtain a solution.',...
' ',...
'Offending image:',...
P.fname,...
' ',...
'Please check that your header information is OK.'};
spm('alert*',str,mfilename,sqrt(-1));
error('insufficient image overlap')
return
%_______________________________________________________________________
%_______________________________________________________________________
function plot_parameters(P,flags)
fg=spm_figure('FindWin','Graphics');
if ~isempty(fg),
P = cat(1,P{:});
if length(P)<2, return; end;
Params = zeros(prod(size(P)),12);
for i=1:prod(size(P)),
Params(i,:) = spm_imatrix(P(i).mat/P(1).mat);
end
% display results
% translation and rotation over time series
%-------------------------------------------------------------------
spm_figure('Clear','Graphics');
ax=axes('Position',[0.1 0.65 0.8 0.2],'Parent',fg,'Visible','off');
set(get(ax,'Title'),'String','Image realignment (INRIAlign toolbox)','FontSize',16,'FontWeight','Bold','Visible','on');
x = 0.1;
y = 0.9;
for i = 1:min([prod(size(P)) 9])
text(x,y,[sprintf('%-4.0f',i) P(i).fname],'FontSize',10,'Interpreter','none','Parent',ax);
y = y - 0.08;
end
if prod(size(P)) > 9
text(x,y,'................ etc','FontSize',10,'Parent',ax); end
% Print important parameters
y=y-0.08; text(x,y,'Parameters','Parent',ax,'FontSize',11,'FontWeight','Bold');
tmp = str2mat('Quadratic','Absolute value','Huber','Cauchy','Geman-McClure','Leclerc-Welsch','Tukey');
tmp2 = str2mat('quadratic','absolute','huber','cauchy','geman','leclerc','tukey');
msg = [' Cost function: ',deblank(tmp(strmatch(flags.rho_func,tmp2),:))];
if ~strcmp(lower(flags.rho_func),'quadratic') & ~strcmp(lower(flags.rho_func),'absolute'),
msg = [msg, ', cut-off distance: ', ...
num2str(flags.cutoff),'\times\sigma'];
end,
y=y-0.08; text(x,y,msg,'Parent',ax,'Interpreter','tex');
msg = [' Quality: ',num2str(flags.quality)];
msg = [msg,' - Subsampling: ',num2str(flags.sep), ' mm'];
msg = [msg,' - Smoothing: ',num2str(flags.fwhm),' mm'];
y=y-0.08; text(x,y,msg,'Parent',ax,'Interpreter','tex');
ax=axes('Position',[0.1 0.35 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on');
plot(Params(:,1:3),'Parent',ax)
% s = ['x translation';'y translation';'z translation'];
% text([2 2 2], Params(2, 1:3), s, 'Fontsize',10,'Parent',ax)
legend(ax,'x translation','y translation','z translation');
set(get(ax,'Title'),'String','translation','FontSize',16,'FontWeight','Bold');
set(get(ax,'Xlabel'),'String','image');
set(get(ax,'Ylabel'),'String','mm');
ax=axes('Position',[0.1 0.05 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on');
plot(Params(:,4:6)*180/pi,'Parent',ax)
% s = ['pitch';'roll ';'yaw '];
% text([2 2 2], Params(2, 4:6)*180/pi, s, 'Fontsize',10,'Parent',ax)
legend(ax,'pitch','roll','yaw');
set(get(ax,'Title'),'String','rotation','FontSize',16,'FontWeight','Bold');
set(get(ax,'Xlabel'),'String','image');
set(get(ax,'Ylabel'),'String','degrees');
% print realigment parameters
spm_print
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function save_parameters(V)
fname = [spm_str_manip(prepend(V(1).fname,'realignment_params_'),'s') '.txt'];
n = length(V);
Q = zeros(n,6);
for j=1:n,
qq = spm_imatrix(V(j).mat/V(1).mat);
Q(j,:) = qq(1:6);
end;
save(fname,'Q','-ascii');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function PO = prepend(PI,pre)
[pth,nm,xt] = fileparts(deblank(PI));
PO = fullfile(pth,[pre nm xt]);
return;
%_______________________________________________________________________
function y = Mweight(x, c, flag)
if c == Inf, flag = 'quadratic'; end,
% To avoid numerical instabilities
cc = max(c, 1e-1);
switch lower(flag)
case 'quadratic'
y = ones(size(x));
case 'absolute'
% To avoid numerical instabilities, the theoretical weighting
% function given by 1/|x| is replaced with a bounded function. This
% corresponds to approximating |x| by sqrt(x^2 + tiny).
ic = 10;
y = 1./sqrt(1 + (ic*x).^2);
case 'huber'
y = ones(size(x));
[aux, msk] = find(abs(x)>cc);
y(msk) = cc./abs(x(msk));
case 'cauchy'
ic = 1/cc;
y = (1 + (x*ic).^2).^(-1);
case 'geman'
ic = 1/cc;
y = (1 + (x*ic).^2).^(-2);
case 'leclerc'
ic = 1/cc;
y = exp( - (x*ic).^2 );
case 'tukey'
ic = 1/cc;
y = ( abs(x)<cc ) .* (1 - (x*ic).^2).^(2);
otherwise
error('no M-estimator specified'),
end,
return;
%_______________________________________________________________________
function B = diagW_A(w,A);
% Computes diag(w)*A without computing w;
% Assumes wt is a column vector.
for i=1:size(A,2),
B(:,i) = w.*A(:,i);
end,
return;
%_______________________________________________________________________
function [dt,dr] = rigid_errors ( T_gt, T );
% Translation error
dt = norm ( T_gt(1:3,4) - T(1:3,4) );
% Rotation error (in degrees)
rad2deg = 57.2958;
dR = inv(T_gt(1:3,1:3))*T(1:3,1:3);
[V,D]=eig(dR);
% Find the indice corresponding to eigenvalue 1
[tmp,in]=min( (diag(D)-1).*conj(diag(D)-1) );
% Rotation axis
n=V(1:3,in);
n=n/norm(n);
% Construct an orthonormal basis (n,v,w)
[tmp,in2]=min(abs(n));
aux=[0 0 0]';
aux(in2)=1;
v=cross(n,aux);
v=v/norm(v);
w=cross(n,v);
w=w/norm(w);
% Rotation angle
drv=dR*v;
dr=atan2(w'*drv,v'*drv);
% Error in degrees
dr = rad2deg * abs(dr);
return;
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
peak_nii.m
|
.m
|
MRtools_Hoffman2-master/peak_nii/peak_nii.m
| 52,648 |
utf_8
|
7408d106e2734ce29a4c904f6457f31e
|
function [voxels voxelstats clusterstats sigthresh regions mapparameters UID]=peak_nii(image,mapparameters)
%%
% USAGE AND EXAMPLES CAN BE FOUND IN PEAK_NII_MANUAL.PDF
%
% License:
% Copyright (c) 2011-12 Donald G. McLaren and Aaron Schultz
% All rights reserved.
%
% Redistribution, with or without modification, is permitted provided that the following conditions are met:
% 1. Redistributions must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
% 2. All advertising materials mentioning features or use of this software must display the following acknowledgement:
% This product includes software developed by the Harvard Aging Brain Project (NIH-P01-AG036694), NIH-R01-AG027435, and The General Hospital Corp.
% 3. Neither the Harvard Aging Brain Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
% 4. You are not permitted under this License to use these files commercially. Use for which any financial return is received shall be defined as commercial use, and includes (1) integration of all or part
% of the source code or the Software into a product for sale or license by or on behalf of Licensee to third parties or (2) use of the Software or any derivative of it for research with the final
% aim of developing software products for sale or license to a third party or (3) use of the Software or any derivative of it for research with the final aim of developing non-software products for
% sale or license to a third party.
% 5. Use of the Software to provide service to an external organization for which payment is received (e.g. contract research) is permissible.
%
% THIS SOFTWARE IS PROVIDED BY DONALD G. MCLAREN ([email protected]) AND AARON SCHULTZ ([email protected]) ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
% TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
% OR CONSEQUENTIAL %DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
% LIABILITY, WHETHER IN CONTRACT, %STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% Licenses related to using various atlases are described in Peak_Nii_Atlases.PDF
%
% For the program in general, please contact [email protected]
%
% peak_nii.v6 -- Last modified on 02/11/2012 by Donald G. McLaren, PhD
% peak_nii.v7 -- Last modified on 05/20/2014 by Donald G. McLaren, PhD
% ([email protected])
% Wisconsin Alzheimer's Disease Research Center - Imaging Core, Univ. of
% Wisconsin - Madison
% Neuroscience Training Program and Department of Medicine, Univ. of
% Wisconsin - Madison
% GRECC, William S. Middleton Memorial Veteren's Hospital, Madison, WI
% GRECC, Bedford VAMC
% Department of Neurology, Massachusetts General Hospital and Havard
% Medical School
%
% For the program in general, please contact [email protected]
%
%% Program begins here
try
if ~strcmp(spm('Ver'),'SPM8') && ~strcmp(spm('Ver'),'SPM12') %KT edit, og: ~strcmp(spm('Ver'),'SPM8') && ~strcmp(spm('Ver'),'SPM12b')
disp('PROGRAM ABORTED:')
disp(' You must use SPM8/SPM12b to process your data; however, you can use SPM.mat files')
disp(' generated with SPM2 or SPM5. In these cases, simply specify the option SPMver')
disp(' in single qoutes followed by a comma and the version number.')
disp(' ')
disp('Make sure to add SPM8 to your MATLAB path before re-running.')
return
else
addpath(fileparts(which('spm')))
end
catch
disp('PROGRAM ABORTED:')
disp(' You must use SPM8 to process your data; however, you can use SPM.mat files')
disp(' generated with SPM2 or SPM5. In these cases, simply specify the option SPMver')
disp(' in single qoutes followed by a comma and the version number.')
disp(' ')
disp('Make sure to add SPM8 to your MATLAB path before re-running.')
return
end
%%Placeholder outputs
voxels=[];
regions=[];
voxelstats=[];
clusterstats=[];
sigthresh=cell(6,1);
sigthresh{1,1}='FWEp: '; sigthresh{2,1}='FDRp: '; sigthresh{3,1}='FDRpk18: '; sigthresh{4,1}='FDRpk26: '; sigthresh{5,1}='FWEc: '; sigthresh{6,1}='FDRc: ';
%% Check inputs
if exist(image,'file')==2
I1=spm_vol(image);
infoI1=I1;
[Iorig,voxelcoord]=spm_read_vols(I1);
if nansum(nansum(nansum(abs(Iorig))))==0
error(['Error: ' image ' is all zeros or all NaNs'])
end
else
error(['File ' image ' does not exist'])
end
if nargin==2
if ischar(mapparameters) && exist(mapparameters,'file')==2
mapparameters=load(mapparameters);
end
if ~isstruct(mapparameters)
error('Mapparameters is not a structure OR not a file that contains a structure');
end
else
error('Mapparameters must be specified as a file or a structure');
end
[mapparameters, errors, errorval]=peak_nii_inputs(mapparameters,infoI1.fname,nargout);
if isfield(mapparameters,'voxel')
if size(mapparameters.voxel,2)==3
mapparameters.voxel=mapparameters.voxel;
elseif size(mapparameters.voxel,1)==3
mapparameters.voxel=mapparameters.voxel';
else
disp('mapparameters.voxel is not a voxel.')
end
end
if ~isempty(errorval) || ~isempty(errors)
disp('There was an error.')
disp(errorval)
if size(errors)>1
for ii=1:size(errors)-1
disp(errors{ii})
end
error(errors{size(errors)})
else
error(errors{1})
end
end
UID=mapparameters.UID;
FIVEF=mapparameters.FIVE;
%% Read in data and mask (if available)
if strcmpi(mapparameters.sign,'neg')
Iorig=-1.*Iorig;
disp(['Threshold is:-' num2str(mapparameters.thresh)])
mapparameters.thresh2=mapparameters.thresh*-1;
else
disp(['Threshold is:' num2str(mapparameters.thresh)])
mapparameters.thresh2=mapparameters.thresh;
end
if ~isempty(mapparameters.mask)
I2=spm_vol(mapparameters.mask);
infoI2=I2;
if infoI1.mat==infoI2.mat
if infoI1.dim==infoI2.dim
I2=spm_read_vols(I2);
else
v = I2;
[XYZ(1,:), XYZ(2,:), XYZ(3,:)]=ind2sub(I1.dim(1:3),1:prod(I1.dim(1:3)));
I2 = spm_data_read(v,'xyz',v.mat\I1.mat*[XYZ; ones(1,size(XYZ,2))]);
end
else
v = I2;
[XYZ(1,:), XYZ(2,:), XYZ(3,:)]=ind2sub(I1.dim(1:3),1:prod(I1.dim(1:3)));
I2 = spm_data_read(v,'xyz',v.mat\I1.mat*[XYZ; ones(1,size(XYZ,2))]);
end
I2=(I2>0)+(I2<0); % Ensures that the mask is binary
I2(I2==0)=NaN; % Since 0 can be used in computations, convert 0s in mask to NaN.
I=Iorig; %Copy original data
I(isnan(I2))=NaN; %Mask out value outside of the mask with NaN
%% Mask Region file
if ~isempty(mapparameters.label.source)
try
mapparameters.label.rf.img=mapparameters.label.rf.img.*(I2~=0);
catch
v = mapparameters.label.rf.hdr;
[XYZ(1,:), XYZ(2,:), XYZ(3,:)]=ind2sub(I1.dim(1:3),1:prod(I1.dim(1:3)));
AtlasMask = spm_data_read(v,'xyz',v.mat\I1.mat*[XYZ; ones(1,size(XYZ,2))]);
mapparameters.label.rf.XYZmm=XYZ;
mapparameters.label.rf.img=zeros(size(I));
mapparameters.label.rf.img=reshape(AtlasMask.*(I2>0),size(I));
end
end
else
I=Iorig;
end
%% Program begins here
% Get all possible p-values
if mapparameters.SV
realI=I(~isnan(I));
realI=realI(realI~=0);
SV=numel(realI);
else
realI=Iorig(~isnan(Iorig));
realI=realI(realI~=0);
SV=numel(realI); %Search space
end
if strcmpi(mapparameters.type,'T')
mapparameters.type='T';%compatibility with spm commands
if ~isempty(mapparameters.df1)
QPs=sort(1-spm_Tcdf(realI,mapparameters.df1)); %uncorrected P values in searched volume (for voxel FDR) - not the masked volume
sigthresh{2,1}=[sigthresh{2,1} num2str(spm_uc_FDR(mapparameters.threshc,[1 mapparameters.df1],mapparameters.type,1,QPs)) ',' num2str(1-spm_Tcdf(spm_uc_FDR(mapparameters.threshc,[1 mapparameters.df1],mapparameters.type,1,QPs),mapparameters.df1))];
else
sigthresh{2,1}='FDRp: Not Computed. No df provided.'
end
elseif strcmpi(mapparameters.type,'F')
mapparameters.type='F';%compatibility with spm commands
if ~isempty(mapparameters.df1) && ~isempty(mapparameters.df2)
QPs=sort(1-spm_Fcdf(realI,mapparameters.df1,mapparameters.df2)); %uncorrected P values in searched volume (for voxel FDR) - not the masked volume
sigthresh{2,1}=[sigthresh{2,1} num2str(spm_uc_FDR(mapparameters.threshc,[mapparameters.df1 mapparameters.df2],mapparameters.type,1,QPs)) ',' num2str(1-spm_Fcdf(spm_uc_FDR(mapparameters.threshc,[mapparameters.df1 mapparameters.df2],mapparameters.type,1,QPs),mapparameters.df1, mapparameters.df2))];
else
sigthresh{2,1}='FDRp: Not Computed. No df provided.'
end
elseif strcmpi(mapparameters.type,'Z')
mapparameters.type='Z';%compatibility with spm commands
QPs=sort(1-spm_Ncdf(realI,0,1)); %uncorrected P values in searched volume (for voxel FDR) - not the masked volume
sigthresh{2,1}=[sigthresh{2,1} num2str(spm_uc_FDR(mapparameters.threshc,[NaN NaN],mapparameters.type,1,QPs)) ',' num2str(1-spm_Ncdf(spm_uc_FDR(mapparameters.threshc,[NaN NaN],mapparameters.type,1,QPs),0,1))];
end
ind=find(I>mapparameters.thresh); %#ok<*EFIND> %Masked file
if isempty(ind)
voxels=[]; regions={};
disp(['NO MAXIMA ABOVE ' num2str(mapparameters.thresh) '.'])
if mapparameters.exact==1
disp('To find the cluster in this subject, please set thresh to 0')
return
else
return
end
end
[L(1,:),L(2,:),L(3,:)]=ind2sub(infoI1.dim,ind);
%Cluster signficant voxels
A=peakcluster(L,mapparameters.conn,infoI1); % A is the cluster of each voxel
A=transpose(A);
n=hist(A,1:max(A));
if max(n)<mapparameters.cluster
voxels=[]; regions={};
display(['NO CLUSTERS LARGER THAN ' num2str(mapparameters.cluster) ' voxels.'])
if mapparameters.exact==1
disp(['The largest cluster in this subject @ ' num2str(mapparameters.thresh2) 'is ' num2str(max(n)) 'voxels.'])
disp('To find the cluster in this subject, please change the cluster size or threshold.')
end
return
end
clear L A n ind
if FIVEF
iterrange=1;
else
iterrange=[1 2];
end
for iter=iterrange
if mapparameters.SV
Iuse=I;
elseif iter==1
Iuse=Iorig;
else
Iuse=I;
end
%Find significant voxels
ind=find(Iuse>mapparameters.thresh);
L=[];
[L(1,:),L(2,:),L(3,:)]=ind2sub(infoI1.dim,ind);
%Cluster signficant voxels
A=peakcluster(L,mapparameters.conn,infoI1); % A is the cluster of each voxel
A=transpose(A);
n=hist(A,1:max(A));
if iter==1 && isfield(mapparameters,'RESELS')
FWHM=mapparameters.FWHM(infoI1.dim>0);
V2R=1/prod(FWHM);
if strcmpi(mapparameters.type,'T') || strcmpi(mapparameters.type,'F')
Pk=NaN(length(n),1);
Pc=NaN(length(n),1);
if strcmpi(mapparameters.type,'T')
DF=[1 mapparameters.df1];
else
DF=[mapparameters.df1 mapparameters.df2];
end
%keyboard (KT-EDIT)
for ii = 1:length(n)
[Pk(ii), Pc(ii)] = spm_P_RF(1,n(ii)*V2R,mapparameters.thresh,DF,mapparameters.type,mapparameters.RESELS,1);
end
QPc=sort(Pc,'ascend')';
[Pk, J] = sort(Pk, 'ascend');
Ifwe = find(Pk <= mapparameters.threshc, 1, 'last');
if isempty(Ifwe)
sigthresh{5,1}=[sigthresh{5,1} 'Inf'];
else
sigthresh{5,1}=[sigthresh{5,1} num2str(n(J(Ifwe)))];
end
Fi = (1:length(Pc))/length(Pc)*mapparameters.threshc/1;%cV = 1; % Benjamini & Yeuketeli cV for independence/PosRegDep case
Ifdr = find(QPc <= Fi, 1, 'last');
if isempty(Ifdr)
sigthresh{6,1}=[sigthresh{6,1} 'Inf'];
else
sigthresh{6,1}=[sigthresh{6,1} num2str(n(J(Ifdr)))];
end
clear Pk Pc J Ifdr Ifwe
else
sigthresh{5,1}=[sigthresh{5,1} 'Only available for T/F-tests.'];
sigthresh{6,1}=[sigthresh{6,1} 'Only available for T/F-tests.'];
end
end
if iter==2
for ii=1:size(A,1)
if n(A(ii))<mapparameters.cluster % removes clusters smaller than extent threshold
A(ii,1:2)=NaN;
else
A(ii,1:2)=[n(A(ii)) A(ii,1)];
end
end
end
% Combine A (cluster labels) and L (voxel indicies)
L=L';
A(:,3:5)=L(:,1:3);
if ~isfield(mapparameters,'voxel')
else
for vv=1:size(mapparameters.voxel,1)
x=spm_XYZreg('NearestXYZ',mapparameters.voxel(vv,:),voxelcoord);
xM=round(infoI1.mat \ [x; 1]);
indvox=find(((A(:,3)==xM(1))+(A(:,4)==xM(2))+(A(:,5)==xM(3)))==3);
if isempty(indvox) && size(mapparameters.voxel,1)==1
disp('voxel is not in a cluster');
return
elseif isempty(indvox)
continue
else
end
Btmp=A(A(:,1)==A(indvox,1),:); %finds current cluster
Btmp(:,2)=vv; %label it as cluster 1
try
B=[B;Btmp];
catch
B=Btmp;
end
clear Btmp
end
try
A2=B;
catch
disp('no voxels are not in a cluster');
voxels=-1;
return;
end
end
% Save clusters
if FIVEF
T=peakcluster(transpose(A(:,3:5)),mapparameters.conn,infoI1,[pwd filesep 'tmp']);
A(:,2)=T(:,1); clear T
A=unique(A(:,1:2),'rows','first');
A(:,1)=n';
voxelsT=[A(:,1) NaN(size(A,1),5) A(:,2)];
Iclust=spm_read_vols(spm_vol([pwd filesep 'tmp_clusters.nii']));
else
T=peakcluster(transpose(A(:,3:5)),mapparameters.conn,infoI1,[mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname]);
A(:,2)=T(:,1); clear T % Save significant data
Iclust=spm_read_vols(spm_vol([mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_clusters.nii']));
if isfield(mapparameters,'voxel')
infoI1.fname='temp_cluster.nii';
infoI1.descrip='temp cluster(s)';
infoI1.pinfo=[1 0 0]';
vol=zeros(infoI1.dim(1),infoI1.dim(2),infoI1.dim(3));
for ii=1:size(A2,1)
vol(A2(ii,3),A2(ii,4),A2(ii,5))=A2(ii,2);
end
spm_write_vol(infoI1,vol);
end
end
% Find all peaks, only look at current cluster to determine the peak
if mapparameters.clustercenter
for ii=1:numel(n)
coords = find(vol == ii);
[out{1:3}] = ind2sub(size(vol),coords);
ctr_v = mean(cell2mat(out),1);
ctr_mm = (infoI1.mat(1:3,:) * [ ctr_v 1]')';
ctr_v = round(ctr_v);
voxelsT(ii,1)=NaN;
voxelsT(ii,2)=Iuse(ind(INDEX(ii)));
voxelsT(ii,3)=ctr_v(1);
voxelsT(ii,4)=ctr_v(2);
voxelsT(ii,5)=ctr_v(3);
voxelsT(ii,6)=NaN;
voxelsT(ii,7)=A(INDEX(ii),2);
voxelsT(ii,8)=2; %Using the cluster cluster.
end
else
INDEX18=[];
INDEX26=[];
if iter==1
if mapparameters.conn==26
INDEX18 = peak_get_lm18(Iuse,L');
INDEX26 = peak_get_lm26(Iuse,L');
voxelsT26=Iuse(ind(INDEX26));
else
INDEX18 = peak_get_lm18(Iuse,L');
for ii=1:max(A(:,2))
ind2=find(Iclust==ii);
L2=[];
[L2(1,:),L2(2,:),L2(3,:)]=ind2sub(infoI1.dim,ind2);
INDEX26 =[INDEX26 ind2(peak_get_lm26(Iuse,L2))'];
end
voxelsT26=Iuse(INDEX26);
end
voxelsT18=Iuse(ind(INDEX18));
else
INDEX26_bad=[];
for ii=1:max(A(:,2))
ind2=find(Iclust==ii);
L2=[];
[L2(1,:),L2(2,:),L2(3,:)]=ind2sub(infoI1.dim,ind2);
tmp18=ind2(peak_get_lm18(Iuse,L2))';
tmp26=ind2(peak_get_lm26(Iuse,L2))';
is26=ismember(tmp18,tmp26);
INDEX18=[INDEX18 tmp18];
INDEX26=[INDEX26 ~is26];
clear tmp18 tmp26
end
[jnk,INDEX]=ismember(INDEX18,ind); clear jnk
voxelsT=zeros(numel(INDEX),7);
for ii=1:numel(INDEX)
voxelsT(ii,1)=A(INDEX(ii),1);
voxelsT(ii,2)=Iuse(ind(INDEX(ii)));
voxelsT(ii,3)=voxelcoord(1,ind(INDEX(ii)));
voxelsT(ii,4)=voxelcoord(2,ind(INDEX(ii)));
voxelsT(ii,5)=voxelcoord(3,ind(INDEX(ii)));
voxelsT(ii,6)=1;
voxelsT(ii,7)=A(INDEX(ii),2);
voxelsT(ii,8)=1;% peak with 26 neighbors, set to zero if not on the next line.
end
voxelsT(INDEX26==0,8)=0; % not a peak with 26 neighbors
%Remove small clusters
voxelsT=voxelsT(abs(voxelsT(:,1))>=mapparameters.cluster,:);
% FUTURE FEATURE: Non-stationary correction
% if mapparameters.NS.do==1
% mRPV=nanmean(spm_get_data(mapparameters.rpv,find(Iclust~=0)));
% for cc=1:max(voxelsT(:,7))
% %% Get cluster and sample rpv image
% rind=find(Iclust==ii);
% rpv_vals = spm_get_data(maparameters.rpv,rind);
% %% SPM8 Resel Computation
% %-Compute average of valid LKC measures for i-th region
% %----------------------------------------------------------
% valid = ~isnan(rpv_vals);
% if any(valid)
% LKC = sum(rpv_vals(valid)) / sum(valid);
% else
% LKC = 1/prod(mapparameters.FWHM); % fall back to whole-brain resel density
% end
%
% %-Intrinsic volume (with surface correction)
% %----------------------------------------------------------
% IV = spm_resels([1 1 1],rind,'V');
% IV = IV*[1/2 2/3 2/3 1]';
% voxelsT(:,9) = IV*LKC;
%
% %% NS Resel Computation
% if any(valid)
% voxelsT(:,10) = (sum(rpv_vals(valid))/sum(valid))*length(rpv_vals);
% else
% voxelsT(:,10) = mRPV*length(rpv_vals);
% end
% end
% else
% voxelsT(:,9)=NaN;
% voxelsT(:,10)=NaN;
% end
end
end
if ~FIVEF
if isfield(mapparameters,'voxel')
% Find the peakin the current cluster
cc=unique(A2(:,2));
voxelsT=zeros(numel(cc),5);
if isfield(mapparameters,'exactvoxel') && mapparameters.exactvoxel==1
for vv=1:numel(cc)
x=spm_XYZreg('NearestXYZ',mapparameters.voxel(vv,:),voxelcoord);
xM=round(infoI1.mat \ [x; 1]);
ind=find(((A2(:,3)==xM(1))+(A2(:,4)==xM(2))+(A2(:,5)==xM(3)))==3);
if ~isempty(ind)
voxind=sub2ind(infoI1.dim,A2(ind,3),A2(ind,4),A2(ind,5));
voxelsT(vv,1)=n(A2(ind,1));
voxelsT(vv,2)=I(voxind);
voxelsT(vv,3)=voxelcoord(1,voxind);
voxelsT(vv,4)=voxelcoord(2,voxind);
voxelsT(vv,5)=voxelcoord(3,voxind);
voxelsT(vv,6)=1;
voxelsT(vv,7)=A2(ind,1);
voxelsT(vv,8)=2; %Using specified voxel.
end
end
else
for vv=1:numel(cc)
ind=sub2ind(infoI1.dim,A2(A2(:,2)==cc(vv),3),A2(A2(:,2)==cc(vv),4),A2(A2(:,2)==cc(vv),5));
if ~isempty(ind)
try
K=sum(voxelsT(1:vv-1,1));
catch
K=0;
end
maxind=find(I(ind)==max(I(ind)));
voxind=sub2ind(infoI1.dim,A2(maxind+K,3),A2(maxind+K,4),A2(maxind+K,5));
voxelsT(vv,1)=n(A2(maxind+K,1));
voxelsT(vv,2)=I(voxind);
voxelsT(vv,3)=voxelcoord(1,voxind);
voxelsT(vv,4)=voxelcoord(2,voxind);
voxelsT(vv,5)=voxelcoord(3,voxind);
voxelsT(vv,6)=1;
voxelsT(vv,7)=A2(maxind+K,1);
voxelsT(vv,8)=2; %Using specified voxel.
end
end
end
voxelsT=unique(voxelsT,'rows');
% Label Peaks
if ~isempty(mapparameters.label.source)
regions=regionname(voxelsT,mapparameters.label.rf,mapparameters.label.ROI,mapparameters.label.ROInames,mapparameters.label.nearest);
end
if strcmpi(mapparameters.type,'F')
df=[mapparameters.df1 mapparameters.df2];
[voxelstats,sigthresh]=calc_voxelstats(mapparameters,voxelsT,voxelsT18,voxelsT26,mapparameters.type,df,QPs,sigthresh,SV);
cstats=1;
elseif strcmpi(mapparameters.type,'T')
df=[1 mapparameters.df1];
[voxelstats,sigthresh]=calc_voxelstats(mapparameters,voxelsT,voxelsT18,voxelsT26,mapparameters.type,df,QPs,sigthresh,SV);
cstats=1;
elseif strcmpi(mapparameters.type,'Z')
df=[];
[voxelstats,sigthresh]=calc_voxelstats(mapparameters,voxelsT,voxelsT18,voxelsT26,mapparameters.type,df,QPs,sigthresh,SV);
cstats=0;
else
end
if isfield(mapparameters,'RESELS')
try
clusterstats=calc_clusterstats(mapparameters,voxelsT,mapparameters.type,df,QPs,QPc,cstats);
catch
clusterstats=calc_clusterstats(mapparameters,voxelsT,mapparameters.type,df,QPs,[],cstats);
end
end
try
savepeaks(mapparameters,regions,voxelsT,voxelstats,clusterstats,sigthresh);
catch
savepeaks(mapparameters,[],voxelsT,voxelstats,clusterstats,sigthresh);
end
try
voxels={voxelsT regions(:,2)};
catch
voxels={voxelsT};
end
return
end
end
end
if ~FIVEF
%Check number of peaks
if size(voxelsT,1)>mapparameters.voxlimit
voxelsT=sortrows(voxelsT,-2);
voxelsT=voxelsT(1:mapparameters.voxlimit,:); % Limit peak voxels to mapparameters.voxlimit
end
% Sort table by cluster w/ max T then by T value within cluster (negative
% data was inverted at beginning, so we are always looking for the max).
uniqclust=unique(voxelsT(:,7));
maxT=zeros(length(uniqclust),2);
for ii=1:length(uniqclust)
maxT(ii,1)=uniqclust(ii);
maxT(ii,2)=max(voxelsT(voxelsT(:,7)==uniqclust(ii),2));
end
maxT=sortrows(maxT,-2);
for ii=1:size(maxT,1)
voxelsT(voxelsT(:,7)==maxT(ii,1),11)=ii;
end
voxelsT=sortrows(voxelsT,[11 -2]);
[cluster,uniq,ind]=unique(voxelsT(:,11)); % get rows of each cluster
if mapparameters.exact
voxelsT(2:end,:)=[];
A=A(A(:,2)==voxelsT(1,7),:); % Keeps most significant cluster
voxind=zeros(size(A,1),1);
for ii=1:size(A,1)
voxind(ii)=sub2ind(infoI1.dim,A(ii,3),A(ii,4),A(ii,5));
A(ii,6)=I(voxind(ii));
end
B=A; %in case eroding doesn't work
while size(A,1)>mapparameters.cluster
A(A(:,6)==min(A(:,6)),:)=[];
end
%check for a single cluster
newclust=peakcluster(A(:,3:5)',mapparameters.conn,infoI1);
if max(newclust)>1
A=B; clear B;
indmax=find(A(:,6)==max(A(:,6)));
cluster=zeros(mapparameters.cluster,1);
cluster(1)=voxind(indmax);
%voxind is the voxel indices
indsearch=[];
for ii=1:(mapparameters.cluster-1)
a={[A(indmax,3)-1:A(indmax,3)+1],[A(indmax,4)-1:A(indmax,4)+1],[A(indmax,5)-1:A(indmax,5)+1]};
[xx yy zz]=ndgrid(a{:});
possind=sub2ind(infoI1.dim,xx(:),yy(:),zz(:));
addind=voxind(ismember(voxind,possind));
indsearch=[indsearch addind']; clear addind; %#ok<AGROW>
indsearch=setdiff(indsearch,cluster);
indmax=find(A(:,6)==max(I(indsearch)));
cluster(ii+1)=voxind(indmax);
end
A=A(ismember(voxind,cluster),:);
end
% Save clusters
peakcluster2(A,voxelsT,infoI1,[mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname]);
% Save significant data
Iclust=spm_read_vols(spm_vol([mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_clusters.nii']));
if strcmpi(mapparameters.sign,'neg')
Ithresh=-1.*I.*(Iclust>0);
else
Ithresh=I.*(Iclust>0);
end
out=infoI1;
out.fname=[mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '.nii'];
out.descrip=['Thresholded Map @ thresh ' num2str(mapparameters.thresh2) ' and cluster extent ' num2str(mapparameters.cluster) ' in ' mapparameters.maskname];
spm_write_vol(out,Ithresh);
if strcmpi(mapparameters.sign,'neg')
voxelsT(:,2)=-1*voxelsT(:,2);
end
voxelsT(:,7)=[];
voxels={voxelsT};
regions={};
savepeaks(mapparameters,regions,voxelsT,voxelstats,clusterstats,sigthresh)
return
end
%Collapse or eliminate peaks closer than a specified distance
voxelsF=zeros(size(voxelsT,1),size(voxelsT,2));
nn=[1 zeros(1,length(cluster)-1)];
for numclust=1:length(cluster)
Distance=eps;
voxelsC=voxelsT(ind==numclust,:);
while min(min(Distance(Distance>0)))<mapparameters.separation
[voxelsC,Distance]=vox_distance(voxelsC);
minD=min(min(Distance(Distance>0)));
if minD<mapparameters.separation
min_ind=find(Distance==(min(min(Distance(Distance>0)))));
[ii,jj]=ind2sub(size(Distance),min_ind(1));
if mapparameters.SPM==1
voxelsC(ii,:)=NaN; % elimate peak
else
voxelsC(jj,1)=voxelsC(jj,1);
voxelsC(jj,2)=voxelsC(jj,2);
voxelsC(jj,3)=((voxelsC(jj,3).*voxelsC(jj,6))+(voxelsC(ii,3).*voxelsC(ii,6)))/(voxelsC(jj,6)+voxelsC(ii,6)); % avg coordinate
voxelsC(jj,4)=((voxelsC(jj,4).*voxelsC(jj,6))+(voxelsC(ii,4).*voxelsC(ii,6)))/(voxelsC(jj,6)+voxelsC(ii,6)); % avg coordinate
voxelsC(jj,5)=((voxelsC(jj,5).*voxelsC(jj,6))+(voxelsC(ii,5).*voxelsC(ii,6)))/(voxelsC(jj,6)+voxelsC(ii,6)); % avg coordinate
voxelsC(jj,6)=voxelsC(jj,6)+voxelsC(ii,6);
voxelsC(jj,7)=voxelsC(jj,7);
voxelsC(jj,8)=voxelsC(jj,8);
%voxelsC(jj,9)=voxelsC(jj,9); % resel counts
%voxelsC(jj,10)=voxelsC(jj,10); % resel counts
voxelsC(jj,11)=voxelsC(jj,11);
voxelsC(ii,:)=NaN; % eliminate second peak
end
voxelsC(any(isnan(voxelsC),2),:) = [];
end
end
try
nn(numclust+1)=nn(numclust)+size(voxelsC,1);
end
voxelsF(nn(numclust):nn(numclust)+size(voxelsC,1)-1,:)=voxelsC;
end
voxelsT=voxelsF(any(voxelsF'),:);
clear voxelsF voxelsC nn
% Label Peaks
if ~isempty(mapparameters.label.source)
[regions]=regionname(voxelsT,mapparameters.label.rf,mapparameters.label.ROI,mapparameters.label.ROInames,mapparameters.label.nearest);
end
% Modify T-values for negative
if strcmpi(mapparameters.sign,'neg')
voxelsT(:,2)=-1*voxelsT(:,2);
end
% Output an image of the peak coordinates (peak number and cluster number)
peakcluster2(A,voxelsT,infoI1,[mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname]); %outputs revised cluster numbers
Iclust=spm_read_vols(spm_vol([mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_clusters.nii']));
if isempty(mapparameters.sphere) && isempty(mapparameters.clustersphere)
if strcmpi(mapparameters.sign,'neg')
Ithresh=-1.*I.*(Iclust>0);
else
Ithresh=I.*(Iclust>0);
end
out=infoI1;
out.fname=[mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '.nii'];
out.descrip=['Thresholded Map @ thresh ' num2str(mapparameters.thresh2) ' and cluster extent ' num2str(mapparameters.cluster) ' in ' mapparameters.maskname];
spm_write_vol(out,Ithresh);
end
Iclusthdr=spm_vol([mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_clusters.nii']);
[Iclust, Ixyz]=spm_read_vols(Iclusthdr);
Ipeak=Iclust.*0;
Ipeak2=Ipeak;
if ~isempty(mapparameters.sphere) || ~isempty(mapparameters.clustersphere)
[simg XYZmmY]=spm_read_vols(Iclusthdr);
sphereimg=simg*0;
xY.def='sphere';
if ~isempty(mapparameters.sphere)
xY.spec=mapparameters.sphere;
else
xY.spec=mapparameters.clustersphere;
end
for ii=size(voxelsT,1):-1:1
xY.xyz=voxelsT(ii,3:5)';
[xY, XYZmm, j] = spm_ROI(xY, XYZmmY);
sphereimg(j)=ii;
end
if ~isempty(mapparameters.clustersphere)
sphereimg=(Iclust>0).*sphereimg;
end
Ithresh(sphereimg<=0)=0; Ithresh(isnan(sphereimg))=0;
spm_write_vol(Iclusthdr,sphereimg);
spm_write_vol(out,Ithresh);
n2=hist(sphereimg(:),0:max(sphereimg(:)));
voxelsT(:,1)=n2(2:end);
voxelsT(:,12)=1:size(voxelsT,1);
end
%Try to determine orientation
oris = [[Iclusthdr.mat(1,1) Iclusthdr.mat(2,2) Iclusthdr.mat(3,3)];...
[Iclusthdr.mat(1,1) Iclusthdr.mat(3,2) Iclusthdr.mat(2,3)];...
[Iclusthdr.mat(2,1) Iclusthdr.mat(1,2) Iclusthdr.mat(3,3)];...
[Iclusthdr.mat(2,1) Iclusthdr.mat(3,2) Iclusthdr.mat(1,3)];...
[Iclusthdr.mat(3,1) Iclusthdr.mat(1,2) Iclusthdr.mat(2,3)];...
[Iclusthdr.mat(3,1) Iclusthdr.mat(2,2) Iclusthdr.mat(1,3)]];
ori = find(mean(abs(oris)>.000001',2) == 1);
if numel(ori)>1 % This part has not been fully tested
oristmp=oris;
tmp(1)=max(abs(diff([1 1 1 1; 2 1 1 1]*Iclusthdr.mat')));
oristmp(abs(oris)==tmp(1))=1;
tmp(2)=max(abs(diff([1 1 1 1; 1 2 1 1]*Iclusthdr.mat')));
oristmp(abs(oris)==tmp(2))=1;
tmp(3)=max(abs(diff([1 1 1 1; 1 1 2 1]*Iclusthdr.mat')));
oristmp(abs(oris)==tmp(3))=1;
ori = find(mean(oristmp,2)==1);
end
%Determine cross hair size, if value is infite, crosshairs are 2 voxels
a(1)=ceil(2*2/abs(oris(ori,1)));
a(2)=ceil(2*2/abs(oris(ori,2)));
a(3)=ceil(2*2/abs(oris(ori,3)));
a(~isfinite(a))=2;
for ii=1:size(voxelsT,1)
[Ipeakxyz,Ipeakind] = spm_XYZreg('NearestXYZ',voxelsT(ii,3:5),Ixyz);
[Ix,Iy,Iz]=ind2sub(size(Ipeak),Ipeakind);
if (Ix-a(1))<=0 && Ix+a(1)<=Iclusthdr.dim(1)
Ipeak(1:Ix+a(1),Iy,Iz)=ii;
elseif (Ix-a(1))<=0
Ipeak(1:Iclusthdr.dim(1),Iy,Iz)=ii;
else
Ipeak(Ix-a(1):Ix+a(1),Iy,Iz)=ii;
end
if (Iy-a(2))<=0 && Iy+a(2)<=Iclusthdr.dim(2)
Ipeak(Ix,1:Iy+a(2),Iz)=ii;
elseif (Iy-a(2))<=0
Ipeak(Ix,1:Iclusthdr.dim(2),Iz)=ii;
else
Ipeak(Ix,Iy-a(2):Iy+a(2),Iz)=ii;
end
if (Iz-a(3))<=0 && Iz+a(3)<=Iclusthdr.dim(3)
Ipeak(Ix,Iy,1:Iz+a(3))=ii;
elseif (Iz-a(3))<=0
Ipeak(Ix,Iy,1:Iclusthdr.dim(3))=ii;
else
Ipeak(Ix,Iy,Iz-a(3):Iz+a(3))=ii;
end
if (Ix-a(1))<=0 && Ix+a(1)<=Iclusthdr.dim(1)
Ipeak2(1:Ix+a(1),Iy,Iz)=voxelsT(ii,11);
elseif (Ix-a(1))<=0
Ipeak2(1:Iclusthdr.dim(1),Iy,Iz)=voxelsT(ii,11);
else
Ipeak2(Ix-a(1):Ix+a(1),Iy,Iz)=voxelsT(ii,11);
end
if (Iy-a(2))<=0 && Iy+a(2)<=Iclusthdr.dim(2)
Ipeak2(Ix,1:Iy+a(2),Iz)=voxelsT(ii,11);
elseif (Iy-a(2))<=0
Ipeak2(Ix,1:Iclusthdr.dim(2),Iz)=voxelsT(ii,11);
else
Ipeak2(Ix,Iy-a(2):Iy+a(2),Iz)=voxelsT(ii,11);
end
if (Iz-a(3))<=0 && Iz+a(3)<=Iclusthdr.dim(3)
Ipeak2(Ix,Iy,1:Iz+a(3))=voxelsT(ii,11);
elseif (Iz-a(3))<=0
Ipeak2(Ix,Iy,1:Iclusthdr.dim(3))=voxelsT(ii,11);
else
Ipeak2(Ix,Iy,Iz-a(3):Iz+a(3))=voxelsT(ii,11);
end
end
out=infoI1;
out.fname=[mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_peaknumber.nii'];
out.descrip=['Peaks of Thresholded Map @ thresh ' num2str(mapparameters.thresh2) ' and cluster extent ' num2str(mapparameters.cluster) ' in ' mapparameters.maskname];
out.pinfo(1)=1;
spm_write_vol(out,Ipeak);
out=infoI1;
out.pinfo(1)=1;
out.fname=[mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_peakcluster.nii'];
out.descrip=['Peaks of Thresholded Map @ thresh ' num2str(mapparameters.thresh2) ' and cluster extent ' num2str(mapparameters.cluster) ' in ' mapparameters.maskname];
spm_write_vol(out,Ipeak2);
%voxelsT(:,7)=[]; Don't want to strip out raw cluster numbers.
end
% Compute voxel and cluster stats
STAT=mapparameters.type;
if ~isempty(mapparameters.df1)
vstats=1; %Compute voxel stats
cstats=1; %Compute cluster stats
else
vstats=0; %Don't Compute voxel stats
cstats=0; %Don't Compute cluster stats
end
if strcmpi(STAT,'F')
df=[mapparameters.df1 mapparameters.df2];
elseif strcmpi(STAT,'T')
df=[1 mapparameters.df1];
elseif strcmpi(STAT,'Z')
df=[];
cstats=0;
else
vstats=0;
cstats=0;
end
if ~isfield(mapparameters,'RESELS')
cstats=0;
end
if strcmp(mapparameters.sign,'neg') && vstats
voxelsT(:,2)=-voxelsT(:,2);
end
% Fill in voxelstats
%--------------------------------------------------------------
if vstats
[voxelstats,sigthresh]=calc_voxelstats(mapparameters,voxelsT,voxelsT18,voxelsT26,STAT,df,QPs,sigthresh,SV,FIVEF);
end
% Fill in clusterstats
%--------------------------------------------------------------
if cstats && ~FIVEF
try
clusterstats=calc_clusterstats(mapparameters,voxelsT,STAT,df,QPs,QPc,cstats);
catch
clusterstats=calc_clusterstats(mapparameters,voxelsT,STAT,df,QPs,[],cstats);
end
end
if ~FIVEF
voxelsT(:,1)=abs(voxelsT(:,1));
if strcmp(mapparameters.sign,'neg') && vstats
voxelsT(:,2)=-voxelsT(:,2);
voxelstats(:,5)=-voxelstats(:,5);
end
try
savepeaks(mapparameters,regions,voxelsT,voxelstats,clusterstats,sigthresh);
catch
savepeaks(mapparameters,[],voxelsT,voxelstats,clusterstats,sigthresh);
end
try
voxels={voxelsT regions(:,2)};
catch
voxels={voxelsT};
end
end
if ~FIVEF && ~isempty(mapparameters.label.source)
AnatomicalDistTable=AnatomicalDist([mapparameters.out '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_clusters.nii'],mapparameters.label.source); %#ok<*NASGU>
[path, filename]=fileparts(mapparameters.out);
if isempty(path)
path=pwd;
end
save([path filesep 'AnatDist_' filename '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_' mapparameters.label.source '.mat'],'AnatomicalDistTable')
%movefile('tmp.txt',[path filesep 'AnatReport_' filename '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_' mapparameters.label.source '.txt'])
clear path filename
end
if mapparameters.savecorrected.do==1
for tt=1:numel(mapparameters.savecorrected.type)
cmapparameters=mapparameters;
cmapparameters.correctedloop=1;
cmapparameters.UID=[UID '_' mapparameters.savecorrected.type{tt}, '_corr' num2str(mapparameters.threshc)];
if strcmpi(mapparameters.savecorrected.type{tt},'cFWE')
[jnk,tmp]=strtok(sigthresh{5,1},':');
cmapparameters.cluster=str2num(tmp(2:end));
cmapparameters.correction=mapparameters.savecorrected.type{tt};
cmapparameters.correctionthresh=mapparameters.threshc;
elseif strcmpi(mapparameters.savecorrected.type{tt},'cFDR')
[jnk,tmp]=strtok(sigthresh{6,1},':');
cmapparameters.cluster=str2num(tmp(2:end));
cmapparameters.correction=mapparameters.savecorrected.type{tt};
cmapparameters.correctionthresh=mapparameters.threshc;
elseif strcmpi(mapparameters.savecorrected.type{tt},'vFWE')
[jnk,tmp]=strtok(sigthresh{1,1},':');
tmp=strtok(tmp,',');
cmapparameters.thresh=str2num(tmp(2:end));
if ~mapparameters.savecorrected.changecluster
cmapparameters.cluster=0;
end
cmapparameters.correction=mapparameters.savecorrected.type{tt};
cmapparameters.correctionthresh=mapparameters.threshc;
elseif strcmpi(mapparameters.savecorrected.type{tt},'vFDR')
[jnk,tmp]=strtok(sigthresh{2,1},':');
tmp=strtok(tmp,',');
cmapparameters.thresh=str2num(tmp(2:end));
if ~mapparameters.savecorrected.changecluster
cmapparameters.cluster=0;
end
cmapparameters.correction=mapparameters.savecorrected.type{tt};
cmapparameters.correctionthresh=mapparameters.threshc;
elseif strcmpi(mapparameters.savecorrected.type{tt},'tFDR26')
[jnk,tmp]=strtok(sigthresh{4,1},':');
cmapparameters.thresh=str2num(tmp(2:end));
if ~mapparameters.savecorrected.changecluster
cmapparameters.cluster=0;
end
cmapparameters.correction=mapparameters.savecorrected.type{tt};
cmapparameters.correctionthresh=mapparameters.threshc;
elseif strcmpi(mapparameters.savecorrected.type{tt},'tFDR18')
[jnk,tmp]=strtok(sigthresh{3,1},':');
cmapparameters.thresh=str2num(tmp(2:end));
if ~mapparameters.savecorrected.changecluster
cmapparameters.cluster=0;
end
cmapparameters.correction=mapparameters.savecorrected.type{tt};
cmapparameters.correctionthresh=mapparameters.threshc;
end
[cvoxels cvoxelstats cclusterstats csigthresh cregions cmapparameters cUID]=peak_nii(image,cmapparameters);
end
end
end
%% Embedded functions
%% Save Peaks
function savepeaks(mapparameters,regions,voxelsT,voxelstats,clusterstats,sigthresh)
[path,file,ext]=fileparts(mapparameters.out);
if ~isempty(path)
save([path filesep 'Peak_' file ext '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '.mat'],'regions', 'voxelsT','mapparameters','voxelstats','clusterstats','sigthresh')
save([path filesep 'Peak_' file ext '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_structure.mat'],'mapparameters')
else
save(['Peak_' file ext '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '.mat'],'regions', 'voxelsT','mapparameters','voxelstats','clusterstats','sigthresh')
save(['Peak_' file ext '_thresh' num2str(mapparameters.thresh2) '_extent' num2str(mapparameters.cluster) mapparameters.maskname '_structure.mat'],'mapparameters')
end
end
%% Vox_distance
function [N,Distance] = vox_distance(voxelsT)
% vox_distance compute the distance between local maxima in an image
% The input is expected to be an N-M matrix with columns 2,3,4 being X,Y,Z
% coordinates
%
% pdist is only available with Statistics Toolbox in recent versions of
% MATLAB, thus, the slower code is secondary if the toolbox is unavailable.
% Speed difference is dependent on cluster sizes, 3x at 1000 peaks.
N=sortrows(voxelsT,-1);
try
Distance=squareform(pdist(N(:,3:5)));
catch
Distance = zeros(size(N,1),size(N,1));
for ii = 1:size(N,1);
TmpD = zeros(size(N,1),3);
for kk = 1:3;
TmpD(:,kk) = (N(:,kk+2)-N(ii,kk+2)).^2;
end
TmpD = sqrt(sum(TmpD,2));
Distance(:,ii) = TmpD;
end
end
end
%% Peakcluster
function A=peakcluster(L,conn,infoI1,out)
dim = infoI1.dim;
vol = zeros(dim(1),dim(2),dim(3));
indx = sub2ind(dim,L(1,:)',L(2,:)',L(3,:)');
vol(indx) = 1;
[cci,num] = spm_bwlabel(vol,conn);
A = cci(indx');
if nargin==4
infoI1.fname=[out '_clusters.nii'];
infoI1.descrip='clusters';
infoI1.pinfo=[1 0 0]';
A=transpose(A);
L=transpose(L);
A(:,2:4)=L(:,1:3);
vol=zeros(dim(1),dim(2),dim(3));
for ii=1:size(A,1)
vol(A(ii,2),A(ii,3),A(ii,4))=A(ii,1);
end
spm_write_vol(infoI1,vol);
end
end
%% Regionname
function [ROIinfo]=regionname(voxels,rf,ROI,ROInames,nearest)
ROIinfo=cell(size(voxels,1),2);
if nearest==0
for jj=1:size(voxels,1)
[xyz,ii] = spm_XYZreg('NearestXYZ',voxels(jj,3:5),rf.XYZmm); % use all voxels
try
ROIinfo{jj,1}=rf.img(ii);
if ROIinfo{jj,1}~=0
ROIind=find([ROI.ID]==ROIinfo{jj,1});
ROIinfo{jj,2}=ROInames{ROIind};
else
ROIinfo{jj,2}='undefined';
end
catch
ROIinfo{jj,1}=0;
ROIinfo{jj,2}='undefined';
end
end
else
nz_ind=find(rf.img>0);
for jj=1:size(voxels,1)
[xyz,j] = spm_XYZreg('NearestXYZ',voxels(jj,3:5),rf.XYZmm(:,nz_ind)); % use only voxels with a region greater than 0.
try
ii=nz_ind(j);
if isempty(ii)
invovkecatchstatement
end
[junk,D]=vox_distance([0 0 xyz';voxels(jj,1:5)]); % need to pad xyz, voxel is made to be 1x4 with 2-4 being coordianates
catch
D(1,2)=Inf;
end
if D(1,2)>8 % further than 5 mm from region
ROIinfo{jj,1}=0;
ROIinfo{jj,2}='undefined';
else
ROIinfo{jj,1}=rf.img(ii);
if ROIinfo{jj,1}~=0
ROIind=find([ROI.ID]==ROIinfo{jj,1});
ROIinfo{jj,2}=ROInames{ROIind};
else
ROIinfo{jj,2}='undefined';
end
end
end
end
end
%% Peakcluster2
function peakcluster2(A,voxelsT,infoI1,out)
dim = infoI1.dim;
vol = zeros(dim(1),dim(2),dim(3));
clusters=unique(voxelsT(:,11));
A(:,6)=-1*A(:,2); % label any small clusters (or clusters with no peaks due to elimination)
% A(:,1)==NaN --> Cluster was smaller than extent - will appear in Anat
% Table this way.
for ii=1:numel(clusters)
firstvoxel=find(voxelsT(:,11)==ii);
A(A(:,2)==voxelsT(firstvoxel(1),7),6)=ii;
end
if nargin==4
infoI1.fname=[out '_clusters.nii'];
infoI1.descrip='clusters';
infoI1.pinfo=[1 0 0]';
for ii=1:size(A,1)
vol(A(ii,3),A(ii,4),A(ii,5))=A(ii,6);
end
spm_write_vol(infoI1,vol);
end
end
%% calc_voxelstats
function [voxelstats,sigthresh]=calc_voxelstats(mapparameters,voxelsT,voxelsT18,voxelsT26,STAT,df,QPs,sigthresh,SV,FIVEF)
if ~isfield(mapparameters,'RESELS')
vstatsR=0;
else
vstatsR=1;
Pu=zeros(size(voxelsT,1),1);
Qp=zeros(size(voxelsT,1),1);
Qp1=zeros(size(voxelsT,1),1);
end
if ~FIVEF
Pz=zeros(size(voxelsT,1),1);
for ii=1:size(voxelsT,1)
Pz(ii) = spm_P(1,0,voxelsT(ii,2),df,STAT,1,1,numel(QPs)); % uncorrected p values
end
if Pz < eps*10
Ze = Inf;
else
Ze = spm_invNcdf(1 - Pz);
end
end
Qu=zeros(size(voxelsT,1),1);
if vstatsR
[P,p,Eu] = spm_P_RF(1,0,mapparameters.thresh,df,STAT,mapparameters.RESELS,1);
%Topological FDR
Ez = zeros(1,numel(voxelsT18));
for i = 1:length(voxelsT18)
[P,p,Ez(i)] = spm_P_RF(1,0,voxelsT18(i),df,STAT,mapparameters.RESELS,1);
end
[Ps, J] = sort(Ez ./ Eu, 'ascend');
QPp18=Ps';
Fi = (1:length(Ps))/length(Ps)*mapparameters.threshc/1;%cV = 1; % Benjamini & Yeuketeli cV for independence/PosRegDep case
Ifdr = find(QPp18' <= Fi, 1, 'last');
if isempty(Ifdr)
sigthresh{3,1}=[sigthresh{3,1} 'Inf'];
else
if strcmpi(STAT,'T')
sigthresh{3,1}=[sigthresh{3,1} num2str(voxelsT18(J(Ifdr))) ',' num2str(1-spm_Tcdf(voxelsT18(J(Ifdr)),df(2)))];
elseif strcmpi(STAT,'F')
sigthresh{3,1}=[sigthresh{3,1} num2str(voxelsT18(J(Ifdr))) ',' num2str(1-spm_Fcdf(voxelsT18(J(Ifdr)),df))];
elseif strcmpi(STAT,'Z')
sigthresh{3,1}=[sigthresh{3,1} num2str(voxelsT18(J(Ifdr))) ',' num2str(1-spm_Ncdf(voxelsT18(J(Ifdr)),0,1))];
else
sigthresh{3,1}=[sigthresh{3,1} num2str(voxelsT18(J(Ifdr)))];
end
end
% peak_nii topological correction (difference is in how peaks are
% defined.
Ez = zeros(1,numel(voxelsT26));
for i = 1:length(voxelsT26)
[P,p,Ez(i)] = spm_P_RF(1,0,voxelsT26(i),df,STAT,mapparameters.RESELS,1);
end
[Ps, J] = sort(Ez ./ Eu, 'ascend');
QPp26=Ps';
Fi = (1:length(Ps))/length(Ps)*mapparameters.threshc/1;%cV = 1; % Benjamini & Yeuketeli cV for independence/PosRegDep case
Ifdr = find(QPp26' <= Fi, 1, 'last');
if isempty(Ifdr)
sigthresh{4,1}=[sigthresh{4,1} 'Inf'];
else
if strcmpi(STAT,'T')
sigthresh{4,1}=[sigthresh{4,1} num2str(voxelsT26(J(Ifdr))) ',' num2str(1-spm_Tcdf(voxelsT26(J(Ifdr)),df(2)))];
elseif strcmpi(STAT,'F')
sigthresh{4,1}=[sigthresh{4,1} num2str(voxelsT26(J(Ifdr))) ',' num2str(1-spm_Fcdf(voxelsT26(J(Ifdr)),df))];
elseif strcmpi(STAT,'Z')
sigthresh{4,1}=[sigthresh{4,1} num2str(voxelsT26(J(Ifdr))) ',' num2str(1-spm_Ncdf(voxelsT26(J(Ifdr)),0,1))];
else
sigthresh{4,1}=[sigthresh{4,1} num2str(voxelsT26(J(Ifdr)))];
end
end
clear Fi Ifdr J
if strcmpi(STAT,'T')
sigthresh{1,1}=[sigthresh{1,1} num2str(spm_uc(mapparameters.threshc,df,STAT,mapparameters.RESELS,1,SV)) ',' num2str(1-spm_Tcdf(spm_uc(mapparameters.threshc,df,STAT,mapparameters.RESELS,1,SV),df(2)))];
elseif strcmpi(STAT,'F')
sigthresh{1,1}=[sigthresh{1,1} num2str(spm_uc(mapparameters.threshc,df,STAT,mapparameters.RESELS,1,SV)) ',' num2str(1-spm_Fcdf(spm_uc(mapparameters.threshc,df,STAT,mapparameters.RESELS,1,SV),df))];
elseif strcmpi(STAT,'Z')
sigthresh{1,1}=[sigthresh{1,1} num2str(spm_uc(mapparameters.threshc,df,STAT,mapparameters.RESELS,1,SV)) ',' num2str(1-spm_Ncdf(spm_uc(mapparameters.threshc,df,STAT,mapparameters.RESELS,1,SV),0,1))];
else
sigthresh{1,1}=[sigthresh{1,1} num2str(spm_uc(mapparameters.threshc,df,STAT,mapparameters.RESELS,1,SV))];
end
end
%disp(['SPM peak count: ' num2str(numel(voxelsT18))])
%disp(['peak_nii peak count: ' num2str(numel(voxelsT26))])
%disp(['Difference as percent of peak_nii: ' num2str((((numel(voxelsT18)-numel(voxelsT26))/numel(voxelsT26)))*100)])
%disp(sigthresh)
if FIVEF
voxelstats=[];
else
for ii=1:size(voxelsT,1)
if vstatsR && ~isfield(mapparameters,'exactvoxel')
Pu(ii) = spm_P(1,0,voxelsT(ii,2),df,STAT,mapparameters.RESELS,1,numel(QPs)); % FWE-corrected {based on Z}
Qp18(ii,1) = spm_P_peakFDR(voxelsT(ii,2),df,STAT,mapparameters.RESELS,1,mapparameters.thresh,QPp18); % topological FDR voxel q-value, based on Z (19 voxel peaks)
Qp26(ii,1) = spm_P_peakFDR(voxelsT(ii,2),df,STAT,mapparameters.RESELS,1,mapparameters.thresh,QPp26); % topological FDR voxel q-value, based on Z (27 voxel peaks)
elseif vstatsR
Pu(ii) = spm_P(1,0,voxelsT(ii,2),df,STAT,mapparameters.RESELS,1,numel(QPs)); % FWE-corrected {based on Z}
Qp18(ii,1) = NaN;
Qp26(ii,1) = NaN;
end
Qu(ii) = spm_P_FDR(voxelsT(ii,2),df,STAT,1,QPs); % voxel FDR-corrected q-value
end
try
Qp26(voxelsT(:,1)<0)=NaN;
voxelstats=[round([Pu Qp18 Qp26 Qu voxelsT(:,2) Ze Pz]*1000)/1000 voxelsT(:,3:5) voxelsT(:,7)];
catch
voxelstats=round([NaN(size(voxelsT,1),3) Qu voxelsT(:,2) Ze Pz]*1000)/1000;
end
end
end
%% Calc_clusterstats
function clusterstats=calc_clusterstats(mapparameters,voxelsT,STAT,df,QPs,QPc,cstats)
[jnk,ind]=unique(voxelsT(:,11),'first');
voxelsT(ind,1)=abs(voxelsT(ind,1));
K=voxelsT(ind,1)*(1/prod(mapparameters.FWHM));
Pk=NaN(numel(K),1);
Pn=NaN(numel(K),1);
Qc=NaN(numel(K),1);
try
if cstats
for ii=1:numel(K)
[Pk(ii) Pn(ii)] = spm_P(1,K(ii),mapparameters.thresh,df,STAT,mapparameters.RESELS,1,numel(QPs)); % [un]corrected {based on K}
end
end
catch
Pk(1:numel(K),1)=NaN;
Pn(1:numel(K),1)=NaN;
end
try
if cstats
for ii=1:numel(K)
Qc(ii) = spm_P_clusterFDR(K(ii),df,STAT,mapparameters.RESELS,1,mapparameters.thresh,QPc'); % topological FDR-corrected voxel q-value, based on K
end
end
catch
Qc(1:numel(K),1)=NaN;
end
clusterstats=[round([(1:numel(K))' Pk Qc voxelsT(ind,1) Pn]*1000)/1000 voxelsT(ind,3:5)];
end
%% Calc_NSclusterstats
function NSclusterstats=calc_NSclusterstats(mapparameters,voxelsT,STAT,df,QPs,QPc,cstats)
[jnk,ind]=unique(voxelsT(:,7),'first');
voxelsT(ind,1)=abs(voxelsT(ind,1));
K=voxelsT(ind,8);
Pk=NaN(numel(K),1);
Pn=NaN(numel(K),1);
Qc=NaN(numel(K),1);
try
if cstats
for ii=1:numel(K)
[Pk(ii) Pn(ii)] = spm_P(1,K(ii),mapparameters.thresh,df,STAT,mapparameters.RESELS,1,numel(QPs)); % [un]corrected {based on K}
end
end
catch
Pk(1:numel(K),1)=NaN;
Pn(1:numel(K),1)=NaN;
end
try
if cstats
for ii=1:numel(K)
Qc(ii) = spm_P_clusterFDR(K(ii),df,STAT,mapparameters.RESELS,1,mapparameters.thresh,QPc'); % topological FDR-corrected voxel q-value, based on K
end
end
catch
Qc(1:numel(K),1)=NaN;
end
clusterstats=[round([(1:numel(K))' Pk Qc voxelsT(ind,1) Pn]*1000)/1000 voxelsT(ind,3:5)];
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
cluster_nii.m
|
.m
|
MRtools_Hoffman2-master/peak_nii/cluster_nii.m
| 9,405 |
utf_8
|
cc65fcdb56ad73f4cd30c65c52f51d77
|
function [voxelsT region invar]=cluster_nii(image,varstruct)
%%
% cluster_nii will find the current cluster and cluster
% INPUTS:
% image string required. This should be a nii or img file.
% varstruct is either a .mat file or a pre-load structure with the
% following fields:
% type: statistic type, 'T' or 'F' or 'none'
% cluster: cluster extent threshold in voxels
% df1: numerator degrees of freedom for T/F-test (if 0<thresh<1)
% df2: denominator degrees of freedom for F-test (if 0<thresh<1)
% nearest: 0 or 1, 0 for leaving some clusters/peaks undefined, 1 for finding the
% nearest label
% label: optional to label clusters, options are 'aal_MNI_V4';
% 'Nitschke_Lab'; FSL ATLASES: 'JHU_tracts', 'JHU_whitematter',
% 'Thalamus', 'Talairach', 'MNI', 'HarvardOxford_cortex', 'Cerebellum-flirt', 'Cerebellum=fnirt', and 'Juelich'.
% 'HarvardOxford_subcortical' is not available at this time because
% the labels don't match the image.
% Other atlas labels may be added in the future
% thresh: T/F statistic or p-value to threshold the data or 0
%
% OUTPUTS:
% voxels -- table of peaks
% col. 1 - Cluster size
% col. 2 - T/F-statistic
% col. 3 - X coordinate
% col. 4 - Y coordinate
% col. 5 - Z coordinate
% col. 6 - region number
% col. 7 - region name
% region - flag for peak_extract_nii
%
% EXAMPLE: voxels=cluster_nii('imagename',varstruct)
%
% License:
% Copyright (c) 2011, Donald G. McLaren and Aaron Schultz
% All rights reserved.
%
% Redistribution, with or without modification, is permitted provided that the following conditions are met:
% 1. Redistributions must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
% 2. All advertising materials mentioning features or use of this software must display the following acknowledgement:
% This product includes software developed by the Harvard Aging Brain Project.
% 3. Neither the Harvard Aging Brain Project nor the
% names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
% 4. You are not permitted under this Licence to use these files
% commercially. Use for which any financial return is received shall be defined as commercial use, and includes (1) integration of all
% or part of the source code or the Software into a product for sale or license by or on behalf of Licensee to third parties or (2) use
% of the Software or any derivative of it for research with the final aim of developing software products for sale or license to a third
% party or (3) use of the Software or any derivative of it for research with the final aim of developing non-software products for sale
% or license to a third party, or (4) use of the Software to provide any service to an external organisation for which payment is received.
%
% THIS SOFTWARE IS PROVIDED BY DONALD G. MCLAREN ([email protected]) AND AARON SCHULTZ ([email protected])
% ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
% FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
% SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
% DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
% TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
% USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% cluster_nii.v1 -- Last modified on 2/23/2011 by Donald G. McLaren, PhD
% ([email protected])
% Wisconsin Alzheimer's Disease Research Center - Imaging Core, Univ. of
% Wisconsin - Madison
% Neuroscience Training Program and Department of Medicine, Univ. of
% Wisconsin - Madison
% GRECC, William S. Middleton Memorial Veteren's Hospital, Madison, WI
% GRECC, Bedford VAMC
% Department of Neurology, Massachusetts General Hospital and Havard
% Medical School
%
% In accordance with the licences of the atlas sources as being distibuted solely
% for non-commercial use; neither this program, also soley being distributed for non-commercial use,
% nor the atlases containe herein should therefore not be used for commercial purposes; for such
% purposes please contact the primary co-ordinator for the relevant
% atlas:
% Harvard-Oxford: [email protected]
% JHU: [email protected]
% Juelich: [email protected]
% Thalamus: [email protected]
% Cerebellum: [email protected]
% AAL_MNI_V4: [email protected] and/or [email protected]
%
% For the program in general, please contact [email protected]
%
%% Check inputs
if exist(image,'file')==2
I=spm_vol(image);
infoI=I;
[I,voxelcoord]=spm_read_vols(I);
if nansum(nansum(nansum(abs(I))))==0
error(['Error: ' image ' is all zeros or all NaNs'])
end
else
error(['File ' image ' does not exist'])
end
try
if exist(varstruct,'file')==2
varstruct=load(varstruct);
end
catch
end
if ~isstruct(varstruct)
error('varstruct is not a structure. Aaron, this should not be possible.')
end
%% Format input instructure
while numel(fields(varstruct))==1
F=fieldnames(varstruct);
varstruct=varstruct.(F{1}); %Ignore coding error flag.
end
%Set defaults:
varstruct.sign='pos';
varstruct.conn=18;
varstrcut.out=[];
varstruct.voxlimit=10; %irrelevant since only the maximum is considered
varstruct.separation=20; %irrelevant since only the maximum is considered
varstruct.SPM=1; % irrelevant since only the maximum is considered
varstruct.mask=[];
invar=peak_nii_inputs(varstruct,infoI.fname,nargout);
if isfield(varstruct,'voxel')
if size(varstruct.voxel)==[3 1]
invar.voxel=varstruct.voxel;
elseif size(varstruct.voxel)==[1 3]
invar.voxel=varstruct.voxel';
else
error('voxel is not a voxel. Aaron, this should not be possible.')
end
else
error('voxel not defined. Aaron, this should not be possible.')
end
%% Program begins here
% Find significant voxels
disp(['Threshold is:' num2str(invar.thresh)])
ind=find(I>invar.thresh);
if isempty(ind)
error(['NO MAXIMA ABOVE ' num2str(invar.thresh) '.'])
else
[L(1,:),L(2,:),L(3,:)]=ind2sub(infoI.dim,ind);
end
% Cluster signficant voxels
A=peakcluster(L,invar.conn,infoI); % A is the cluster of each voxel
A=transpose(A);
n=hist(A,1:max(A));
for ii=1:size(A,1)
if n(A(ii))<invar.cluster % removes clusters smaller than extent threshold
A(ii,1:2)=NaN;
else
A(ii,1:2)=[n(A(ii)) A(ii,1)];
end
end
% Combine A (cluster labels) and L (voxel indicies)
L=L';
A(:,3:5)=L(:,1:3);
% Remove voxels that are not the current cluster
x=spm_XYZreg('NearestXYZ',invar.voxel,voxelcoord);
xM=round(infoI.mat \ [x; 1]);
ind=find(((A(:,3)==xM(1))+(A(:,4)==xM(2))+(A(:,5)==xM(3)))==3);
if isempty(ind)
error('voxel is not in a cluster');
end
A=A(A(:,2)==A(ind,2),:); %finds current cluster
A(:,2)=1; %label it as cluster 1
region=[]; %used as a flag in peak_extract_nii
%Output temp cluster file
infoI.fname='temp_cluster.nii';
infoI.descrip='temp cluster';
infoI.pinfo=[1 0 0]';
vol=zeros(infoI.dim(1),infoI.dim(2),infoI.dim(3));
for ii=1:size(A,1)
vol(A(ii,3),A(ii,4),A(ii,5))=1;
end
spm_write_vol(infoI,vol);
% Find the peakin the current cluster
voxelsT=cell(1,5);
ind=sub2ind(infoI.dim,A(:,3),A(:,4),A(:,5));
maxind=find(I(ind)==max(I(ind)));
voxind=sub2ind(infoI.dim,A(maxind,3),A(maxind,4),A(maxind,5));
voxelsT{1,1}=A(maxind,1);
voxelsT{1,2}=I(voxind);
voxelsT{1,3}=voxelcoord(1,voxind);
voxelsT{1,4}=voxelcoord(2,voxind);
voxelsT{1,5}=voxelcoord(3,voxind);
% Label Peaks
if ~isempty(invar.label.source)
[voxelsT{1,6} voxelsT{1,7}]=regionname(cell2mat(voxelsT),invar.label.rf,invar.label.ROI,invar.label.ROInames,invar.label.nearest);
end
%% Peakcluster
function A=peakcluster(L,conn,infoI1)
dim = infoI1.dim;
vol = zeros(dim(1),dim(2),dim(3));
indx = sub2ind(dim,L(1,:)',L(2,:)',L(3,:)');
vol(indx) = 1;
[cci,num] = spm_bwlabel(vol,conn);
A = cci(indx');
return
%% Regionname
function [ROInum ROIname]=regionname(voxel,rf,ROI,ROInames,nearest)
if nearest==0
[xyz,ii] = spm_XYZreg('NearestXYZ',voxel(3:5),rf.XYZmm); % use all voxels
ROInum=rf.img(ii);
else
nz_ind=find(rf.img>0);
[xyz,j] = spm_XYZreg('NearestXYZ',voxel(3:5),rf.XYZmm(:,nz_ind)); % use only voxels with a region greater than 0.
ii=nz_ind(j);
[junk,D]=vox_distance([0 0 xyz';voxel(1:5)]); % need to pad xyz, voxel is made to be 1x4 with 2-4 being coordianates
if D(1,2)>8 % further than 5 mm from region
ROInum=0;
else
ROInum=rf.img(ii);
end
end
if ROInum~=0
ROIind=find([ROI.ID]==ROInum);
ROIname=ROInames{ROIind};
else
ROIname='undefined';
end
return
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
label_peaks.m
|
.m
|
MRtools_Hoffman2-master/peak_nii/label_peaks.m
| 11,785 |
utf_8
|
140977839c187a93ba333672ee8a7f67
|
function peaks_wlabels=label_peaks(label,peaks,nearest)
%%
% USAGE AND EXAMPLES CAN BE FOUND IN PEAK_NII_MANUAL.PDF
%
% License:
% Copyright (c) 2011, Donald G. McLaren and Aaron Schultz
% All rights reserved.
%
% Redistribution, with or without modification, is permitted provided that the following conditions are met:
% 1. Redistributions must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
% 2. All advertising materials mentioning features or use of this software must display the following acknowledgement:
% This product includes software developed by the Harvard Aging Brain Project (NIH-P01-AG036694), NIH-R01-AG027435, and The General Hospital Corp.
% 3. Neither the Harvard Aging Brain Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
% 4. You are not permitted under this License to use these files commercially. Use for which any financial return is received shall be defined as commercial use, and includes (1) integration of all or part
% of the source code or the Software into a product for sale or license by or on behalf of Licensee to third parties or (2) use of the Software or any derivative of it for research with the final
% aim of developing software products for sale or license to a third party or (3) use of the Software or any derivative of it for research with the final aim of developing non-software products for
% sale or license to a third party.
% 5. Use of the Software to provide service to an external organization for which payment is received (e.g. contract research) is permissible.
%
% THIS SOFTWARE IS PROVIDED BY DONALD G. MCLAREN ([email protected]) AND AARON SCHULTZ ([email protected]) ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
% TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
% OR CONSEQUENTIAL %DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
% LIABILITY, WHETHER IN CONTRACT, %STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% Licenses related to using various atlases are described in Peak_Nii_Atlases.PDF
%
% For the program in general, please contact [email protected]
%
% label_peaks.v1 -- Last modified on 11/15/2011 by Donald G. McLaren, PhD
% ([email protected])
% Wisconsin Alzheimer's Disease Research Center - Imaging Core, Univ. of
% Wisconsin - Madison
% Neuroscience Training Program and Department of Medicine, Univ. of
% Wisconsin - Madison
% GRECC, William S. Middleton Memorial Veteren's Hospital, Madison, WI
% GRECC, Bedford VAMC
% Department of Neurology, Massachusetts General Hospital and Havard
% Medical School
%
% For the program in general, please contact [email protected]
%
%% Program begins here
try
if ~strcmp(spm('Ver'),'SPM8')
disp('PROGRAM ABORTED:')
disp(' You must use SPM8 to process your data; however, you can use SPM.mat files')
disp(' generated with SPM2 or SPM5. In these cases, simply specify the option SPMver')
disp(' in single qoutes followed by a comma and the version number.')
disp(' ')
disp('Make sure to add SPM8 to your MATLAB path before re-running.')
return
else
addpath(fileparts(which('spm')))
end
catch
disp('PROGRAM ABORTED:')
disp(' You must use SPM8 to process your data; however, you can use SPM.mat files')
disp(' generated with SPM2 or SPM5. In these cases, simply specify the option SPMver')
disp(' in single qoutes followed by a comma and the version number.')
disp(' ')
disp('Make sure to add SPM8 to your MATLAB path before re-running.')
return
end
%% Define Output
peaks_wlabels=cell(size(peaks,1),5);
%% Error Check
if nargin<3
nearest=0;
elseif ~isnumeric(nearest)
nearest=0;
end
if nargin<2
disp('You must specify at least two input arguments')
else
if size(peaks,2)~=3
disp('Peaks must be an n-by-3 matrix of coordinates');
return
end
[labels, errorval]=roilabels(label);
if isempty(labels)
disp(['label ' label ' does not exist.']);
return
end
end
%% Find Regionnames
for vv=1:size(peaks,1)
if nearest==0
[xyz,ii] = spm_XYZreg('NearestXYZ',peaks(vv,:),labels.rf.XYZmm); % use all voxels
try
ROInum=labels.rf.img(ii);
catch
ROInum=0;
end
else
nz_ind=find(labels.rf.img>0);
[xyz,j] = spm_XYZreg('NearestXYZ',peaks(vv,:),labels.rf.XYZmm(:,nz_ind)); % use only voxels with a region greater than 0.
try
ii=nz_ind(j);
if isempty(ii)
invovkecatchstatement
end
[junk,D]=vox_distance([xyz';peaks(vv,:)]); % need to pad xyz, voxel is made to be 1x4 with 2-4 being coordianates
catch
D(1,2)=Inf;
end
if D(1,2)>8 % further than 8 mm from region
ROInum=0;
else
ROInum=labels.rf.img(ii);
end
end
if ROInum~=0
try
ROIind=find([labels.ROI.ID]==ROInum);
ROIname=labels.ROInames{ROIind};
catch
keyboard
end
else
ROIname='undefined';
end
peaks_wlabels{vv,1}=peaks(vv,1);
peaks_wlabels{vv,2}=peaks(vv,2);
peaks_wlabels{vv,3}=peaks(vv,3);
peaks_wlabels{vv,4}=ROInum; clear ROIind
peaks_wlabels{vv,5}=ROIname; clear ROIname
end
return
%% ROILABELS
function [label, errorval]=roilabels(source)
errorval=[];
peak_nii_dir=fileparts(which('peak_nii.m'));
switch source
case 'AAL_MNI_V4'
regionfile=[peak_nii_dir filesep 'aal_MNI_V4.img']; % From WFU_pickatlas
load([peak_nii_dir filesep 'aal_MNI_V4_List.mat']);
case 'Nitschke_Lab'
regionfile=[peak_nii_dir filesep 'ControlabilityMask.nii']; % Provided by Deb Kerr
load([peak_nii_dir filesep 'ControlabilityMask_List.mat']);
case 'JHU_tracts'
regionfile=[peak_nii_dir filesep 'JHU-ICBM-tracts-maxprob-thr0-1mm.nii']; % From FSL Atlas Files
load([peak_nii_dir filesep 'JHU_tract_labels.mat']);
case 'JHU_whitematter'
regionfile=[peak_nii_dir filesep 'JHU-WhiteMatter-labels-1mm.nii']; % From FSL Atlas Files
load([peak_nii_dir filesep 'JHU_labels.mat']);
case 'Thalamus'
regionfile=[peak_nii_dir filesep 'Thalamus-maxprob-thr0-1mm.nii']; % From FSL Thalamus Atlas Files
load([peak_nii_dir filesep 'Thalamus_labels.mat']);
case 'Talairach'
regionfile=[peak_nii_dir filesep 'Talairach-labels-1mm.nii']; % From FSL Talairach Atlas Files
load([peak_nii_dir filesep 'Talairach_Labels.mat']);
case 'MNI'
regionfile=[peak_nii_dir filesep 'MNI-maxprob-thr0-1mm.nii']; % From FSL MNI Atlas Files
load([peak_nii_dir filesep 'MNI_labels.mat']);
case 'HarvardOxford_cortex'
regionfile=[peak_nii_dir filesep 'HarvardOxford-cort-maxprob-thr0-1mm.nii']; % From FSL Atlas Files
load([peak_nii_dir filesep 'HarvardOxford_cortical_labels']);
%case 'HarvardOxford_subcortical' % Labels do not match image
% regionfile=[peak_nii_dir filesep 'HarvardOxford-sub-maxprob-thr0-1mm.nii']; % From FSL Atlas Files
% load([peak_nii_dir filesep 'HarvardOxford_subcortical_labels']);
case 'Juelich'
regionfile=[peak_nii_dir filesep 'Juelich-maxprob-thr0-1mm.nii']; % From FSL Atlas Files
load([peak_nii_dir filesep 'Juelich_labels.mat']);
case 'Cerebellum-flirt'
regionfile=[peak_nii_dir filesep 'Cerebellum-MNIflirt-maxprob-thr0-1mm.nii']; % From FSL Atlas Files
load([peak_nii_dir filesep 'Cerebellum_labels.mat']);
case 'Cerebellum-fnirt'
regionfile=[peak_nii_dir filesep 'Cerebellum-MNIfnirt-maxprob-thr0-1mm.nii']; % From FSL Atlas Files
load([peak_nii_dir filesep 'Cerebellum_labels.mat']);
case 'Hammers'
if exist([fileparts(which('spm')) filesep 'toolbox' filesep 'HammersAtlas' filesep 'Hammers_mith_atlas_n30r83_SPM5.img'],'file') && exist([fileparts(which('spm')) filesep 'toolbox' filesep 'HammersAtlas' filesep 'Hammers_mith_atlas_n30r83_labels.mat'],'file')
regionfile=[fileparts(which('spm')) filesep 'toolbox' filesep 'HammersAtlas' filesep 'Hammers_mith_atlas_n30r83_SPM5.img'];
load([fileparts(which('spm')) filesep 'toolbox' filesep 'HammersAtlas' filesep 'Hammers_mith_atlas_n30r83_labels.mat']);
else
errorval='The HammersAtlas is not available. Please contact Alex Hammers ([email protected]) for the atlas';
disp('===========')
disp('IMPORTANT: Once you have downloaded the Atlas files, please put them into a directory called HammersAtlas in the toolbox directory of SPM');
disp('===========')
label.source=source;
return
end
case 'BucknerYeo_7_loose'
regionfile=[peak_nii_dir filesep 'BucknerYeo' filesep 'BucknerYeo2011_7Networks_Loose_MNI152_1mm.nii']; % Derived from http://surfer.nmr.mgh.harvard.edu/fswiki/CerebellumParcellation_Buckner2011 & http://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation_Yeo2011
load([peak_nii_dir filesep 'BucknerLabels.mat']);
case 'BucknerYeo_7_tight'
regionfile=[peak_nii_dir filesep 'BucknerYeo' filesep 'BucknerYeo2011_7Networks_Tight_MNI152_1mm.nii']; % Derived from http://surfer.nmr.mgh.harvard.edu/fswiki/CerebellumParcellation_Buckner2011 & http://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation_Yeo2011
load([peak_nii_dir filesep 'BucknerLabels.mat']);
case 'BucknerYeo_17_loose'
regionfile=[peak_nii_dir filesep 'BucknerYeo' filesep 'BucknerYeo2011_17Networks_Loose_MNI152_1mm.nii']; % Derived from http://surfer.nmr.mgh.harvard.edu/fswiki/CerebellumParcellation_Buckner2011 & http://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation_Yeo2011
load([peak_nii_dir filesep 'BucknerLabels.mat']);
case 'BucknerYeo_17_tight'
regionfile=[peak_nii_dir filesep 'BucknerYeo' filesep 'BucknerYeo2011_17Networks_Tight_MNI152_1mm.nii']; % Derived from http://surfer.nmr.mgh.harvard.edu/fswiki/CerebellumParcellation_Buckner2011 & http://surfer.nmr.mgh.harvard.edu/fswiki/CorticalParcellation_Yeo2011
load([peak_nii_dir filesep 'BucknerYeo' filesep 'BucknerYeo_Network_Labels.mat']);
case 'SPMAnatomy'
regionfile=[peak_nii_dir filesep 'AllAreas_v18_peaknii.nii'];
load([peak_nii_dir filesep 'AllAreas_v18_MPM_Labels.mat']);
case 'SPMAnatomyMNI'
regionfile=[peak_nii_dir filesep 'AllAreas_v18_peaknii_MNI.nii'];
load([peak_nii_dir filesep 'AllAreas_v18_MPM_Labels.mat']);
%case 'Custom'
% regionfile=['ROI image file'];
% load(['ROIlist mat-file']);
otherwise
label=[];
return
end
label.source=source;
label.rf.hdr=spm_vol(regionfile);
[label.rf.img,label.rf.XYZmm]=spm_read_vols(label.rf.hdr);
label.ROI=ROI;
label.ROInames={ROI.Nom_C}; %ROInames is taken from ROI, where ROI is structure
if ~isfield(ROI,'ID')
display('ERROR: ROI must be a structure with an ID field that is the ID of values in region file')
return
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
spm_data_read.m
|
.m
|
MRtools_Hoffman2-master/peak_nii/spm_data_read.m
| 3,297 |
utf_8
|
1b550cecf27e5a0864c1978b02b5276d
|
function Y = spm_data_read(V,varargin)
% Read data from disk [Y = V(I)]
% FORMAT Y = spm_data_read(V)
% V - a structure array (see spm_data_hdr_read)
% Y - an array of data values; the last dimension indexes numel(V)
%
% FORMAT Y = spm_data_read(V,'slice',S)
% V - a structure array of image volumes (see spm_data_hdr_read)
% S - an array of slice indices
% Y - an array of data values with dimensions (x,y,s,v)
%
% FORMAT Y = spm_data_read(V,'xyz',XYZ)
% V - a structure array (see spm_data_hdr_read)
% XYZ - a [n x m] array of m coordinates {voxel (n=3 or 4)/vertex (n=1)}
% Y - an array of data values with dimensions (v,m)
%
% FORMAT Y = spm_data_read(V,I1,I2,...)
% V - a structure array (see spm_data_hdr_read)
% I1,I2,...- subscript arrays
% Y - an array of data values with dimensions (v,m)
%__________________________________________________________________________
% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_data_read.m 5916 2014-03-13 13:15:02Z guillaume $
if ~isstruct(V)
V = spm_data_hdr_read(V);
end
cl = class(V(1).private);
if isfield(V(1),'dat'), cl = 'nifti'; end
switch cl
case 'nifti'
if isempty(varargin)
% Y = V.private.dat(); % if numel(V)==1, is faster
Y = spm_read_vols(V);
elseif ischar(varargin{1}) && ~isequal(varargin{1},':')
switch lower(varargin{1})
case 'slice'
for i=1:numel(V), for p=1:numel(varargin{2})
Y(:,:,p,i) = spm_slice_vol(V(i),spm_matrix([0 0 varargin{2}(p)]),V(i).dim(1:2),0);
end, end
if numel(V)==1, Y=Y(:,:,:,1); end
case 'xyz'
Y = spm_get_data(V,varargin{2});
otherwise
error('Unknown input option.');
end
else
indices = varargin;
n = get_ndata(V(1).dim,indices{:});
Y = zeros(numel(V),prod(n));
for i=1:numel(V)
if numel(indices) == 1
ind = {indices{1} + (V(i).n(1)-1)*prod(V(i).dim)};
else
ind = indices;
end
Y(i,:) = reshape(V(i).private.dat(ind{:}),1,[]);
end
end
case 'gifti'
indices = varargin;
if isempty(indices)
indices = repmat({':'},1,ndims(V));
elseif strcmpi(indices{1},'xyz')
indices = {indices{2}(1,:)};
end
n = get_ndata(V(1).dim,indices{:});
Y = zeros(numel(V),prod(n));
for i=1:numel(V)
Y(i,:) = reshape(V(i).private.cdata(indices{:}),1,[]);
end
if isempty(varargin), Y = Y'; end % to be coherent with spm_read_vols
otherwise
error('Unknown data type.');
end
%==========================================================================
function n = get_ndata(dim,varargin)
n = zeros(1,numel(varargin));
for i=1:numel(varargin)
if isequal(varargin{i},':')
if i==numel(varargin)
n(i) = dim(i); %prod(dim(i:end));
else
n(i) = dim(i);
end
else
n(i) = numel(varargin{i});
end
end
|
github
|
scanUCLA/MRtools_Hoffman2-master
|
peak_extract_nii.m
|
.m
|
MRtools_Hoffman2-master/peak_nii/peak_extract_nii.m
| 35,865 |
utf_8
|
11a5a83b58ec99bfa25a7ebdb35adf0f
|
function [resultsvoxels columnlistvoxels resultscluster columnlistcluster clusters mapparams subjparams UID]=peak_extract_nii(subjectparameters,mapparameters)
% This program is designed to extract data from a set of ROIS or peak
% coordinates.
%
% peak_extract_nii.v6
%
% See PEAK_NII_TOOLBOX_MANUAL.pdf for usage details.
%
% License:
% Copyright (c) 2011-2, Donald G. McLaren and Aaron Schultz
% All rights reserved.
%
% Redistribution, with or without modification, is permitted provided that the following conditions are met:
% 1. Redistributions must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
% 2. All advertising materials mentioning features or use of this software must display the following acknowledgement:
% This product includes software developed by the Harvard Aging Brain Project (NIH-P01-AG036694), NIH-R01-AG027435, and The General Hospital Corp.
% 3. Neither the Harvard Aging Brain Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
% 4. You are not permitted under this License to use these files commercially. Use for which any financial return is received shall be defined as commercial use, and includes (1) integration of all or part
% of the source code or the Software into a product for sale or license by or on behalf of Licensee to third parties or (2) use of the Software or any derivative of it for research with the final
% aim of developing software products for sale or license to a third party or (3) use of the Software or any derivative of it for research with the final aim of developing non-software products for
% sale or license to a third party.
% 5. Use of the Software to provide service to an external organization for which payment is received (e.g. contract research) is permissible.
%
% THIS SOFTWARE IS PROVIDED BY DONALD G. MCLAREN ([email protected]) AND AARON SCHULTZ ([email protected]) ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
% TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
% OR CONSEQUENTIAL %DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
% LIABILITY, WHETHER IN CONTRACT, %STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% Licenses related to using various atlases are described in Peak_Nii_Atlases.PDF
%
% For the program in general, please contact [email protected]
%
%
% Last modified on 2/11/2012 by Donald G. McLaren ([email protected])
% GRECC, Bedford VAMC
% Department of Neurology, Massachusetts General Hospital and Havard
% Medical School
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
resultsvoxels={}; columnlistvoxels={}; resultscluster={}; columnlistcluster={}; clusters={}; UID=[]; mapparams=struct();
%%Program Begins Here
try
if ~strcmp(spm('Ver'),'SPM8')
disp('PROGRAM ABORTED:')
disp(' You must use SPM8 to process your data; however, you can use SPM.mat files')
disp(' generated with SPM2 or SPM5. In these cases, simply specify the option SPMver')
disp(' in single qoutes followed by a comma and the version number.')
disp(' ')
disp('Make sure to add SPM8 to your MATLAB path before re-running.')
return
else
addpath(fileparts(which('spm')))
end
catch
disp('PROGRAM ABORTED:')
disp(' You must use SPM8 to process your data; however, you can use SPM.mat files')
disp(' generated with SPM2 or SPM5. In these cases, simply specify the option SPMver')
disp(' in single qoutes followed by a comma and the version number.')
disp(' ')
disp('Make sure to add SPM8 to your MATLAB path before re-running.')
return
end
%Check for extraction parameters (mappparameters)
if ischar(mapparameters) && exist(mapparameters,'file')==2
try
mapparameters=load(mapparameters);
catch
error('mapparameters file does not exist.')
end
elseif ~exist('mapparameters','var')
error('mapparameters must be a file, a structure, or a variable.')
end
if isstruct(mapparameters)
while numel(fields(mapparameters))==1
F=fieldnames(mapparameters);
mapparameters=mapparameters.(F{1}); %Ignore coding error flag.
end
end
if isstruct(mapparameters) && ~isfield(mapparameters,'voxel')
if ~isfield(mapparameters,'image') || ~exist(mapparameters.image,'file')
error('mapparameters.image file does not exist.')
end
x='[voxelsT voxelstats clusterstats sigthresh regions mapparams UID]=peak_nii(mapparameters.image,mapparameters);';
elseif isstruct(mapparameters) && (size(mapparameters.voxel,1)==3 || size(mapparameters.voxel,2)==3)
if size(mapparameters.voxel,1)==3 && size(mapparameters.voxel,2)~=3
mapparameters.voxel=mapparameters.voxel';
elseif size(mapparameters.voxel,2)==3
mapparameters.voxel=mapparameters.voxel;
end
if isfield(mapparameters,'image') && exist(mapparameters.image,'file')==2
x='[voxelsT voxelstats clusterstats sigthresh region mapparams]=peak_nii(mapparameters.image,mapparameters);';
end
elseif size(mapparameters,1)==3
voxels(:,3:5)=mapparameters';
elseif size(mapparameters,2)==3
voxels(:,3:5)=mapparameters;
else
error('mapparameters must be a file that contains a structure, a Nx3 variable of peak coordinates, or a 3xN variable of peak coordinates.')
end
% Load subject structure
if ~isstruct(subjectparameters) && ~iscell(subjectparameters) && exist(subjectparameters,'file')==2
subjectparameters=load(subjectparameters);
end
if isstruct(subjectparameters)
subjparams=subjectparameters; clear subjectparameters;
while numel(fieldnames(subjparams))==1 && ~any(strcmp(fieldnames(subjparams),{'P' 'directory' 'subjectpeak' 'searchsphere' 'extractsphere' 'SPMmat' 'Imat' 'xY' 'neg' 'nanmethod'}))
F=fieldnames(subjparams);
subjparams=subjparams.(F{1}); %Ignore coding error flag.
end
clear F
if numel(subjparams)~=1
error('Subject parameter structure is the wrong size')
end
elseif iscell(subjectparameters)
for ii=1:numel(subjectparameters)
subjectparameters{ii}=strtok(subjectparameters{ii},',');
end
subjparams.P=char(subjectparameters); clear subjectparameters;
elseif isempty(subjectparameters)
subjparams=subjectparameters; clear subjectparameters;
else
subjparams=[];clear subjectparameters;
end
if ~isfield(subjparams,'directory') || isempty(subjparams.directory)
subjparams.directory=pwd;
end
if isfield(subjparams,'SPMmat') && isfield(subjparams,'Imat')
error('subjparams has conflicting fields SPMmat and Imat. Only one can be entered.')
end
%Load images for extraction
VY=0; %skips using pinfo field from SPM.mat file
if isstruct(mapparameters) && isfield(mapparameters,'voxel')
try
if exist([pwd 'SPM.mat'],'file')==2 || exist([pwd 'I.mat'],'file')==2
spmpath=pwd;
else
spmpath=fileparts(mapparameters.image);
if isempty(spmpath)
spmpath=pwd;
end
end
try
load([spmpath filesep 'SPM.mat']);
Imat=0;
catch
load([spmpath filesep 'I.mat']);
Imat=1;
end
if isfield(mapparameters,'beta') && isnumeric(mapparameters.beta) && mapparameters.beta==1 % SPM.mat contains the variable SPM, loaded in the previous line.
if ~Imat
tmpsubjhdrs=SPM.Vbeta;
else
error('Imat cannot be used with the beta field.')
end
else
if ~Imat
tmpsubjhdrs=SPM.xY.VY; % SPM.mat contains the variable SPM, loaded in the previous line.
VY=1;
else
for ii=1:numel(I.Scans)
if exist(strtok(I.Scans{ii},','),'file')==2
subjhdrs(ii)=spm_vol(strtok(I.Scans{ii},','));
else
invokecatchstatement
end
end
end
end
if VY==1 && ~Imat
for ii=1:numel(tmpsubjhdrs)
if exist(tmpsubjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(tmpsubjhdrs(ii).fname);
elseif exist([subjparams.directory filesep tmpsubjhdrs(ii).fname],'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory filesep tmpsubjhdrs(ii).fname]);
else
spm_input('SPM.mat input/beta files do not exist!',1,'bd','ok',1,1)
invokecatchstatement
end
subjhdrs(ii).pinfo(1)=SPM.xY.VY(ii).pinfo(1);
end
elseif ~Imat
for ii=1:numel(tmpsubjhdrs)
if exist(tmpsubjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(tmpsubjhdrs(ii).fname);
elseif exist([subjparams.directory filesep tmpsubjhdrs(ii).fname],'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory filesep tmpsubjhdrs(ii).fname]);
else
spm_input('SPM.mat input/beta files do not exist!',1,'bd','ok',1,1)
invokecatchstatement
end
end
end
[subjimgs XYZmm]=spm_read_vols(subjhdrs);
catch
str = {'Do you want to use an SPM.mat file?'};
if (isfield(subjparams,'SPMmat') && isnumeric(subjparams.SPMmat) && subjparams.SPMmat==1) && ~isfield(subjparams,'Imat') || spm_input(str,1,'bd','yes|no',[1,0],1)
[spmmatfile, sts]=spm_select(1,'^SPM\.mat$','Select SPM.mat');
swd = spm_str_manip(spmmatfile,'H');
try
load(fullfile(swd,'SPM.mat'));
catch
error(['Cannot read ' fullfile(swd,'SPM.mat')]);
end
if isfield(mapparameters,'beta') && isnumeric(mapparameters.beta) && mapparameters.beta==1 % SPM.mat contains the variable SPM, loaded in the previous line.
subjhdrs=SPM.Vbeta;
else
subjhdrs=SPM.xY.VY; % SPM.mat contains the variable SPM, loaded in the previous line.
VY=1;
end
if VY==1
for ii=1:numel(subjhdrs)
if exist(subjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(subjhdrs(ii).fname);
elseif exist([subjparams.directory filesep subjhdrs(ii).fname],'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory filesep subjhdrs(ii).fname]);
else
spm_input('SPM.mat input files do not exist!',1,'bd','ok',1,1)
error('SPM.mat input files do not exist!')
end
subjhdrs(ii).pinfo(1)=SPM.xY.VY(ii).pinfo(1);
end
else
for ii=1:numel(subjhdrs)
if exist(subjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(subjhdrs(ii).fname);
elseif exist([subjparams.directory filesep subjhdrs(ii).fname],'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory filesep subjhdrs(ii).fname]);
else
spm_input('SPM.mat input files do not exist!',1,'bd','ok',1,1)
error('SPM.mat input files do not exist!')
end
end
end
[subjimgs XYZmm]=spm_read_vols(subjhdrs);
else
str = {'Do you want to use an I.mat file?'};
if (isfield(subjparams,'Imat') && isnumeric(subjparams.Imat) && subjparams.Imat==1) || spm_input(str,1,'bd','yes|no',[1,0],1)
[spmmatfile, sts]=spm_select(1,'^I\.mat$','Select I.mat');
swd = spm_str_manip(spmmatfile,'H');
try
load(fullfile(swd,'I.mat'));
catch
error(['Cannot read ' fullfile(swd,'I.mat')]);
end
for ii=1:numel(I.Scans)
if exist(strtok(I.Scans{ii},','),'file')==2
subjhdrs(ii)=spm_vol(strtok(I.Scans{ii},','));
else
spm_input('I.mat input files do not exist!',1,'bd','ok',1,1)
error('I.mat input files do not exist!')
end
end
[subjimgs XYZmm]=spm_read_vols(subjhdrs);
else
subjparams.P = spm_select(Inf,'image','Select con/beta/other images for extraction',{},pwd,'.*','1');
t = struct(spm_vol(subjparams.P(1,:))); F=fieldnames(t); for ii=1:numel(F); t.(F{ii})=[]; end
subjhdrs(1:size(subjparams.P,1))=t; clear t;
for ii=1:size(subjparams.P,1)
subjhdrs(ii)=spm_vol(subjparams.P(ii,:));
end
[subjimgs XYZmm]=spm_read_vols(subjhdrs);
end
end
end
else %typical processing stream for peak_extract_nii.m
try
if isfield(subjparams,'xY') && isfield(subjparams.xY,'VY')
tmpsubjhdrs=subjparams.xY.VY;
for ii=1:numel(subjhdrs)
if exist(subjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(subjhdrs(ii).fname);
elseif exist([subjparams.directory filesep subjhdrs(ii).fname],'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory filesep subjhdrs(ii).fname]);
else
spm_input('SPM.mat input files do not exist!',1,'bd','ok',1,1)
error('SPM.mat input files do not exist!')
end
subjhdrs(ii).pinfo(1)=SPM.xY.VY(ii).pinfo(1);
end
elseif isfield(subjparams,'SPMmat') && isnumeric(subjparams.SPMmat) && subjparams.SPMmat==1 && isfield(subjparams,'beta') && isnumeric(subjparams.beta) && subjparams.beta==1
try
load([subjparams.directory filesep 'SPM.mat']);
tmpsubjhdrs=SPM.Vbeta;
for ii=1:numel(tmpsubjhdrs)
if exist(tmpsubjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(tmpsubjhdrs(ii).fname);
elseif exist([subjparams.directory filesep tmpsubjhdrs(ii).fname],'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory filesep tmpsubjhdrs(ii).fname]);
else
spm_input('SPM.mat beta files do not exist!',1,'bd','ok',1,1)
invokecatchstatement
end
end
catch
invokecatchstatement
end
elseif isfield(subjparams,'SPMmat') && isnumeric(subjparams.SPMmat) && subjparams.SPMmat==1
try
load([subjparams.directory filesep 'SPM.mat']);
tmpsubjhdrs=SPM.xY.VY;
for ii=1:numel(tmpsubjhdrs)
if exist(tmpsubjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(tmpsubjhdrs(ii).fname);
else
spm_input('SPM.mat input files do not exist!',1,'bd','ok',1,1)
invokecatchstatement
end
subjhdrs(ii).pinfo(1)=SPM.xY.VY(ii).pinfo(1);
end
catch
invokecatchstatement
end
elseif isfield(subjparams,'Imat') && isnumeric(subjparams.Imat) && subjparams.Imat==1
try
load([subjparams.directory filesep 'I.mat']);
for ii=1:numel(I.Scans)
if exist(strtok(I.Scans{ii},','),'file')==2
subjhdrs(ii)=spm_vol(strtok(I.Scans{ii},','));
else
invokecatchstatement
end
end
catch
invokecatchstatement
end
else
subjparams.P;
if iscell(subjparams.P)
try
tmpP=cell2mat(subjparams.P);
subjparams.P=tmpP;
catch
P=[];
for ii=1:size(subjparams.P,1)
P = strvcat(P,subjparams.P{ii});
end
subjparams.P=P; clear P
end
end
t = struct(spm_vol(subjparams.P(1,:))); F=fieldnames(t); for ii=1:numel(F); t.(F{ii})=[]; end
subjhdrs(1:size(subjparams.P,1))=t; clear t;
for ii=1:size(subjparams.P,1)
if exist(deblank(subjparams.P(ii,:)),'file')==2
subjhdrs(ii)=spm_vol(subjparams.P(ii,:));
elseif exist(strtok(deblank(subjparams.P(ii,:)),','),'file')==2
subjhdrs(ii)=spm_vol(strtok(deblank(subjparams.P(ii,:)),','));
elseif exist(deblank([subjparams.directory subjparams.P(ii,:)]),'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory subjparams.P(ii,:)]);
elseif exist(strtok(deblank([subjparams.directory subjparams.P(ii,:)]),','),'file')==2
subjhdrs(ii)=spm_vol(strtok(deblank([subjparams.directory subjparams.P(ii,:)]),','));
else
invokecatchstatement
end
end
end
[subjimgs XYZmm]=spm_read_vols(subjhdrs);
catch
subjparams.P=[];
str = {'Do you want to use an SPM.mat file?'};
if (isfield(subjparams,'SPMmat') && isnumeric(subjparams.SPMmat) && subjparams.SPMmat==1) && ~isfield(subjparams,'Imat') || spm_input(str,1,'bd','yes|no',[1,0],1)
[spmmatfile, sts]=spm_select(1,'^SPM\.mat$','Select SPM.mat');
swd = spm_str_manip(spmmatfile,'H');
try
load(fullfile(swd,'SPM.mat'));
catch
error(['Cannot read ' fullfile(swd,'SPM.mat')]);
end
if isfield(subjparams,'beta') && isnumeric(subjparams.beta) && subjparams.beta==1
tmpsubjhdrs=SPM.Vbeta;
else
tmpsubjhdrs=SPM.xY.VY;
VY=1;
end
if VY==1
for ii=1:numel(tmpsubjhdrs)
if exist(tmpsubjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(tmpsubjhdrs(ii).fname);
elseif exist([subjparams.directory filesep tmpsubjhdrs(ii).fname],'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory filesep tmpsubjhdrs(ii).fname]);
else
error('SPM.mat input/beta files do not exist!');
end
subjhdrs(ii).pinfo(1)=SPM.xY.VY(ii).pinfo(1);
end
else
for ii=1:numel(tmpsubjhdrs)
if exist(tmpsubjhdrs(ii).fname,'file')==2
subjhdrs(ii)=spm_vol(tmpsubjhdrs(ii).fname);
elseif exist([subjparams.directory filesep tmpsubjhdrs(ii).fname],'file')==2
subjhdrs(ii)=spm_vol([subjparams.directory filesep tmpsubjhdrs(ii).fname]);
else
error('SPM.mat input/beta files do not exist!');
end
end
end
else
str = {'Do you want to use an I.mat file?'};
if (isfield(subjparams,'Imat') && isnumeric(subjparams.Imat) && subjparams.Imat==1) || spm_input(str,1,'bd','yes|no',[1,0],1)
[spmmatfile, sts]=spm_select(1,'^I\.mat$','Select I.mat');
swd = spm_str_manip(spmmatfile,'H');
try
load(fullfile(swd,'I.mat'));
catch
error(['Cannot read ' fullfile(swd,'I.mat')]);
end
for ii=1:numel(I.Scans)
if exist(strtok(I.Scans{ii},','),'file')==2
subjhdrs(ii)=spm_vol(strtok(I.Scans{ii},','));
else
spm_input('I.mat input files do not exist!',1,'bd','ok',1,1)
error('I.mat input files do not exist!')
end
end
[subjimgs XYZmm]=spm_read_vols(subjhdrs);
else
subjparams.P = spm_select(Inf,'image','Select con/beta/other images for extraction',{},pwd,'.*','1');
t = struct(spm_vol(subjparams.P(1,:))); F=fieldnames(t); for ii=1:numel(F); t.(F{ii})=[]; end
subjhdrs(1:size(subjparams.P,1))=t; clear t;
for ii=1:size(subjparams.P,1)
subjhdrs(ii)=spm_vol(subjparams.P(ii,:));
end
[subjimgs XYZmm]=spm_read_vols(subjhdrs);
end
end
end
end
%Check that all headers are the same
dims = cat(1,subjhdrs.dim);
matx = reshape(cat(3,subjhdrs.mat),[16,numel(subjhdrs)]);
if any(any(diff(dims,1,1),1))
error('Images for extraction do not have the same dimensions.')
end
if any(any(abs(diff(matx,1,2))>1e-4))
error('Images for extraction do not have the same orientations.')
end
%Check for subject peaks?
if isfield(subjparams,'subjectpeak') && subjparams.subjectpeak==1
try
if strncmp(subjhdrs(1).fname,'con_',4)
t = struct(spm_vol([subjhdrs(1).fname(1,1:a-1) 'spmT_' subjhdrs(ii).fname(1,a+4:end)])); F=fieldnames(t); for ii=1:numel(F); t.(F{ii})=[]; end
subjpeakhdrs(1:numel(subjhdrs))=t; clear t;
for ii=1:numel(subjhdrs)
a=strfind(subjhdrs(ii).fname,'con_');
subjpeakhdrs(ii)=spm_vol([subjhdrs(ii).fname(1,1:a-1) 'spmT_' subjhdrs(ii).fname(1,a+4:end)]);
end
subjpeakimgs=spm_read_vols(subjpeakhdrs);
else
subjpeakimgs=subjimgs;
end
if isfield(subjparams,'neg') && subjparams.neg==1
subjpeakimgs=-1*subjpeakimgs;
elseif isfield(subjparams,'neg') && ~isnumeric(subjparams.neg)
error('neg field is not specified correctly')
end
catch
error('Subjectpeak settings are wrong. Missing spmT maps.')
end
else
subjparams.subjectpeak=0;
end
%Check NaN Method
if ~isfield(subjparams,'nanmethod') || ~isnumeric(subjparams.nanmethod)
subjparams.nanmethod=0;
end
%Get Cluster information
try
eval(x);
clusters=voxelsT;
if isempty(clusters)
display('No clusters found.');
return
else
if exist('regions','var')
voxels=voxelsT{1};
elseif exist('region','var')
voxels=voxelsT{1};
else
voxels=cell2mat(voxelsT(1:5));
end
end
catch
if exist('x','var')
if isfield(mapparameters,'exact') && isnumeric(mapparameters.exact) && mapparameters.exact==1
if mapparameters.cluster<=0
error('Cluster must be greater than 0')
end
mapmaskimg=spm_read_vols(spm_vol(mapparameters.mask));
if mapparameters.cluster>sum(mapmaskimg(:)>0)
error('Cluster must be smaller than mask')
end
if isfield(mapparameters,'label')
error('Error in peak_nii. Mapparameters is not correct. Missing something.')
else
error('Error in peak_nii. Label was not set.')
end
else
if isfield(mapparameters,'label')
error('Error in peak_nii. Mapparameters is not correct. Missing something.')
else
error('Error in peak_nii. Label was not set.')
end
end
else
error('peak_nii was not execute because mapparameters.image does not exist')
end
end
%%Extraction Code
if subjparams.subjectpeak==1
subjectpeaklocationsvoxel=cell(numel(subjhdrs),size(voxels,1));
subjectpeakspherevaluesvoxel=zeros(numel(subjhdrs),size(voxels,1))*NaN;
subjectpeaksvaluesvoxel=zeros(numel(subjhdrs),size(voxels,1))*NaN;
end
peakspherevaluesavg=zeros(numel(subjhdrs),size(voxels,1))*NaN;
peakspherevalueseig=zeros(numel(subjhdrs),size(voxels,1))*NaN;
peakvalues=zeros(numel(subjhdrs),size(voxels,1))*NaN;
for ii=1:size(voxels,1)
% Extract peak voxel
[xyz,ind]=spm_XYZreg('NearestXYZ',voxels(ii,3:5)',XYZmm);
peakvalues(:,ii)=subjimgs(ind:prod(subjhdrs(1).dim):end);
clear ind
% Extract sphere around peak
if isfield(subjparams,'extractsphere') && isnumeric(subjparams.extractsphere)
ind=find(sum((XYZmm - repmat(voxels(ii,3:5)',1,size(XYZmm,2))).^2) <= subjparams.extractsphere^2);
inds=zeros(1,numel(ind)*numel(subjhdrs));
for jj=1:numel(ind)
inds((jj-1)*numel(subjhdrs)+1:jj*numel(subjhdrs))=ind(jj):prod(subjhdrs(1).dim):prod(subjhdrs(1).dim)*numel(subjhdrs);
end
inds=sort(inds);
data=reshape(subjimgs(inds),numel(ind),numel(subjhdrs));
[peakspherevaluesavg(:,ii) peakspherevalueseig(:,ii)]=regionalcomps(data',subjparams.nanmethod);
elseif isfield(subjparams,'extractsphere') && ~isnumeric(subjparams.extractsphere) && ~ischar(subjparams.extractsphere)
error('extractsphere field must be a number or empty or a string')
else
subjparams.extractsphere='NaN';
peakspherevaluesavg(:,ii)=NaN;
peakspherevalueseig(:,ii)=NaN;
end
clear ind
% Extract sphere around subject peak voxel within X mm of peak
if subjparams.subjectpeak==1
if isfield(subjparams,'searchsphere') && isnumeric(subjparams.searchsphere)
ind=find(sum((XYZmm - repmat(voxels(ii,3:5)',1,size(XYZmm,2))).^2) <= subjparams.searchsphere^2);
for jj=1:numel(subjhdrs)
subjectpeak=find(subjimgs((jj-1)*prod(subjhdrs(1).dim)+ind)==max(subjimgs((jj-1)*prod(subjhdrs(1).dim)+ind)));
subjectpeaklocationsvoxel{jj,ii}=XYZmm(:,ind(subjectpeak))';
subjectpeaksvaluesvoxel(jj,ii)=subjimgs((jj-1)*prod(subjhdrs(1).dim)+ind(subjectpeak));
if isfield(subjparams,'extractsphere') && isnumeric(subjparams.extractsphere)
ind2=find(sum((XYZmm - repmat(XYZmm(:,ind(subjectpeak)),1,size(XYZmm,2))).^2) <= subjparams.extractsphere^2);
subjectpeakspherevaluesvoxel(jj,ii)=mean(subjimgs((jj-1)*prod(subjhdrs(1).dim)+ind2));
else
subjectpeakspherevaluesvoxel(jj,ii)=NaN;
end
end
elseif isfield(subjparams,'searchsphere') && ~isnumeric(subjparams.searchsphere)
error('searchsphere field must be a number or empty')
end
clear ind
end
end
if exist('region','var')
clusterhead='temp_cluster.nii';
regions=region;
end
if exist('regions','var')
%Extractions using clusters
try
clusterhead;
catch
clusterhead=spm_vol([mapparams.out '_thresh' num2str(mapparams.thresh2) '_extent' num2str(mapparams.cluster) mapparams.maskname '_clusters.nii']);
end
clusterimg=zeros(subjhdrs(1).dim(1:3));
for p = 1:subjhdrs(1).dim(3),
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
M = inv(B*inv(subjhdrs(1).mat)*clusterhead.mat);
Yp = spm_slice_vol(clusterhead,M,subjhdrs(1).dim(1:2),[0,NaN]);
if prod(subjhdrs(1).dim(1:2)) ~= numel(Yp),
error(['"',f,'" produced incompatible image.']);
end
clusterimg(:,:,p) = reshape(Yp,subjhdrs(1).dim(1:2));
end
% Extract all significant voxels
ind=find(clusterimg>0);
inds=zeros(1,numel(ind)*numel(subjhdrs));
for jj=1:numel(ind)
inds((jj-1)*numel(subjhdrs)+1:jj*numel(subjhdrs))=ind(jj):prod(subjhdrs(1).dim):prod(subjhdrs(1).dim)*numel(subjhdrs);
end
inds=sort(inds);
data=reshape(subjimgs(inds),numel(ind),numel(subjhdrs));
[allvalueavg allvalueeig]=regionalcomps(data',subjparams.nanmethod);
clear ind inds
% Extract clusters
clustervalueavg=zeros(numel(subjhdrs),max(voxels(:,7)))*NaN;
clustervalueeig=zeros(numel(subjhdrs),max(voxels(:,7)))*NaN;
if subjparams.subjectpeak==1
subjectpeaklocationscluster=cell(numel(subjhdrs),max(voxels(:,7)));
subjectpeakspherevaluescluster=zeros(numel(subjhdrs),max(voxels(:,7)))*NaN;
subjectpeaksvaluescluster=zeros(numel(subjhdrs),max(voxels(:,7)))*NaN;
end
for ii=1:max(voxels(:,7))
ind=find(clusterimg==ii);
inds=zeros(1,numel(ind)*numel(subjhdrs));
for jj=1:numel(ind)
inds((jj-1)*numel(subjhdrs)+1:jj*numel(subjhdrs))=ind(jj):prod(subjhdrs(1).dim):prod(subjhdrs(1).dim)*numel(subjhdrs);
end
inds=sort(inds);
data=reshape(subjimgs(inds),numel(ind),numel(subjhdrs));
[clustervalueavg(:,ii) clustervalueeig(:,ii)]=regionalcomps(data',subjparams.nanmethod);
clear inds
% Extract peak voxel and sphere around subject peak voxel, 1 per
% cluster
if subjparams.subjectpeak==1
for jj=1:numel(subjhdrs)
subjectpeak=find(subjimgs((jj-1)*prod(subjhdrs(1).dim)+ind)==max(subjimgs((jj-1)*prod(subjhdrs(1).dim)+ind)));
subjectpeaklocationscluster{jj,ii}=XYZmm(:,ind(subjectpeak))';
subjectpeaksvaluescluster(jj,ii)=subjimgs((jj-1)*prod(subjhdrs(1).dim)+ind(subjectpeak));
if isfield(subjparams,'extractsphere') && isnumeric(subjparams.extractsphere)
ind2=find(sum((XYZmm - repmat(XYZmm(:,ind(subjectpeak)),1,size(XYZmm,2))).^2) <= subjparams.extractsphere^2);
subjectpeakspherevaluescluster(jj,ii)=mean(subjimgs((jj-1)*prod(subjhdrs(1).dim)+ind2));
else
subjectpeakspherevaluescluster(jj,ii)=NaN;
end
clear ind2
end
end
clear ind inds
end
end
if exist('region','var')
%Extractions using clusters
clusterhead=spm_vol('temp_cluster.nii');
for p = 1:subjhdrs(1).dim(3),
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
M = inv(B*inv(subjhdrs(1).mat)*clusterhead.mat);
Yp = spm_slice_vol(clusterhead,M,subjhdrs(1).dim(1:2),[0,NaN]);
if prod(subjhdrs(1).dim(1:2)) ~= numel(Yp),
error(['"',f,'" produced incompatible image.']);
end
clusterimg(:,:,p) = reshape(Yp,subjhdrs(1).dim(1:2));
end
eval('!rm temp_cluster.nii')
% Extract clusters
clustervalueavg=zeros(numel(subjhdrs),1);
clustervalueeig=zeros(numel(subjhdrs),1);
ind=find(clusterimg==1);
inds=zeros(1,numel(ind)*numel(subjhdrs));
for jj=1:numel(ind)
inds((jj-1)*numel(subjhdrs)+1:jj*numel(subjhdrs))=ind(jj):prod(subjhdrs(1).dim):prod(subjhdrs(1).dim)*numel(subjhdrs);
end
inds=sort(inds);
data=reshape(subjimgs(inds),numel(ind),numel(subjhdrs));
[clustervalueavg(:,ii) clustervalueeig(:,ii)]=regionalcomps(data',subjparams.nanmethod);
clear inds
end
%Initialize outputs
if exist('regions','var')
tempa=cell(1,numel(unique(voxels(:,7))));
tempb=cell(1,numel(unique(voxels(:,7))));
tempc=cell(numel(subjhdrs),numel(unique(voxels(:,7))));
tempd=cell(numel(subjhdrs),numel(unique(voxels(:,7))));
for ii=1:numel(unique(voxels(:,7)))
tempa{1,ii}=['average @ cluster number ' num2str(ii)];
tempb{1,ii}=['eigenvariate @ cluster number ' num2str(ii)];
if subjparams.subjectpeak==1
for jj=1:numel(subjhdrs)
tempc{jj,ii}=['subject peak @ ' num2str(subjectpeaklocationscluster{jj,ii})];
tempd{jj,ii}=['subject peak ' num2str(subjparams.extractsphere) 'mm sphere @ ' num2str(subjectpeaklocationscluster{jj,ii})];
end
end
end
end
if exist('region','var')
tempa=cell(1,1);
tempb=cell(1,1);
tempc=cell(numel(subjhdrs),1);
tempd=cell(numel(subjhdrs),1);
tempa{1,1}=['average @ cluster number ' num2str(ii)];
tempb{1,1}=['eigenvariate @ cluster number ' num2str(ii)];
end
tempi=cell(1,size(voxels,1));
tempe=cell(1,size(voxels,1));
tempf=cell(1,size(voxels,1));
tempg=cell(numel(subjhdrs),size(voxels,1));
temph=cell(numel(subjhdrs),size(voxels,1));
for ii=1:size(voxels,1)
tempi{1,ii}=num2str(voxels(ii,3:5));
tempe{1,ii}=['average ' num2str(subjparams.extractsphere) 'mm sphere @ ' num2str(voxels(ii,3:5))];
tempf{1,ii}=['eigenvariate ' num2str(subjparams.extractsphere) 'mm sphere @ ' num2str(voxels(ii,3:5))];
if subjparams.subjectpeak==1
for jj=1:numel(subjhdrs)
tempg{jj,ii}=['subject peak @ ' num2str(subjectpeaklocationsvoxel{jj,ii})];
temph{jj,ii}=['subject peak ' num2str(subjparams.extractsphere) 'mm sphere @ ' num2str(subjectpeaklocationsvoxel{jj,ii})];
end
end
end
%Define outputs
if exist('region','var')
resultscluster={clustervalueavg clustervalueeig};
columnlistcluster={tempa tempb};
resultsvoxels={peakvalues peakspherevaluesavg peakspherevalueseig};
columnlistvoxels={tempi tempe tempf};
elseif subjparams.subjectpeak==1
if exist('regions','var')
resultscluster={allvalueavg allvalueeig clustervalueavg clustervalueeig subjectpeaksvaluescluster subjectpeakspherevaluescluster};
columnlistcluster={'global average' 'global eigenvariate' tempa tempb tempc tempd};
end
resultsvoxels={peakvalues peakspherevaluesavg peakspherevalueseig subjectpeaksvaluesvoxel subjectpeakspherevaluesvoxel};
columnlistvoxels={tempi tempe tempf tempg temph};
else
if exist('regions','var')
resultscluster={allvalueavg allvalueeig clustervalueavg clustervalueeig};
columnlistcluster={'global average' 'global eigenvariate' tempa tempb};
end
resultsvoxels={peakvalues peakspherevaluesavg peakspherevalueseig};
columnlistvoxels={tempi tempe tempf};
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Embedded Functions
function [avg eig]=regionalcomps(y,nanmethod)
eig = zeros(size(y,1),1)*NaN;
avg = zeros(size(y,1),1)*NaN;
rows=1:1:size(y,1);
if nanmethod==1
columns=~any(isnan(y), 1);
y2=y(:,columns);
if size(y2,2)==0
disp('No common voxels, use nanmethod=3 to analyze')
eig(:) = NaN;
avg(:) = NaN;
return
end
elseif nanmethod==2
rows=~any(isnan(y), 2);
y2=y(rows,:);
if size(y2,1)==0
disp('No subjects with all voxels, use nanmethod=3 to analyze')
eig(:) = NaN;
avg(:) = NaN;
return
end
elseif numel(isnan(y))>0 %nanmethod3
eig(:) = NaN;
avg = nanmean(y,2);
return
else
y2=y;
end
[m n] = size(y2);
if m > n
[v s v] = svd(y2'*y2);
s = diag(s);
v = v(:,1);
u = y2*v/sqrt(s(1));
else
[u s u] = svd(y2*y2');
s = diag(s);
u = u(:,1);
v = y2'*u/sqrt(s(1));
end
d = sign(sum(v));
u = u*d;
v = v*d;
eig(rows,:) = (u*sqrt(s(1)/n));
avg(rows,:) = mean(y2,2);
end
|
github
|
vsariola/sideaxes-m-master
|
export_all.m
|
.m
|
sideaxes-m-master/examples/export_all.m
| 874 |
utf_8
|
22c7159f51097ac8c07e48cd3822f2f6
|
function export_all
filelist = dir('example_*.m');
if ~exist('../images/pdfs','dir')
mkdir('../images/pdfs');
end
for i = 1:length(filelist)
close all;
n = filelist(i).name;
runInSepareteWorkspace(n);
s = regexp(n,'example_(\w+)','once','tokens');
warning('');
exportedName = sprintf('../images/pdfs/%s.pdf',s{1});
export_fig(exportedName,'-transparent');
[warnMsg, warnId] = lastwarn;
if ~isempty(warnMsg)
fig = gcf;
fig.Color = 'none';
fig.InvertHardcopy = 'off';
fig.PaperPositionMode = 'auto';
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];
print(gcf, '-dpdf', exportedName);
end
end
end
function runInSepareteWorkspace(script)
run(script);
end
|
github
|
vsariola/sideaxes-m-master
|
test_logscales.m
|
.m
|
sideaxes-m-master/tests/test_logscales.m
| 917 |
utf_8
|
ace57753de691423a575aff33f97105e
|
function test_logscales
addpath('..');
figure;
axes('position',[0.1 0.1 0.4 0.4],'visible','off');
make_test_plot();
text(5,5,'Points should align to ticks','Clipping','off');
ax = axes('position',[0.6 0.1 0.4 0.4],'visible','off');
make_test_plot();
ax.XScale = 'log';
ax = axes('position',[0.1 0.6 0.4 0.4],'visible','off');
make_test_plot();
ax.YScale = 'log';
ax = axes('position',[0.6 0.6 0.4 0.4],'visible','off');
make_test_plot();
ax.XScale = 'log';
ax.XDir = 'reverse';
ax.YScale = 'log';
ax.YDir = 'reverse';
rmpath('..');
end
function make_test_plot
ax = gca;
x = 2:9;
hold on;
plot(x,2,'k.');
plot(2,x,'k.');
hold off;
axis([1 10 1 10]);
sideaxes(ax,'west','size',0.1);
ticks(x);
sideaxes(ax,'south','size',0.1);
ticks(x);
axes(ax);
end
|
github
|
vsariola/sideaxes-m-master
|
test_autoticks.m
|
.m
|
sideaxes-m-master/tests/test_autoticks.m
| 863 |
utf_8
|
afb81e67ba8b5de81a0913210c46c444
|
function test_autoticks
addpath('..');
x = randn(1000,1);
y = randn(1000,1);
figure;
axes('position',[0.1 0.1 0.4 0.4],'visible','off');
make_test_plot(x,y);
ax = axes('position',[0.6 0.1 0.4 0.4],'visible','off');
make_test_plot(x,y);
axis([-0.5 0.5 -0.5 0.5]);
ax = axes('position',[0.1 0.6 0.4 0.4],'visible','off');
make_test_plot(x,y);
axis([-0.1 0.1 -0.1 0.1]);
ax = axes('position',[0.6 0.6 0.4 0.4],'visible','off');
make_test_plot(x,y);
axis([-0.05 0.05 -0.05 0.05]);
end
function make_test_plot(x,y)
ax = gca;
hold on;
plot(x,y,'k.');
hold off;
sideaxes(ax,'west','size',1);
rangeline(min(y),max(y));
autoticks();
sideaxes(ax,'south','size',1);
rangeline(min(y),max(y));
autoticks();
axes(ax);
end
|
github
|
samiuluofc/Matlab-master
|
fitness_mix.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_3_ga_optimization/fitness_mix.m
| 2,148 |
utf_8
|
183824430ec981a49af0b3c488e8c105
|
% This function will take a row vector W (contains four weights) as
% parameter, and returns the average error (of 5 different experiments) as
% fitness value for the Genetic algorithm.
function err = fitness_mix(W) % W is the weight vector
% Load scores
load('score.mat');
% For 5 random experiments
no_of_iter = 5;
% Number of test and training (M and F)
no_M_train = 80; %out of 113 (70%)
no_F_train = 43; %out of 60 (70%)
no_M_test = 113 - no_M_train;
no_F_test = 60 - no_F_train;
total_test = no_F_test + no_M_test;
% Initializations
TP = 0; % True positive
TN = 0; % true negative
FP = 0; % False positive
FN = 0; % False negative
for iter = 1 : 1 : no_of_iter % for all five experiments
% Data selection according to experiment number (iter)
st = ((iter-1)*total_test)+1;
en = ((iter-1)*total_test)+50;
P_list = score(st:en,:); % Total test data
M_count = 0;
F_count = 0;
%%% score = [SVM_score, KNN_score, TREE_score, LASSO_score];
combine_P = (P_list(:,1).*W(1) + P_list(:,2).*W(2) + P_list(:,3).*W(3) + P_list(:,4).*W(4))/sum(W); % Combined score (weighted average)
% Calculate Threshold value
pdM = fitdist(combine_P(1 : no_M_test,1),'Normal'); % Male dist
pdF = fitdist(combine_P(no_M_test+1 : total_test,1),'Normal'); % Female dist
P_thres = (pdM.mu + pdF.mu)/2;
% Counting male predictions
for i = 1 : no_M_test
if combine_P(i) > P_thres
M_count = M_count + 1;
end
end
% Counting female predictions
for i = no_M_test+1 : total_test
if combine_P(i) <= P_thres
F_count = F_count + 1;
end
end
% Calculating Cumulative TP,TN,FN and FP
TP = TP + M_count;
FN = FN + (33-M_count);
TN = TN + F_count;
FP = FP + (17-F_count);
end
% Average error
err = 1 - ((TP + TN)/(TP + TN + FN + FP));
end
|
github
|
samiuluofc/Matlab-master
|
fitness_tree.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_2_generate_test_scores/fitness_tree.m
| 2,892 |
utf_8
|
205f19f76c81c0b85031166e44165e21
|
% This function receives selected features for DTree and returns
% gender probabilities of 50 test persons in 5 different experiments.
function TREE_score = fitness_tree(bin_chrom)
% Load necessary Data
load('F_60.mat'); % Z score normalized data
load('M_113.mat');
% provide F_index_image and M_index_image matrix.
% These two matrix contains random indices of images.
load('random_index.mat');
% Select the features based on binary chromosome
fs = find(bin_chrom);
% Five random experiments
no_of_iter = 5;
% Number of test and training (M and F)
no_M_train = 80; % out of 113 (70%)
no_F_train = 43; % out of 60 (70%)
no_M_test = 113 - no_M_train;
no_F_test = 60 - no_F_train;
total_test = no_F_test + no_M_test;
% Initialization
total_avg = 0;
total_avg_M = 0;
total_avg_F = 0;
L = 29; % Number of minimum leaf for DTree
TREE_score = [];
% For each experiment (random sampling), we conduct training and testing.
% Calculate average accuracy of 5 experiments.
for iter = 1 : 1 : no_of_iter
% Selection of Training and testing data for males
M_train = M(M_index_image(1:no_M_train * 200,iter),fs);
M_test = M(M_index_image((no_M_train*200) + 1 : 113 * 200,iter),fs);
% Selection of Training and testing data for females
F_train = F(F_index_image(1:no_F_train * 200,iter),fs);
F_test = F(F_index_image((no_F_train*200) + 1 : 60 * 200,iter),fs);
X = [M_train; F_train]; % Total train data
Y = [ones(no_M_train*200,1) ; ones(no_F_train*200,1) .* -1]; % Labels
X_test = [M_test; F_test]; % Total test data
% Training with DTree
model = ClassificationTree.fit(X, Y, 'MinLeaf',L);
% Testing
[result,~] = predict(model,X_test);
% Calculate gender probability
P_list = zeros(total_test,1);
for i = 1: total_test
S = sum(result(((i-1)*200) + 1 : ((i-1)*200) + 200,1));
P_list(i,1) = S/200;
end
TREE_score = [TREE_score; P_list]; % Appending scores
M_count = 0;
F_count = 0;
% Calculate threshold value
pdM = fitdist(P_list(1 : no_M_test,1),'Normal'); % Male dist
pdF = fitdist(P_list(no_M_test+1 : total_test,1),'Normal'); % Female dist
P_thres = (pdM.mu + pdF.mu)/2;
% Counting male predictions
for i = 1 : no_M_test
if P_list(i) > P_thres
M_count = M_count + 1;
end
end
% Counting female predictions
for i = no_M_test+1 : total_test
if P_list(i) <= P_thres
F_count = F_count + 1;
end
end
% Calculating average accuracies
M_acc = (M_count/no_M_test)*100;
F_acc = (F_count/no_F_test)*100;
avg_accu = (M_acc + F_acc)/2;
total_avg = total_avg + avg_accu;
total_avg_M = total_avg_M + M_acc;
total_avg_F = total_avg_F + F_acc;
end
|
github
|
samiuluofc/Matlab-master
|
fitness_lasso.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_2_generate_test_scores/fitness_lasso.m
| 2,967 |
utf_8
|
88cb9d7b11637e8a91c8361ae473c846
|
% This function receives selected features for LASSO and returns
% gender probabilities of 50 test persons in 5 different experiments.
function LASSO_score = fitness_lasso(bin_chrom)
% Load necessary Data
load('F_60.mat'); % Z score normalized data
load('M_113.mat');
% provide F_index_image and M_index_image matrix.
% These two matrix contains random indices of images.
load('random_index.mat'); % provide F_index_image and M_index_image
% Select the features based on binary chromosome
fs = find(bin_chrom);
% Five random experiments
no_of_iter = 5;
% Number of test and training (M and F)
no_M_train = 80; %out of 113 (70%)
no_F_train = 43; %out of 60 (70%)
no_M_test = 113 - no_M_train;
no_F_test = 60 - no_F_train;
total_test = no_F_test + no_M_test;
% Initialization
total_avg = 0;
total_avg_M = 0;
total_avg_F = 0;
LASSO_score = [];
% For each experiment (random sampling), we conduct training and testing.
% Calculate average accuracy of 5 experiments.
for iter = 1 : 1 : no_of_iter
% Selection of Training and testing data for males
M_train = M(M_index_image(1:no_M_train * 200,iter),fs);
M_test = M(M_index_image((no_M_train*200) + 1 : 113 * 200,iter),fs);
% Selection of Training and testing data for females
F_train = F(F_index_image(1:no_F_train * 200,iter),fs);
F_test = F(F_index_image((no_F_train*200) + 1 : 60 * 200,iter),fs);
X = [M_train; F_train];% Total train data
Y = [ones(no_M_train*200,1) ; ones(no_F_train*200,1) .* -1]; % Labels
X_test = [M_test; F_test];% Total test data
% Training with LASSO
[B fitinfo] = lasso(X,Y,'Standardize',false,'Lambda',0.0001);
% Testing
result = X_test * B(:,1);
% Calculate gender probability
P_list = zeros(total_test,1); % Total test data
for i = 1: total_test
S = sum(result(((i-1)*200) + 1 : ((i-1)*200) + 200,1));
P_list(i,1) = S/200;
end
P_list = mat2gray(P_list); % Min-max normalization
LASSO_score = [LASSO_score; P_list]; % Appending scores
M_count = 0;
F_count = 0;
% Calculate threshold value
pdM = fitdist(P_list(1 : no_M_test,1),'Normal'); % Male dist
pdF = fitdist(P_list(no_M_test+1 : total_test,1),'Normal'); % Female dist
P_thres = (pdM.mu + pdF.mu)/2;
% Counting male predictions
for i = 1 : no_M_test
if P_list(i) > P_thres
M_count = M_count + 1;
end
end
% Counting female predictions
for i = no_M_test+1 : total_test
if P_list(i) <= P_thres
F_count = F_count + 1;
end
end
% Calculating average accuracies
M_acc = (M_count/no_M_test)*100;
F_acc = (F_count/no_F_test)*100;
avg_accu = (M_acc + F_acc)/2;
total_avg = total_avg + avg_accu;
total_avg_M = total_avg_M + M_acc;
total_avg_F = total_avg_F + F_acc;
end
|
github
|
samiuluofc/Matlab-master
|
fitness_svm.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_2_generate_test_scores/fitness_svm.m
| 2,955 |
utf_8
|
3e865f0e0ac512a37d4ce85246235411
|
% This function receives selected features for SVM and returns
% gender probabilities of 50 test persons in 5 different experiments.
function SVM_score = fitness_svm(bin_chrom)
% Load necessary Data
load('F_60.mat'); % Z score normalized data
load('M_113.mat');
% provide F_index_image and M_index_image matrix.
% These two matrix contains random indices of images.
load('random_index.mat');
% Select the features based on binary chromosome
fs = find(bin_chrom);
% Five random experiments
no_of_iter = 5;
% Number of test and training (M and F)
no_M_train = 80; %out of 113 (70%)
no_F_train = 43; %out of 60 (70%)
no_M_test = 113 - no_M_train;
no_F_test = 60 - no_F_train;
total_test = no_F_test + no_M_test;
% Initialization
total_avg = 0;
total_avg_M = 0;
total_avg_F = 0;
C = 0.008; % Soft Margin for SVM
SVM_score = [];
% For each experiment (random sampling), we conduct training and testing.
% Calculate average accuracy of 5 experiments.
for iter = 1 : 1 : no_of_iter
% Selection of Training and testing data for males
M_train = M(M_index_image(1:no_M_train * 200,iter),fs);
M_test = M(M_index_image((no_M_train*200) + 1 : 113 * 200,iter),fs);
% Selection of Training and testing data for females
F_train = F(F_index_image(1:no_F_train * 200,iter),fs);
F_test = F(F_index_image((no_F_train*200) + 1 : 60 * 200,iter),fs);
X = [M_train; F_train]; % Total train data
Y = [ones(no_M_train*200,1) ; ones(no_F_train*200,1) .* -1]; % Labels
X_test = [M_test; F_test]; % Total test data
% Training with SVM
op = statset('MaxIter',30000);
model = svmtrain(X, Y,'autoscale',false,'boxconstraint',C,'kernel_function','linear','options', op);
% Testing
result = svmclassify(model,X_test);
% Calculate gender probability
P_list = zeros(total_test,1);
for i = 1: total_test
S = sum(result(((i-1)*200) + 1 : ((i-1)*200) + 200,1));
P_list(i,1) = S/200;
end
SVM_score = [SVM_score; P_list]; % Appending scores
M_count = 0;
F_count = 0;
% Calculate threshold value
pdM = fitdist(P_list(1 : no_M_test,1),'Normal'); % Male dist
pdF = fitdist(P_list(no_M_test+1 : total_test,1),'Normal'); % Female dist
P_thres = (pdM.mu + pdF.mu)/2;
% Counting male predictions
for i = 1 : no_M_test
if P_list(i) > P_thres
M_count = M_count + 1;
end
end
% Counting female predictions
for i = no_M_test+1 : total_test
if P_list(i) <= P_thres
F_count = F_count + 1;
end
end
% Calculating average accuracies
M_acc = (M_count/no_M_test)*100;
F_acc = (F_count/no_F_test)*100;
avg_accu = (M_acc + F_acc)/2;
total_avg = total_avg + avg_accu;
total_avg_M = total_avg_M + M_acc;
total_avg_F = total_avg_F + F_acc;
end
|
github
|
samiuluofc/Matlab-master
|
fitness_knn.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_2_generate_test_scores/fitness_knn.m
| 2,884 |
utf_8
|
fa8128233d198ab1d012a42b750771d0
|
% This function receives selected features for KNN and returns
% gender probabilities of 50 test persons in 5 different experiments.
function KNN_score = fitness_knn(bin_chrom)
% Load necessary Data
load('F_60.mat'); % Z score normalized data
load('M_113.mat');
% provide F_index_image and M_index_image matrix.
% These two matrix contains random indices of images.
load('random_index.mat');
% Select the features based on binary chromosome
fs = find(bin_chrom);
% Five random experiments
no_of_iter = 5;
% Number of test and training (M and F)
no_M_train = 80; % out of 113 (70%)
no_F_train = 43; % out of 60 (70%)
no_M_test = 113 - no_M_train;
no_F_test = 60 - no_F_train;
total_test = no_F_test + no_M_test;
% Initialization
total_avg = 0;
total_avg_M = 0;
total_avg_F = 0;
N = 30; % Number of neighbor for KNN
KNN_score = [];
% For each experiment (random sampling), we conduct training and testing.
% Calculate average accuracy of 5 experiments.
for iter = 1 : 1 : no_of_iter
% Selection of Training and testing data for males
M_train = M(M_index_image(1:no_M_train * 200,iter),fs);
M_test = M(M_index_image((no_M_train*200) + 1 : 113 * 200,iter),fs);
% Selection of Training and testing data for females
F_train = F(F_index_image(1:no_F_train * 200,iter),fs);
F_test = F(F_index_image((no_F_train*200) + 1 : 60 * 200,iter),fs);
X = [M_train; F_train]; % Total train data
Y = [ones(no_M_train*200,1) ; ones(no_F_train*200,1) .* -1]; % Labels
X_test = [M_test; F_test]; % Total test data
% Training with KNN
model = ClassificationKNN.fit(X, Y, 'NumNeighbors',N);
% Testing
[result,~] = predict(model,X_test);
% Calculate gender probability
P_list = zeros(total_test,1);
for i = 1: total_test
S = sum(result(((i-1)*200) + 1 : ((i-1)*200) + 200,1));
P_list(i,1) = S/200;
end
KNN_score = [KNN_score; P_list]; % Appending scores
M_count = 0;
F_count = 0;
% Calculate threshold value
pdM = fitdist(P_list(1 : no_M_test,1),'Normal'); % Male dist
pdF = fitdist(P_list(no_M_test+1 : total_test,1),'Normal'); % Female dist
P_thres = (pdM.mu + pdF.mu)/2;
% Counting male predictions
for i = 1 : no_M_test
if P_list(i) > P_thres
M_count = M_count + 1;
end
end
% Counting female predictions
for i = no_M_test+1 : total_test
if P_list(i) <= P_thres
F_count = F_count + 1;
end
end
% Calculating average accuracies
M_acc = (M_count/no_M_test)*100;
F_acc = (F_count/no_F_test)*100;
avg_accu = (M_acc + F_acc)/2;
total_avg = total_avg + avg_accu;
total_avg_M = total_avg_M + M_acc;
total_avg_F = total_avg_F + F_acc;
end
|
github
|
samiuluofc/Matlab-master
|
fitness_tree.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_1_feature_selection/fitness_tree.m
| 2,950 |
utf_8
|
5f7575c7228947ea528071ca45f6e0a7
|
% This function receives selected features for Decision Tree and returns average
% gender prediction error of 5 different experiments.
function err = fitness_tree(bin_chrom)
% Load necessary Data
load('F_60.mat'); % Z score normalized data
load('M_113.mat');
% provide F_index_image and M_index_image matrix.
% These two matrix contains random indices of images.
load('random_index.mat');
% Select the features based on binary chromosome
fs = find(bin_chrom);
% Five random experiments
no_of_iter = 5;
% Number of test and training (M and F)
no_M_train = 80; % out of 113 (70%)
no_F_train = 43; % out of 60 (70%)
no_M_test = 113 - no_M_train;
no_F_test = 60 - no_F_train;
total_test = no_F_test + no_M_test;
% Initialization
total_avg = 0;
total_avg_M = 0;
total_avg_F = 0;
L = 29; % Number of minimum leaf for DTree
% For each experiment (random sampling), we conduct training and testing.
% Calculate average accuracy of 5 experiments.
for iter = 1 : 1 : no_of_iter
% Selection of Training and testing data for males
M_train = M(M_index_image(1:no_M_train * 200,iter),fs);
M_test = M(M_index_image((no_M_train*200) + 1 : 113 * 200,iter),fs);
% Selection of Training and testing data for females
F_train = F(F_index_image(1:no_F_train * 200,iter),fs);
F_test = F(F_index_image((no_F_train*200) + 1 : 60 * 200,iter),fs);
X = [M_train; F_train]; % Total train data
Y = [ones(no_M_train*200,1) ; ones(no_F_train*200,1) .* -1]; % Labels
X_test = [M_test; F_test]; % Total test data
% Training with DTree
model = ClassificationTree.fit(X, Y, 'MinLeaf',L);
% Testing
[result,~] = predict(model,X_test);
% Calculate gender probability
P_list = zeros(total_test,1);
for i = 1: total_test
S = sum(result(((i-1)*200) + 1 : ((i-1)*200) + 200,1));
P_list(i,1) = S/200;
end
M_count = 0;
F_count = 0;
% Calculate threshold value
pdM = fitdist(P_list(1 : no_M_test,1),'Normal'); % Male dist
pdF = fitdist(P_list(no_M_test+1 : total_test,1),'Normal'); % Female dist
P_thres = (pdM.mu + pdF.mu)/2;
% Counting male predictions
for i = 1 : no_M_test
if P_list(i) > P_thres
M_count = M_count + 1;
end
end
% Counting female predictions
for i = no_M_test+1 : total_test
if P_list(i) <= P_thres
F_count = F_count + 1;
end
end
% Calculating average accuracies
M_acc = (M_count/no_M_test)*100;
F_acc = (F_count/no_F_test)*100;
avg_accu = (M_acc + F_acc)/2;
total_avg = total_avg + avg_accu;
total_avg_M = total_avg_M + M_acc;
total_avg_F = total_avg_F + F_acc;
end
err = 100-(total_avg/no_of_iter); % Return total error in percentage
errM = 100-(total_avg_M/no_of_iter);
errF = 100-(total_avg_F/no_of_iter);
|
github
|
samiuluofc/Matlab-master
|
fitness_svm.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_1_feature_selection/fitness_svm.m
| 3,006 |
utf_8
|
d7f34deaf24ab758507319650dcf249a
|
% This function receives selected features for SVM and returns average
% gender prediction error of 5 different experiments.
function err = fitness_svm(bin_chrom)
% Load necessary Data
load('F_60.mat'); % Z score normalized data
load('M_113.mat');
% provide F_index_image and M_index_image matrix.
% These two matrix contains random indices of images.
load('random_index.mat');
% Select the features based on binary chromosome
fs = find(bin_chrom);
% Five random experiments
no_of_iter = 5;
% Number of test and training (M and F)
no_M_train = 80; %out of 113 (70%)
no_F_train = 43; %out of 60 (70%)
no_M_test = 113 - no_M_train;
no_F_test = 60 - no_F_train;
total_test = no_F_test + no_M_test;
% Initialization
total_avg = 0;
total_avg_M = 0;
total_avg_F = 0;
C = 0.008; % Soft Margin for SVM
% For each experiment (random sampling), we conduct training and testing.
% Calculate average accuracy of 5 experiments.
for iter = 1 : 1 : no_of_iter
% Selection of Training and testing data for males
M_train = M(M_index_image(1:no_M_train * 200,iter),fs);
M_test = M(M_index_image((no_M_train*200) + 1 : 113 * 200,iter),fs);
% Selection of Training and testing data for females
F_train = F(F_index_image(1:no_F_train * 200,iter),fs);
F_test = F(F_index_image((no_F_train*200) + 1 : 60 * 200,iter),fs);
X = [M_train; F_train]; % Total train data
Y = [ones(no_M_train*200,1) ; ones(no_F_train*200,1) .* -1]; % Labels
X_test = [M_test; F_test]; % Total test data
% Training with SVM
op = statset('MaxIter',30000);
model = svmtrain(X, Y,'autoscale',false,'boxconstraint',C,'kernel_function','linear','options', op);
% Testing
result = svmclassify(model,X_test);
% Calculate gender probability
P_list = zeros(total_test,1);
for i = 1: total_test
S = sum(result(((i-1)*200) + 1 : ((i-1)*200) + 200,1));
P_list(i,1) = S/200;
end
M_count = 0;
F_count = 0;
% Calculate threshold value
pdM = fitdist(P_list(1 : no_M_test,1),'Normal'); % Male dist
pdF = fitdist(P_list(no_M_test+1 : total_test,1),'Normal'); % Female dist
P_thres = (pdM.mu + pdF.mu)/2;
% Counting male predictions
for i = 1 : no_M_test
if P_list(i) > P_thres
M_count = M_count + 1;
end
end
% Counting female predictions
for i = no_M_test+1 : total_test
if P_list(i) <= P_thres
F_count = F_count + 1;
end
end
% Calculating average accuracies
M_acc = (M_count/no_M_test)*100;
F_acc = (F_count/no_F_test)*100;
avg_accu = (M_acc + F_acc)/2;
total_avg = total_avg + avg_accu;
total_avg_M = total_avg_M + M_acc;
total_avg_F = total_avg_F + F_acc;
end
err = 100-(total_avg/no_of_iter); % Return total error in percentage
errM = 100-(total_avg_M/no_of_iter);
errF = 100-(total_avg_F/no_of_iter);
|
github
|
samiuluofc/Matlab-master
|
fitness_knn.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_1_feature_selection/fitness_knn.m
| 2,936 |
utf_8
|
eb7db7664eaf5176151cbc1185e805d8
|
% This function receives selected features for KNN and returns average
% gender prediction error of 5 different experiments.
function err = fitness_knn(bin_chrom)
% Load necessary Data
load('F_60.mat'); % Z score normalized data
load('M_113.mat');
% provide F_index_image and M_index_image matrix.
% These two matrix contains random indices of images.
load('random_index.mat');
% Select the features based on binary chromosome
fs = find(bin_chrom);
% Five random experiments
no_of_iter = 5;
% Number of test and training (M and F)
no_M_train = 80; % out of 113 (70%)
no_F_train = 43; % out of 60 (70%)
no_M_test = 113 - no_M_train;
no_F_test = 60 - no_F_train;
total_test = no_F_test + no_M_test;
% Initialization
total_avg = 0;
total_avg_M = 0;
total_avg_F = 0;
N = 30; % Number of neighbor for KNN
% For each experiment (random sampling), we conduct training and testing.
% Calculate average accuracy of 5 experiments.
for iter = 1 : 1 : no_of_iter
% Selection of Training and testing data for males
M_train = M(M_index_image(1:no_M_train * 200,iter),fs);
M_test = M(M_index_image((no_M_train*200) + 1 : 113 * 200,iter),fs);
% Selection of Training and testing data for females
F_train = F(F_index_image(1:no_F_train * 200,iter),fs);
F_test = F(F_index_image((no_F_train*200) + 1 : 60 * 200,iter),fs);
X = [M_train; F_train]; % Total train data
Y = [ones(no_M_train*200,1) ; ones(no_F_train*200,1) .* -1]; % Labels
X_test = [M_test; F_test]; % Total test data
% Training with KNN
model = ClassificationKNN.fit(X, Y, 'NumNeighbors',N);
% Testing
[result,~] = predict(model,X_test);
% Calculate gender probability
P_list = zeros(total_test,1);
for i = 1: total_test
S = sum(result(((i-1)*200) + 1 : ((i-1)*200) + 200,1));
P_list(i,1) = S/200;
end
M_count = 0;
F_count = 0;
% Calculate threshold value
pdM = fitdist(P_list(1 : no_M_test,1),'Normal'); % Male dist
pdF = fitdist(P_list(no_M_test+1 : total_test,1),'Normal'); % Female dist
P_thres = (pdM.mu + pdF.mu)/2;
% Counting male predictions
for i = 1 : no_M_test
if P_list(i) > P_thres
M_count = M_count + 1;
end
end
% Counting female predictions
for i = no_M_test+1 : total_test
if P_list(i) <= P_thres
F_count = F_count + 1;
end
end
% Calculating average accuracies
M_acc = (M_count/no_M_test)*100;
F_acc = (F_count/no_F_test)*100;
avg_accu = (M_acc + F_acc)/2;
total_avg = total_avg + avg_accu;
total_avg_M = total_avg_M + M_acc;
total_avg_F = total_avg_F + F_acc;
end
err = 100-(total_avg/no_of_iter); % Return total error in percentage
errM = 100-(total_avg_M/no_of_iter);
errF = 100-(total_avg_F/no_of_iter);
|
github
|
samiuluofc/Matlab-master
|
tamura.m
|
.m
|
Matlab-master/Gender_recognition_project/Step_0_feature_extraction/tamura.m
| 4,806 |
utf_8
|
aefd118080f549efc228a2ebfe14829c
|
% Copyright (C) 2003 Open Microscopy Environment
% Massachusetts Institue of Technology,
% National Institutes of Health,
% University of Dundee
%
%
%
% This library 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 2.1 of the License, or (at your option) any later version.
%
% This library 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 Lesser General Public
% License along with this library; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Written by: Nikita Orlov <[email protected]>
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%% Tamura texture signatures: coarseness, directionality, contrast
%%
%% Reference: Tamura H., Mori S., Yamawaki T.,
%% 'Textural features corresponsing to visual perception'.
%% IEEE Trans. on Systems, Man and Cybernetics, 8, 1978, 460-472
%%
%% Nikita Orlov
%% Computational Biology Unit, LG,NIA/NIH
%% :: revision :: 07-20-2005
%%
%% input: Img (input image)
%% output1: Total coarseness, a scalar
%% output2: Coarseness histogram, a 1x3 vector
%% output3: Directionality, a scalar
%% output4: Contrast, a scalar
%%
%% Examples:
%% allTFeatures = Tamura3Sigs(Im);
%%
function allTFeatures = tamura(Im)
if ~isa(Im,'double')
Im = im2double(Im);
end
[TM_Coarseness,TM_Coarseness_hist] = Tamura_Coarseness(Im);
TM_Directionality = Tamura_Directionality(Im);
TM_Contrast = Tamura_Contrast(Im);
allTFeatures = [TM_Coarseness TM_Coarseness_hist TM_Directionality TM_Contrast];
return;
end
function Fdir = Tamura_Directionality(Im)
[gx,gy] = gradient(Im); [t,r] = cart2pol(gx,gy);
nbins = 125;
r(r<.15.*max(r(:))) = 0;
t0 = t; t0(abs(r)<1e-4) = 0;
r = r(:)'; t0 = t0(:)';
Hd = hist(t0,nbins);
nrm = hist(r(:).^2+t0(:).^2,nbins);
fmx = find(Hd==max(Hd));
ff = 1:length(Hd); ff2 = (ff - fmx).^2;
Fdir = sum(Hd.*ff2)./sum(nrm);
Fdir = abs(log(Fdir+eps));
return;
end
function Fc = Tamura_Contrast(Im)
Im = Im(:)';
ss = std(Im);
if abs(ss)<1e-10
Fc = 0;
return;
else
k = kurtosis(Im);
end
alf = k ./ ss.^4;
Fc = ss./(alf.^(.25));
return;
end
function [total_coarseness,coarseness_hist] = Tamura_Coarseness(Im)
kk = 0:6; %nh = []; nv = [];
for ii = 1:kk(end)
A = moveav(Im,2.^(kk(ii)));
%shift = 200;
shift = 2.^(kk(ii));
implus = zeros(size(A));
implus(:,1:end-shift+1) = A(:,shift:end);
iminus = zeros(size(A));
iminus(:,shift:end) = A(:,1:end-shift+1);
Hdelta(:,:,ii) = abs(implus-iminus);
implus = zeros(size(A));
implus(1:end-shift+1,:) = A(shift:end,:);
iminus = zeros(size(A));
iminus(shift:end,:) = A(1:end-shift+1,:);
Vdelta(:,:,ii) = abs(implus-iminus);
end
HdeltaMax = max(Hdelta,[],3);
hs = sum(HdeltaMax(:));
VdeltaMax = max(Vdelta,[],3);
vs = sum(VdeltaMax(:));
hij = reshape(Hdelta,size(Hdelta,1)*size(Hdelta,2),size(Hdelta,3)); %shij = sum(hij,1);
vij = reshape(Vdelta,size(Vdelta,1)*size(Vdelta,2),size(Vdelta,3)); %svij = sum(vij,1);
newh = zeros(size(hij,1),1);
for ii = 1:size(hij,1)
tmp1 = hij(ii,:); tmp2 = vij(ii,:);
mtmp1 = max(tmp1);
mtmp2 = max(tmp2);
mtmp1 = mtmp1(1);
mtmp2 = mtmp2(1);
mm = max(mtmp1,mtmp2);
im1 = find(tmp1==mtmp1);
im2 = find(tmp2==mtmp2);
if mm == mtmp1
imm = im1(1);
else
imm = im2(1);
end
newh(ii) = kk(imm);
end
total_coarseness = mean(newh);
newh = reshape(2.^newh,size(Im,1),size(Im,2));
nbin = 3;
coarseness_hist = hist(newh(:),nbin);
coarseness_hist = coarseness_hist./max(coarseness_hist);
%coarseness_hist = uint16(coarseness_hist);
return;
end
function sm = moveav(Im,nk)
kern = ones(nk)./nk.^2; sm = conv2(Im,kern,'same');
return;
end
|
github
|
samiuluofc/Matlab-master
|
tamura.m
|
.m
|
Matlab-master/Person_identification_project/Step_0_Feature_extraction/Local_perceptual/tamura.m
| 4,806 |
utf_8
|
aefd118080f549efc228a2ebfe14829c
|
% Copyright (C) 2003 Open Microscopy Environment
% Massachusetts Institue of Technology,
% National Institutes of Health,
% University of Dundee
%
%
%
% This library 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 2.1 of the License, or (at your option) any later version.
%
% This library 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 Lesser General Public
% License along with this library; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Written by: Nikita Orlov <[email protected]>
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%% Tamura texture signatures: coarseness, directionality, contrast
%%
%% Reference: Tamura H., Mori S., Yamawaki T.,
%% 'Textural features corresponsing to visual perception'.
%% IEEE Trans. on Systems, Man and Cybernetics, 8, 1978, 460-472
%%
%% Nikita Orlov
%% Computational Biology Unit, LG,NIA/NIH
%% :: revision :: 07-20-2005
%%
%% input: Img (input image)
%% output1: Total coarseness, a scalar
%% output2: Coarseness histogram, a 1x3 vector
%% output3: Directionality, a scalar
%% output4: Contrast, a scalar
%%
%% Examples:
%% allTFeatures = Tamura3Sigs(Im);
%%
function allTFeatures = tamura(Im)
if ~isa(Im,'double')
Im = im2double(Im);
end
[TM_Coarseness,TM_Coarseness_hist] = Tamura_Coarseness(Im);
TM_Directionality = Tamura_Directionality(Im);
TM_Contrast = Tamura_Contrast(Im);
allTFeatures = [TM_Coarseness TM_Coarseness_hist TM_Directionality TM_Contrast];
return;
end
function Fdir = Tamura_Directionality(Im)
[gx,gy] = gradient(Im); [t,r] = cart2pol(gx,gy);
nbins = 125;
r(r<.15.*max(r(:))) = 0;
t0 = t; t0(abs(r)<1e-4) = 0;
r = r(:)'; t0 = t0(:)';
Hd = hist(t0,nbins);
nrm = hist(r(:).^2+t0(:).^2,nbins);
fmx = find(Hd==max(Hd));
ff = 1:length(Hd); ff2 = (ff - fmx).^2;
Fdir = sum(Hd.*ff2)./sum(nrm);
Fdir = abs(log(Fdir+eps));
return;
end
function Fc = Tamura_Contrast(Im)
Im = Im(:)';
ss = std(Im);
if abs(ss)<1e-10
Fc = 0;
return;
else
k = kurtosis(Im);
end
alf = k ./ ss.^4;
Fc = ss./(alf.^(.25));
return;
end
function [total_coarseness,coarseness_hist] = Tamura_Coarseness(Im)
kk = 0:6; %nh = []; nv = [];
for ii = 1:kk(end)
A = moveav(Im,2.^(kk(ii)));
%shift = 200;
shift = 2.^(kk(ii));
implus = zeros(size(A));
implus(:,1:end-shift+1) = A(:,shift:end);
iminus = zeros(size(A));
iminus(:,shift:end) = A(:,1:end-shift+1);
Hdelta(:,:,ii) = abs(implus-iminus);
implus = zeros(size(A));
implus(1:end-shift+1,:) = A(shift:end,:);
iminus = zeros(size(A));
iminus(shift:end,:) = A(1:end-shift+1,:);
Vdelta(:,:,ii) = abs(implus-iminus);
end
HdeltaMax = max(Hdelta,[],3);
hs = sum(HdeltaMax(:));
VdeltaMax = max(Vdelta,[],3);
vs = sum(VdeltaMax(:));
hij = reshape(Hdelta,size(Hdelta,1)*size(Hdelta,2),size(Hdelta,3)); %shij = sum(hij,1);
vij = reshape(Vdelta,size(Vdelta,1)*size(Vdelta,2),size(Vdelta,3)); %svij = sum(vij,1);
newh = zeros(size(hij,1),1);
for ii = 1:size(hij,1)
tmp1 = hij(ii,:); tmp2 = vij(ii,:);
mtmp1 = max(tmp1);
mtmp2 = max(tmp2);
mtmp1 = mtmp1(1);
mtmp2 = mtmp2(1);
mm = max(mtmp1,mtmp2);
im1 = find(tmp1==mtmp1);
im2 = find(tmp2==mtmp2);
if mm == mtmp1
imm = im1(1);
else
imm = im2(1);
end
newh(ii) = kk(imm);
end
total_coarseness = mean(newh);
newh = reshape(2.^newh,size(Im,1),size(Im,2));
nbin = 3;
coarseness_hist = hist(newh(:),nbin);
coarseness_hist = coarseness_hist./max(coarseness_hist);
%coarseness_hist = uint16(coarseness_hist);
return;
end
function sm = moveav(Im,nk)
kern = ones(nk)./nk.^2; sm = conv2(Im,kern,'same');
return;
end
|
github
|
rising-turtle/slam_matlab-master
|
find_index.m
|
.m
|
slam_matlab-master/plot_traj/find_index.m
| 489 |
utf_8
|
4a74fe943cd8030d30c158271c8fe7f1
|
%% compute first index of gt, given the already matched timestamp from test_gt
function index = find_index(t, first_timestamp_pose)
index = -1;
%% the following two are matched
vt = 1498879054.726535936;
gt = 12.125;
if first_timestamp_pose > 1e12
first_timestamp_pose = first_timestamp_pose * 1e-9;
end
dt = vt - first_timestamp_pose;
for i=1:size(t,1)
if t(i) + dt >= gt
index = i;
break;
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
compare_trajectory_with_gt.m
|
.m
|
slam_matlab-master/plot_traj/compare_trajectory_with_gt.m
| 1,999 |
utf_8
|
dbd23bc55a865245d9f8a9f9e0ad6f99
|
%
% Feb. 24, 2018, He Zhang, [email protected]
%
% compare the trajectories of viorb, okvis, vins-mono
% the realsesne datasets
%
function compare_trajectory_with_gt(fdir)
if nargin == 0
fdir = './results/GT';
end
% load viorb trajectory
% f_viorb = strcat(fdir, '/viorb.log');
% T_viorb = load(f_viorb);
% load okvis trajecotry
f_okvis = strcat(fdir, '/okvis.log');
T_okvis = load(f_okvis);
% load vins-mono trajectory
f_vins = strcat(fdir, '/vins-mono.log');
T_vins = load(f_vins);
% load vins-mono_ext trajectory
f_ext = strcat(fdir, '/vins-mono_ext.log');
T_ext = load(f_ext);
% transform viorb based on the coordinate of VINS-Mono_ext
% T_viorb(:, 1:8) = transform_viorb(T_ext(1,1:8), T_viorb(:, 1:8));
% load ground truth
f_gt = strcat(fdir, '/ground_truth.log');
T_gt = load(f_gt);
s = 1;
e = 1000;
% plot_xyz(-T_viorb(:,3), -T_viorb(:, 2), T_viorb(:, 4), 'm-');
% plot_xyz(T_viorb(:,2), -T_viorb(:, 3), T_viorb(:, 4), 'm-');
% hold on;
plot_xyz(T_okvis(s:e,2), T_okvis(s:e, 3), T_okvis(s:e, 4), 'b:');
hold on;
plot_xyz(T_gt(s:2*e,2), -T_gt(s:2*e,4),T_gt(s:2*e,3), 'k-');
grid on;
hold on;
plot_xyz(T_vins(s:e,2), T_vins(s:e, 3), T_vins(s:e, 4), 'r-.');
hold on;
plot_xyz(T_ext(s:e,2), T_ext(s:e, 3), T_ext(s:e, 4), 'g-');
% legend('VIORB', 'OKVIS', 'VINS-Mono', 'Proposed');
legend('OKVIS', 'GT','VINS-Mono', 'Proposed');
% title('Trajectory Comparison');
end
%% viorb's coordinate is different from vins-mono and okvis
function pose = transform_viorb( pose_base, pose)
Too = construct(pose(1, 2:8));
Too_inv = inv(Too);
Tg2s = construct(pose_base(2:8));
Ts2c = [1 0 0 0;
0 0 1 0;
0 -1 0 0;
0 0 0 1];
for i=1:size(pose,1)
Tii = construct(pose(i, 2:8));
Tc2i = Too_inv * Tii;
Tg2i = Tg2s * Ts2c * Tc2i;
[q, t] = deconstruct(Tg2i);
% Tb2i = Tb2o * To2i;
% [q, t] = deconstruct(Tb2i);
pose(i, 2:4) = t(:);
pose(i, 5:8) = q(:);
end
end
|
github
|
rising-turtle/slam_matlab-master
|
rmat2quat.m
|
.m
|
slam_matlab-master/plot_traj/rmat2quat.m
| 795 |
utf_8
|
238c076762b7266d10f6726f613f660c
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Converts (orthogonal) rotation matrices R to (unit) quaternion
% representations
%
% Input: A 3x3xn matrix of rotation matrices
% Output: A 4xn matrix of n corresponding quaternions
%
% http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion
function quaternion = rmat2quat(R)
Qxx = R(1,1,:);
Qxy = R(1,2,:);
Qxz = R(1,3,:);
Qyx = R(2,1,:);
Qyy = R(2,2,:);
Qyz = R(2,3,:);
Qzx = R(3,1,:);
Qzy = R(3,2,:);
Qzz = R(3,3,:);
w = 0.5 * sqrt(1+Qxx+Qyy+Qzz);
x = 0.5 * sign(Qzy-Qyz) .* sqrt(1+Qxx-Qyy-Qzz);
y = 0.5 * sign(Qxz-Qzx) .* sqrt(1-Qxx+Qyy-Qzz);
z = 0.5 * sign(Qyx-Qxy) .* sqrt(1-Qxx-Qyy+Qzz);
quaternion = reshape([w;x;y;z],4,[]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
rising-turtle/slam_matlab-master
|
compute_transform.m
|
.m
|
slam_matlab-master/plot_traj/compute_transform.m
| 921 |
utf_8
|
7f9d4b2132ff0bbd3fe74d35b6654223
|
%% find transformation between two point sets
function [pose, pose_err] = compute_transform(pose, pF, pT)
% plot_xyz(pts_f(:,1), pts_f(:,2), pts_f(:,3), 'r*');
% hold on;
% plot_xyz(pts_t(:,1), pts_t(:,2), pts_t(:,3), 'bs');
pts_f = pF(:,2:4);
pts_t = pT(:,2:4);
[rot, trans] = eq_point(pts_t', pts_f');
pts_tt = rot * pts_f' + repmat(trans,1, size(pts_f,1));
pts_tt = pts_tt';
dt = pts_t(1,:) - pts_tt(1,:);
if nargout == 2
pts_tt = pts_tt' + repmat(dt', 1, size(pts_f,1));
pose_err = zeros(size(pT,1),2);
pose_err(:,1) = pT(:,1);
d_pos = pts_tt - pts_t';
pose_err(:,2) = sqrt(sum(d_pos.*d_pos));
end
% hold on;
% plot_xyz(pts_tt(:,1), pts_tt(:,2), pts_tt(:,3), 'g+');
for i=1:size(pose)
t = pose(i, 2:4);
t = rot * t' + trans + dt';
pose(i,2:4) = t';
end
end
|
github
|
rising-turtle/slam_matlab-master
|
compare_trajectory.m
|
.m
|
slam_matlab-master/plot_traj/compare_trajectory.m
| 1,768 |
utf_8
|
4781b8053894727bea8f96a135231f69
|
%
% Feb. 21, 2018, He Zhang, [email protected]
%
% compare the trajectories of viorb, okvis, vins-mono
% the realsesne datasets
%
function compare_trajectory(fdir)
if nargin == 0
fdir = './results/ETAS_2F_640_30';
fdir = './results/ETAS_F4_640_30';
end
% load viorb trajectory
f_viorb = strcat(fdir, '/viorb.log');
T_viorb = load(f_viorb);
% load okvis trajecotry
f_okvis = strcat(fdir, '/okvis.log');
%f_okvis = strcat(fdir, '/run_7.log');
T_okvis = load(f_okvis);
% load vins-mono trajectory
f_vins = strcat(fdir, '/vins-mono.log');
T_vins = load(f_vins);
% load vins-mono_ext trajectory
f_ext = strcat(fdir, '/vins-mono_ext.log');
T_ext = load(f_ext);
% transform viorb based on the coordinate of VINS-Mono_ext
T_viorb(:, 1:8) = transform_viorb(T_ext(1,1:8), T_viorb(:, 1:8));
plot_xyz(-T_viorb(:,3), -T_viorb(:, 2), T_viorb(:, 4), 'm-');
hold on;
plot_xyz(T_okvis(:,2), T_okvis(:, 3), T_okvis(:, 4), 'b:');
hold on;
% grid on;
plot_xyz(T_vins(:,2), T_vins(:, 3), T_vins(:, 4), 'r-.');
hold on;
plot_xyz(T_ext(:,2), T_ext(:, 3), T_ext(:, 4), 'g-');
legend('VIORB', 'OKVIS', 'VINS-Mono', 'Proposed');
% title('Trajectory Comparison');
end
%% viorb's coordinate is different from vins-mono and okvis
function pose = transform_viorb( pose_base, pose)
Too = construct(pose(1, 2:8));
Too_inv = inv(Too);
Tg2s = construct(pose_base(2:8));
Ts2c = [1 0 0 0;
0 0 1 0;
0 -1 0 0;
0 0 0 1];
for i=1:size(pose,1)
Tii = construct(pose(i, 2:8));
Tc2i = Too_inv * Tii;
Tg2i = Tg2s * Ts2c * Tc2i;
[q, t] = deconstruct(Tg2i);
% Tb2i = Tb2o * To2i;
% [q, t] = deconstruct(Tb2i);
pose(i, 2:4) = t(:);
pose(i, 5:8) = q(:);
end
end
|
github
|
rising-turtle/slam_matlab-master
|
quat2rmat.m
|
.m
|
slam_matlab-master/plot_traj/quat2rmat.m
| 798 |
utf_8
|
fb153dbeaab428656e51bea7b133b87c
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Converts (unit) quaternion representations to (orthogonal) rotation matrices R
%
% Input: A 4xn matrix of n quaternions
% Output: A 3x3xn matrix of corresponding rotation matrices
%
% http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#From_a_quaternion_to_an_orthogonal_matrix
function R = quat2rmat(quaternion)
q0(1,1,:) = quaternion(1,:);
qx(1,1,:) = quaternion(2,:);
qy(1,1,:) = quaternion(3,:);
qz(1,1,:) = quaternion(4,:);
R = [q0.^2+qx.^2-qy.^2-qz.^2 2*qx.*qy-2*q0.*qz 2*qx.*qz+2*q0.*qy;
2*qx.*qy+2*q0.*qz q0.^2-qx.^2+qy.^2-qz.^2 2*qy.*qz-2*q0.*qx;
2*qx.*qz-2*q0.*qy 2*qy.*qz+2*q0.*qx q0.^2-qx.^2-qy.^2+qz.^2];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
rising-turtle/slam_matlab-master
|
transform_to_synchronized.m
|
.m
|
slam_matlab-master/plot_traj/transform_to_synchronized.m
| 1,377 |
utf_8
|
b2a5bbeb814e5be9d3ac6ba6f982cab3
|
%% transform into the coordinate of the synchronized pose
function [pose, pt_f, pt_t] = transform_to_synchronized(pose, gt, index)
Tw2l = construct(gt(index, 2:8));
Tl2s = transformB2S();
Tw2s = Tw2l * Tl2s;
time_s = 1.;
t_p = pose(1,1);
if t_p > 1e12
time_s = 1e-9;
end
t_p = t_p * time_s;
t_g = gt(index,1);
% plot_axis(Tw2l(1:3, 1:3), Tw2s(1:3,4), 1);
% hold on;
% plot_axis(Tw2s(1:3, 1:3), Tw2s(1:3,4), 2);
pt_f = [];
pt_t = [];
from = 1;
for i = 1:size(pose,1)
Ts2i = construct(pose(i,2:8));
Tw2i = Tw2s * Ts2i;
[q, t] = deconstruct(Tw2i);
pose(i, 2:4) = t(:);
pose(i, 5:7) = q(2:4);
pose(i, 8) = q(1);
%% find correspond point sets
timestamp = pose(i,1)*time_s;
j = find_correspond( gt(:,1), t_g + timestamp - t_p, from);
if j > from
pt_f = [pt_f; pose(i,1:4)];
pt_t = [pt_t; gt(j, 1:4)];
from = j;
else
% fprintf('find_correspond error? from = %d j = %d\n', from, j);
end
end
end
%% construct Tb2s
function Tb2s = transformB2S()
t_b2s = [-0.01, -0.015, 0.03]';
theta = 20*pi/180;
cs = cos(theta);
ss = sin(theta);
R_b2s = [1 0 0;
0 cs -ss;
0 ss cs];
Tb2s = [R_b2s t_b2s;
0 0 0 1];
end
|
github
|
rising-turtle/slam_matlab-master
|
align_transform.m
|
.m
|
slam_matlab-master/plot_traj/align_transform.m
| 250 |
utf_8
|
6caa31298f67c2f9adbd540e282938ff
|
%%
function [pose, pose_err] = align_transform(pose, gt)
index = find_index(gt(:,1), pose(1,1));
[pose, pts_f, pts_t] = transform_to_synchronized(pose, gt, index);
[pose, pose_err] = compute_transform(pose, pts_f(:,:), pts_t(:,:));
end
|
github
|
rising-turtle/slam_matlab-master
|
traj_in_IMU.m
|
.m
|
slam_matlab-master/plot_traj/traj_in_IMU.m
| 1,914 |
utf_8
|
c4b52bcfa530457b7262515b3f8dba45
|
%%%
% transform coordinates from world to IMU
% Now this file has been extended to show the trajectory comparison of the
% R200_GT_DENSE_SLOW dataset
% Feb. 26 2018, He Zhang, [email protected]
function traj_in_IMU(fdir)
if nargin == 0
fdir = './results/GT';
end
addpath('../ground_truth_zh');
% load viorb trajectory
% f_viorb = strcat(fdir, '/viorb.log');
% T_viorb = load(f_viorb);
% load okvis trajecotry
f_okvis = strcat(fdir, '/okvis.log');
T_okvis = load(f_okvis);
% load vins-mono trajectory
f_vins = strcat(fdir, '/vins-mono.log');
T_vins = load(f_vins);
% load vins-mono_ext trajectory
f_ext = strcat(fdir, '/vins-mono_ext.log');
T_ext = load(f_ext);
% transform viorb based on the coordinate of VINS-Mono_ext
% T_viorb(:, 1:8) = transform_viorb(T_ext(1,1:8), T_viorb(:, 1:8));
% load ground truth
f_gt = strcat(fdir, '/ground_truth_g.log');
T_gt = load(f_gt);
s = 1;
e = 200;
%% transform into the coordinate of the first pose
T_okvis = transform_to_first(T_okvis);
T_vins = transform_to_first(T_vins);
T_ext = transform_to_first(T_ext);
%% transform to synchronized pose got from test_gt,
% and then align with gt's trajectory
T_vins = align_transform(T_vins, T_gt);
T_ext = align_transform(T_ext, T_gt);
T_okvis = align_transform(T_okvis, T_gt);
% T_okvis = transform_to_synchronized(T_okvis, T_gt, 237);
% plot_xyz(-T_viorb(:,3), -T_viorb(:, 2), T_viorb(:, 4), 'm-');
% plot_xyz(T_viorb(:,2), -T_viorb(:, 3), T_viorb(:, 4), 'm-');
% hold on;
plot_xyz(T_okvis(:,2), T_okvis(:, 4), T_okvis(:, 3), 'b:');
hold on;
% plot_xyz( T_gt(:,4), -T_gt(:,2),T_gt(:,3), 'k-');
plot_xyz(T_vins(:,2), T_vins(:, 4), T_vins(:, 3), 'r--.');
hold on;
plot_xyz(T_ext(:,2), T_ext(:, 4), T_ext(:, 3), 'g-.');
hold on;
plot_xyz( T_gt(:,2), T_gt(:,4), T_gt(:,3), 'k-');
grid on;
% legend('VIORB', 'OKVIS', 'VINS-Mono', 'Proposed');
legend('OKVIS', 'VINS-Mono', 'Proposed', 'GT');
end
|
github
|
rising-turtle/slam_matlab-master
|
transToFirst.m
|
.m
|
slam_matlab-master/plot_traj/transToFirst.m
| 792 |
utf_8
|
94c3469b01e233f12371e0688cffe076
|
function [ TO ] = transToFirst( TI )
% Transform to the first frame as basic coordinate system
% Aug. 30 2017, He Zhang, [email protected]
% INPUT: array [timestamp, x, y, z, qw, qx, qy, qz]
% OUTPUT: array [timestamp, x, y, z, qw, qx, qy, qz]
%
TO = zeros(size(TI,1), 8);
T1 = construct(TI(1,2:end));
for i=1:size(TI,1)
Ti = construct(TI(i, 2:end));
Ti_new = T1\Ti;
[q, t] = deconstruct(Ti_new);
TO(i,:) = [TI(i,1), t', q'];
end
end
function [q, t] = deconstruct(T)
[R,t] = decompose(T);
q = rmat2quat(R);
end
function [T] = construct(v)
t = v(1:3);
q = v(4:7);
R = quat2rmat(q');
T = combine(R, t');
end
function [T] = combine(R, t)
T = [R t; 0 0 0 1];
end
function [R, t] = decompose(T)
R = T(1:3, 1:3);
t = T(1:3, 4);
end
|
github
|
rising-turtle/slam_matlab-master
|
plot_error_bar.m
|
.m
|
slam_matlab-master/plot_traj/plot_error_bar.m
| 2,874 |
utf_8
|
5788a1e38b91d7d76c88b70767806e29
|
%%
% Dec. 27, 2018, He Zhang, [email protected]
% plot the error bar of the translation err
function plot_error_bar()
load('vins-mono_err.mat');
load('gt.mat');
load('vins-mono_ext_err.mat');
load('okvis_err.mat');
tps = find_dis_tps(T_gt, 2);
x = tps(:,2);
vins_mono_err_x = [];
vins_mono_std_x = [];
vins_mono_ext_err_x = [];
vins_mono_ext_std_x = [];
okvis_err_x = [];
okvis_std_x = [];
for i=1:size(tps)
tp = tps(i,1);
vins_mono_err_i = [];
vins_mono_ext_err_i= [];
okvis_err_i = [];
for j=1:10
E_vins = vins_err{j};
er = find_err(tp, E_vins);
if er >= 0
vins_mono_err_i = [vins_mono_err_i; er];
end
E_vins_ext = vins_ext_err{j};
er = find_err(tp, E_vins_ext);
if er >= 0
vins_mono_ext_err_i = [vins_mono_ext_err_i; er];
end
E_okvis = okvis_err{j};
er = find_err(tp, E_okvis);
if er >= 0
okvis_err_i = [okvis_err_i; er];
end
end
mu = mean(vins_mono_err_i);
sigma = std(vins_mono_err_i);
vins_mono_err_x = [vins_mono_err_x; mu];
vins_mono_std_x = [vins_mono_std_x; sigma];
mu = mean(vins_mono_ext_err_i);
sigma = std(vins_mono_ext_err_i);
vins_mono_ext_err_x = [vins_mono_ext_err_x; mu];
vins_mono_ext_std_x = [vins_mono_ext_std_x; sigma];
mu = mean(okvis_err_i);
sigma = std(okvis_err_i);
okvis_err_x = [okvis_err_x; mu];
okvis_std_x = [okvis_std_x; sigma];
end
% draw bar
errorbar(x, okvis_err_x, okvis_std_x, 'd', 'MarkerFaceColor', 'blue');
hold on;
errorbar(x + 0.1, vins_mono_err_x, vins_mono_std_x, 's', 'MarkerFaceColor', 'red');
hold on;
errorbar(x + 0.2, vins_mono_ext_err_x, vins_mono_ext_std_x, '*', 'MarkerFaceColor', 'green');
hold on;
grid on;
grid on;
xlabel('Distance traveled [m]');
ylabel('Translation Error [m]');
legend('OKVIS', 'VINS-Mono', 'Proposed');
xlim([0, 28])
end
%% find err value at given timestamp
function err = find_err(tp, Er)
err = -1;
for i=1:size(Er,1)
if Er(i,1) >= tp
if Er(i,1) - tp <= 0.2
err = Er(i,2);
break;
else
if i>1 && tp - Er(i-1,2) <= 0.2
err = Er(i-1,2);
break;
end
end
end
end
end
%% find timestamps at given distance
function [tps] = find_dis_tps(gt, dis)
tps = [];
last = 1;
j = 1;
m = size(gt,1);
last_dis = 0;
while j < m
t1 = gt(last, 2:4);
for j=last:m
t2 = gt(j,2:4);
dt = t2 - t1;
cur_dis = sqrt(dt*dt');
if cur_dis >= dis
tps = [tps; gt(j,1), dis+last_dis];
last = j;
last_dis = dis + last_dis;
break;
end
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
statistic_translation_error.m
|
.m
|
slam_matlab-master/plot_traj/statistic_translation_error.m
| 1,000 |
utf_8
|
1642aa08763e6bae13221a04d95481fa
|
%%
% Dec. 27, 2018, He Zhang, [email protected]
% compute the translation error compared to path length
function [ output_args ] = statistic_translation_error(fdir)
if nargin == 0
fdir = './results/GT/vins-mono_GT';
fdir = './results/GT/vins-mono_ext_GT';
fdir = './results/GT/okvis_GT';
end
addpath('../ground_truth_zh');
f_gt = strcat('./results/GT', '/ground_truth_g.log');
T_gt = load(f_gt);
% vins_err = {};
% vins_ext_err = {};
okvis_err = {};
j = 1;
for i = 1:10 %6:15
fname = strcat('/run_', int2str(i));
% fname = strcat(fname, '.csv');
fname = strcat(fname, '.log');
fname = strcat(fdir, fname);
T = load(fname);
T = transform_to_first(T);
[T, Te] = align_transform(T, T_gt);
% vins_err{j} = Te;
% vins_ext_err{j} = Te;
okvis_err{j} = Te;
j= j+1;
end
% save('vins-mono_err.mat', 'vins_err');
% save('gt.mat', 'T_gt');
% save('vins-mono_ext_err.mat', 'vins_ext_err');
save('okvis_err.mat', 'okvis_err');
end
|
github
|
rising-turtle/slam_matlab-master
|
find_correspond.m
|
.m
|
slam_matlab-master/plot_traj/find_correspond.m
| 235 |
utf_8
|
c8fde5fe7636408d30305a01e739f8c1
|
%% find corresponding point
function j = find_correspond(x, timestamp, from)
j = from;
for i = from:size(x,1)
if x(i) > timestamp && x(i) - timestamp < 0.03
j = i;
break;
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
test_gt.m
|
.m
|
slam_matlab-master/plot_traj/test_gt.m
| 960 |
utf_8
|
d6c24ad51365e497f00763a5ec7084a6
|
%%%
% to align gt with trajectories from vins, okvis,
% find out the timestamp at 1350 of gt match to timestamp at 53 of vins
% which means gt's timestamp 12.125 vins' timestamp 1498879054.726535936
% then gt's timestamp 6.925 (at 738) match to vins-mono' start timestamp 1498879049.526535936
% gt's timestamp 7.225 (at 774) match to vins-mono_ext's start timestamp 1498879049.826536192
% gt's timestamp 2.667 (at 237) match to okvis's start timestamp 1498879045.268399370
% gt's timestamp 2.691 (at 240) to viorb's start timestamp 1498879045.293203
function test_gt(st)
if nargin == 0
st = 1230;
end
% load ground truth
f_gt = strcat('./results/GT', '/ground_truth_g.log');
T_gt = load(f_gt);
figure;
r = 200;
plot_xyz( -T_gt(st:st+r,2), -T_gt(st:st+r,4), T_gt(st:st+r,3), 'k-');
view(2);
% compute_dx(T_gt(st:st+r,2));
end
function compute_dx(x)
m = size(x,1)
x1 = x(2:end);
x0 = x(1:m-1);
dx = abs(1000*(x1 - x0));
plot(dx,'b-*');
end
|
github
|
rising-turtle/slam_matlab-master
|
transform_to_first.m
|
.m
|
slam_matlab-master/plot_traj/transform_to_first.m
| 347 |
utf_8
|
bf27f9b19d15e12a6f85768b89f828c1
|
%% transform into the coordinate of the first pose
function pose = transform_to_first(pose)
Too = construct(pose(1, 2:8));
Too_inv = inv(Too);
for i=1:size(pose,1)
Tii = construct(pose(i, 2:8));
Ts2i = Too_inv * Tii;
[q, t] = deconstruct(Ts2i);
pose(i, 2:4) = t(:);
pose(i, 5:8) = q(:);
end
end
|
github
|
rising-turtle/slam_matlab-master
|
plot_feature_pts.m
|
.m
|
slam_matlab-master/plot_traj/plot_feature_pts.m
| 748 |
utf_8
|
a6b31abd76d5d9da3824a8fe62d53155
|
function [ output_args ] = plot_feature_pts( fname )
%UNTITLED3 Summary of this function goes here
% Detailed explanation goes here
if nargin == 0
fname = 'vins_mono_ext_feature_pts.log';
end
pts = load(fname);
pts = filter_distant(pts);
hold on;
grid on;
plot3(pts(:,1), pts(:,2), pts(:,3), '.', 'MarkerSize', 5);
view(3);
end
function pts = filter_distant(pts)
epts = zeros(size(pts));
k = 1;
for i=1:size(pts, 1)
good = true;
for j=1:3
if pts(i, j) > 40 || pts(i, j) < -40
good = false;
break;
end
end
if good == true
epts(k, :) = pts(i, :);
k = k + 1;
end
end
pts = epts(1:k,:);
end
|
github
|
rising-turtle/slam_matlab-master
|
load_camera_frame.m
|
.m
|
slam_matlab-master/VRO/load_camera_frame.m
| 2,267 |
utf_8
|
fead0b7e8d4edb2989241e7cafbb1d1b
|
function [img, frm, des, p, ld_err] = load_camera_frame(fid)
%
% David Z, March 3th, 2015
% load camera data:
% img, 2D pixels
% frm,
% p [x y z]; (width, height, 3)
% ld_err = 1, if not exist
global g_data_dir g_data_prefix g_data_suffix g_camera_type
global g_filter_type
ld_err = 0; % TODO: take the load data error into consideration
% now only support SwissRanger
cut_off_boarder = 0; % weather to cut off the boarder pixels
dm = 1; % directory of data?
scale = 1; % scale the intensity image to the range [0~255]
value_type = 'int'; % convert to int, after scaling the image
%% feature has been stored
if file_exist(fid) ~= 0
[img, frm, des, p] = load_feature(fid);
return ;
else
if strcmp(g_camera_type, 'creative')
[img, x, y, z, c] = LoadCreative_dat(g_camera_type, fid);
else
if strcmp(g_data_suffix, 'dat')
[img, x, y, z, c] = LoadSR_no_bpc(g_camera_type, g_filter_type, ...
cut_off_boarder, dm, fid, scale, value_type);
elseif strcmp(g_data_suffix, 'bdat')
[img, x, y, z, c] = LoadSR_no_bpc_time_single_binary(g_camera_type, ...
g_filter_type, cut_off_boarder, dm, fid, scale, value_type);
end
end
if isempty(img)
frm = []; des = []; p =[];
ld_err = 1;
return;
end
end
%% sift feature
global g_sift_threshold
if g_sift_threshold == 0
[frm, des] = sift(img);
else
[frm, des] = sift(img, 'threshold', g_sift_threshold);
end
%% plot the point cloud
% plot_pc(x, y, z, 'b');
% dump2ply('tmp.ply', x, y, z, img);
%% confindence filtering
if c ~=0
[frm, des] = confidence_filtering(frm, des, c);
end
%% construct return value
[m, n] = size(x);
p = zeros(m, n, 3);
p(:,:,1) = x;
p(:,:,2) = y;
p(:,:,3) = z;
%% save it into file
global g_save_vro_middle_result
if g_save_vro_middle_result
save_feature(fid, img, frm, des, p);
end
end
function plot_pc(x, y, z, c)
plot3(x, y, z, c);
end
%% check weather this visul feature exist
function [exist_flag] = file_exist(id)
%% get file name
global g_data_dir g_data_prefix g_feature_dir
file_name = sprintf('%s/%s/%s_%04d.mat', g_data_dir, g_feature_dir, g_data_prefix, id);
exist_flag = exist(file_name, 'file');
end
|
github
|
rising-turtle/slam_matlab-master
|
pre_check_dir.m
|
.m
|
slam_matlab-master/VRO/pre_check_dir.m
| 547 |
utf_8
|
8a7e9d1ce4f080306bd3b5ee748a06f2
|
%
% David Z, Jan 22th, 2015
% pre-check the save dir, if not exist, create it
%
function pre_check_dir(dir_)
global g_feature_dir g_matched_dir g_pose_std_dir
feature_dir = sprintf('/%s', g_feature_dir);
match_dir = sprintf('/%s', g_matched_dir);
not_exist_then_create(strcat(dir_, feature_dir));
not_exist_then_create(strcat(dir_, match_dir));
% not_exist_then_create(strcat(dir_, '/pose_std'));
not_exist_then_create('./results');
end
function not_exist_then_create(dir_)
if ~isdir(dir_)
mkdir(dir_);
end
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadCreative_dat.m
|
.m
|
slam_matlab-master/VRO/LoadCreative_dat.m
| 783 |
utf_8
|
f539355d95dcac539680013bc4ae091c
|
%
% David Z, Jan 22th, 2015
% Load Creative Data
%
function [img, x, y, z, c, time, err] = LoadCreative_dat(data_name, j)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name);
img = []; x = []; y = []; z = []; c = [];
err = 0;
%% time elapse
t_pre = tic;
%% load data file
[file_name, err] = sprintf('%s%d.dat', prefix, j);
if ~exist(file_name, 'file')
fprintf('LoadCreative_dat.m: file not exist: %s\n', file_name);
err = 1;
return ;
end
a = load(file_name); % elapsed time := 0.2 sec
if isempty(a)
fprintf('LoadCreative_dat.m: file is empty!\n');
err = 1;
return;
end
row = size(a, 1);
img = a(1:row/4, :);
x = a((row/4+1):row/2, :);
y= a(row/2+1:3*row/4, :);
z = a(3*row/4+1:row, :);
c = zeros(size(x));
time = toc(t_pre);
end
|
github
|
rising-turtle/slam_matlab-master
|
graphslam_addpath.m
|
.m
|
slam_matlab-master/VRO/graphslam_addpath.m
| 1,409 |
utf_8
|
503a943bb30b3483282203370b1e5f57
|
% Add the path for graph slam
%
% Author : Soonhac Hong ([email protected])
% Date : 10/16/12
function graphslam_addpath
% addpath('D:\Soonhac\SW\gtsam-toolbox-2.3.0-win64\toolbox');
% addpath('D:\soonhac\SW\kdtree');
% addpath('D:\soonhac\SW\LevenbergMarquardt');
% addpath('D:\soonhac\SW\Localization');
% addpath('D:\soonhac\SW\SIFT\sift-0.9.19-bin\sift');
% addpath('D:\soonhac\SW\slamtoolbox\slamToolbox_11_09_08\FrameTransforms\Rotations');
% addpath('D:\Soonhac\SW\plane_fitting_code');
% addpath('F:\co-worker\soonhac\gtsam-toolbox-2.3.0-win64\toolbox');
% addpath('F:\co-worker\soonhac\SW\kdtree');
% addpath('F:\co-worker\soonhac\LevenbergMarquardt');
% addpath('F:\co-worker\soonhac\Localization');
% addpath('F:\co-worker\soonhac\SIFT\sift-0.9.19-bin\sift');
% addpath('F:\co-worker\soonhac\slamtoolbox\slamToolbox_11_09_08\FrameTransforms\Rotations');
% addpath('F:\co-worker\soonhac\plane_fitting_code');
global g_ws_dir;
addpath(strcat(g_ws_dir, '/gtsam-toolbox-2.3.0-win64/toolbox'));
addpath(strcat(g_ws_dir, '/kdtree'));
addpath(strcat(g_ws_dir, '/LevenbergMarquardt'));
addpath(strcat(g_ws_dir, '/SIFT/sift-0.9.19-bin/sift'));
addpath(strcat(g_ws_dir, '/slamtoolbox/slamToolbox_11_09_08/FrameTransforms/Rotations'));
addpath(strcat(g_ws_dir, '/plane_fitting_code'));
%% modified modules
addpath(strcat(g_ws_dir, '/Localization')); %%
addpath(strcat(g_ws_dir, '/GraphSLAM')); %%
end
|
github
|
rising-turtle/slam_matlab-master
|
plot_graph_trajectory.m
|
.m
|
slam_matlab-master/VRO/plot_graph_trajectory.m
| 1,866 |
utf_8
|
57a03921cd0e61d805de50b94592cd8c
|
function plot_graph_trajectory(gtsam_pose_initial, gtsam_pose_result)
%
% David Z, 3/6/2015
% draw the trajectory in the graph structure
%
import gtsam.*
plot_xyz_initial = [];
%% plot the initial pose trajectory : VRO result
keys = KeyVector(gtsam_pose_initial.keys);
initial_max_index = keys.size-1;
for i=0:int32(initial_max_index)
key = keys.at(i);
x = gtsam_pose_initial.at(key);
% T = x.matrix();
% [ry, rx, rz] = rot_to_euler(T(1:3,1:3));
plot_xyz_initial(i+1,:)=[x.x x.y x.z];
end
plot_xyz_result = [];
%% plot the result pose trajectory : GO graph optimization result
if exist('gtsam_pose_result', 'var')
keys = KeyVector(gtsam_pose_result.keys);
initial_max_index = keys.size-1;
for i=0:int32(initial_max_index)
key = keys.at(i);
x = gtsam_pose_result.at(key);
% T = x.matrix();
% [ry, rx, rz] = rot_to_euler(T(1:3,1:3));
plot_xyz_result(i+1,:)=[x.x x.y x.z];
end
end
%% plot them
figure(1);
subplot(1,2,2);
plot(plot_xyz_initial(:,1),plot_xyz_initial(:,2),'b-', 'LineWidth', 2);
legend('VRO');
hold on;
plot_start_point(plot_xyz_initial);
if exist('gtsam_pose_result', 'var')
plot(plot_xyz_result(:,1),plot_xyz_result(:,2),'r-', 'LineWidth', 2);
legend('PGO');
end
xlabel('X');ylabel('Y');
% Modify size of x in the graph
% xlim([-7 15]); % for etas523_exp2
% xlim([-15 5]); % for Amir's exp1
% xlim([-10 10]); % for etas523_exp2_lefthallway
% ylim([-5 15]);
global g_dis_x_min g_dis_x_max g_dis_y_min g_dis_y_max
xlim([g_dis_x_min g_dis_x_max]); % for etas523_exp2_lefthallway
ylim([g_dis_y_min g_dis_y_max]);
hold off;
grid;
axis equal;
end
function plot_start_point(plot_xyz_result)
plot(plot_xyz_result(1,1),plot_xyz_result(1,2),'ko', 'LineWidth', 3,'MarkerSize', 3);
text(plot_xyz_result(1,1)-1.5,plot_xyz_result(1,2)-1.5,'Start','Color',[0 0 0]);
end
|
github
|
rising-turtle/slam_matlab-master
|
img_preprocess.m
|
.m
|
slam_matlab-master/VRO/img_preprocess.m
| 1,748 |
utf_8
|
b8de79b4d263155edea6f71fe59278e6
|
function [ img ] = img_preprocess( data_name, old_file_version)
%IMG_PREPROCESS Summary of this function goes here
% Detailed explanation goes here
if nargin < 1
old_file_version = 1; % 1;
% data_name='/home/davidz/work/EmbMess/mesa/pcl_mesa/build/bin/sr_data/d1_0001.bdat';
data_name='/home/davidz/work/data/SwissRanger4000/try/d1_0001.bdat';
end
fileID=fopen(data_name);
if fileID==-1
%disp('File open fails !!');
return;
end
sr4k_image_width = 176;
sr4k_image_height = 144;
if old_file_version
z=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
x=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
y=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
img=fread(fileID,[sr4k_image_width,sr4k_image_height],'uint16');
% img=fread(fileID,[144,176],'uint16');
else
img=fread(fileID,[sr4k_image_width,sr4k_image_height],'uint16');
dis=fread(fileID,[sr4k_image_width,sr4k_image_height],'uint16');
dis = dis';
dis = scale_image(dis);
imshow(dis);
end
img = img';
img = scale_image(img);
imshow(img);
end
function [img] = scale_image(img)
%% set the pixels that is larger than limit = 65000, to 0
[m, n] = find (img>65000); %????
imgt=img;
num=size(m,1);
for kk=1:num
imgt(m(kk), n(kk))=0;
end
%% set the pixels larger than limit, to max(imgt) value
imax=max(max(imgt));
for kk=1:num
img(m(kk),n(kk))=imax;
end
%% sqrt(img) and rescale to 0-255
img=sqrt(img).*255./sqrt(max(max(img))); %This line degrade the performance of SURF
img = uint8(img);
%% Adaptive histogram equalization
% img = adapthisteq(img);
%% gaussian filter
gaussian_h = fspecial('gaussian',[3 3],1); %sigma = 1
% img=imfilter(img, gaussian_h,'replicate');
end
|
github
|
rising-turtle/slam_matlab-master
|
VRO.m
|
.m
|
slam_matlab-master/VRO/VRO.m
| 9,975 |
utf_8
|
4545c083032007c6b92bf22dd096529c
|
function [t, pose_std, e] = VRO(id1, id2, img1, img2, des1, frm1, p1, des2, frm2, p2)
%
% March 3th, 2015, David Z
% match two images and return the transformation between img1 and img2
% t : [ phi, theta, psi, trans];
% pose_std: pose covariance
% e : error
%
%% extract features, match img1 to img2
if ~exist('des1','var')
[frm1, des1] = sift(img1);
end
if ~exist('des2','var')
[frm2, des2] = sift(img2);
end
%% pose covariance
pose_std = [];
if file_exist(id1, id2) ~= 0 %% match points stored in a middle file
[op_match, e] = load_matched_points_zh(id1, id2);
if e > 0
[t,e] = error_exist('ransac filter failed!', 2);
return ;
end
else
%% if save the intermiddle data, do it
global g_save_feature_for_debug
if g_save_feature_for_debug
ftar_name = sprintf('tar_nodes/node_%d.log', id1);
fsrc_name = sprintf('src_nodes/node_%d.log', id2);
save_feature(ftar_name, des1, frm1, p1, id1);
save_feature(fsrc_name, des2, frm2, p2, id2);
end
%% first, sift feature match
% match = siftmatch(des1, des2, 2.);
match = siftmatch(des1, des2);
% fprintf('VRO.m after siftmatch, matched num: %d\n',size(match,2));
%% valid depth filter match correspondences
global g_depth_filter_max g_minimum_ransac_num
match = depth_filter(match, g_depth_filter_max, 0, frm1, frm2, p1, p2);
% fprintf('VRO.m after depth_filter, matched num: %d\n',size(match,2));
pnum = size(match,2); % pnum: matched feature pairs
if pnum <= g_minimum_ransac_num
[t,e] = error_exist('too few valid sift points for ransac!', 1);
return;
end
%% second, ransac to obtain the final transformation result
[op_match, e] = ransac_filter(match, frm1, frm2, p1, p2);
% op_match = match;
if e > 0
[t,e] = error_exist('ransac filter failed!', 2);
save_matched_points_zh(id1, id2, op_match, e);
return ;
end
%% save the match points
global g_save_vro_middle_result
if g_save_vro_middle_result
save_matched_points_zh(id1, id2, op_match);
end
end
%% lastly, SVD to compute the transformation
[t, pose_std, e] = svd_transformation(op_match, frm1, frm2, p1, p2);
end
%% SVD transformation
function [t, pose_std, e] = svd_transformation(op_match, frm1, frm2, p1, p2)
e = 0;
op_num = size(op_match, 2);
op_pset_cnt = 1;
x1 = p1(:,:,1); y1 = p1(:,:,2); z1 = p1(:,:,3);
x2 = p2(:,:,1); y2 = p2(:,:,2); z2 = p2(:,:,3);
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
end
%% SVD solve
[rot, trans, sta] = find_transform_matrix_e6(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
t = [ phi, theta, psi, trans'];
if sta <= 0
[t,e] = error_exist('no solution in SVD.', 3);
end
%% compute pose convariance
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
end
%% delete the pairs that contain (0,0,0) points
function match = filter_zero_pairs(match, frm1, frm2, p1, p2)
pnum = size(match, 2);
r_match = []; % return match
x1 = p1(:,:,1); y1 = p1(:,:,2); z1 = p1(:,:,3);
x2 = p2(:,:,1); y2 = p2(:,:,2); z2 = p2(:,:,3);
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
p1x=-x1(ROW1, COL1); p1z=z1(ROW1, COL1); p1y=y1(ROW1, COL1);
p2x=-x2(ROW2, COL2); p2z=z2(ROW2, COL2); p2y=y2(ROW2, COL2);
%% deletet the zero pairs
if (p1x + p1z + p1y == 0) || (p2x + p2y + p2z == 0)
continue;
end
r_match = [r_match match(:,i)];
end
match = r_match;
end
%% ransac transformation to get the result
function [op_match, error] = ransac_filter(match, frm1, frm2, p1, p2)
global g_ransac_iteration_limit
% pnum = size(match,2); % number of matched pairs
error = 0;
op_match = [];
%% delete the pairs that contain (0,0,0) points
match = filter_zero_pairs(match, frm1, frm2, p1, p2);
pnum = size(match,2); % number of matched pairs
%% ransac with a limited number
if g_ransac_iteration_limit > 0
% rst = min(g_ransac_iteration_limit, nchoosek(pnum, 4)); % at least C_n^4 times
rst = g_ransac_iteration_limit;
tmp_nmatch = zeros(2, pnum, rst);
tmp_cnum = zeros(rst,1);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, p1(:,:,1),...
p1(:,:,2), p1(:,:,3), p2(:,:,1), p2(:,:,2), p2(:,:,3), 'SwissRange');
% [n_match, rs_match, cnum, translation] = ransac(frm1, frm2, match, p1(:,:,1),...
% p1(:,:,2), p1(:,:,3), p2(:,:,1), p2(:,:,2), p2(:,:,3), 'SwissRange', i);
% tmp_nmatch(:,1:cnum, i) = n_match(:,1:cnum);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_cnum(i) = cnum;
if cnum > 0
% fprintf('iteration %d inlier num: %d, translation %f %f %f\n', i, cnum, translation);
fprintf('iteration %d inlier num: %d,\n', i, cnum);
end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
i=0;
eta_0 = 0.03; % 97 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
max_iteration = 120000;
while eta > eta_0
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, p1(:,:,1),...
p1(:,:,2), p1(:,:,3), p2(:,:,1), p2(:,:,2), p2(:,:,3), 'SwissRange');
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
% tmp_nmatch(:,1:cnum,i) = n_match(:,1:cnum);
tmp_cnum(i) = cnum;
if cnum > 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
error = 1;
break;
end
end
ransac_iteration = i;
end
valid_ransac = 3; % this is the least valid number
[rs_max, rs_ind] = max(tmp_cnum);
fprintf('select %d with matched num = %d\n', rs_ind, rs_max);
op_num = tmp_cnum(rs_ind);
if (op_num < valid_ransac || error > 0)
error = 1;
return;
end
%% optimal matched pair set
op_match(:, 1:op_num) = tmp_nmatch(:, 1:op_num, rs_ind);
end
%% error exist
function [t, e] = error_exist(msg_err, e_type)
fprintf('VRO.m: %s\n', msg_err);
e = e_type;
t = zeros(1,6);
end
%% using depth to filter the erroreous matches
% p1 [x1 y1 z1] p2 [x2 y2 z2]
%
function match = depth_filter(m, max_d, min_d, frm1, frm2, p1, p2)
match = [];
m_img1 = [];
m_img2 = [];
m_dpt1 = [];
m_dpt2 = [];
cnt_new = 1;
pnum = size(m,2);
for i=1:pnum
frm1_index = m(1,i); frm2_index = m(2,i);
m_pix1 = frm1(:, frm1_index); m_pix2 = frm2(:, frm2_index);
COL1 = round(m_pix1(1))+1; COL2 = round(m_pix2(1))+1;
ROW1 = round(m_pix1(2))+1; ROW2 = round(m_pix2(2))+1;
%% ? row, col is right?
%% this match is a valid pair, this test is for Kinect
% if z(ROW1, COL1) > min_d && z(ROW1, COL1) < max_d ...
% && z(ROW2, COL2) > min_d && z(ROW2, COL2) < max_d
% ...
% end
temp_pt1=[-p1(ROW1, COL1, 1), p1(ROW1, COL1, 3), p1(ROW1, COL1, 2)];
temp_pt2=[-p2(ROW2, COL2, 1), p2(ROW2, COL2, 3), p2(ROW2, COL2, 2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= min_d && temp_pt1_dist <= max_d ...
&& temp_pt2_dist >= min_d && temp_pt2_dist <= max_d
match(:,cnt_new) = m(:,i);
cnt_new = cnt_new + 1;
end
end
end
%% check weather this matched file exist
function [exist_flag] = file_exist(id1, id2)
%% get file name
global g_data_dir g_data_prefix g_matched_dir
file_name = sprintf('%s/%s/%s_%04d_%04d.mat', g_data_dir, g_matched_dir ...
,g_data_prefix, id1, id2);
exist_flag = exist(file_name, 'file');
end
%% save feature in a style that can be loaded into vo in my sr_slam
function save_feature(fname, des, frm, p, id)
%% open file
fid = fopen(fname, 'w');
%% save feature loaction, size, orientation
M = size(frm, 2);
fprintf(fid, '-1 -1 %d 1 0\n', id);
fprintf(fid, '%d\n', M);
%% sift 2d information
response = zeros(1, M);
octave = zeros(1, M);
class_id = ones(1, M).*-1;
sift_loc_2d = [frm; response; octave; class_id]';
fprintf(fid, '%f %f %f %f %f %d %d \n', sift_loc_2d');
%% sift 3d location
sift_loc_3d = zeros(M, 4);
for i=1:M
m_pix = frm(:, i);
COL = round(m_pix(1))+1;
ROW = round(m_pix(2))+1;
pt =[-p(ROW, COL, 1), p(ROW, COL, 3), p(ROW, COL, 2)];
sift_loc_3d(i,1:3) = pt(1:3); sift_loc_3d(i,4) = 1;
end
fprintf(fid, '%f %f %f %f\n', sift_loc_3d');
%% sift descriptors
D_SIZE = size(des, 1);
fprintf(fid, '%d\n', D_SIZE);
for i=1:M
for j=1:D_SIZE
fprintf(fid, '%f ', des(j,i));
end
fprintf(fid, '\n');
end
fclose(fid);
end
|
github
|
rising-turtle/slam_matlab-master
|
dump_matrix_2_file.m
|
.m
|
slam_matlab-master/VRO/dump_matrix_2_file.m
| 364 |
utf_8
|
ff92d9360b0b19252a256ed0ebd60fd3
|
function dump_matrix_2_file(fname, m)
%
% David Z, Feb 19, 2015
% try to construct a function to dump every kind of matrix into a text file
%
dump_matrix_2_file_wf(fname, m)
end
function dump_matrix_2_file_wf(f, m)
f_id = fopen(f, 'w+');
for i=1:size(m,1)
fprintf(f_id, '%f ', m(i,:));
fprintf(f_id, '\n');
end
fclose(f_id);
end
|
github
|
rising-turtle/slam_matlab-master
|
reassign_states.m
|
.m
|
slam_matlab-master/libs_dir/CEKF-SLAM/trunk/reassign_states.m
| 1,961 |
utf_8
|
debcceaaa5d4187361570a36d17ada01
|
function reassign_states(maxd)
%function reassign_states()
%
% This function is really simply implemented!
%
global XA XB PA PAB PB g_current_ala_center g_current_ala_center_cov
% set new active local area
g_current_ala_center = XA(1:2,:);
g_current_ala_center_cov = PA(1:2,1:2);
% reassign part A and B
if length(XB) == 1
x = XA;
p = PA;
else
x = [XA; XB];
p = [PA PAB; PAB' PB];
end
% firstly find ...
xa_features= []; % all index of features that should be assigned to XA
xb_features= [];
features_num = (length(x) -3) / 2;
for i = 1:features_num
if distance( x(1:2,:), x(3+i*2-1:3+i*2,:) ) < maxd
xa_features = [xa_features i];
else
xb_features = [xb_features i];
end
end
% secondly,
lenxa = length(xa_features);
lenxb = length(xb_features);
indexxb = 1;
for indexxa = lenxa:-1:1
if indexxb <= lenxb && ( xa_features(indexxa) > xb_features(indexxb) ) % switch these two states
%switch features: xa_features(indexxa), xb_features(indexxb)
Nx1S = 3 + 2*xa_features(indexxa) -1;
Nx1E = Nx1S + 1;
Nx2S = 3 + 2*xb_features(indexxb) -1;
Nx2E = Nx2S + 1;
tmp = x(Nx1S:Nx1E,:);
x(Nx1S:Nx1E,:) = x(Nx2S:Nx2E,:);
x(Nx2S:Nx2E,:) = tmp;
tmp = p(:,Nx1S:Nx1E);
p(:,Nx1S:Nx1E) = p(:,Nx2S:Nx2E);
p(:,Nx2S:Nx2E) = tmp;
tmp = p(Nx1S:Nx1E,:);
p(Nx1S:Nx1E,:) = p(Nx2S:Nx2E,:);
p(Nx2S:Nx2E,:) = tmp;
%
indexxb = indexxb+1;
else % done
break;
end
end
%finally
lengthofxa = 3+lenxa*2;
XA = x(1:lengthofxa,:);
PA = p(1:lengthofxa,1:lengthofxa);
if lenxb ~= 0
XB = x(lengthofxa+1:end,:);
PAB = p(1:lengthofxa, lengthofxa+1:end);
PB = p(lengthofxa+1:end,lengthofxa+1:end);
else
XB = zeros(1);
PAB = zeros(1);
PB = zeros(1);
end
%check
%
%
function dist = distance(pt1,pt2)
%
delta = abs(pt1-pt2);
dist =sqrt(delta'*delta);
|
github
|
rising-turtle/slam_matlab-master
|
frontend.m
|
.m
|
slam_matlab-master/libs_dir/CEKF-SLAM/trunk/frontend.m
| 5,629 |
utf_8
|
40ab053f4d5fa90d8e26eea477b5e80c
|
function varargout = frontend(varargin)
%EKF-SLAM environment-making GUI
%
% This program permits the graphical creation and manipulation
% of an environment of point landmarks, and the specification of
% vehicle path waypoints therein.
%
% USAGE: type 'frontend' to start.
% 1. Click on the desired operation: <enter>, <move>, or <delete>.
% 2. Click on the type: <waypoint> or <landmark> to commence the
% operation.
% 3. If entering new landmarks or waypoints, click with the left
% mouse button to add new points. Click the right mouse button, or
% hit <enter> key to finish.
% 4. To move or delete a point, just click near the desired point.
% 5. Saving maps and loading previous maps is accomplished via the
% <save> and <load> buttons, respectively.
%
% Tim Bailey and Juan Nieto 2004.
% FRONTEND Application M-file for frontend.fig
% FIG = FRONTEND launch frontend GUI.
% FRONTEND('callback_name', ...) invoke the named callback.
global WAYPOINTS LANDMARKS FH
if nargin == 0 % LAUNCH GUI
%initialisation
WAYPOINTS= [0;0];
LANDMARKS= [];
% open figure
fig = openfig(mfilename,'reuse');
hh= get(fig, 'children');
set(hh(3), 'value', 1)
hold on
FH.hl= plot(0,0,'g*'); plot(0,0,'w*')
FH.hw= plot(0,0,0,0,'ro');
plotwaypoints(WAYPOINTS);
% Use system color scheme for figure:
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
set(fig,'name', 'SLAM Map-Making GUI')
% Generate a structure of handles to pass to callbacks, and store it.
handles = guihandles(fig);
guidata(fig, handles);
if nargout > 0
varargout{1} = fig;
end
elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK
try
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
catch
disp(lasterr);
end
end
% --------------------------------------------------------------------
function varargout = waypoint_checkbox_Callback(h, eventdata, handles, varargin)
global WAYPOINTS
set(handles.landmark_checkbox, 'value', 0)
WAYPOINTS= perform_task(WAYPOINTS, handles.waypoint_checkbox, handles);
plotwaypoints(WAYPOINTS);
% --------------------------------------------------------------------
function varargout = landmark_checkbox_Callback(h, eventdata, handles, varargin)
global LANDMARKS
set(handles.waypoint_checkbox, 'value', 0)
LANDMARKS= perform_task(LANDMARKS, handles.landmark_checkbox, handles);
plotlandmarks(LANDMARKS);
% --------------------------------------------------------------------
function varargout = enter_checkbox_Callback(h, eventdata, handles, varargin)
set(handles.enter_checkbox, 'value', 1)
set(handles.move_checkbox, 'value', 0)
set(handles.delete_checkbox, 'value', 0)
% --------------------------------------------------------------------
function varargout = move_checkbox_Callback(h, eventdata, handles, varargin)
set(handles.enter_checkbox, 'value', 0)
set(handles.move_checkbox, 'value', 1)
set(handles.delete_checkbox, 'value', 0)
% --------------------------------------------------------------------
function varargout = delete_checkbox_Callback(h, eventdata, handles, varargin)
set(handles.enter_checkbox, 'value', 0)
set(handles.move_checkbox, 'value', 0)
set(handles.delete_checkbox, 'value', 1)
% --------------------------------------------------------------------
function varargout = load_button_Callback(h, eventdata, handles, varargin)
global WAYPOINTS LANDMARKS
seed = {'*.mat','MAT-files (*.mat)'};
[fn,pn] = uigetfile(seed, 'Load landmarks and waypoints');
if fn==0, return, end
fnpn = strrep(fullfile(pn,fn), '''', '''''');
load(fnpn)
WAYPOINTS= wp; LANDMARKS= lm;
plotwaypoints(WAYPOINTS);
plotlandmarks(LANDMARKS);
% --------------------------------------------------------------------
function varargout = save_button_Callback(h, eventdata, handles, varargin)
global WAYPOINTS LANDMARKS
wp= WAYPOINTS; lm= LANDMARKS;
seed = {'*.mat','MAT-files (*.mat)'};
[fn,pn] = uiputfile(seed, 'Save landmarks and waypoints');
if fn==0, return, end
fnpn = strrep(fullfile(pn,fn), '''', '''''');
save(fnpn, 'wp', 'lm');
% --------------------------------------------------------------------
function plotwaypoints(x)
global FH
set(FH.hw(1), 'xdata', x(1,:), 'ydata', x(2,:))
set(FH.hw(2), 'xdata', x(1,:), 'ydata', x(2,:))
% --------------------------------------------------------------------
function plotlandmarks(x)
global FH
set(FH.hl, 'xdata', x(1,:), 'ydata', x(2,:))
% --------------------------------------------------------------------
function i= find_nearest(x)
xp= ginput(1);
d2= (x(1,:)-xp(1)).^2 + (x(2,:)-xp(2)).^2;
i= find(d2 == min(d2));
i= i(1);
% --------------------------------------------------------------------
function x= perform_task(x, h, handles)
if get(h, 'value') == 1
zoom off
if get(handles.enter_checkbox, 'value') == 1 % enter points
[xn,yn,bn]= ginput(1);
while ~isempty(xn) & bn == 1
x= [x [xn;yn]];
if h == handles.waypoint_checkbox
plotwaypoints(x);
else
plotlandmarks(x);
end
[xn,yn,bn]= ginput(1);
end
else
i= find_nearest(x);
if get(handles.delete_checkbox, 'value') == 1 % delete nearest point
x= [x(:,1:i-1) x(:,i+1:end)];
elseif get(handles.move_checkbox, 'value') == 1 % move nearest point
xt= x(:,i);
plot(xt(1), xt(2),'kx', 'markersize',10)
x(:,i)= ginput(1)';
plot(xt(1), xt(2),'wx', 'markersize',10)
end
end
set(h, 'value', 0)
end
|
github
|
rising-turtle/slam_matlab-master
|
data_associate.m
|
.m
|
slam_matlab-master/libs_dir/CEKF-SLAM/trunk/data_associate.m
| 1,506 |
utf_8
|
cc46d9a2d98b8271e2c4bb7c3854295c
|
function [zf,idf, zn]= data_associate(x,P,z,R, gate1, gate2)
%
% Simple gated nearest-neighbour data-association. No clever feature
% caching tricks to speed up association, so computation is O(N), where
% N is the number of features in the state.
%
% Tim Bailey 2004.
zf= []; zn= [];
idf= [];
Nxv= 3; % number of vehicle pose states
Nf= (length(x) - Nxv)/2; % number of features already in map
% linear search for nearest-neighbour, no clever tricks (like a quick
% bounding-box threshold to remove distant features; or, better yet,
% a balanced k-d tree lookup). TODO: implement clever tricks.
for i=1:size(z,2)
jbest= 0;
nbest= inf;
outer= inf;
% search for neighbours
for j=1:Nf
[nis, nd]= compute_association(x,P,z(:,i),R, j);
if nis < gate1 && nd < nbest % if within gate, store nearest-neighbour
nbest= nd;
jbest= j;
elseif nis < outer % else store best nis value
outer= nis;
end
end
% add nearest-neighbour to association list
if jbest ~= 0
zf= [zf z(:,i)];
idf= [idf jbest];
elseif outer > gate2 % z too far to associate, but far enough to be a new feature
zn= [zn z(:,i)];
end
end
function [nis, nd]= compute_association(x,P,z,R,idf)
%
% return normalised innovation squared (ie, Mahalanobis distance) and normalised distance
[zp,H]= observe_model(x, idf);
v= z-zp;
v(2)= pi_to_pi(v(2));
S= H*P*H' + R;
nis= v'*inv(S)*v;
nd= nis + log(det(S));
|
github
|
rising-turtle/slam_matlab-master
|
cekfslam.m
|
.m
|
slam_matlab-master/libs_dir/CEKF-SLAM/trunk/cekfslam.m
| 13,612 |
utf_8
|
be6f45a2731675739a5f1f9ed0d9a19c
|
function data= cekfslam(lm, wp)
%function data= cekfslam(lm, wp)
%
% INPUTS:
% lm - set of landmarks
% wp - set of waypoints
%
% OUTPUTS:
% data - a data structure containing:
% data.i : number of states
% data.true : the vehicle 'true'-path (ie, where the vehicle *actually* went)
% data.path : the vehicle path estimate (ie, where SLAM estimates the vehicle went)
% data.state(k).x: the SLAM state vector at time k
% data.state(k).P: the diagonals of the SLAM covariance matrix at time k
% data.finalx : the estimated states when a simulation is done
% data.finalcov : the estimated states covariance when a simulation is done
% data.finalcorr : the estimated states correlations when a simulation is done
%
%To run this simulator:
% 1. load loop902.mat to the workspace
% 2. run "data = cekfslam(lm,wp)" in the command window
%
% NOTES:
% This program is a compressed extended Kalman filter(CEKF) based SLAM simulator.
% To use, create a set of landmarks and vehicle waypoints (ie, waypoints for the desired vehicle path).
% The program 'frontend.m' may be used to create this simulated environment - type
% 'help frontend' for more information.
% The configuration of the simulator is managed by the script file
% 'configfile.m'. To alter the parameters of the vehicle, sensors, etc
% adjust this file. There are also several switches that control certain
% filter options.
%
% Thanks to Tim Bailey and Juan Nieto 2004.Version 1.0
%
% Zhang Haiqiang 2007-11-22
%
% ALGORITHM USED:
% This program adopts Compressed Extended Kalman Filter to SLAM, and
% when SWITCH_BATCH_UPDATE = 0, I used the sparsity of Observation
% Jacobian Matrix to reduce computation complexity.
%
% MODELS:
% The motion model is setup to be like a Pioneer3-AT robot(skid-steering),
% The observation mode are setup to be like a LMS200.
%
% NOTES:
% It is VERY important that the data association should always be
% correct, if wrong data association occurs, the whole state will
% probably diverge.
%
% Zhang Haiqiang 2007-11-20
% Zhang Haiqiang 2007-5-11
%
format compact
configfile;
% setup plots
if SWITCH_ANIMATION_ON == 1
scrsz= get(0,'ScreenSize')*0.75;
fig=figure('Position',[0 0 scrsz(3) scrsz(4)]);
plot(lm(1,:),lm(2,:),'b*')
hold on, axis equal, grid on
%plot(wp(1,:),wp(2,:), 'g', wp(1,:),wp(2,:),'g.')
MAXX = max([max(lm(1,:)) max(wp(1,:))]);
MINX = min([min(lm(1,:)) min(wp(1,:))]);
MAXY = max([max(lm(2,:)) max(wp(2,:))]);
MINY = min([min(lm(2,:)) min(wp(2,:))]);
axis([MINX-10 MAXX+10 MINY-10 MAXY+10])
xlabel('metres'), ylabel('metres')
set(fig, 'name', ' Compressed EKF-SLAM via Pioneer3-AT & LMS200')
h= setup_animations;
veh= 0.5*[1 1 -1 -1; 1 -1 1 -1]; % vehicle animation
%plines=[]; % for laser line animation
pcount=0;
end
%
% zhq: 'stem' the diag of the state covariance matrix
%
if SWITCH_VISULIZE_THE_EVOLUTION_OF_COVARIANCE_DIAG == 1
fig_DiagOfStateCovMatrix = figure;
set( fig_DiagOfStateCovMatrix, 'Name', 'diag of the state covariance matrix');
axes_DiagOfStateCovMatrix = axes;
end
%%%
% initialise states
global vtrue XA PA XB PB PAB
vtrue= zeros(3,1);% true pose of the vehicle
XA = zeros(3,1); % part A of SLAM state
PA = zeros(3); %
XB = zeros(1); % part B of SLAM state
PB = zeros(1); %
PAB =zeros(1); % cross covariance of part A and B
% CEKF auxiliary parameters
global PsiXB OmegaPB PhiPAB
PsiXB = zeros(1);
OmegaPB = zeros(1);
PhiPAB = zeros(1);
% CEKF
global g_current_ala_center g_current_ala_center_cov
g_current_ala_center = zeros(2,1);
g_current_ala_center_cov = zeros(2);
% CEKF predict auxiliary parameter
global JXA
JXA= zeros(1);
%
global GDATA
% initialise other variables and constants
dt= DT_CONTROLS; % change in time between predicts
dtsum= 0; % change in time since last observation
iwp= 1; % index to first waypoint
W = 0; % initial rotation speed
% time lapsed since the vehicle started
g_sim_time = 0;
if SWITCH_OFFLINE_DATA_ON == 1 || SWITCH_ANIMATION_ON == 1
initialise_store(); % stored data for off-line
end
QE= Q; RE= R;
if SWITCH_INFLATE_NOISE, QE= 2*Q; RE= 8*R; end % inflate estimated noises (ie, add stabilising noise)
if SWITCH_SEED_RANDOM, randn('state',SWITCH_SEED_RANDOM), end
%
if SWITCH_PROFILE, profile on -detail mmex, end
% main loop
counter = 0;
frame_counter= 0;
while iwp ~= 0
g_sim_time= g_sim_time + dt;
counter = counter+1;
% zhq: visulize the diag of the state covariance matrix
if SWITCH_VISULIZE_THE_EVOLUTION_OF_COVARIANCE_DIAG == 1
dP = diag(PA);
stem( axes_DiagOfStateCovMatrix, 1:length(dP), dP );
set( axes_DiagOfStateCovMatrix, 'XLim', [1 length(dP)], 'XTick', 1: length(dP), 'YLim', [ 0 ceil(max(dP)+1e-9)], 'YTick', 0: ceil(max(dP)+1e-9)/10: ceil(max(dP)+1e-9) );
if SWITCH_ANIMATION_ON == 0, drawnow, end
end
%%%
% compute true data
[W,iwp] = compute_rotationspeed(wp, iwp, AT_WAYPOINT, W, MAXW, dt);
if iwp==0 && NUMBER_LOOPS > 1
iwp=1;
NUMBER_LOOPS= NUMBER_LOOPS-1;
end % perform loops: if final waypoint reached, go back to first
vtrue = vehicle_model(vtrue, V, W,dt);
[Vn, Wn] = add_control_noise (V,W,Q,SWITCH_CONTROL_NOISE);
% CEKF predict step
predict(Vn,Wn,QE, dt);
% CEKF update step
dtsum= dtsum + dt;
%if dtsum >= DT_OBSERVE %zhq: dtsum >= DT_OBSERVE - 1e-6 is better
if dtsum >= DT_OBSERVE - 1e-6 || iwp == 0
dtsum= 0;
[z]= get_observations(vtrue, lm, MAX_RANGE);
z= add_observation_noise(z,R, SWITCH_SENSOR_NOISE);
% try your best to make sure the data associate works correctly!
[zf,idf, zn]= data_associate(XA,PA,z,RE, GATE_REJECT, GATE_AUGMENT);
check_data_association(idf);
if size(zf,1) > 0
update(zf,RE,idf,SWITCH_BATCH_UPDATE);
else
if size(PAB,1) ~= 1
if size(PhiPAB,1) ~= 1
PhiPAB=JXA*PhiPAB;
else
PAB=JXA*PAB;
end
JXA=zeros(1);
end
end
if size(zn,1) >0, augment(zn,RE); end
if switch_active_local_area(RESTRICING_ALA_R) ~= 0
full_states_update();
reassign_states(ENVIRONING_ALA_R);
end
end
% simulation is almost finished
if iwp == 0, full_states_update(); end
% offline data store
if SWITCH_OFFLINE_DATA_ON == 1, store_data(); end
% plots
if SWITCH_ANIMATION_ON == 1
xt= TransformToGlobal(veh,vtrue);
xv= TransformToGlobal(veh,XA(1:3));
set(h.xt, 'xdata', xt(1,:), 'ydata', xt(2,:))
set(h.xv, 'xdata', xv(1,:), 'ydata', xv(2,:))
set(h.xfa, 'xdata', XA(4:2:end), 'ydata', XA(5:2:end))
if size(XB,1) ~= 1, set(h.xfb, 'xdata', XB(1:2:end), 'ydata', XB(2:2:end)), end
ptmp= make_covariance_ellipses(XA(1:3),PA(1:3,1:3));
pcova(:,1:size(ptmp,2))= ptmp;
if dtsum==0
set(h.cova, 'xdata', pcova(1,:), 'ydata', pcova(2,:))
pcount= pcount+1;
if pcount == 15
set(h.pth, 'xdata', GDATA.path(1,1:GDATA.i), 'ydata', GDATA.path(2,1:GDATA.i))
set(h.pthtrue, 'xdata', GDATA.true(1,1:GDATA.i), 'ydata', GDATA.true(2,1:GDATA.i))
pcount=0;
end
if ~isempty(z)
plines= make_laser_lines (z,XA(1:3));
set(h.obs, 'xdata', plines(1,:), 'ydata', plines(2,:))
pcova= make_covariance_ellipses(XA,PA);
end
%set(h.timeelapsed, 'String', num2str(g_sim_time))
if size(XB,1) ~= 1 && size(OmegaPB,1) == 1
pcovb = make_covariance_ellipses_xb(XB,PB);
set(h.covb, 'xdata', pcovb(1,:), 'ydata', pcovb(2,:))
end
end
[strict_circle, environ_circle] = make_range_circles(RESTRICING_ALA_R, ENVIRONING_ALA_R);
set(h.restrict, 'xdata', strict_circle(1,:), 'ydata', strict_circle(2,:))
set(h.environ, 'xdata', environ_circle(1,:), 'ydata', environ_circle(2,:))
drawnow
if SWITCH_RECORD_THE_PROCESS==1 && mod(counter,30) == 1,
frame_counter= frame_counter+1;
FRAMES(:,frame_counter)=getframe;
end
end
end %end of while
if SWITCH_OFFLINE_DATA_ON == 1, finalise_data(); end
if SWITCH_ANIMATION_ON == 1
set(h.pth, 'xdata', GDATA.path(1,:), 'ydata', GDATA.path(2,:))
set(h.pthtrue, 'xdata', GDATA.true(1,:), 'ydata', GDATA.true(2,:)) % zhq-draw true path
set(h.timeelapsed, 'String', num2str(g_sim_time))
drawnow
if SWITCH_RECORD_THE_PROCESS == 1
frame_counter= frame_counter+1;
FRAMES(:,frame_counter)=getframe;
movie2avi(FRAMES,'a.avi','quality',100);
end
end
if SWITCH_PROFILE, profile report, end
GDATA.finalx = [XA; XB];
GDATA.finalcov = [PA PAB; PAB' PB];
vari = diag(GDATA.finalcov).^(1/2);
GDATA.finalcorr = GDATA.finalcov./ (vari*vari');
data= GDATA;
clear global vtrue XA PA XB PB PAB PsiXB OmegaPB PhiPAB
clear global g_current_ala_center g_current_ala_center_cov
clear global JXA GDATA
%
%
function h= setup_animations()
h.xt= patch(0,0,'b','erasemode','xor'); % vehicle true
h.xv= patch(0,0,'r','erasemode','xor'); % vehicle estimate
h.pth= plot(0,0,'r.','markersize',2,'erasemode','background'); % vehicle path estimate
h.pthtrue= plot(0,0,'b.','markersize',2,'erasemode','background'); % vehicle path true
h.obs= plot(0,0,'k','erasemode','xor'); % observations
h.timeelapsed = annotation('textbox',[0.89 0.9 0.1 0.05]);
h.xfa= plot(0,0,'r+','erasemode','xor'); % estimated features of part A
h.cova= plot(0,0,'r','erasemode','xor'); % covariance ellipses
h.xfb= plot(0,0,'k+','erasemode','xor'); % estimated features of part B
h.covb= plot(0,0,'k','erasemode','xor'); % covariance ellipses
h.restrict= plot(0,0,'k','erasemode','xor', 'LineWidth',1, 'LineStyle','-');
h.environ= plot(0,0,'k','erasemode','xor', 'LineWidth',2, 'LineStyle','-');
%
%
function p= make_laser_lines (rb,xv)
% compute set of line segments for laser range-bearing measurements
if isempty(rb), p=[]; return, end
len= size(rb,2);
lnes(1,:)= zeros(1,len)+ xv(1);
lnes(2,:)= zeros(1,len)+ xv(2);
lnes(3:4,:)= TransformToGlobal([rb(1,:).*cos(rb(2,:)); rb(1,:).*sin(rb(2,:))], xv);
p= line_plot_conversion (lnes);
%
%
function p= make_covariance_ellipses(x,P)
% compute ellipses for plotting state covariances
N= 10;
inc= 2*pi/N;
phi= 0:inc:2*pi;
lenx= length(x);
lenf= (lenx-3)/2;
p= zeros (2,(lenf+1)*(N+2));
ii=1:N+2;
p(:,ii)= make_ellipse(x(1:2), P(1:2,1:2), 2, phi);
ctr= N+3;
for i=1:lenf
ii= ctr:(ctr+N+1);
jj= 2+2*i; jj= jj:jj+1;
p(:,ii)= make_ellipse(x(jj), P(jj,jj), 2, phi);
ctr= ctr+N+2;
end
%
%
function p= make_ellipse(x,P,s, phi)
% make a single 2-D ellipse of s-sigmas over phi angle intervals
s=2.448; %corresponding cdf is 0.95
r= sqrtm(P);
a= s*r*[cos(phi); sin(phi)];
p(2,:)= [a(2,:)+x(2) NaN];
p(1,:)= [a(1,:)+x(1) NaN];
% % Use the following codes for a naive and visually better ellipse
% cdf=0.95;
% k=sqrt( -2*log(1-cdf) );
% px=P(1,1);py=P(2,2);pxy=P(1,2);
% if px==py,theta=pi/4; else theta=1/2*atan(2*pxy/(px-py));end
% r1=px*cos(theta)^2 + py*sin(theta)^2 + pxy*sin(2*theta);
% r2=px*sin(theta)^2 + py*cos(theta)^2 - pxy*sin(2*theta);
% T=[cos(theta) -sin(theta); sin(theta) cos(theta) ];
% pts=k*T*[sqrt(r1) 0; 0 sqrt(r2)]*[cos(phi); sin(phi)];
% p(1,:)=[pts(1,:)+x(1) NaN];
% p(2,:)=[pts(2,:)+x(2) NaN];
%
%
function p= make_covariance_ellipses_xb(x,P)
% compute ellipses for plotting state part B covariances
N= 10;
inc= 2*pi/N;
phi= 0:inc:2*pi;
lenx= length(x);
lenf= lenx/2;
p= zeros (2,(lenf)*(N+2));
ctr= 1;
for i=1:lenf
ii= ctr:(ctr+N+1);
jj= 2*i-1; jj= jj:jj+1;
p(:,ii)= make_ellipse(x(jj), P(jj,jj), 2, phi);
ctr= ctr+N+2;
end
%
%
function [circle1, circle2] = make_range_circles(r1, r2)
%
global g_current_ala_center
phi = 0:2*pi/50:2*pi;
aa = [cos(phi); sin(phi)];
circle1(1,:) = [r1*aa(1,:) + g_current_ala_center(1) NaN];
circle1(2,:) = [r1*aa(2,:) + g_current_ala_center(2) NaN];
circle2(1,:) = [r2*aa(1,:) + g_current_ala_center(1) NaN];
circle2(2,:) = [r2*aa(2,:) + g_current_ala_center(2) NaN];
%
%
function initialise_store()
% offline storage initialisation
global GDATA XA PA vtrue
GDATA.i=1;
GDATA.path= XA;
GDATA.true= vtrue;
GDATA.state(1).x= XA;
GDATA.state(1).P= diag(PA);
%
%
function store_data()
% add current data to offline storage
global GDATA XA XB PA PB vtrue
CHUNK= 5000;
if GDATA.i == size(GDATA.path,2) % grow array in chunks to amortise reallocation
GDATA.path= [GDATA.path zeros(3,CHUNK)];
GDATA.true= [GDATA.true zeros(3,CHUNK)];
end
i= GDATA.i + 1;
GDATA.i= i;
GDATA.path(:,i)= XA(1:3);
GDATA.true(:,i)= vtrue;
if size(XB,1) > 1
GDATA.state(i).x= [XA; XB];
GDATA.state(i).P= [diag(PA); diag(PB)];
else
GDATA.state(i).x = XA;
GDATA.state(i).P= diag(PA);
end
%
%
function finalise_data()
% offline storage finalisation
global GDATA
GDATA.path= GDATA.path(:,1:GDATA.i);
GDATA.true= GDATA.true(:,1:GDATA.i);
function check_data_association(list)
%
a= sort(list);
if length(a) > 1
for i = 1:1:length(a)-1,
if (a(i+1)-a(i) < 0.5)
list
error('data association error!')
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
get_observations.m
|
.m
|
slam_matlab-master/libs_dir/CEKF-SLAM/trunk/get_observations.m
| 1,250 |
utf_8
|
3ceb9d696ae12356c6a0d8905242514d
|
function [z]= get_observations(x, lm, rmax)
%function [z]= get_observations(x, lm, rmax)
%
% INPUTS:
% x - vehicle pose [x;y;phi]
% lm - set of all landmarks
% rmax - maximum range of range-bearing sensor
%
% OUTPUTS:
% z - set of range-bearing observations
%
% Tim Bailey 2004.
% Zhang Haiqiang 2007-11-22
%
[lm]= get_visible_landmarks(x,lm,rmax);
z= compute_range_bearing(x,lm);
%
%
function [lm]= get_visible_landmarks(x,lm,rmax)
% Select set of landmarks that are visible within vehicle's semi-circular field-of-view
dx= lm(1,:) - x(1);
dy= lm(2,:) - x(2);
phi= x(3);
% incremental tests for bounding semi-circle
ii= find(abs(dx) < rmax & abs(dy) < rmax ... % bounding box
& (dx*cos(phi) + dy*sin(phi)) > 0 ... % bounding line
& (dx.^2 + dy.^2) < rmax^2); % bounding circle
% Note: the bounding box test is unnecessary but illustrates a possible speedup technique
% as it quickly eliminates distant points. Ordering the landmark set would make this operation
% O(logN) rather that O(N).
lm= lm(:,ii);
%
%
function z= compute_range_bearing(x,lm)
% Compute exact observation
dx= lm(1,:) - x(1);
dy= lm(2,:) - x(2);
phi= x(3);
z= [sqrt(dx.^2 + dy.^2);
atan2(dy,dx) - phi];
z(2,:)= pi_to_pi(z(2,:));
|
github
|
rising-turtle/slam_matlab-master
|
update.m
|
.m
|
slam_matlab-master/libs_dir/CEKF-SLAM/trunk/update.m
| 2,743 |
utf_8
|
f29b94211b7add286c6351c8b0e825c8
|
function update(z,R,idf,batch)
% function update(z,R,idf,batch)
%
% Inputs:
% z, R - range-bearing measurements and covariances
% idf - feature index for each z
% batch - whether to process measurements together or sequentially
%
% GLOBAL INPUTS:
% XA PA JXA OmegaPB PsiXB PhiPAB
%
% GLOBAL OUTPUTS:
% XA, PA - updated state and covariance of part A
% JXA - will be reset to zeros(1) once used
% OmegaPB PsiXB PhiPAB
%
if batch == 1
batch_update(z,R,idf);
else
single_update(z,R,idf);
end
%
%
%
function batch_update(z,R,idf)
global XA PA JXA OmegaPB PsiXB PhiPAB XB
lenz= size(z,2);
lenXA= length(XA);
H= zeros(2*lenz, lenXA);
v= zeros(2*lenz, 1);
RR= zeros(2*lenz);
for i=1:lenz
ii= 2*i + (-1:0);
[zp,H(ii,:)]= observe_model(XA, idf(i));
v(ii)= [z(1,i)-zp(1);
pi_to_pi(z(2,i)-zp(2))];
RR(ii,ii)= R;
end
%
PHt = PA*H';
S = H*PHt+RR;
Si = inv(S);
Si= make_symmetric(Si);
%PSD_check= chol(Si);
W= PHt*Si;
Kappa = H'*Si*H;
Zeta = W*H;
% update part A
XA = XA + W*v;
PA = PA - make_symmetric(W*S*W');
%PSD_check= chol(PA);
% calculate OmegaPB PsiXB PhiPAB
if length(XB)~=1
if size(OmegaPB,1) == 1
OmegaPB = JXA'*Kappa*JXA;
PsiXB = JXA'*H'*Si*v;
PhiPAB = (eye(size(XA,1)) - Zeta)*JXA;
else
OmegaPB = OmegaPB + PhiPAB'*JXA'*Kappa*JXA*PhiPAB;
PsiXB = PsiXB + PhiPAB'*JXA'*H'*Si*v;
PhiPAB = ((eye(size(XA,1)) - Zeta)*JXA)*PhiPAB;
end
JXA = zeros(1); %
end
%
%
%
function single_update(z,R,idf)
global XA PA JXA OmegaPB PsiXB PhiPAB XB
lenz= size(z,2);
for i=1:lenz
[zp,H]= observe_model(XA, idf(i));
v= [z(1,i)-zp(1);
pi_to_pi(z(2,i)-zp(2))];
% update part A
% this code is copied from KF_tricksimple_update()
Ns = 3 + 2*idf(i) - 1;
Ne = Ns+1;
Hv = H(:,1:3);
Hi = H(:,Ns:Ne);
PHt= PA(:,1:3)*Hv' + PA(:,Ns:Ne)*Hi';
S = Hv*PHt(1:3,:) + Hi*PHt(Ns:Ne,:) + R;
Si= inv(S);
Si= make_symmetric(Si);
%PSD_check= chol(Si);
W= PHt*Si;
Kappa = H'*Si*H;
Zeta = W*H;
XA= XA + W*v;
PA= PA - make_symmetric(W*PHt');
%PSD_check= chol(PA);
%%%
% calculateOmegaPB PsiXB PhiPAB
if length(XB) ~= 1
if size(OmegaPB,1) == 1
OmegaPB = JXA'*Kappa*JXA;
PsiXB = JXA'*H'*Si*v;
PhiPAB = (eye(size(XA,1)) - Zeta)*JXA;
else
OmegaPB = OmegaPB + PhiPAB'*JXA'*Kappa*JXA*PhiPAB;
PsiXB = PsiXB + PhiPAB'*JXA'*H'*Si*v;
PhiPAB = ((eye(size(XA,1)) - Zeta)*JXA)*PhiPAB;
end
JXA = eye(size(JXA));
end
end
JXA = zeros(1); %
function P= make_symmetric(P)
P= (P+P')*0.5;
|
github
|
rising-turtle/slam_matlab-master
|
augment.m
|
.m
|
slam_matlab-master/libs_dir/CEKF-SLAM/trunk/augment.m
| 1,060 |
utf_8
|
d2b0762e712316bc4f43f34b4896f657
|
function augment(z,R)
%function augment(z,R)
%
% INPUTS:
% z, R - range-bearing measurements and covariances, each of a new feature
%
% GLOBAL INPUTS:
% XA, PA
% PhiPAB
% JXA
%
% GLOBAL OUTPUTS:
% XA, PA
% PhiPAB
%
%
% Haiqiang Zhang 2008-5-11
% add new features to state
for i=1:size(z,2)
add_one_z(z(:,i),R);
end
%
%
%
function add_one_z(z,R)
global XA PA PhiPAB PAB
len= length(XA);
r= z(1); b= z(2);
s= sin(XA(3)+b);
c= cos(XA(3)+b);
% augment XA
XA= [XA;
XA(1) + r*c;
XA(2) + r*s];
% jacobians
Gv= [1 0 -r*s;
0 1 r*c];
Gz= [c -r*s;
s r*c];
% augment PA
rng= len+1:len+2;
PA(rng,rng)= Gv*PA(1:3,1:3)*Gv' + Gz*R*Gz'; % feature cov
PA(rng,1:3)= Gv*PA(1:3,1:3); % vehicle to feature xcorr
PA(1:3,rng)= PA(rng,1:3)';
if len>3
rnm= 4:len;
PA(rng,rnm)= Gv*PA(1:3,rnm); % map to feature xcorr
PA(rnm,rng)= PA(rng,rnm)';
end
%augment PhiPAB
if size(PAB,1) ~= 1
if size(PhiPAB,1) ~= 1
PhiPAB = [PhiPAB; Gv*PhiPAB(1:3,:)];
else
PAB=[PAB; Gv*PAB(1:3,:)];
end
end
|
github
|
rising-turtle/slam_matlab-master
|
plotmatches.m
|
.m
|
slam_matlab-master/libs_dir/SIFT/sift-0.9.19-bin/sift/plotmatches.m
| 10,144 |
utf_8
|
4d7daa0d3265f0885ebc7f3310a47fc1
|
function h=plotmatches(I1,I2,P1,P2,matches,varargin)
% PLOTMATCHES Plot keypoint matches
% PLOTMATCHES(I1,I2,P1,P2,MATCHES) plots the two images I1 and I2
% and lines connecting the frames (keypoints) P1 and P2 as specified
% by MATCHES.
%
% P1 and P2 specify two sets of frames, one per column. The first
% two elements of each column specify the X,Y coordinates of the
% corresponding frame. Any other element is ignored.
%
% MATCHES specifies a set of matches, one per column. The two
% elementes of each column are two indexes in the sets P1 and P2
% respectively.
%
% The images I1 and I2 might be either both grayscale or both color
% and must have DOUBLE storage class. If they are color the range
% must be normalized in [0,1].
%
% The function accepts the following option-value pairs:
%
% 'Stacking' ['h']
% Stacking of images: horizontal ['h'], vertical ['v'], diagonal
% ['h'], overlap ['o']
%
% 'Interactive' [0]
% If set to 1, starts the interactive session. In this mode the
% program lets the user browse the matches by moving the mouse:
% Click to select and highlight a match; press any key to end.
% If set to a value greater than 1, the feature matches are not
% drawn at all (useful for cluttered scenes).
%
% See also PLOTSIFTDESCRIPTOR(), PLOTSIFTFRAME(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
stack='h' ;
interactive=0 ;
only_interactive=0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'stacking'
stack=varargin{k+1} ;
case 'interactive'
interactive=varargin{k+1};
otherwise
error(['[Unknown option ''', varargin{k}, '''.']) ;
end
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
[M1,N1,K1]=size(I1) ;
[M2,N2,K2]=size(I2) ;
switch stack
case 'h'
N3=N1+N2 ;
M3=max(M1,M2) ;
oj=N1 ;
oi=0 ;
case 'v'
M3=M1+M2 ;
N3=max(N1,N2) ;
oj=0 ;
oi=M1 ;
case 'd'
M3=M1+M2 ;
N3=N1+N2 ;
oj=N1 ;
oi=M1 ;
case 'o'
M3=max(M1,M2) ;
N3=max(N1,N2) ;
oj=0;
oi=0;
otherwise
error(['Unkown stacking type '''], stack, ['''.']) ;
end
% Combine the two images. In most cases just place one image next to
% the other. If the stacking is 'o', however, combine the two images
% linearly.
I=zeros(M3,N3,K1) ;
if stack ~= 'o'
I(1:M1,1:N1,:) = I1 ;
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
else
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
I(1:M1,1:N1,:) = I(1:M1,1:N1,:) + I1 ;
I(1:min(M1,M2),1:min(N1,N2),:) = 0.5 * I(1:min(M1,M2),1:min(N1,N2),:) ;
end
axes('Position', [0 0 1 1]) ;
imagesc(I) ; colormap gray ; hold on ; axis image ; axis off ;
K = size(matches, 2) ;
nans = NaN * ones(1,K) ;
x = [ P1(1,matches(1,:)) ; P2(1,matches(2,:))+oj ; nans ] ;
y = [ P1(2,matches(1,:)) ; P2(2,matches(2,:))+oi ; nans ] ;
% if interactive > 1 we do not drive lines, but just points.
if(interactive > 1)
h = plot(x(:),y(:),'g.') ;
else
h = line(x(:)', y(:)') ;
end
set(h,'Marker','.','Color','g') ;
% --------------------------------------------------------------------
% Interactive
% --------------------------------------------------------------------
if(~interactive), return ; end
sel1 = unique(matches(1,:)) ;
sel2 = unique(matches(2,:)) ;
K1 = length(sel1) ; %size(P1,2) ;
K2 = length(sel2) ; %size(P2,2) ;
X = [ P1(1,sel1) P2(1,sel2)+oj ;
P1(2,sel1) P2(2,sel2)+oi ; ] ;
fig = gcf ;
is_hold = ishold ;
hold on ;
% save the handlers for later to restore
dhandler = get(fig,'WindowButtonDownFcn') ;
uhandler = get(fig,'WindowButtonUpFcn') ;
mhandler = get(fig,'WindowButtonMotionFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'KeyPressFcn', @key_handler) ;
set(fig,'WindowButtonDownFcn',@click_down_handler) ;
set(fig,'WindowButtonUpFcn', @click_up_handler) ;
set(fig,'Pointer','crosshair') ;
data.exit = 0 ; % signal exit to the interactive mode
data.selected = [] ; % currently selected feature
data.X = X ; % feature anchors
highlighted = [] ; % currently highlighted feature
hh = [] ; % hook of the highlight plot
guidata(fig,data) ;
while ~ data.exit
uiwait(fig) ;
data = guidata(fig) ;
if(any(size(highlighted) ~= size(data.selected)) || ...
any(highlighted ~= data.selected) )
highlighted = data.selected ;
% delete previous highlight
if( ~isempty(hh) )
delete(hh) ;
end
hh=[] ;
% each selected feature uses its own color
c=1 ;
colors=[1.0 0.0 0.0 ;
0.0 1.0 0.0 ;
0.0 0.0 1.0 ;
1.0 1.0 0.0 ;
0.0 1.0 1.0 ;
1.0 0.0 1.0 ] ;
% more than one feature might be seleted at one time...
for this=highlighted
% find matches
if( this <= K1 )
sel=find(matches(1,:)== sel1(this)) ;
else
sel=find(matches(2,:)== sel2(this-K1)) ;
end
K=length(sel) ;
% plot matches
x = [ P1(1,matches(1,sel)) ; P2(1,matches(2,sel))+oj ; nan*ones(1,K) ] ;
y = [ P1(2,matches(1,sel)) ; P2(2,matches(2,sel))+oi ; nan*ones(1,K) ] ;
hh = [hh line(x(:)', y(:)',...
'Marker','*',...
'Color',colors(c,:),...
'LineWidth',3)];
if( size(P1,1) == 4 )
f1 = unique(P1(:,matches(1,sel))','rows')' ;
hp=plotsiftframe(f1);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
if( size(P2,1) == 4 )
f2 = unique(P2(:,matches(2,sel))','rows')' ;
f2(1,:)=f2(1,:)+oj ;
f2(2,:)=f2(2,:)+oi ;
hp=plotsiftframe(f2);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
c=c+1 ;
end
drawnow ;
end
end
if( ~isempty(hh) )
delete(hh) ;
end
if ~is_hold
hold off ;
end
set(fig,'WindowButtonDownFcn', dhandler) ;
set(fig,'WindowButtonUpFcn', uhandler) ;
set(fig,'WindowButtonMotionFcn',mhandler) ;
set(fig,'KeyPressFcn', khandler) ;
set(fig,'Pointer', pointer ) ;
% ====================================================================
function data=selection_helper(data)
% --------------------------------------------------------------------
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
d = (data.X(1,:) - P(1)).^2 + (data.X(2,:) - P(2)).^2 ;
dmin=min(d) ;
idx=find(d==dmin) ;
data.selected = idx ;
% ====================================================================
function click_down_handler(obj,event)
% --------------------------------------------------------------------
% select a feature and change motion handler for dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
data.mhandler = get(fig,'WindowButtonMotionFcn') ;
set(fig,'WindowButtonMotionFcn',@motion_handler) ;
data = selection_helper(data) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function click_up_handler(obj,event)
% --------------------------------------------------------------------
% stop dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
set(fig,'WindowButtonMotionFcn',data.mhandler) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function motion_handler(obj,event)
% --------------------------------------------------------------------
% select features while dragging
data = guidata(obj) ;
data = selection_helper(data);
guidata(obj,data) ;
uiresume(obj) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
% use keypress to exit
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github
|
rising-turtle/slam_matlab-master
|
gaussianss.m
|
.m
|
slam_matlab-master/libs_dir/SIFT/sift-0.9.19-bin/sift/gaussianss.m
| 7,935 |
utf_8
|
ea953b78ba9dcf80cd10b1f4c599408e
|
function SS = gaussianss(I,sigman,O,S,omin,smin,smax,sigma0)
% GAUSSIANSS
% SS = GAUSSIANSS(I,SIGMAN,O,S,OMIN,SMIN,SMAX,SIGMA0) returns the
% Gaussian scale space of image I. Image I is assumed to be
% pre-smoothed at level SIGMAN. O,S,OMIN,SMIN,SMAX,SIGMA0 are the
% parameters of the scale space as explained in PDF:SIFT.USER.SS.
%
% See also DIFFSS(), PDF:SIFT.USER.SS.
% History
% 4-15-2006 Fixed some comments
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(nargin < 6)
error('Six arguments are required.') ;
end
if(~isreal(I) || ndims(I) > 2)
error('I must be a real two dimensional matrix') ;
end
if(smin >= smax)
error('smin must be greather or equal to smax') ;
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
% Scale multiplicative step
k = 2^(1/S) ;
% Lowe's convention: the scale (o,s)=(0,-1) has standard deviation
% 1.6 (was it variance?)
if(nargin < 7)
sigma0 = 1.6 * k ;
end
dsigma0 = sigma0 * sqrt(1 - 1/k^2) ; % Scale step factor
sigman = 0.5 ; % Nominal smoothing of the image
% Scale space structure
SS.O = O ;
SS.S = S ;
SS.sigma0 = sigma0 ;
SS.omin = omin ;
SS.smin = smin ;
SS.smax = smax ;
% If mino < 0, multiply the size of the image.
% (The rest of the code is consistent with this.)
if omin < 0
for o=1:-omin
I = doubleSize(I) ;
end
elseif omin > 0
for o=1:omin
I = halveSize(I) ;
end
end
[M,N] = size(I) ;
% Index offset
so = -smin+1 ;
% --------------------------------------------------------------------
% First octave
% --------------------------------------------------------------------
%
% The first level of the first octave has scale index (o,s) =
% (omin,smin) and scale coordinate
%
% sigma(omin,smin) = sigma0 2^omin k^smin
%
% The input image I is at nominal scale sigman. Thus in order to get
% the first level of the pyramid we need to apply a smoothing of
%
% sqrt( (sigma0 2^omin k^smin)^2 - sigman^2 ).
%
% As we have pre-scaled the image omin octaves (up or down,
% depending on the sign of omin), we need to correct this value
% by dividing by 2^omin, getting
%e
% sqrt( (sigma0 k^smin)^2 - (sigman/2^omin)^2 )
%
if(sigma0 * 2^omin * k^smin < sigman)
warning('The nominal smoothing exceeds the lowest level of the scale space.') ;
end
SS.octave{1} = zeros(M,N,smax-smin+1) ;
SS.octave{1}(:,:,1) = imsmooth(I, ...
sqrt((sigma0*k^smin)^2 - (sigman/2^omin)^2)) ;
for s=smin+1:smax
% Here we go from (omin,s-1) to (omin,s). The extra smoothing
% standard deviation is
%
% (sigma0 2^omin 2^(s/S) )^2 - (simga0 2^omin 2^(s/S-1/S) )^2
%
% Aftred dividing by 2^omin (to take into account the fact
% that the image has been pre-scaled omin octaves), the
% standard deviation of the smoothing kernel is
%
% dsigma = sigma0 k^s sqrt(1-1/k^2)
%
dsigma = k^s * dsigma0 ;
SS.octave{1}(:,:,s +so) = ...
imsmooth(squeeze(...
SS.octave{1}(:,:,s-1 +so)...
), dsigma ) ;
end
% --------------------------------------------------------------------
% Other octaves
% --------------------------------------------------------------------
for o=2:O
% We need to initialize the first level of octave (o,smin) from
% the closest possible level of the previous octave. A level (o,s)
% in this octave corrsponds to the level (o-1,s+S) in the previous
% octave. In particular, the level (o,smin) correspnds to
% (o-1,smin+S). However (o-1,smin+S) might not be among the levels
% (o-1,smin), ..., (o-1,smax) that we have previously computed.
% The closest pick is
%
% / smin+S if smin+S <= smax
% (o-1,sbest) , sbest = |
% \ smax if smin+S > smax
%
% The amount of extra smoothing we need to apply is then given by
%
% ( sigma0 2^o 2^(smin/S) )^2 - ( sigma0 2^o 2^(sbest/S - 1) )^2
%
% As usual, we divide by 2^o to cancel out the effect of the
% downsampling and we get
%
% ( sigma 0 k^smin )^2 - ( sigma0 2^o k^(sbest - S) )^2
%
sbest = min(smin + S, smax) ;
TMP = halveSize(squeeze(SS.octave{o-1}(:,:,sbest+so))) ;
target_sigma = sigma0 * k^smin ;
prev_sigma = sigma0 * k^(sbest - S) ;
if(target_sigma > prev_sigma)
TMP = imsmooth(TMP, sqrt(target_sigma^2 - prev_sigma^2) ) ;
end
[M,N] = size(TMP) ;
SS.octave{o} = zeros(M,N,smax-smin+1) ;
SS.octave{o}(:,:,1) = TMP ;
for s=smin+1:smax
% The other levels are determined as above for the first octave.
dsigma = k^s * dsigma0 ;
SS.octave{o}(:,:,s +so) = ...
imsmooth(squeeze(...
SS.octave{o}(:,:,s-1 +so)...
), dsigma) ;
end
end
% -------------------------------------------------------------------------
% Auxiliary functions
% -------------------------------------------------------------------------
function J = doubleSize(I)
[M,N]=size(I) ;
J = zeros(2*M,2*N) ;
J(1:2:end,1:2:end) = I ;
J(2:2:end-1,2:2:end-1) = ...
0.25*I(1:end-1,1:end-1) + ...
0.25*I(2:end,1:end-1) + ...
0.25*I(1:end-1,2:end) + ...
0.25*I(2:end,2:end) ;
J(2:2:end-1,1:2:end) = ...
0.5*I(1:end-1,:) + ...
0.5*I(2:end,:) ;
J(1:2:end,2:2:end-1) = ...
0.5*I(:,1:end-1) + ...
0.5*I(:,2:end) ;
function J = halveSize(I)
J=I(1:2:end,1:2:end) ;
%[M,N] = size(I) ;
%m=floor((M+1)/2) ;
%n=floor((N+1)/2) ;
%J = I(:,1:2:2*n) + I(:,2:2:2*n+1) ;
%J = 0.25*(J(1:2:2*m,:)+J(2:2:2*m+1,:)) ;
|
github
|
rising-turtle/slam_matlab-master
|
plotsiftdescriptor.m
|
.m
|
slam_matlab-master/libs_dir/SIFT/sift-0.9.19-bin/sift/plotsiftdescriptor.m
| 5,461 |
utf_8
|
4159397cc60b624656bb3372023a43e9
|
function h=plotsiftdescriptor(d,f)
% PLOTSIFTDESCRIPTOR Plot SIFT descriptor
% PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptors D, stored as
% columns of the matrix D. D has the same format used by SIFT().
%
% PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to the
% SIFT frames F, specified as columns of the matrix F. F has
% the same format used by SIFT().
%
% H=PLOTSIFTDESCRIPTOR(...) returns the handle H to the line drawing
% representing the descriptors.
%
% REMARK. Currently the function supports only descriptors with 4x4
% spatial bins and 8 orientation bins (Lowe's default.)
%
% See also PLOTSIFTFRAME(), PLOTMATCHES(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
lowe_compatible = 1 ;
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(size(d,1) ~= 128)
error('D should be a 128xK matrix (only standard descriptors accepted)') ;
end
if nargin > 1
if(size(f,1) ~= 4)
error('F should be a 4xK matrix');
end
if(size(f,2) ~= size(f,2))
error('D and F must have the same number of columns') ;
end
end
% Descriptors are often non-double numeric arrays
d = double(d) ;
K = size(d,2) ;
if nargin < 2
f = repmat([0;0;1;0],1,K) ;
end
maginf = 3.0 ;
NBP=4 ;
NBO=8 ;
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
xall=[] ;
yall=[] ;
for k=1:K
SBP = maginf * f(3,k) ;
th=f(4,k) ;
c=cos(th) ;
s=sin(th) ;
[x,y] = render_descr(d(:,k)) ;
xall = [xall SBP*(c*x-s*y)+f(1,k)+1] ;
yall = [yall SBP*(s*x+c*y)+f(2,k)+1] ;
end
h=line(xall,yall) ;
% --------------------------------------------------------------------
% Helper functions
% --------------------------------------------------------------------
% Renders a single descriptor
function [x,y] = render_descr( d )
lowe_compatible=1;
NBP=4 ;
NBO=8 ;
[x,y] = meshgrid(-NBP/2:NBP/2,-NBP/2:NBP/2) ;
% Rescale d so that the biggest peak fits inside the bin diagram
d = 0.4 * d / max(d(:)) ;
% We have NBP*NBP bins to plot. Here are the centers:
xc = x(1:end-1,1:end-1) + 0.5 ;
yc = y(1:end-1,1:end-1) + 0.5 ;
% We swap the order of the bin diagrams because they are stored row
% major into the descriptor (Lowe's convention that we follow.)
xc = xc' ;
yc = yc' ;
% Each bin contains a star with eight tips
xc = repmat(xc(:)',NBO,1) ;
yc = repmat(yc(:)',NBO,1) ;
% Do the stars
th=linspace(0,2*pi,NBO+1) ;
th=th(1:end-1) ;
if lowe_compatible
xd = repmat(cos(-th), 1, NBP*NBP ) ;
yd = repmat(sin(-th), 1, NBP*NBP ) ;
else
xd = repmat(cos(th), 1, NBP*NBP ) ;
yd = repmat(sin(th), 1, NBP*NBP ) ;
end
xd = xd .* d(:)' ;
yd = yd .* d(:)' ;
% Re-arrange in sequential order the lines to draw
nans = NaN * ones(1,NBP^2*NBO) ;
x1 = xc(:)' ;
y1 = yc(:)' ;
x2 = x1 + xd ;
y2 = y1 + yd ;
xstars = [x1;x2;nans] ;
ystars = [y1;y2;nans] ;
% Horizontal lines of the grid
nans = NaN * ones(1,NBP+1);
xh = [x(:,1)' ; x(:,end)' ; nans] ;
yh = [y(:,1)' ; y(:,end)' ; nans] ;
% Verical lines of the grid
xv = [x(1,:) ; x(end,:) ; nans] ;
yv = [y(1,:) ; y(end,:) ; nans] ;
x=[xstars(:)' xh(:)' xv(:)'] ;
y=[ystars(:)' yh(:)' yv(:)'] ;
|
github
|
rising-turtle/slam_matlab-master
|
moreindatatip.m
|
.m
|
slam_matlab-master/libs_dir/slamtoolbox/slamToolbox_11_09_08/Graphics/moreindatatip.m
| 3,133 |
utf_8
|
a282d8242a72fbe01e0564a1ef3c3d07
|
function moreindatatip
% MOREINDATATIP Display index information in the data tip.
%
% Extends the displayed text of the datatip to get the index of the clicked
% point. The extension remains until the figure is deleted. If datatip(s)
% was previously present, a message prompts the user to right-click on the
% figure to delete all datatips in order to switch on the capabilities of
% the datatip.
%
% may 2006
% [email protected]
dcm_obj = datacursormode(gcf);
if ~isempty(findall(gca,'type','hggroup','marker','square'))% if there is datatip, please delete it
info_struct = getCursorInfo(dcm_obj);
xdat=get(info_struct.Target,'xdata');
ydat=get(info_struct.Target,'ydata');
zdat=get(info_struct.Target,'zdata');
if isempty(zdat),zdat=zeros(size(xdat));set(info_struct.Target,'zdata',zdat),end
index=info_struct.DataIndex;
ht=text(xdat(index)*1.05,ydat(index)*1.05,zdat(index)*1.05,...
{'right-click on the figure';'to ''delete all datatips''';'in order to get more'},...
'backgroundcolor',[1,0,0.5],'tag','attention');
end
set(dcm_obj,'enable','on','updatefcn',@myupdatefcn,'displaystyle','datatip')
%-------------------------------------------------------------------------%
function txt = myupdatefcn(empt,event_obj)
% Change the text displayed in the datatip. Note than the actual coordinates
% are displyed rather the position field of the info_struct.
ht=findobj('tag','attention');
if ~isempty(ht),delete(ht),end
dcm_obj = datacursormode(gcf);
info_struct = getCursorInfo(dcm_obj);
xdat=get(info_struct.Target,'xdata');
ydat=get(info_struct.Target,'ydata');
zdat=get(info_struct.Target,'zdata');
index=info_struct.DataIndex;
if isempty(zdat)
txt = {['X: ',num2str(xdat(index))],...
['Y: ',num2str(ydat(index))],...
['index: ',num2str(index)]};
else
txt = {['X: ',num2str(xdat(index))],...
['Y: ',num2str(ydat(index))],...
['Z: ',num2str(zdat(index))],...
['index: ',num2str(index)]};
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright 2007,2008,2009
% by Joan Sola, David Marquez and Jean Marie Codol @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
initNewLmk.m
|
.m
|
slam_matlab-master/libs_dir/slamtoolbox/slamToolbox_11_09_08/InterfaceLevel/initNewLmk.m
| 6,870 |
utf_8
|
34d7ff329dfed725430c53a5095f1ecf
|
function [Lmk,Obs] = initNewLmk(Rob, Sen, Raw, Lmk, Obs, Opt)
%INITNEWLMK Initialise one landmark.
% [LMK, OBS] = INITNEWLMK(ROB, SEN, RAW, LMK, OBS) returns the new
% set of landmarks.
%
% This "new set" contains the "old set" plus new elements. These new
% elements are extracted from the recent observations (RAW), from the
% current state estimated (ROB for robot and SEN for the sensor).
%
% Finally, we can have a mean and a variance-covariance estimation for
% the new landmark state.
%
% See also GETNEWLMKCOVS
% Copyright 2009 Jean Marie Codol, David Marquez @ LAAS-CNRS
% 0. UPDATE ROB AND SEN INFO FROM MAP
Rob = map2rob(Rob);
Sen = map2sen(Sen);
% Type of the lmk to initialize - with error check.
switch Opt.init.initType
case {'hmgPnt'}
lmkSize = 4;
case {'ahmPnt'}
lmkSize = 7;
case {'idpPnt','plkLin'}
lmkSize = 6;
case {'idpLin','aplLin'}
lmkSize = 9;
case {'hmgLin'}
lmkSize = 8;
case {'fhmPnt','ahmLin'}
lmkSize = 11;
case {'eucPnt'}
error('??? Unable to initialize lmk type ''%s''. Try using ''idpPnt'' instead.',Opt.init.initType);
otherwise
error('??? Unknown landmark type ''%s''.', Opt.init.initType);
end
% get free space in the Map.
r = newRange(lmkSize);
% index to first free lmk
lmk = newLmk(Lmk);
if (numel(r) < lmkSize)
% disp('!!! Map full. Unable to initialize landmark.')
return
end
if isempty(lmk)
% disp('!!! Lmk structure array full. Unable to initialize new landmark.')
return;
end
% Feature detection
switch Raw.type
case {'simu'}
[newId, app, meas, exp, inn] = simDetectFeat(...
Opt.init.initType, ...
[Lmk([Lmk.used]).id], ...
Raw.data, ...
Sen.par.pixCov, ...
Sen.par.imSize);
case {'real'}
existingProj = getExistingProj(Obs);
[app, meas, exp, inn] = detectFeat(...
Opt.init.initType, ...
Raw.data, ...
Sen.par.pixCov, ...
existingProj, ...
Sen.imGrid);
newId = getNewId();
% NYI : Not Yet Implemented
%[newId, app, meas, exp, inn] = detectFeat([Lmk(usedLmks).id],Raw.data,Sen.par);
% error('??? Unknown Raw type. ''real'': NYI.');
end
if ~isempty(meas.y) % a feature was detected --> initialize it
% fill Obs struct before continuing
Obs(lmk).sen = Sen.sen;
Obs(lmk).lmk = lmk;
Obs(lmk).sid = Sen.id;
Obs(lmk).lid = newId;
Obs(lmk).stype = Sen.type;
Obs(lmk).ltype = Opt.init.initType;
Obs(lmk).meas = meas;
Obs(lmk).exp = exp;
Obs(lmk).exp.um = det(inn.Z); % uncertainty measure
Obs(lmk).inn = inn;
Obs(lmk).app.curr = app;
Obs(lmk).app.pred = app;
Obs(lmk).vis = true;
Obs(lmk).measured = true;
Obs(lmk).matched = true;
Obs(lmk).updated = true;
% retro-project feature onto 3D space
[l, L_rf, L_sf, L_obs, L_n, N] = retroProjLmk(Rob,Sen,Obs(lmk),Opt);
% get new Lmk, covariance and cross-variance.
[P_LL,P_LX] = getNewLmkCovs( ...
Sen.frameInMap, ...
Rob.frame.r, ...
Sen.frame.r, ...
L_rf, ...
L_sf, ...
L_obs, ...
L_n, ...
meas.R, ...
N) ;
% add to Map and get lmk range in Map
Lmk(lmk).state.r = addToMap(l,P_LL,P_LX);
% Fill Lmk structure
Lmk(lmk).lmk = lmk;
Lmk(lmk).id = newId;
Lmk(lmk).type = Opt.init.initType ;
Lmk(lmk).used = true;
Lmk(lmk).sig = app;
Lmk(lmk).nSearch = 1;
Lmk(lmk).nMatch = 1;
Lmk(lmk).nInlier = 1;
% Init off-filter landmark params
[Lmk(lmk),Obs(lmk)] = initLmkParams(Rob,Sen,Lmk(lmk),Obs(lmk));
% fprintf('Initialized landmark ''%d''.\n',Lmk(lmk).id)
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [P_LL,P_LX] = getNewLmkCovs(SenFrameInMap, RobFrameR, SenFrameR,...
L_rf, L_sf, L_obs, L_n, R, N)
% GETNEWLMKCOVS return lmk co and cross-variance for initialization.
% [P_LL,P_LX] = GETNEWLMKCOVS( ...
% SENFRAMEINMAP, ...
% ROBFRAMERANGE, ...
% SENFRAMERANGE, ...
% L_RF, ...
% L_SF, ...
% L_OBS, ...
% L_N, ...
% R, ...
% N)
%
% Return the covariance 'Lmk/Lmk' (P_LL) and cross-variance 'Lmk/Map.used'
% (P_LX) given :
% - if the sensor frame is in map (SENFRAMEINMAP).
% - the robot frame range in map (ROBFRAMERANGE).
% - the sensor frame range in map (SENFRAMERANGE).
% - the jacobian 'Lmk/robot frame' (L_RF).
% - the jacobian 'Lmk/sensor frame' (L_SF).
% - the jacobian 'Lmk/observation' (L_OBS).
% - the jacobian 'Lmk/non observable part' (L_N).
% - the observation covariance (R).
% - the observation non observable part covariance (N).
%
% P_LL and P_LX can be placed for example in Map covariance like:
%
% P = | P P_LX' |
% | P_LX P_LL |
%
% (c) 2009 Jean Marie Codol, David Marquez @ LAAS-CNRS
global Map
% Group all map Jacobians and ranges
if SenFrameInMap % if the sensor frame is in the state
mr = [RobFrameR;SenFrameR];
L_m = [L_rf L_sf] ;
else
mr = RobFrameR;
L_m = L_rf ;
end
% co- and cross-variance of map variables (robot and eventually sensor)
P_MM = Map.P(mr,mr) ;
P_MX = Map.P(mr,(Map.used)) ;
% landmark co- and cross-variance
P_LL = ...
L_m * P_MM * L_m' + ... % by map cov
L_obs * R * L_obs' + ... % by observation cov (for pinHole it is a pixel)
L_n * N * L_n' ; % by nom cov
P_LX = L_m*P_MX ;
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright 2007,2008,2009
% by Joan Sola, David Marquez and Jean Marie Codol @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
chi2.m
|
.m
|
slam_matlab-master/libs_dir/slamtoolbox/slamToolbox_11_09_08/Math/chi2.m
| 25,797 |
utf_8
|
28d82af99c6ba03eec54f93ee2d67f95
|
function chi2 = chi2(n,p)
% CHI2 Chi square distribution
% TH = CHI2(N,P) gives the critical values of the N-dimensional
% Chi-squared distribuiton function for a right-tail probability area P
% Copyright 2009 Joan Sola @ LAAS-CNRS.
[nTab,pTab,Chi2Tab] = chi2tab();
if (n == floor(n))
% values of p
if p < .001
warning('Too small probability. Assuming P=0.001')
p = 0.001;
elseif (p > 0.2) && (p<0.975) && (p~=0.5)
warning('Poor data in table. Inaccurate results. Use P<0.2 or P>0.975.')
elseif p > 0.995
warning('Too big probability. Assuming P=0.995')
p = 0.995;
end
% values of n
if (n > 1000)
error('Chi2 Lookup table only up to N=1000 DOF')
elseif (n > 250) && (mod(n,50)~=0)
warning('Value of N-DOF not found. Innacurate results. Use N in [1:1:250,300:50:1000]')
end
% 2-D interpolation
chi2 = interp2(pTab,nTab,Chi2Tab,p,n);
else
error('Dimension N must be a positive integer value in [1:1000]')
end
end
%% Lookup tables
function [DOF,PRB,TAB] = chi2tab()
PRB = [0.995 0.975 0.20 0.10 0.05 0.025 0.02 0.01 0.005 0.002 0.001];
DOF = [1:250 300:50:1000];
TAB = [...
1 0.0000393 0.000982 1.642 2.706 3.841 5.024 5.412 6.635 7.879 9.550 10.828
2 0.0100 0.0506 3.219 4.605 5.991 7.378 7.824 9.210 10.597 12.429 13.816
3 0.0717 0.216 4.642 6.251 7.815 9.348 9.837 11.345 12.838 14.796 16.266
4 0.207 0.484 5.989 7.779 9.488 11.143 11.668 13.277 14.860 16.924 18.467
5 0.412 0.831 7.289 9.236 11.070 12.833 13.388 15.086 16.750 18.907 20.515
6 0.676 1.237 8.558 10.645 12.592 14.449 15.033 16.812 18.548 20.791 22.458
7 0.989 1.690 9.803 12.017 14.067 16.013 16.622 18.475 20.278 22.601 24.322
8 1.344 2.180 11.030 13.362 15.507 17.535 18.168 20.090 21.955 24.352 26.124
9 1.735 2.700 12.242 14.684 16.919 19.023 19.679 21.666 23.589 26.056 27.877
10 2.156 3.247 13.442 15.987 18.307 20.483 21.161 23.209 25.188 27.722 29.588
11 2.603 3.816 14.631 17.275 19.675 21.920 22.618 24.725 26.757 29.354 31.264
12 3.074 4.404 15.812 18.549 21.026 23.337 24.054 26.217 28.300 30.957 32.909
13 3.565 5.009 16.985 19.812 22.362 24.736 25.472 27.688 29.819 32.535 34.528
14 4.075 5.629 18.151 21.064 23.685 26.119 26.873 29.141 31.319 34.091 36.123
15 4.601 6.262 19.311 22.307 24.996 27.488 28.259 30.578 32.801 35.628 37.697
16 5.142 6.908 20.465 23.542 26.296 28.845 29.633 32.000 34.267 37.146 39.252
17 5.697 7.564 21.615 24.769 27.587 30.191 30.995 33.409 35.718 38.648 40.790
18 6.265 8.231 22.760 25.989 28.869 31.526 32.346 34.805 37.156 40.136 42.312
19 6.844 8.907 23.900 27.204 30.144 32.852 33.687 36.191 38.582 41.610 43.820
20 7.434 9.591 25.038 28.412 31.410 34.170 35.020 37.566 39.997 43.072 45.315
21 8.034 10.283 26.171 29.615 32.671 35.479 36.343 38.932 41.401 44.522 46.797
22 8.643 10.982 27.301 30.813 33.924 36.781 37.659 40.289 42.796 45.962 48.268
23 9.260 11.689 28.429 32.007 35.172 38.076 38.968 41.638 44.181 47.391 49.728
24 9.886 12.401 29.553 33.196 36.415 39.364 40.270 42.980 45.559 48.812 51.179
25 10.520 13.120 30.675 34.382 37.652 40.646 41.566 44.314 46.928 50.223 52.620
26 11.160 13.844 31.795 35.563 38.885 41.923 42.856 45.642 48.290 51.627 54.052
27 11.808 14.573 32.912 36.741 40.113 43.195 44.140 46.963 49.645 53.023 55.476
28 12.461 15.308 34.027 37.916 41.337 44.461 45.419 48.278 50.993 54.411 56.892
29 13.121 16.047 35.139 39.087 42.557 45.722 46.693 49.588 52.336 55.792 58.301
30 13.787 16.791 36.250 40.256 43.773 46.979 47.962 50.892 53.672 57.167 59.703
31 14.458 17.539 37.359 41.422 44.985 48.232 49.226 52.191 55.003 58.536 61.098
32 15.134 18.291 38.466 42.585 46.194 49.480 50.487 53.486 56.328 59.899 62.487
33 15.815 19.047 39.572 43.745 47.400 50.725 51.743 54.776 57.648 61.256 63.870
34 16.501 19.806 40.676 44.903 48.602 51.966 52.995 56.061 58.964 62.608 65.247
35 17.192 20.569 41.778 46.059 49.802 53.203 54.244 57.342 60.275 63.955 66.619
36 17.887 21.336 42.879 47.212 50.998 54.437 55.489 58.619 61.581 65.296 67.985
37 18.586 22.106 43.978 48.363 52.192 55.668 56.730 59.893 62.883 66.633 69.346
38 19.289 22.878 45.076 49.513 53.384 56.896 57.969 61.162 64.181 67.966 70.703
39 19.996 23.654 46.173 50.660 54.572 58.120 59.204 62.428 65.476 69.294 72.055
40 20.707 24.433 47.269 51.805 55.758 59.342 60.436 63.691 66.766 70.618 73.402
41 21.421 25.215 48.363 52.949 56.942 60.561 61.665 64.950 68.053 71.938 74.745
42 22.138 25.999 49.456 54.090 58.124 61.777 62.892 66.206 69.336 73.254 76.084
43 22.859 26.785 50.548 55.230 59.304 62.990 64.116 67.459 70.616 74.566 77.419
44 23.584 27.575 51.639 56.369 60.481 64.201 65.337 68.710 71.893 75.874 78.750
45 24.311 28.366 52.729 57.505 61.656 65.410 66.555 69.957 73.166 77.179 80.077
46 25.041 29.160 53.818 58.641 62.830 66.617 67.771 71.201 74.437 78.481 81.400
47 25.775 29.956 54.906 59.774 64.001 67.821 68.985 72.443 75.704 79.780 82.720
48 26.511 30.755 55.993 60.907 65.171 69.023 70.197 73.683 76.969 81.075 84.037
49 27.249 31.555 57.079 62.038 66.339 70.222 71.406 74.919 78.231 82.367 85.351
50 27.991 32.357 58.164 63.167 67.505 71.420 72.613 76.154 79.490 83.657 86.661
51 28.735 33.162 59.248 64.295 68.669 72.616 73.818 77.386 80.747 84.943 87.968
52 29.481 33.968 60.332 65.422 69.832 73.810 75.021 78.616 82.001 86.227 89.272
53 30.230 34.776 61.414 66.548 70.993 75.002 76.223 79.843 83.253 87.507 90.573
54 30.981 35.586 62.496 67.673 72.153 76.192 77.422 81.069 84.502 88.786 91.872
55 31.735 36.398 63.577 68.796 73.311 77.380 78.619 82.292 85.749 90.061 93.168
56 32.490 37.212 64.658 69.919 74.468 78.567 79.815 83.513 86.994 91.335 94.461
57 33.248 38.027 65.737 71.040 75.624 79.752 81.009 84.733 88.236 92.605 95.751
58 34.008 38.844 66.816 72.160 76.778 80.936 82.201 85.950 89.477 93.874 97.039
59 34.770 39.662 67.894 73.279 77.931 82.117 83.391 87.166 90.715 95.140 98.324
60 35.534 40.482 68.972 74.397 79.082 83.298 84.580 88.379 91.952 96.404 99.607
61 36.301 41.303 70.049 75.514 80.232 84.476 85.767 89.591 93.186 97.665 100.888
62 37.068 42.126 71.125 76.630 81.381 85.654 86.953 90.802 94.419 98.925 102.166
63 37.838 42.950 72.201 77.745 82.529 86.830 88.137 92.010 95.649 100.182 103.442
64 38.610 43.776 73.276 78.860 83.675 88.004 89.320 93.217 96.878 101.437 104.716
65 39.383 44.603 74.351 79.973 84.821 89.177 90.501 94.422 98.105 102.691 105.988
66 40.158 45.431 75.424 81.085 85.965 90.349 91.681 95.626 99.330 103.942 107.258
67 40.935 46.261 76.498 82.197 87.108 91.519 92.860 96.828 100.554 105.192 108.526
68 41.713 47.092 77.571 83.308 88.250 92.689 94.037 98.028 101.776 106.440 109.791
69 42.494 47.924 78.643 84.418 89.391 93.856 95.213 99.228 102.996 107.685 111.055
70 43.275 48.758 79.715 85.527 90.531 95.023 96.388 100.425 104.215 108.929 112.317
71 44.058 49.592 80.786 86.635 91.670 96.189 97.561 101.621 105.432 110.172 113.577
72 44.843 50.428 81.857 87.743 92.808 97.353 98.733 102.816 106.648 111.412 114.835
73 45.629 51.265 82.927 88.850 93.945 98.516 99.904 104.010 107.862 112.651 116.092
74 46.417 52.103 83.997 89.956 95.081 99.678 101.074 105.202 109.074 113.889 117.346
75 47.206 52.942 85.066 91.061 96.217 100.839 102.243 106.393 110.286 115.125 118.599
76 47.997 53.782 86.135 92.166 97.351 101.999 103.410 107.583 111.495 116.359 119.850
77 48.788 54.623 87.203 93.270 98.484 103.158 104.576 108.771 112.704 117.591 121.100
78 49.582 55.466 88.271 94.374 99.617 104.316 105.742 109.958 113.911 118.823 122.348
79 50.376 56.309 89.338 95.476 100.749 105.473 106.906 111.144 115.117 120.052 123.594
80 51.172 57.153 90.405 96.578 101.879 106.629 108.069 112.329 116.321 121.280 124.839
81 51.969 57.998 91.472 97.680 103.010 107.783 109.232 113.512 117.524 122.507 126.083
82 52.767 58.845 92.538 98.780 104.139 108.937 110.393 114.695 118.726 123.733 127.324
83 53.567 59.692 93.604 99.880 105.267 110.090 111.553 115.876 119.927 124.957 128.565
84 54.368 60.540 94.669 100.980 106.395 111.242 112.712 117.057 121.126 126.179 129.804
85 55.170 61.389 95.734 102.079 107.522 112.393 113.871 118.236 122.325 127.401 131.041
86 55.973 62.239 96.799 103.177 108.648 113.544 115.028 119.414 123.522 128.621 132.277
87 56.777 63.089 97.863 104.275 109.773 114.693 116.184 120.591 124.718 129.840 133.512
88 57.582 63.941 98.927 105.372 110.898 115.841 117.340 121.767 125.913 131.057 134.745
89 58.389 64.793 99.991 106.469 112.022 116.989 118.495 122.942 127.106 132.273 135.978
90 59.196 65.647 101.054 107.565 113.145 118.136 119.648 124.116 128.299 133.489 137.208
91 60.005 66.501 102.117 108.661 114.268 119.282 120.801 125.289 129.491 134.702 138.438
92 60.815 67.356 103.179 109.756 115.390 120.427 121.954 126.462 130.681 135.915 139.666
93 61.625 68.211 104.241 110.850 116.511 121.571 123.105 127.633 131.871 137.127 140.893
94 62.437 69.068 105.303 111.944 117.632 122.715 124.255 128.803 133.059 138.337 142.119
95 63.250 69.925 106.364 113.038 118.752 123.858 125.405 129.973 134.247 139.546 143.344
96 64.063 70.783 107.425 114.131 119.871 125.000 126.554 131.141 135.433 140.755 144.567
97 64.878 71.642 108.486 115.223 120.990 126.141 127.702 132.309 136.619 141.962 145.789
98 65.694 72.501 109.547 116.315 122.108 127.282 128.849 133.476 137.803 143.168 147.010
99 66.510 73.361 110.607 117.407 123.225 128.422 129.996 134.642 138.987 144.373 148.230
100 67.328 74.222 111.667 118.498 124.342 129.561 131.142 135.807 140.169 145.577 149.449
101 68.146 75.083 112.726 119.589 125.458 130.700 132.287 136.971 141.351 146.780 150.667
102 68.965 75.946 113.786 120.679 126.574 131.838 133.431 138.134 142.532 147.982 151.884
103 69.785 76.809 114.845 121.769 127.689 132.975 134.575 139.297 143.712 149.183 153.099
104 70.606 77.672 115.903 122.858 128.804 134.111 135.718 140.459 144.891 150.383 154.314
105 71.428 78.536 116.962 123.947 129.918 135.247 136.860 141.620 146.070 151.582 155.528
106 72.251 79.401 118.020 125.035 131.031 136.382 138.002 142.780 147.247 152.780 156.740
107 73.075 80.267 119.078 126.123 132.144 137.517 139.143 143.940 148.424 153.977 157.952
108 73.899 81.133 120.135 127.211 133.257 138.651 140.283 145.099 149.599 155.173 159.162
109 74.724 82.000 121.192 128.298 134.369 139.784 141.423 146.257 150.774 156.369 160.372
110 75.550 82.867 122.250 129.385 135.480 140.917 142.562 147.414 151.948 157.563 161.581
111 76.377 83.735 123.306 130.472 136.591 142.049 143.700 148.571 153.122 158.757 162.788
112 77.204 84.604 124.363 131.558 137.701 143.180 144.838 149.727 154.294 159.950 163.995
113 78.033 85.473 125.419 132.643 138.811 144.311 145.975 150.882 155.466 161.141 165.201
114 78.862 86.342 126.475 133.729 139.921 145.441 147.111 152.037 156.637 162.332 166.406
115 79.692 87.213 127.531 134.813 141.030 146.571 148.247 153.191 157.808 163.523 167.610
116 80.522 88.084 128.587 135.898 142.138 147.700 149.383 154.344 158.977 164.712 168.813
117 81.353 88.955 129.642 136.982 143.246 148.829 150.517 155.496 160.146 165.900 170.016
118 82.185 89.827 130.697 138.066 144.354 149.957 151.652 156.648 161.314 167.088 171.217
119 83.018 90.700 131.752 139.149 145.461 151.084 152.785 157.800 162.481 168.275 172.418
120 83.852 91.573 132.806 140.233 146.567 152.211 153.918 158.950 163.648 169.461 173.617
121 84.686 92.446 133.861 141.315 147.674 153.338 155.051 160.100 164.814 170.647 174.816
122 85.520 93.320 134.915 142.398 148.779 154.464 156.183 161.250 165.980 171.831 176.014
123 86.356 94.195 135.969 143.480 149.885 155.589 157.314 162.398 167.144 173.015 177.212
124 87.192 95.070 137.022 144.562 150.989 156.714 158.445 163.546 168.308 174.198 178.408
125 88.029 95.946 138.076 145.643 152.094 157.839 159.575 164.694 169.471 175.380 179.604
126 88.866 96.822 139.129 146.724 153.198 158.962 160.705 165.841 170.634 176.562 180.799
127 89.704 97.698 140.182 147.805 154.302 160.086 161.834 166.987 171.796 177.743 181.993
128 90.543 98.576 141.235 148.885 155.405 161.209 162.963 168.133 172.957 178.923 183.186
129 91.382 99.453 142.288 149.965 156.508 162.331 164.091 169.278 174.118 180.103 184.379
130 92.222 100.331 143.340 151.045 157.610 163.453 165.219 170.423 175.278 181.282 185.571
131 93.063 101.210 144.392 152.125 158.712 164.575 166.346 171.567 176.438 182.460 186.762
132 93.904 102.089 145.444 153.204 159.814 165.696 167.473 172.711 177.597 183.637 187.953
133 94.746 102.968 146.496 154.283 160.915 166.816 168.600 173.854 178.755 184.814 189.142
134 95.588 103.848 147.548 155.361 162.016 167.936 169.725 174.996 179.913 185.990 190.331
135 96.431 104.729 148.599 156.440 163.116 169.056 170.851 176.138 181.070 187.165 191.520
136 97.275 105.609 149.651 157.518 164.216 170.175 171.976 177.280 182.226 188.340 192.707
137 98.119 106.491 150.702 158.595 165.316 171.294 173.100 178.421 183.382 189.514 193.894
138 98.964 107.372 151.753 159.673 166.415 172.412 174.224 179.561 184.538 190.688 195.080
139 99.809 108.254 152.803 160.750 167.514 173.530 175.348 180.701 185.693 191.861 196.266
140 100.655 109.137 153.854 161.827 168.613 174.648 176.471 181.840 186.847 193.033 197.451
141 101.501 110.020 154.904 162.904 169.711 175.765 177.594 182.979 188.001 194.205 198.635
142 102.348 110.903 155.954 163.980 170.809 176.882 178.716 184.118 189.154 195.376 199.819
143 103.196 111.787 157.004 165.056 171.907 177.998 179.838 185.256 190.306 196.546 201.002
144 104.044 112.671 158.054 166.132 173.004 179.114 180.959 186.393 191.458 197.716 202.184
145 104.892 113.556 159.104 167.207 174.101 180.229 182.080 187.530 192.610 198.885 203.366
146 105.741 114.441 160.153 168.283 175.198 181.344 183.200 188.666 193.761 200.054 204.547
147 106.591 115.326 161.202 169.358 176.294 182.459 184.321 189.802 194.912 201.222 205.727
148 107.441 116.212 162.251 170.432 177.390 183.573 185.440 190.938 196.062 202.390 206.907
149 108.291 117.098 163.300 171.507 178.485 184.687 186.560 192.073 197.211 203.557 208.086
150 109.142 117.985 164.349 172.581 179.581 185.800 187.678 193.208 198.360 204.723 209.265
151 109.994 118.871 165.398 173.655 180.676 186.914 188.797 194.342 199.509 205.889 210.443
152 110.846 119.759 166.446 174.729 181.770 188.026 189.915 195.476 200.657 207.054 211.620
153 111.698 120.646 167.495 175.803 182.865 189.139 191.033 196.609 201.804 208.219 212.797
154 112.551 121.534 168.543 176.876 183.959 190.251 192.150 197.742 202.951 209.383 213.973
155 113.405 122.423 169.591 177.949 185.052 191.362 193.267 198.874 204.098 210.547 215.149
156 114.259 123.312 170.639 179.022 186.146 192.474 194.384 200.006 205.244 211.710 216.324
157 115.113 124.201 171.686 180.094 187.239 193.584 195.500 201.138 206.390 212.873 217.499
158 115.968 125.090 172.734 181.167 188.332 194.695 196.616 202.269 207.535 214.035 218.673
159 116.823 125.980 173.781 182.239 189.424 195.805 197.731 203.400 208.680 215.197 219.846
160 117.679 126.870 174.828 183.311 190.516 196.915 198.846 204.530 209.824 216.358 221.019
161 118.536 127.761 175.875 184.382 191.608 198.025 199.961 205.660 210.968 217.518 222.191
162 119.392 128.651 176.922 185.454 192.700 199.134 201.076 206.790 212.111 218.678 223.363
163 120.249 129.543 177.969 186.525 193.791 200.243 202.190 207.919 213.254 219.838 224.535
164 121.107 130.434 179.016 187.596 194.883 201.351 203.303 209.047 214.396 220.997 225.705
165 121.965 131.326 180.062 188.667 195.973 202.459 204.417 210.176 215.539 222.156 226.876
166 122.823 132.218 181.109 189.737 197.064 203.567 205.530 211.304 216.680 223.314 228.045
167 123.682 133.111 182.155 190.808 198.154 204.675 206.642 212.431 217.821 224.472 229.215
168 124.541 134.003 183.201 191.878 199.244 205.782 207.755 213.558 218.962 225.629 230.383
169 125.401 134.897 184.247 192.948 200.334 206.889 208.867 214.685 220.102 226.786 231.552
170 126.261 135.790 185.293 194.017 201.423 207.995 209.978 215.812 221.242 227.942 232.719
171 127.122 136.684 186.338 195.087 202.513 209.102 211.090 216.938 222.382 229.098 233.887
172 127.983 137.578 187.384 196.156 203.602 210.208 212.201 218.063 223.521 230.253 235.053
173 128.844 138.472 188.429 197.225 204.690 211.313 213.311 219.189 224.660 231.408 236.220
174 129.706 139.367 189.475 198.294 205.779 212.419 214.422 220.314 225.798 232.563 237.385
175 130.568 140.262 190.520 199.363 206.867 213.524 215.532 221.438 226.936 233.717 238.551
176 131.430 141.157 191.565 200.432 207.955 214.628 216.641 222.563 228.074 234.870 239.716
177 132.293 142.053 192.610 201.500 209.042 215.733 217.751 223.687 229.211 236.023 240.880
178 133.157 142.949 193.654 202.568 210.130 216.837 218.860 224.810 230.347 237.176 242.044
179 134.020 143.845 194.699 203.636 211.217 217.941 219.969 225.933 231.484 238.328 243.207
180 134.884 144.741 195.743 204.704 212.304 219.044 221.077 227.056 232.620 239.480 244.370
181 135.749 145.638 196.788 205.771 213.391 220.148 222.185 228.179 233.755 240.632 245.533
182 136.614 146.535 197.832 206.839 214.477 221.251 223.293 229.301 234.891 241.783 246.695
183 137.479 147.432 198.876 207.906 215.563 222.353 224.401 230.423 236.026 242.933 247.857
184 138.344 148.330 199.920 208.973 216.649 223.456 225.508 231.544 237.160 244.084 249.018
185 139.210 149.228 200.964 210.040 217.735 224.558 226.615 232.665 238.294 245.234 250.179
186 140.077 150.126 202.008 211.106 218.820 225.660 227.722 233.786 239.428 246.383 251.339
187 140.943 151.024 203.052 212.173 219.906 226.761 228.828 234.907 240.561 247.532 252.499
188 141.810 151.923 204.095 213.239 220.991 227.863 229.935 236.027 241.694 248.681 253.659
189 142.678 152.822 205.139 214.305 222.076 228.964 231.040 237.147 242.827 249.829 254.818
190 143.545 153.721 206.182 215.371 223.160 230.064 232.146 238.266 243.959 250.977 255.976
191 144.413 154.621 207.225 216.437 224.245 231.165 233.251 239.386 245.091 252.124 257.135
192 145.282 155.521 208.268 217.502 225.329 232.265 234.356 240.505 246.223 253.271 258.292
193 146.150 156.421 209.311 218.568 226.413 233.365 235.461 241.623 247.354 254.418 259.450
194 147.020 157.321 210.354 219.633 227.496 234.465 236.566 242.742 248.485 255.564 260.607
195 147.889 158.221 211.397 220.698 228.580 235.564 237.670 243.860 249.616 256.710 261.763
196 148.759 159.122 212.439 221.763 229.663 236.664 238.774 244.977 250.746 257.855 262.920
197 149.629 160.023 213.482 222.828 230.746 237.763 239.877 246.095 251.876 259.001 264.075
198 150.499 160.925 214.524 223.892 231.829 238.861 240.981 247.212 253.006 260.145 265.231
199 151.370 161.826 215.567 224.957 232.912 239.960 242.084 248.329 254.135 261.290 266.386
200 152.241 162.728 216.609 226.021 233.994 241.058 243.187 249.445 255.264 262.434 267.541
201 153.112 163.630 217.651 227.085 235.077 242.156 244.290 250.561 256.393 263.578 268.695
202 153.984 164.532 218.693 228.149 236.159 243.254 245.392 251.677 257.521 264.721 269.849
203 154.856 165.435 219.735 229.213 237.240 244.351 246.494 252.793 258.649 265.864 271.002
204 155.728 166.338 220.777 230.276 238.322 245.448 247.596 253.908 259.777 267.007 272.155
205 156.601 167.241 221.818 231.340 239.403 246.545 248.698 255.023 260.904 268.149 273.308
206 157.474 168.144 222.860 232.403 240.485 247.642 249.799 256.138 262.031 269.291 274.460
207 158.347 169.047 223.901 233.466 241.566 248.739 250.900 257.253 263.158 270.432 275.612
208 159.221 169.951 224.943 234.529 242.647 249.835 252.001 258.367 264.285 271.574 276.764
209 160.095 170.855 225.984 235.592 243.727 250.931 253.102 259.481 265.411 272.715 277.915
210 160.969 171.759 227.025 236.655 244.808 252.027 254.202 260.595 266.537 273.855 279.066
211 161.843 172.664 228.066 237.717 245.888 253.122 255.302 261.708 267.662 274.995 280.217
212 162.718 173.568 229.107 238.780 246.968 254.218 256.402 262.821 268.788 276.135 281.367
213 163.593 174.473 230.148 239.842 248.048 255.313 257.502 263.934 269.912 277.275 282.517
214 164.469 175.378 231.189 240.904 249.128 256.408 258.601 265.047 271.037 278.414 283.666
215 165.344 176.283 232.230 241.966 250.207 257.503 259.701 266.159 272.162 279.553 284.815
216 166.220 177.189 233.270 243.028 251.286 258.597 260.800 267.271 273.286 280.692 285.964
217 167.096 178.095 234.311 244.090 252.365 259.691 261.898 268.383 274.409 281.830 287.112
218 167.973 179.001 235.351 245.151 253.444 260.785 262.997 269.495 275.533 282.968 288.261
219 168.850 179.907 236.391 246.213 254.523 261.879 264.095 270.606 276.656 284.106 289.408
220 169.727 180.813 237.432 247.274 255.602 262.973 265.193 271.717 277.779 285.243 290.556
221 170.604 181.720 238.472 248.335 256.680 264.066 266.291 272.828 278.902 286.380 291.703
222 171.482 182.627 239.512 249.396 257.758 265.159 267.389 273.939 280.024 287.517 292.850
223 172.360 183.534 240.552 250.457 258.837 266.252 268.486 275.049 281.146 288.653 293.996
224 173.238 184.441 241.592 251.517 259.914 267.345 269.584 276.159 282.268 289.789 295.142
225 174.116 185.348 242.631 252.578 260.992 268.438 270.681 277.269 283.390 290.925 296.288
226 174.995 186.256 243.671 253.638 262.070 269.530 271.777 278.379 284.511 292.061 297.433
227 175.874 187.164 244.711 254.699 263.147 270.622 272.874 279.488 285.632 293.196 298.579
228 176.753 188.072 245.750 255.759 264.224 271.714 273.970 280.597 286.753 294.331 299.723
229 177.633 188.980 246.790 256.819 265.301 272.806 275.066 281.706 287.874 295.465 300.868
230 178.512 189.889 247.829 257.879 266.378 273.898 276.162 282.814 288.994 296.600 302.012
231 179.392 190.797 248.868 258.939 267.455 274.989 277.258 283.923 290.114 297.734 303.156
232 180.273 191.706 249.908 259.998 268.531 276.080 278.354 285.031 291.234 298.867 304.299
233 181.153 192.615 250.947 261.058 269.608 277.171 279.449 286.139 292.353 300.001 305.443
234 182.034 193.524 251.986 262.117 270.684 278.262 280.544 287.247 293.472 301.134 306.586
235 182.915 194.434 253.025 263.176 271.760 279.352 281.639 288.354 294.591 302.267 307.728
236 183.796 195.343 254.063 264.235 272.836 280.443 282.734 289.461 295.710 303.400 308.871
237 184.678 196.253 255.102 265.294 273.911 281.533 283.828 290.568 296.828 304.532 310.013
238 185.560 197.163 256.141 266.353 274.987 282.623 284.922 291.675 297.947 305.664 311.154
239 186.442 198.073 257.179 267.412 276.062 283.713 286.016 292.782 299.065 306.796 312.296
240 187.324 198.984 258.218 268.471 277.138 284.802 287.110 293.888 300.182 307.927 313.437
241 188.207 199.894 259.256 269.529 278.213 285.892 288.204 294.994 301.300 309.058 314.578
242 189.090 200.805 260.295 270.588 279.288 286.981 289.298 296.100 302.417 310.189 315.718
243 189.973 201.716 261.333 271.646 280.362 288.070 290.391 297.206 303.534 311.320 316.859
244 190.856 202.627 262.371 272.704 281.437 289.159 291.484 298.311 304.651 312.450 317.999
245 191.739 203.539 263.409 273.762 282.511 290.248 292.577 299.417 305.767 313.580 319.138
246 192.623 204.450 264.447 274.820 283.586 291.336 293.670 300.522 306.883 314.710 320.278
247 193.507 205.362 265.485 275.878 284.660 292.425 294.762 301.626 307.999 315.840 321.417
248 194.391 206.274 266.523 276.935 285.734 293.513 295.855 302.731 309.115 316.969 322.556
249 195.276 207.186 267.561 277.993 286.808 294.601 296.947 303.835 310.231 318.098 323.694
250 196.161 208.098 268.599 279.050 287.882 295.689 298.039 304.940 311.346 319.227 324.832
300 240.663 253.912 320.397 331.789 341.395 349.874 352.425 359.906 366.844 375.369 381.425
350 285.608 300.064 372.051 384.306 394.626 403.723 406.457 414.474 421.900 431.017 437.488
400 330.903 346.482 423.590 436.649 447.632 457.305 460.211 468.724 476.606 486.274 493.132
450 376.483 393.118 475.035 488.849 500.456 510.670 513.736 522.717 531.026 541.212 548.432
500 422.303 439.936 526.401 540.930 553.127 563.852 567.070 576.493 585.207 595.882 603.446
550 468.328 486.910 577.701 592.909 605.667 616.878 620.241 630.084 639.183 650.324 658.215
600 514.529 534.019 628.943 644.800 658.094 669.769 673.270 683.516 692.982 704.568 712.771
650 560.885 581.245 680.134 696.614 710.421 722.542 726.176 736.807 746.625 758.639 767.141
700 607.380 628.577 731.280 748.359 762.661 775.211 778.972 789.974 800.131 812.556 821.347
750 653.997 676.003 782.386 800.043 814.822 827.785 831.670 843.029 853.514 866.336 875.404
800 700.725 723.513 833.456 851.671 866.911 880.275 884.279 895.984 906.786 919.991 929.329
850 747.554 771.099 884.492 903.249 918.937 932.689 936.808 948.848 959.957 973.534 983.133
900 794.475 818.756 935.499 954.782 970.904 985.032 989.263 1001.630 1013.036 1026.974 1036.826
950 841.480 866.477 986.478 1006.272 1022.816 1037.311 1041.651 1054.334 1066.031 1080.320 1090.418
1000 888.564 914.257 1037.431 1057.724 1074.679 1089.531 1093.977 1106.969 1118.948 1133.579 1143.917];
% remove DOF column
TAB = TAB(:,2:end);
% add the P=0.5 column
PRB = [PRB(1:2) 0.500 PRB(3:end)];
TAB = [TAB(:,1:2) DOF' TAB(:,3:end)];
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright 2007,2008,2009
% by Joan Sola, David Marquez and Jean Marie Codol @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
vecnorm.m
|
.m
|
slam_matlab-master/libs_dir/slamtoolbox/slamToolbox_11_09_08/Math/vecnorm.m
| 1,534 |
utf_8
|
79b38e4a6fe6b82aa4e59d153995e278
|
function [n, N_v] = vecnorm(v)
% VECNORM Vector norm, with Jacobian
% VECNORM(V) is the same as NORM(V)
%
% [n, N_v] = VECNORM(V) returns also the Jacobian.
if nargout == 1
n = sqrt(v'*v);
else
n = sqrt(v'*v);
N_v = v'/n;
end
end
%%
function f()
%%
syms v1 v2 real
v = [v1;v2];
[n,N_v] = vecnorm(v);
N_v - jacobian(n,v)
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright 2007, 2008, 2009, 2010
% by Joan Sola @ LAAS-CNRS.
% SLAMTB is Copyright 2009
% by Joan Sola, David Marquez and Jean Marie Codol @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
toFrameHmg.m
|
.m
|
slam_matlab-master/libs_dir/slamtoolbox/slamToolbox_11_09_08/Points/toFrameHmg.m
| 3,142 |
utf_8
|
3a88bb83e7b0e927258f70d4fdd76b12
|
function [hf,HF_f,HF_h] = toFrameHmg(F,h)
% TOFRAMEHMG To-frame transformation for homogeneous coordinates
% P = TOFRAMEHMG(F,PF) transforms homogeneous point P from the global
% frame to local frame F.
%
% [p,Pf,Ppf] = ... returns the Jacobians wrt F and PF.
% Copyright 2008-2011 Joan Sola @ LAAS-CNRS.
[t,q,R] = splitFrame(F) ;
iF = [R' -R'*t ; 0 0 0 1];
hf = iF*h;
if nargout > 1
[x,y,z] = split(t);
[a,b,c,d] = split(q);
[hx,hy,hz,ht] = split(h);
HF_f = [...
[ -ht*(a^2 + b^2 - c^2 - d^2), (-2)*ht*(a*d + b*c), 2*ht*(a*c - b*d), 2*a*hx - 2*c*hz + 2*d*hy - 2*ht*(a*x - c*z + d*y), 2*b*hx + 2*c*hy + 2*d*hz - 2*ht*(b*x + c*y + d*z), 2*b*hy - 2*a*hz - 2*c*hx + 2*ht*(a*z - b*y + c*x), 2*a*hy + 2*b*hz - 2*d*hx - 2*ht*(a*y + b*z - d*x)]
[ 2*ht*(a*d - b*c), -ht*(a^2 - b^2 + c^2 - d^2), (-2)*ht*(a*b + c*d), 2*a*hy + 2*b*hz - 2*d*hx - 2*ht*(a*y + b*z - d*x), 2*a*hz - 2*b*hy + 2*c*hx - 2*ht*(a*z - b*y + c*x), 2*b*hx + 2*c*hy + 2*d*hz - 2*ht*(b*x + c*y + d*z), 2*c*hz - 2*a*hx - 2*d*hy + 2*ht*(a*x - c*z + d*y)]
[ (-2)*ht*(a*c + b*d), 2*ht*(a*b - c*d), -ht*(a^2 - b^2 - c^2 + d^2), 2*a*hz - 2*b*hy + 2*c*hx - 2*ht*(a*z - b*y + c*x), 2*d*hx - 2*b*hz - 2*a*hy + 2*ht*(a*y + b*z - d*x), 2*a*hx - 2*c*hz + 2*d*hy - 2*ht*(a*x - c*z + d*y), 2*b*hx + 2*c*hy + 2*d*hz - 2*ht*(b*x + c*y + d*z)]
[ 0, 0, 0, 0, 0, 0, 0]];
HF_h = iF;
end
end
%%
function f()
%%
syms x y z a b c d hx hy hz ht real
F.x=[x;y;z;a;b;c;d];
F=updateFrame(F);
h = [hx;hy;hz;ht];
hf = toFrameHmg(F,h)
HF_f = simplify(jacobian(hf,F.x))
HF_h = simplify(jacobian(hf,h))
[hf,HF_f,HF_h] = toFrameHmg(F,h);
simplify(HF_f - jacobian(hf,F.x))
simplify(HF_h - jacobian(hf,h))
%%
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright 2007,2008,2009
% by Joan Sola, David Marquez and Jean Marie Codol @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
invDistortion.m
|
.m
|
slam_matlab-master/libs_dir/slamtoolbox/slamToolbox_11_09_08/Observations/invDistortion.m
| 4,410 |
utf_8
|
01b198fd2276fbb194a08f453ffa5317
|
function kc = invDistortion(kd,n,cal,draw)
% INVDISTORTION Radial distortion correction calibration.
%
% Kc = INVDISTORTION(Kd,n) computes the least squares optimal set
% of n parameters of the correction radial distortion function
% for a normalized camera:
%
% r = c(rd) = rd (1 + c2 rd^2 + ... + c2n rd^2n)
%
% that best approximates the inverse of the distortion function
%
% rd = d(r) = r (1 + d2 r^2 + d4 r^4 + ...)
%
% which can be of any length.
%
% Kc = INVDISTORTION(Kd,n,cal) accepts the intrinsic parameters
% of the camera cal = [u_0, v_0, a_u, a_v].
%
% The format of the distortion and correction vectors is
%
% Kd = [d2, d4, d6, ...]
% Kc = [c2, c4, ..., c2n]
%
% Kc = INVDISTORTION(...,DRAW) with DRAW~=0 additionally plots the
% distortion and correction mappings r_d=d(r) and r=c(r_d)
% and the error (r - r_d).
%
% See also PINHOLE, INVPINHOLE.
% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.
if numel(kd) == 0
kc = [];
else
if nargin == 2 || isempty(cal)
cal = [1 1 1 1];
end
% fprintf(' Obtaining correction vector from distortion vector...');
rmax2 = (cal(1)/cal(3))^2 + (cal(2)/cal(4))^2;
rmax = sqrt(rmax2); % maximum radius in normalized coordinates
rdmax = 1.1*rmax;
% N=101 sampling points of d(r)
rc = [0:.01*rdmax:rdmax]; % rc is the undistorted radius vector
rd = c2d(kd,rc); % rd is the distorted radius vector
% 1. non-linear least-squares method (for other than radial distortion)
% comment out for testing against psudo-inverse method
% x0 = zeros(1,n);
% kc = lsqnonlin(@(x) fun(x,rc,rd),x0);
% 2. pseudo-inverse method (indicated for radial distortion)
% we solve the system A*Kc = rc-rd via Kc = pinv(A)*(rc-rd).
A = []; % construction of A for Kc of length n
for i = 1:n
A = [A rd'.^(2*i+1)];
end
B = pinv(A);
kc = (rc-rd)*B'; % All transposed because we are working with row-vectors
% fprintf(' OK.\n');
if nargin == 4 && draw
% normalized error
erc = d2c(kc,rd);
% correction and distortion functions
figure(9)
subplot(3,1,[1 2])
plot(rc,rd,'linewidth',2)
title('Distortion mapping'),xlabel('r'),ylabel('rd'),grid
set(gca,'xlim',[0 rdmax])
hold on
plot(erc,rd,'r--','linewidth',2)
hold off
% error function (in pixels)
subplot(3,1,3)
plot(rc,cal(3)*(rc-erc))
title('Correction error [pix]'),xlabel('r'),ylabel('error'),grid
set(gca,'xlim',[0 rdmax])
% error values
err_max = cal(3)*max (abs(rc-erc));
err_mean = cal(3)*mean(rc-erc);
err_std = cal(3)*std (rc-erc);
fprintf(1,' Errors. Max: %.2f | Mean: %.2f | Std: %.2f pixels.\n',err_max,err_mean,err_std)
end
end
% Necessary functions
% corr- to dis- conversion
function rd = c2d(kd,rc)
c = ones(1,length(rc));
for i=1:length(kd)
c = c+kd(i)*rc.^(2*i);
end
rd = rc.*c;
% dis- to corr- conversion
function rc = d2c(kc,rd)
c = ones(1,length(rd));
for i=1:length(kc)
c = c+kc(i)*rd.^(2*i);
end
rc = rd.*c;
% error function (only for non-linear least squares - normally
% not necessary)
function e = fun(kc,rc,rd)
e = d2c(kc,rd) - rc;
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright 2007,2008,2009
% by Joan Sola, David Marquez and Jean Marie Codol @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
rotx.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/rotx.m
| 306 |
utf_8
|
e3472a26436b5f238dac19d5fd0b871c
|
%ROTX Rotation about X axis
%
% ROTX(theta) returns a homogeneous transformation representing a
% rotation of theta about the X axis.
%
% See also ROTY, ROTZ, ROTVEC.
% Copyright (C) Peter Corke 1990
function r = rotx(t)
ct = cos(t);
st = sin(t);
r = [1 0 0 0
0 ct -st 0
0 st ct 0
0 0 0 1];
|
github
|
rising-turtle/slam_matlab-master
|
rotz.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/rotz.m
| 306 |
utf_8
|
46e0bf3113efb75d4014488b019f3576
|
%ROTZ Rotation about Z axis
%
% ROTZ(theta) returns a homogeneous transformation representing a
% rotation of theta about the X axis.
%
% See also ROTX, ROTY, ROTVEC.
% Copyright (C) Peter Corke 1990
function r = rotz(t)
ct = cos(t);
st = sin(t);
r = [ct -st 0 0
st ct 0 0
0 0 1 0
0 0 0 1];
|
github
|
rising-turtle/slam_matlab-master
|
rpy2tr.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/rpy2tr.m
| 511 |
utf_8
|
a94f613d4341e10ddaf4c0551555471f
|
%RPY2TR Roll/pitch/yaw to homogenous transform
%
% RPY2TR([R P Y])
% RPY2TR(R,P,Y) returns a homogeneous tranformation for the specified
% roll/pitch/yaw angles. These correspond to rotations about the
% Z, X, Y axes respectively.
%
% See also TR2RPY, EUL2TR
% Copright (C) Peter Corke 1993
function r = rpy2tr(roll, pitch, yaw)
if length(roll) == 3,
r = rotz(roll(1)) * roty(roll(2)) * rotx(roll(3));
else
r = rotz(roll) * roty(pitch) * rotx(yaw);
end
|
github
|
rising-turtle/slam_matlab-master
|
roty.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/roty.m
| 306 |
utf_8
|
d1d8eb762d99bd1091278e9fc3c26dc2
|
%ROTY Rotation about Y axis
%
% ROTY(theta) returns a homogeneous transformation representing a
% rotation of theta about the Y axis.
%
% See also ROTX, ROTZ, ROTVEC.
% Copyright (C) Peter Corke 1990
function r = roty(t)
ct = cos(t);
st = sin(t);
r = [ct 0 st 0
0 1 0 0
-st 0 ct 0
0 0 0 1];
|
github
|
rising-turtle/slam_matlab-master
|
q2tr.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/q2tr.m
| 452 |
utf_8
|
a142148cdf478b8beae43593bc74cb66
|
%Q2TR Convert unit-quaternion to homogeneous transform
%
% T = q2tr(Q)
%
% Return the rotational homogeneous transform corresponding to the unit
% quaternion Q.
%
% See also TR2Q
% Copyright (C) 1993 Peter Corke
function t = q2tr(q)
s = q(1);
x = q(2);
y = q(3);
z = q(4);
r = [ 1-2*(y^2+z^2) 2*(x*y-s*z) 2*(x*z+s*y)
2*(x*y+s*z) 1-2*(x^2+z^2) 2*(y*z-s*x)
2*(x*z-s*y) 2*(y*z+s*x) 1-2*(x^2+y^2) ];
t = eye(4,4);
t(1:3,1:3) = r;
t(4,4) = 1;
|
github
|
rising-turtle/slam_matlab-master
|
tr2rpy.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/tr2rpy.m
| 647 |
utf_8
|
bfaa28ddb877e05439892857e8cdc115
|
%TR2RPY Convert a homogeneous transform matrix to roll/pitch/yaw angles
%
% [A B C] = TR2RPY(TR) returns a vector of Euler angles
% corresponding to the rotational part of the homogeneous transform TR.
%
% See also RPY2TR, TR2EUL
% Copright (C) Peter Corke 1993
function rpy = tr2rpy(m)
rpy = zeros(1,3);
if abs(m(1,1)) < eps & abs(m(2,1)) < eps,
rpy(1) = 0;
rpy(2) = atan2(-m(3,1), m(1,1));
rpy(3) = atan2(-m(2,3), m(2,2));
else,
rpy(1) = atan2(m(2,1), m(1,1));
sp = sin(rpy(1));
cp = cos(rpy(1));
rpy(2) = atan2(-m(3,1), cp * m(1,1) + sp * m(2,1));
rpy(3) = atan2(sp * m(1,3) - cp * m(2,3), cp*m(2,2) - sp*m(1,2));
end
|
github
|
rising-turtle/slam_matlab-master
|
tr2q.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/tr2q.m
| 1,163 |
utf_8
|
b848d8e8dd98bb791156d6b2e1684d69
|
%TR2Q Convert homogeneous transform to a unit-quaternion
%
% Q = tr2q(T)
%
% Return a unit quaternion corresponding to the rotational part of the
% homogeneous transform T.
%
% See also Q2TR
% Copyright (C) 1993 Peter Corke
function q = tr2q(t)
q = zeros(1,4);
q(1) = sqrt(trace(t))/2;
kx = t(3,2) - t(2,3); % Oz - Ay
ky = t(1,3) - t(3,1); % Ax - Nz
kz = t(2,1) - t(1,2); % Ny - Ox
if (t(1,1) >= t(2,2)) & (t(1,1) >= t(3,3))
kx1 = t(1,1) - t(2,2) - t(3,3) + 1; % Nx - Oy - Az + 1
ky1 = t(2,1) + t(1,2); % Ny + Ox
kz1 = t(3,1) + t(1,3); % Nz + Ax
add = (kx >= 0);
elseif (t(2,2) >= t(3,3))
kx1 = t(2,1) + t(1,2); % Ny + Ox
ky1 = t(2,2) - t(1,1) - t(3,3) + 1; % Oy - Nx - Az + 1
kz1 = t(3,2) + t(2,3); % Oz + Ay
add = (ky >= 0);
else
kx1 = t(3,1) + t(1,3); % Nz + Ax
ky1 = t(3,2) + t(2,3); % Oz + Ay
kz1 = t(3,3) - t(1,1) - t(2,2) + 1; % Az - Nx - Oy + 1
add = (kz >= 0);
end
if add
kx = kx + kx1;
ky = ky + ky1;
kz = kz + kz1;
else
kx = kx - kx1;
ky = ky - ky1;
kz = kz - kz1;
end
nm = norm([kx ky kz]);
if nm == 0,
q = [1 0 0 0];
else
s = sqrt(1 - q(1)^2) / nm;
q(2:4) = s*[kx ky kz];
end
|
github
|
rising-turtle/slam_matlab-master
|
fast_corner_detect_12.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/fast-matlab-src/fast_corner_detect_12.m
| 126,136 |
utf_8
|
a893a7b42ef9722d64ec819cfb934614
|
%FAST_CORNER_DETECT_12 perform an 12 point FAST corner detection.
% corners = FAST_CORNER_DETECT_12(image, threshold) performs the detection on the image
% and returns the X coordinates in corners(:,1) and the Y coordinares in corners(:,2).
%
% If you use this in published work, please cite:
% Fusing Points and Lines for High Performance Tracking, E. Rosten and T. Drummond, ICCV 2005
% Machine learning for high-speed corner detection, E. Rosten and T. Drummond, ECCV 2006
% The Bibtex entries are:
%
% @inproceedings{rosten_2005_tracking,
% title = "Fusing points and lines for high performance tracking.",
% author = "Edward Rosten and Tom Drummond",
% year = "2005",
% month = "October",
% pages = "1508--1511",
% volume = "2",
% booktitle = "IEEE International Conference on Computer Vision",
% notes = "Oral presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2005_tracking.pdf"
% }
%
% @inproceedings{rosten_2006_machine,
% title = "Machine learning for high-speed corner detection",
% author = "Edward Rosten and Tom Drummond",
% year = "2006",
% month = "May",
% booktitle = "European Conference on Computer Vision (to appear)",
% notes = "Poster presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2006_machine.pdf"
% }
%
%
% Additional information from the generating program:
%
% Automatically generated code
% Parameters:
% splat_subtree = 1
% corner_pointers = 2
% force_first_question = 0
% corner_type = 12
% barrier = 25
%
% Data:
% Number of frames: 120
% Potential features: 25786080
% Real features: 69141
% Questions per pixel: 2.26105
%
%
% See also FAST_NONMAX FAST_CORNER_DETECT_9 FAST_CORNER_DETECT_10 FAST_CORNER_DETECT_11 FAST_CORNER_DETECT_12
%
function coords = fast_corner_detect_12(im, threshold)
sz = size(im);
xsize=sz(2);
ysize=sz(1);
cs = zeros(5000, 2);
nc = 0;
for x = 4 : xsize - 3
for y = 4 : ysize -3
cb = im(y,x) + threshold;
c_b= im(y,x) - threshold;
if im(y+-3,x+0) > cb
if im(y+2,x+2) > cb
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+-1) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+0) > cb
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
else
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+-1) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+1) < c_b
if im(y+0,x+3) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+3,x+-1) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+3) < c_b
continue;
else
if im(y+3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+-1) > cb
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
end
elseif im(y+1,x+-3) < c_b
if im(y+1,x+3) > cb
else
continue;
end
else
if im(y+0,x+3) > cb
if im(y+3,x+1) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+2,x+-2) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+1,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+3,x+1) > cb
if im(y+-3,x+-1) > cb
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+-2,x+2) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+-3) < c_b
if im(y+0,x+3) > cb
if im(y+1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+1) > cb
if im(y+2,x+-2) > cb||im(y+2,x+-2) < c_b
else
if im(y+-2,x+-2) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+0,x+-3) < c_b
if im(y+3,x+-1) > cb
if im(y+0,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+1) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+1,x+-3) > cb
if im(y+-2,x+2) > cb
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+-3,x+-1) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+-1) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+0) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+-2) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+-1) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+1,x+-3) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+-1,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
if im(y+0,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+-1) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+1) > cb
if im(y+-3,x+-1) > cb
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+1,x+-3) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+1,x+-3) > cb
if im(y+-3,x+1) > cb
else
continue;
end
elseif im(y+1,x+-3) < c_b
continue;
else
if im(y+-3,x+-1) > cb
if im(y+2,x+-2) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+-2) > cb
if im(y+-3,x+-1) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+-1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+2) < c_b
if im(y+3,x+0) > cb
if im(y+0,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+1) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+-3,x+-1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+0) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+0,x+3) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
if im(y+-2,x+2) < c_b
if im(y+-3,x+1) > cb
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+-1) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+1) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+0) > cb
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+0,x+3) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+1,x+3) > cb
if im(y+0,x+3) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+1) < c_b
if im(y+0,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+0) > cb||im(y+3,x+0) < c_b
continue;
else
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) > cb
if im(y+-2,x+-2) > cb
if im(y+1,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+-1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+-1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+0,x+3) < c_b
continue;
else
if im(y+3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+0) < c_b
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+-2) > cb
if im(y+0,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+2,x+2) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+-2,x+2) > cb
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+2,x+2) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) > cb
if im(y+3,x+1) > cb||im(y+3,x+1) < c_b
continue;
else
if im(y+1,x+-3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
if im(y+0,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+3,x+-1) > cb
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+0) < c_b
if im(y+0,x+-3) > cb
if im(y+1,x+3) < c_b
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+-1,x+3) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
else
if im(y+1,x+-3) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+-3) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+-1,x+-3) < c_b
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+-1) < c_b
if im(y+0,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+-3) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+0,x+-3) < c_b
if im(y+-1,x+-3) > cb
if im(y+0,x+3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
if im(y+2,x+-2) > cb
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+-2,x+2) > cb
if im(y+2,x+2) < c_b
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-2,x+2) < c_b
if im(y+1,x+-3) > cb
continue;
elseif im(y+1,x+-3) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
else
if im(y+0,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+1,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+2,x+2) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+3,x+-1) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
else
if im(y+-1,x+3) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+-3,x+1) < c_b
if im(y+1,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
if im(y+1,x+-3) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+1,x+-3) > cb
continue;
elseif im(y+1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+1) < c_b
if im(y+2,x+-2) > cb
continue;
elseif im(y+2,x+-2) < c_b
else
if im(y+-2,x+-2) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+-1) < c_b
if im(y+2,x+-2) > cb
continue;
elseif im(y+2,x+-2) < c_b
else
if im(y+-2,x+-2) < c_b
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
if im(y+1,x+-3) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
if im(y+1,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+2,x+2) < c_b
if im(y+-3,x+1) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+2,x+2) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) > cb
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+2,x+-2) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+3,x+1) > cb||im(y+3,x+1) < c_b
continue;
else
end
else
continue;
end
end
elseif im(y+2,x+2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+1,x+-3) > cb
if im(y+3,x+1) < c_b
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+1,x+3) > cb
continue;
elseif im(y+1,x+3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
if im(y+3,x+-1) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+1) < c_b
if im(y+1,x+3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+1,x+3) > cb
elseif im(y+1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+-1) < c_b
if im(y+1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) > cb
if im(y+0,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+1) > cb
else
continue;
end
elseif im(y+-1,x+-3) < c_b
continue;
else
if im(y+-3,x+1) > cb
if im(y+-2,x+2) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+-1) > cb
else
continue;
end
else
if im(y+-3,x+-1) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+-3,x+1) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-2,x+2) > cb
if im(y+2,x+2) > cb
if im(y+2,x+-2) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+1,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
continue;
else
if im(y+-3,x+1) > cb
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+-3) < c_b
if im(y+0,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) < c_b
if im(y+1,x+-3) < c_b
if im(y+2,x+2) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) > cb
if im(y+-2,x+2) > cb
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+0) < c_b
if im(y+-1,x+-3) > cb
continue;
elseif im(y+-1,x+-3) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
if im(y+-3,x+1) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+-1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+1,x+-3) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
if im(y+-1,x+-3) > cb
continue;
elseif im(y+-1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+1) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+0) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
nc = nc + 1;
if nc > length(cs)
cs(length(cs)*2,1) = 0;
end
cs(nc,1) = x;
cs(nc,2) = y;
end
end
coords = cs([1:nc],:);
|
github
|
rising-turtle/slam_matlab-master
|
fast_corner_detect_9.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/fast-matlab-src/fast_corner_detect_9.m
| 177,871 |
utf_8
|
23105cc2b05a91688c4a17e952fcd7e3
|
%FAST_CORNER_DETECT_9 perform an 9 point FAST corner detection.
% corners = FAST_CORNER_DETECT_9(image, threshold) performs the detection on the image
% and returns the X coordinates in corners(:,1) and the Y coordinares in corners(:,2).
%
% If you use this in published work, please cite:
% Fusing Points and Lines for High Performance Tracking, E. Rosten and T. Drummond, ICCV 2005
% Machine learning for high-speed corner detection, E. Rosten and T. Drummond, ECCV 2006
% The Bibtex entries are:
%
% @inproceedings{rosten_2005_tracking,
% title = "Fusing points and lines for high performance tracking.",
% author = "Edward Rosten and Tom Drummond",
% year = "2005",
% month = "October",
% pages = "1508--1511",
% volume = "2",
% booktitle = "IEEE International Conference on Computer Vision",
% notes = "Oral presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2005_tracking.pdf"
% }
%
% @inproceedings{rosten_2006_machine,
% title = "Machine learning for high-speed corner detection",
% author = "Edward Rosten and Tom Drummond",
% year = "2006",
% month = "May",
% booktitle = "European Conference on Computer Vision (to appear)",
% notes = "Poster presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2006_machine.pdf"
% }
%
%
% Additional information from the generating program:
%
% Automatically generated code
% Parameters:
% splat_subtree = 1
% corner_pointers = 2
% force_first_question = 0
% corner_type = 9
% barrier = 25
%
% Data:
% Number of frames: 120
% Potential features: 25786080
% Real features: 219300
% Questions per pixel: 2.27059
%
%
% See also FAST_NONMAX FAST_CORNER_DETECT_9 FAST_CORNER_DETECT_10 FAST_CORNER_DETECT_11 FAST_CORNER_DETECT_12
%
function coords = fast_corner_detect_9(im, threshold)
sz = size(im);
xsize=sz(2);
ysize=sz(1);
cs = zeros(5000, 2);
nc = 0;
for x = 4 : xsize - 3
for y = 4 : ysize -3
cb = im(y,x) + threshold;
c_b= im(y,x) - threshold;
if im(y+0,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+0) > cb
if im(y+-3,x+-1) > cb
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+3,x+0) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+3,x+0) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+3,x+1) > cb
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+0) > cb
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+3,x+1) > cb
if im(y+1,x+3) > cb
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+-1,x+-3) > cb
else
continue;
end
end
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-1,x+-3) > cb
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+-2) < c_b
if im(y+3,x+-1) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+1) > cb
else
continue;
end
elseif im(y+-2,x+2) < c_b
continue;
else
if im(y+1,x+-3) > cb
else
continue;
end
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
if im(y+-3,x+-1) > cb
if im(y+3,x+1) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+0) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+-1) < c_b
if im(y+3,x+1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+0,x+-3) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+0) > cb
if im(y+3,x+0) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+-3,x+-1) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+1) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
if im(y+3,x+1) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+-1) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+0) > cb
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+-1) > cb
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
continue;
else
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+3,x+0) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-3,x+-1) < c_b
if im(y+3,x+-1) > cb
else
continue;
end
else
if im(y+3,x+-1) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+0) > cb
else
continue;
end
elseif im(y+-2,x+2) < c_b
continue;
else
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+3,x+0) > cb
if im(y+-3,x+0) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
elseif im(y+2,x+2) < c_b
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+0) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+-3) < c_b
if im(y+-1,x+-3) > cb
if im(y+1,x+3) > cb
else
continue;
end
elseif im(y+-1,x+-3) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+-2) < c_b
if im(y+3,x+0) < c_b
if im(y+-1,x+-3) < c_b
if im(y+0,x+-3) < c_b
if im(y+3,x+-1) < c_b
if im(y+3,x+1) < c_b
if im(y+1,x+-3) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+3,x+-1) < c_b
if im(y+3,x+1) < c_b
if im(y+3,x+0) < c_b
if im(y+-2,x+2) > cb
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+-2) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+0,x+-3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+3) > cb
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+2,x+-2) > cb
else
continue;
end
end
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+1) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-2,x+2) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+0) > cb
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+1) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+-3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+3,x+1) < c_b
if im(y+0,x+-3) < c_b
if im(y+3,x+0) < c_b
if im(y+2,x+-2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+1) < c_b
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
if im(y+3,x+1) > cb
if im(y+2,x+2) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+0,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+3,x+-1) > cb
if im(y+2,x+2) > cb
if im(y+1,x+3) > cb
if im(y+3,x+1) > cb
else
continue;
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+-2,x+-2) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+-3) < c_b
if im(y+-1,x+3) > cb
if im(y+-2,x+2) > cb
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+0) > cb||im(y+-3,x+0) < c_b
continue;
else
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+-3) < c_b
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+2) > cb
else
continue;
end
end
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+3,x+-1) > cb
if im(y+-2,x+2) < c_b
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
if im(y+0,x+-3) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
if im(y+1,x+-3) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+-3,x+0) > cb
continue;
elseif im(y+-3,x+0) < c_b
else
if im(y+3,x+1) < c_b
else
continue;
end
end
else
if im(y+2,x+2) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+1,x+3) < c_b
else
continue;
end
end
else
continue;
end
else
if im(y+-2,x+2) < c_b
if im(y+1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+-1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+0,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+1,x+3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+1) > cb
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+0) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+2) < c_b
continue;
else
if im(y+-3,x+-1) > cb
if im(y+0,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+0) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
elseif im(y+2,x+2) < c_b
continue;
else
if im(y+-3,x+-1) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+1) > cb
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+0) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+-2,x+2) > cb
if im(y+1,x+3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+-1) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+3) < c_b
if im(y+0,x+-3) > cb
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+2,x+2) > cb
if im(y+3,x+1) > cb
if im(y+1,x+3) > cb
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+-2,x+-2) > cb
else
continue;
end
end
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+0) > cb
else
continue;
end
end
elseif im(y+2,x+2) < c_b
continue;
else
if im(y+-3,x+-1) > cb
if im(y+3,x+1) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
else
continue;
end
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+0) > cb
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+3,x+0) < c_b
if im(y+-2,x+-2) > cb
if im(y+-1,x+-3) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
if im(y+1,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+0) < c_b
if im(y+-1,x+-3) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+0,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
elseif im(y+0,x+3) < c_b
if im(y+3,x+-1) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+-2) > cb
if im(y+3,x+0) > cb
else
continue;
end
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+1,x+3) > cb
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
continue;
else
if im(y+-1,x+3) > cb
else
continue;
end
end
else
continue;
end
elseif im(y+3,x+1) < c_b
if im(y+-3,x+1) > cb
if im(y+0,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+3,x+0) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
end
else
if im(y+-3,x+1) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+-3,x+0) > cb
if im(y+3,x+0) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
end
else
continue;
end
elseif im(y+-3,x+-1) < c_b
if im(y+1,x+3) > cb
if im(y+0,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+3,x+1) > cb
if im(y+2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
elseif im(y+2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+1) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
if im(y+-2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-2,x+-2) > cb
if im(y+2,x+2) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+-1,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+3,x+0) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+1,x+3) > cb
else
continue;
end
else
if im(y+1,x+3) > cb
if im(y+3,x+1) > cb
if im(y+0,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+2) < c_b
if im(y+3,x+0) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+-3) < c_b
if im(y+1,x+3) > cb
if im(y+0,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+-3,x+0) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
if im(y+3,x+1) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+2,x+2) > cb||im(y+2,x+2) < c_b
continue;
else
if im(y+3,x+1) > cb
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+0) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+2) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+1) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
if im(y+3,x+0) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
if im(y+-2,x+2) > cb
if im(y+0,x+-3) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) > cb
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
end
elseif im(y+0,x+-3) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+1,x+-3) < c_b
if im(y+1,x+3) > cb
continue;
elseif im(y+1,x+3) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+0) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+-1) < c_b
else
continue;
end
end
else
continue;
end
else
if im(y+-3,x+-1) < c_b
else
continue;
end
end
else
if im(y+-1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
if im(y+1,x+3) > cb
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+1) > cb
if im(y+2,x+-2) < c_b
if im(y+3,x+0) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
if im(y+2,x+2) > cb
if im(y+-1,x+-3) < c_b
else
continue;
end
elseif im(y+2,x+2) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
if im(y+3,x+0) > cb
continue;
elseif im(y+3,x+0) < c_b
else
if im(y+-3,x+0) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
end
else
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+0) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+1,x+-3) < c_b
if im(y+-3,x+-1) > cb
elseif im(y+-3,x+-1) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
else
if im(y+-2,x+-2) < c_b
else
continue;
end
end
else
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
end
else
if im(y+3,x+1) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) > cb
continue;
elseif im(y+-3,x+0) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
else
if im(y+2,x+2) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
end
else
if im(y+1,x+-3) < c_b
else
continue;
end
end
else
continue;
end
else
if im(y+1,x+-3) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
if im(y+3,x+0) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+1,x+-3) < c_b
if im(y+-1,x+3) > cb
if im(y+0,x+-3) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+0) > cb
continue;
elseif im(y+3,x+0) < c_b
if im(y+1,x+3) > cb
continue;
elseif im(y+1,x+3) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
else
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-3,x+1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+-3,x+-1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
if im(y+2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+0) < c_b
if im(y+2,x+-2) < c_b
if im(y+1,x+3) > cb
continue;
elseif im(y+1,x+3) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
if im(y+-2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+0) > cb
continue;
elseif im(y+3,x+0) < c_b
if im(y+1,x+3) > cb
continue;
elseif im(y+1,x+3) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
else
if im(y+-3,x+-1) < c_b
else
continue;
end
end
else
if im(y+-2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
else
if im(y+-3,x+1) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+-3,x+-1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+3,x+0) > cb
continue;
elseif im(y+3,x+0) < c_b
else
if im(y+1,x+3) > cb||im(y+1,x+3) < c_b
continue;
else
end
end
else
continue;
end
else
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
else
if im(y+3,x+0) < c_b
if im(y+1,x+3) > cb||im(y+1,x+3) < c_b
continue;
else
if im(y+-2,x+-2) < c_b
else
continue;
end
end
else
continue;
end
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
end
else
if im(y+-3,x+0) > cb
if im(y+-2,x+2) > cb
if im(y+2,x+-2) > cb
if im(y+-1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+0,x+-3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+1,x+-3) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
if im(y+-1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-3,x+0) < c_b
if im(y+2,x+2) > cb
if im(y+0,x+-3) > cb
if im(y+1,x+3) < c_b
if im(y+-1,x+-3) < c_b
else
continue;
end
else
continue;
end
elseif im(y+0,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-1,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+2) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+1) > cb
if im(y+1,x+-3) > cb
continue;
elseif im(y+1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+1,x+3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+1) < c_b
if im(y+1,x+3) > cb
continue;
elseif im(y+1,x+3) < c_b
if im(y+-3,x+-1) > cb
elseif im(y+-3,x+-1) < c_b
if im(y+-3,x+1) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
else
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+3,x+0) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-2,x+-2) < c_b
if im(y+1,x+3) > cb
continue;
elseif im(y+1,x+3) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+0) > cb||im(y+3,x+0) < c_b
continue;
else
if im(y+-3,x+1) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
else
if im(y+1,x+-3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
if im(y+-1,x+-3) < c_b
if im(y+1,x+3) > cb
if im(y+0,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
if im(y+2,x+-2) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
end
else
if im(y+0,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+-1) > cb
if im(y+-3,x+0) > cb
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+1) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+2,x+2) > cb
if im(y+3,x+1) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+1,x+3) > cb
if im(y+3,x+1) > cb
if im(y+3,x+-1) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+-2,x+-2) > cb
else
continue;
end
end
else
continue;
end
else
if im(y+3,x+-1) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+-1) > cb
if im(y+-3,x+0) > cb
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+1) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+2,x+2) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+1,x+3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
if im(y+-3,x+-1) > cb
if im(y+-1,x+3) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+-1) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
if im(y+2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+-2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+2) < c_b
if im(y+3,x+1) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
if im(y+-3,x+-1) > cb
if im(y+3,x+1) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+3,x+0) > cb
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+-1) > cb
else
continue;
end
elseif im(y+2,x+2) < c_b
if im(y+-3,x+-1) > cb
else
continue;
end
else
if im(y+-3,x+-1) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+0) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+-1,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+2,x+2) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
elseif im(y+0,x+-3) < c_b
if im(y+3,x+-1) > cb
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-3,x+0) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+-2,x+2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+-1) > cb
if im(y+1,x+3) > cb
continue;
elseif im(y+1,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+1) < c_b
if im(y+2,x+-2) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+1) < c_b
if im(y+-2,x+2) < c_b
continue;
else
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+-1) < c_b
if im(y+1,x+-3) < c_b
if im(y+2,x+-2) > cb
continue;
elseif im(y+2,x+-2) < c_b
if im(y+3,x+1) > cb
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
else
if im(y+3,x+0) < c_b
else
continue;
end
end
elseif im(y+3,x+1) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
if im(y+3,x+0) > cb
continue;
elseif im(y+3,x+0) < c_b
else
if im(y+-3,x+1) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
end
else
if im(y+1,x+3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
end
else
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
if im(y+3,x+0) < c_b
if im(y+-3,x+0) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
end
else
if im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+2,x+2) < c_b
if im(y+-2,x+-2) > cb
if im(y+1,x+3) < c_b
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+1) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
if im(y+-2,x+2) < c_b
if im(y+1,x+-3) < c_b
if im(y+-1,x+3) > cb
if im(y+2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
nc = nc + 1;
if nc > length(cs)
cs(length(cs)*2,1) = 0;
end
cs(nc,1) = x;
cs(nc,2) = y;
end
end
coords = cs([1:nc],:);
|
github
|
rising-turtle/slam_matlab-master
|
fast_corner_detect_10.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/fast-matlab-src/fast_corner_detect_10.m
| 164,469 |
utf_8
|
219987a5a165436df9ac811d9ec40fdb
|
%FAST_CORNER_DETECT_10 perform an 10 point FAST corner detection.
% corners = FAST_CORNER_DETECT_10(image, threshold) performs the detection on the image
% and returns the X coordinates in corners(:,1) and the Y coordinares in corners(:,2).
%
% If you use this in published work, please cite:
% Fusing Points and Lines for High Performance Tracking, E. Rosten and T. Drummond, ICCV 2005
% Machine learning for high-speed corner detection, E. Rosten and T. Drummond, ECCV 2006
% The Bibtex entries are:
%
% @inproceedings{rosten_2005_tracking,
% title = "Fusing points and lines for high performance tracking.",
% author = "Edward Rosten and Tom Drummond",
% year = "2005",
% month = "October",
% pages = "1508--1511",
% volume = "2",
% booktitle = "IEEE International Conference on Computer Vision",
% notes = "Oral presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2005_tracking.pdf"
% }
%
% @inproceedings{rosten_2006_machine,
% title = "Machine learning for high-speed corner detection",
% author = "Edward Rosten and Tom Drummond",
% year = "2006",
% month = "May",
% booktitle = "European Conference on Computer Vision (to appear)",
% notes = "Poster presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2006_machine.pdf"
% }
%
%
% Additional information from the generating program:
%
% Automatically generated code
% Parameters:
% splat_subtree = 1
% corner_pointers = 2
% force_first_question = 0
% corner_type = 10
% barrier = 25
%
% Data:
% Number of frames: 120
% Potential features: 25786080
% Real features: 136945
% Questions per pixel: 2.41637
%
%
% See also FAST_NONMAX FAST_CORNER_DETECT_9 FAST_CORNER_DETECT_10 FAST_CORNER_DETECT_11 FAST_CORNER_DETECT_12
%
function coords = fast_corner_detect_10(im, threshold)
sz = size(im);
xsize=sz(2);
ysize=sz(1);
cs = zeros(5000, 2);
nc = 0;
for x = 4 : xsize - 3
for y = 4 : ysize -3
cb = im(y,x) + threshold;
c_b= im(y,x) - threshold;
if im(y+-3,x+-1) > cb
if im(y+2,x+2) > cb
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+1) > cb
if im(y+-3,x+0) > cb
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+2,x+-2) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+0) < c_b
if im(y+-1,x+-3) > cb
if im(y+-3,x+0) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
if im(y+3,x+1) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
if im(y+3,x+1) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+3,x+0) > cb
else
continue;
end
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+3,x+0) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
if im(y+0,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+-1) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+1) > cb
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+1) > cb
else
continue;
end
end
elseif im(y+-1,x+-3) < c_b
continue;
else
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+0,x+3) < c_b
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+0,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+-1) > cb
if im(y+3,x+1) > cb
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+1) > cb
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+-1,x+3) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+-2,x+2) > cb
if im(y+3,x+1) > cb
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+3,x+-1) > cb
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+-2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+3,x+1) > cb
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+1) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+-2,x+2) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
if im(y+-1,x+3) > cb
else
continue;
end
else
if im(y+-1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+0) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+2) < c_b
if im(y+2,x+-2) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+3) > cb
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+0) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+3,x+-1) > cb
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+-1) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+0,x+-3) > cb
if im(y+-3,x+0) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
if im(y+3,x+1) > cb
if im(y+-3,x+0) > cb
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+1) < c_b
continue;
else
if im(y+-3,x+1) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+3,x+0) > cb
if im(y+0,x+-3) > cb
if im(y+-3,x+0) > cb
if im(y+-2,x+-2) > cb
if im(y+3,x+-1) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+1,x+-3) > cb
else
continue;
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+3,x+1) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
if im(y+-1,x+3) > cb
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+0,x+3) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
if im(y+1,x+-3) > cb
if im(y+0,x+3) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+0,x+-3) < c_b
if im(y+0,x+3) < c_b
if im(y+-1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) < c_b
if im(y+-1,x+-3) < c_b
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+3) < c_b
if im(y+1,x+-3) > cb
if im(y+-3,x+1) < c_b
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+-2,x+2) > cb
if im(y+0,x+-3) < c_b
if im(y+3,x+0) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+2) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+0,x+3) < c_b
if im(y+3,x+0) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+0,x+3) > cb
continue;
elseif im(y+0,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
else
if im(y+-2,x+-2) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
if im(y+-3,x+1) < c_b
if im(y+3,x+-1) < c_b
if im(y+-2,x+2) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+-3) < c_b
if im(y+0,x+3) > cb
continue;
elseif im(y+0,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+3,x+0) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) > cb
if im(y+3,x+1) < c_b
if im(y+1,x+3) < c_b
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+1,x+3) < c_b
else
continue;
end
end
else
continue;
end
end
else
continue;
end
end
else
if im(y+0,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+-3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+3,x+1) > cb
else
continue;
end
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
continue;
else
if im(y+1,x+3) > cb
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+-2,x+2) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
if im(y+1,x+-3) > cb
elseif im(y+1,x+-3) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
if im(y+0,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+-2) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
else
if im(y+1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+0,x+3) < c_b
continue;
else
if im(y+2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
else
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+2,x+-2) > cb
if im(y+-1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+0) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
continue;
else
if im(y+1,x+3) > cb
if im(y+0,x+3) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+1,x+3) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+1,x+-3) > cb
if im(y+0,x+3) > cb
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
continue;
else
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+0) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
elseif im(y+-3,x+-1) < c_b
if im(y+3,x+1) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+0,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+2,x+2) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+2) < c_b
if im(y+0,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+0,x+3) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
else
if im(y+2,x+-2) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+0,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+2,x+2) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
else
if im(y+2,x+-2) > cb
else
continue;
end
end
elseif im(y+0,x+3) < c_b
continue;
else
if im(y+-1,x+-3) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+-3) < c_b
if im(y+-3,x+1) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
if im(y+3,x+-1) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+1) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+0,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+3) < c_b
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+0,x+3) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
if im(y+-2,x+-2) > cb
if im(y+1,x+3) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+-3) < c_b
if im(y+2,x+2) > cb
if im(y+1,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+2) < c_b
if im(y+-3,x+1) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+1,x+3) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) > cb
if im(y+0,x+3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+0,x+-3) > cb
continue;
elseif im(y+0,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
if im(y+0,x+3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+2) < c_b
if im(y+-3,x+1) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+0,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+3) < c_b
continue;
else
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
if im(y+3,x+-1) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+1) < c_b
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+1) < c_b
if im(y+0,x+3) > cb
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+-3,x+0) > cb
if im(y+2,x+2) < c_b
else
continue;
end
elseif im(y+-3,x+0) < c_b
if im(y+-2,x+-2) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+3,x+0) > cb
continue;
elseif im(y+3,x+0) < c_b
else
if im(y+-2,x+2) < c_b
else
continue;
end
end
else
if im(y+-1,x+3) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+3,x+-1) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+3) < c_b
if im(y+-2,x+2) > cb
if im(y+0,x+-3) < c_b
if im(y+3,x+-1) < c_b
if im(y+-1,x+3) > cb
if im(y+2,x+2) < c_b
else
continue;
end
elseif im(y+-1,x+3) < c_b
else
if im(y+-3,x+0) > cb
continue;
elseif im(y+-3,x+0) < c_b
else
if im(y+2,x+2) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
end
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+2) < c_b
if im(y+1,x+3) > cb
if im(y+0,x+-3) < c_b
if im(y+1,x+-3) < c_b
if im(y+-1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+3,x+0) > cb
elseif im(y+3,x+0) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
if im(y+-3,x+0) > cb
continue;
elseif im(y+-3,x+0) < c_b
else
if im(y+2,x+-2) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+-2) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+3,x+-1) < c_b
if im(y+1,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+-3,x+1) > cb
continue;
elseif im(y+-3,x+1) < c_b
else
if im(y+2,x+2) < c_b
else
continue;
end
end
else
if im(y+3,x+-1) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+3,x+-1) < c_b
if im(y+1,x+-3) < c_b
if im(y+-1,x+-3) > cb
continue;
elseif im(y+-1,x+-3) < c_b
if im(y+3,x+0) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
else
if im(y+1,x+3) < c_b
else
continue;
end
end
else
if im(y+-3,x+0) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+-1,x+3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) > cb
elseif im(y+-3,x+0) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+3,x+0) > cb
continue;
elseif im(y+3,x+0) < c_b
else
if im(y+-2,x+2) < c_b
else
continue;
end
end
else
if im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+2,x+2) < c_b
if im(y+3,x+-1) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+-3) < c_b
if im(y+3,x+-1) > cb
if im(y+1,x+3) > cb
if im(y+1,x+-3) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+0,x+3) > cb
continue;
elseif im(y+0,x+3) < c_b
if im(y+-3,x+0) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
if im(y+-3,x+1) < c_b
if im(y+0,x+-3) > cb
if im(y+2,x+2) < c_b
else
continue;
end
elseif im(y+0,x+-3) < c_b
if im(y+2,x+-2) > cb
continue;
elseif im(y+2,x+-2) < c_b
if im(y+-2,x+2) > cb
if im(y+3,x+0) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+2) < c_b
if im(y+1,x+-3) > cb
continue;
elseif im(y+1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+3,x+0) < c_b
if im(y+-2,x+-2) < c_b
if im(y+1,x+-3) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+-3) > cb
if im(y+1,x+3) < c_b
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
if im(y+1,x+3) < c_b
if im(y+-1,x+3) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+0,x+3) > cb
if im(y+-1,x+3) < c_b
if im(y+2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
if im(y+1,x+-3) < c_b
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+1,x+3) > cb
if im(y+1,x+-3) < c_b
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) > cb
if im(y+0,x+-3) < c_b
else
continue;
end
elseif im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+0) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+0) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+1,x+-3) < c_b
if im(y+0,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+1,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
end
else
continue;
end
end
else
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+-2,x+2) > cb
if im(y+0,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
continue;
else
if im(y+-3,x+0) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+-3,x+0) > cb
if im(y+2,x+2) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+1) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+0) < c_b
continue;
else
if im(y+2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-3,x+1) > cb
if im(y+2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+1) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+-3,x+0) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
if im(y+-3,x+0) > cb
if im(y+2,x+2) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
elseif im(y+0,x+3) < c_b
if im(y+0,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+2) < c_b
if im(y+-1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+0,x+3) > cb
if im(y+-3,x+0) < c_b
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+0) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+3) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+-3) > cb
elseif im(y+-1,x+-3) < c_b
continue;
else
if im(y+-1,x+3) > cb
if im(y+0,x+3) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+-2) < c_b
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+0,x+3) > cb
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+-1,x+-3) > cb
if im(y+0,x+3) > cb
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+1) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+-1,x+-3) > cb
else
continue;
end
else
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+-1,x+3) > cb
if im(y+-2,x+-2) < c_b
if im(y+-3,x+0) > cb
if im(y+2,x+-2) < c_b
else
continue;
end
elseif im(y+-3,x+0) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+3,x+0) < c_b
if im(y+1,x+-3) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+1,x+-3) > cb
if im(y+-3,x+0) > cb
continue;
elseif im(y+-3,x+0) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+0,x+3) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+-3) < c_b
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
elseif im(y+-2,x+2) < c_b
if im(y+0,x+3) > cb
continue;
elseif im(y+0,x+3) < c_b
if im(y+3,x+1) < c_b
if im(y+2,x+-2) > cb
continue;
elseif im(y+2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
if im(y+-3,x+0) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+0) < c_b
if im(y+0,x+3) > cb
if im(y+2,x+2) < c_b
else
continue;
end
elseif im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
if im(y+-2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-3,x+1) < c_b
if im(y+0,x+3) < c_b
if im(y+2,x+-2) > cb
if im(y+-1,x+-3) > cb
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+1) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+0) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+0) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+-3) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+0) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
nc = nc + 1;
if nc > length(cs)
cs(length(cs)*2,1) = 0;
end
cs(nc,1) = x;
cs(nc,2) = y;
end
end
coords = cs([1:nc],:);
|
github
|
rising-turtle/slam_matlab-master
|
fast_nonmax.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/fast-matlab-src/fast_nonmax.m
| 2,828 |
utf_8
|
d1862ded31ac358dc7d19418039cb6ea
|
% FAST_NONMAX perform non-maximal suppression on FAST features.
%
% nonmax = FAST_NONMAX(image, threshold, FAST_CORNER_DETECT_9(image, threshold));
% returns a list of nonmaximally suppressed corners with the X coordinate
% in nonmax(:,1) and Y in nonmax(:,2).
%
% If you use this in published work, please cite:
% Fusing Points and Lines for High Performance Tracking, E. Rosten and T. Drummond, ICCV 2005
% Machine learning for high-speed corner detection, E. Rosten and T. Drummond, ECCV 2006
% The Bibtex entries are:
%
% @inproceedings{rosten_2005_tracking,
% title = "Fusing points and lines for high performance tracking.",
% author = "Edward Rosten and Tom Drummond",
% year = "2005",
% month = "October",
% pages = "1508--1511",
% volume = "2",
% booktitle = "IEEE International Conference on Computer Vision",
% notes = "Oral presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2005_tracking.pdf"
% }
%
% @inproceedings{rosten_2006_machine,
% title = "Machine learning for high-speed corner detection",
% author = "Edward Rosten and Tom Drummond",
% year = "2006",
% month = "May",
% booktitle = "European Conference on Computer Vision (to appear)",
% notes = "Poster presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2006_machine.pdf"
% }
%
%
%
% See also FAST_CORNER_DETECT_9, FAST_CORNER_DETECT_10
% FAST_CORNER_DETECT_11, FAST_CORNER_DETECT_12
function ret = fast_nonmax(im, barrier, c)
sz = size(im);
ysize = sz(1);
% x, y
dir=[ 0,3
1,3
2,2
3,1
3,0
3,-1
2,-2
1,-3
0,-3
-1,-3
-2,-2
-3,-1
-3,0
-3,1
-2,2
-1,3];
dir = dir(:,2) + dir(:,1) * ysize;
centres = c(:,2) + (c(:,1)-1) * ysize;
%First pass: compute scores for all of the pixels:
scores = zeros(sz(1) * sz(2), 1);
for i=1:length(centres)
p1 = im(centres(i)+dir) -( im(centres(i)) + barrier);
pos = sum(p1 .* (p1 > 0));
n1 = im(centres(i)) - barrier - im(centres(i)+dir);
neg = sum(n1 .* (n1 > 0));
scores(centres(i)) = max([pos neg]);
end
cs = zeros(length(centres),1);
up = -1;
down = 1;
left =-ysize;
right = ysize;
%second pass: get local maxima
for i=1:length(centres)
p = centres(i);
square=p + [ up down left right up+left up+right down+left down+right];
cs(i) = (sum(scores(p) >= scores(square)) == 8);
end
%Get the maxima positions
maximas = centres(find(cs));
ret = zeros(length(maximas), 2);
ret(:,1) = 1 + floor(maximas / ysize);
ret(:,2) = mod(maximas, ysize);
|
github
|
rising-turtle/slam_matlab-master
|
fast_corner_detect_11.m
|
.m
|
slam_matlab-master/libs_dir/ekfmonoslam/trunk/matlab_code/fast-matlab-src/fast_corner_detect_11.m
| 132,321 |
utf_8
|
ae44e523c1f863bcd9e42e13bb4612d2
|
%FAST_CORNER_DETECT_11 perform an 11 point FAST corner detection.
% corners = FAST_CORNER_DETECT_11(image, threshold) performs the detection on the image
% and returns the X coordinates in corners(:,1) and the Y coordinares in corners(:,2).
%
% If you use this in published work, please cite:
% Fusing Points and Lines for High Performance Tracking, E. Rosten and T. Drummond, ICCV 2005
% Machine learning for high-speed corner detection, E. Rosten and T. Drummond, ECCV 2006
% The Bibtex entries are:
%
% @inproceedings{rosten_2005_tracking,
% title = "Fusing points and lines for high performance tracking.",
% author = "Edward Rosten and Tom Drummond",
% year = "2005",
% month = "October",
% pages = "1508--1511",
% volume = "2",
% booktitle = "IEEE International Conference on Computer Vision",
% notes = "Oral presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2005_tracking.pdf"
% }
%
% @inproceedings{rosten_2006_machine,
% title = "Machine learning for high-speed corner detection",
% author = "Edward Rosten and Tom Drummond",
% year = "2006",
% month = "May",
% booktitle = "European Conference on Computer Vision (to appear)",
% notes = "Poster presentation",
% url = "http://mi.eng.cam.ac.uk/~er258/work/rosten_2006_machine.pdf"
% }
%
%
% Additional information from the generating program:
%
% Automatically generated code
% Parameters:
% splat_subtree = 1
% corner_pointers = 2
% force_first_question = 0
% corner_type = 11
% barrier = 25
%
% Data:
% Number of frames: 120
% Potential features: 25786080
% Real features: 93213
% Questions per pixel: 2.37184
%
%
% See also FAST_NONMAX FAST_CORNER_DETECT_9 FAST_CORNER_DETECT_10 FAST_CORNER_DETECT_11 FAST_CORNER_DETECT_12
%
function coords = fast_corner_detect_11(im, threshold)
sz = size(im);
xsize=sz(2);
ysize=sz(1);
cs = zeros(5000, 2);
nc = 0;
for x = 4 : xsize - 3
for y = 4 : ysize -3
cb = im(y,x) + threshold;
c_b= im(y,x) - threshold;
if im(y+-3,x+0) > cb
if im(y+3,x+1) > cb
if im(y+0,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+-1) > cb
if im(y+-1,x+3) > cb
if im(y+2,x+2) > cb
if im(y+-3,x+-1) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+0) > cb
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+-1,x+-3) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-3,x+-1) < c_b
continue;
else
if im(y+2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+0) > cb
else
continue;
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+0,x+-3) > cb
else
continue;
end
end
else
continue;
end
end
elseif im(y+2,x+2) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+-1) < c_b
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
continue;
else
if im(y+3,x+0) > cb
else
continue;
end
end
else
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+2,x+2) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
elseif im(y+2,x+2) < c_b
continue;
else
if im(y+1,x+-3) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
if im(y+-2,x+-2) > cb
if im(y+3,x+0) > cb
if im(y+2,x+-2) > cb
if im(y+2,x+2) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+-3,x+1) > cb
else
continue;
end
else
if im(y+-1,x+3) > cb
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+0) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+3) > cb
if im(y+2,x+2) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
end
elseif im(y+-2,x+2) < c_b
if im(y+0,x+-3) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+2,x+-2) > cb
if im(y+-1,x+-3) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+2,x+2) > cb
if im(y+-2,x+-2) > cb
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+-1,x+3) > cb
else
continue;
end
end
elseif im(y+2,x+2) < c_b
continue;
else
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+3) < c_b
if im(y+1,x+-3) > cb
if im(y+2,x+2) < c_b
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+-1) > cb
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+-2,x+2) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+2,x+2) > cb
if im(y+3,x+0) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+0,x+3) < c_b
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+-2) > cb
if im(y+2,x+2) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+2) < c_b
if im(y+-3,x+1) > cb
if im(y+3,x+-1) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+-1) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+3,x+-1) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+0) > cb
elseif im(y+3,x+0) < c_b
continue;
else
if im(y+-1,x+3) > cb
if im(y+-2,x+2) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+2,x+2) > cb
if im(y+-3,x+-1) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+1) < c_b
if im(y+3,x+-1) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+3,x+0) > cb
if im(y+-2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
if im(y+0,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
if im(y+0,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+-2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
continue;
else
if im(y+2,x+2) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+3) < c_b
continue;
else
if im(y+2,x+-2) > cb
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+0,x+-3) < c_b
if im(y+0,x+3) > cb
if im(y+-3,x+-1) < c_b
if im(y+1,x+3) < c_b
else
continue;
end
else
continue;
end
elseif im(y+0,x+3) < c_b
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-2,x+2) < c_b
if im(y+1,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+-3) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-1,x+-3) < c_b
if im(y+-1,x+3) > cb
continue;
elseif im(y+-1,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
if im(y+-2,x+-2) < c_b
else
continue;
end
end
else
continue;
end
end
else
if im(y+-3,x+-1) < c_b
else
continue;
end
end
else
if im(y+-3,x+1) < c_b
else
continue;
end
end
else
if im(y+0,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+3,x+0) > cb||im(y+3,x+0) < c_b
continue;
else
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+-3,x+-1) > cb
else
continue;
end
else
if im(y+-2,x+2) > cb
if im(y+-3,x+1) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+2,x+-2) < c_b
continue;
else
if im(y+1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+0,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+-3) > cb
if im(y+-1,x+3) > cb
if im(y+1,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+0,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
continue;
else
if im(y+2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+0,x+3) < c_b
continue;
else
if im(y+3,x+-1) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+3,x+-1) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+-1) > cb
if im(y+1,x+-3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+3,x+-1) > cb
if im(y+2,x+-2) > cb
if im(y+-1,x+-3) > cb
if im(y+-2,x+2) > cb
if im(y+1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+3,x+-1) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+-2,x+-2) > cb
if im(y+-3,x+1) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+-1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
end
elseif im(y+-1,x+3) < c_b
if im(y+-2,x+2) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+0) > cb
if im(y+-2,x+2) > cb
if im(y+-1,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+1,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+-2,x+-2) > cb
if im(y+3,x+-1) > cb
if im(y+-3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
elseif im(y+-3,x+0) < c_b
if im(y+3,x+0) > cb
if im(y+1,x+3) > cb
if im(y+-1,x+-3) > cb
if im(y+-1,x+3) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
if im(y+2,x+2) > cb
if im(y+0,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+1,x+-3) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+3) < c_b
continue;
else
if im(y+-2,x+-2) > cb
if im(y+0,x+3) > cb
if im(y+1,x+-3) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+-2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+-3) < c_b
if im(y+0,x+3) > cb
if im(y+0,x+-3) > cb
if im(y+-2,x+2) > cb
else
continue;
end
else
continue;
end
elseif im(y+0,x+3) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+-1) > cb||im(y+3,x+-1) < c_b
continue;
else
if im(y+-2,x+2) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+-2,x+2) > cb
if im(y+0,x+-3) > cb
if im(y+0,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+-1,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+1,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+-3) > cb
continue;
elseif im(y+1,x+-3) < c_b
if im(y+-1,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+0,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+2) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+0,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+3,x+0) < c_b
if im(y+0,x+-3) > cb
if im(y+1,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+-2) > cb
if im(y+2,x+-2) > cb
if im(y+-3,x+-1) < c_b
if im(y+3,x+-1) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+-2,x+2) < c_b
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+-3,x+-1) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+-1) < c_b
if im(y+2,x+2) < c_b
if im(y+0,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-2,x+-2) < c_b
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+-3,x+1) < c_b
if im(y+3,x+1) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+3,x+-1) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+0,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+0,x+3) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+-3) < c_b
if im(y+-1,x+-3) > cb
if im(y+0,x+3) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
if im(y+2,x+-2) > cb
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+2,x+-2) < c_b
if im(y+1,x+-3) > cb
continue;
elseif im(y+1,x+-3) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
if im(y+-3,x+1) > cb
if im(y+2,x+2) < c_b
else
continue;
end
elseif im(y+-3,x+1) < c_b
if im(y+3,x+1) > cb
continue;
elseif im(y+3,x+1) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
else
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-2,x+2) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
if im(y+0,x+3) < c_b
else
continue;
end
end
else
continue;
end
end
else
if im(y+2,x+2) < c_b
if im(y+3,x+-1) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
else
if im(y+0,x+3) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-2,x+-2) > cb
continue;
elseif im(y+-2,x+-2) < c_b
else
if im(y+3,x+-1) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+3,x+1) < c_b
if im(y+2,x+-2) > cb
continue;
elseif im(y+2,x+-2) < c_b
else
if im(y+-3,x+-1) < c_b
else
continue;
end
end
else
continue;
end
else
if im(y+-2,x+-2) < c_b
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+0,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+3,x+-1) > cb
continue;
elseif im(y+3,x+-1) < c_b
if im(y+-3,x+-1) > cb
continue;
elseif im(y+-3,x+-1) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-2,x+-2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-1,x+-3) < c_b
if im(y+0,x+3) > cb
if im(y+-1,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+1,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+3) < c_b
if im(y+1,x+3) > cb
if im(y+2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+1) > cb
if im(y+0,x+-3) < c_b
if im(y+1,x+-3) > cb
continue;
elseif im(y+1,x+-3) < c_b
if im(y+-1,x+3) < c_b
else
continue;
end
else
if im(y+2,x+2) < c_b
else
continue;
end
end
else
continue;
end
elseif im(y+3,x+1) < c_b
if im(y+-3,x+1) < c_b
if im(y+2,x+2) > cb
continue;
elseif im(y+2,x+2) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+1,x+-3) > cb
if im(y+2,x+2) < c_b
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+2,x+2) < c_b
if im(y+-3,x+1) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
if im(y+2,x+-2) < c_b
if im(y+0,x+-3) < c_b
if im(y+-2,x+2) < c_b
if im(y+1,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-3,x+-1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+3,x+-1) < c_b
if im(y+-1,x+3) < c_b
if im(y+0,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+1,x+-3) < c_b
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-2,x+-2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
if im(y+1,x+-3) > cb
if im(y+1,x+3) > cb
if im(y+3,x+-1) > cb
if im(y+-1,x+-3) > cb
if im(y+-3,x+-1) > cb
if im(y+2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+2,x+2) > cb
if im(y+-2,x+-2) > cb
if im(y+3,x+1) > cb
else
continue;
end
elseif im(y+-2,x+-2) < c_b
continue;
else
if im(y+0,x+3) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+-3) < c_b
continue;
else
if im(y+-3,x+1) > cb
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+-3,x+-1) < c_b
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+3) > cb
if im(y+3,x+1) > cb
if im(y+2,x+-2) > cb
if im(y+0,x+-3) > cb
if im(y+2,x+2) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+-2,x+-2) > cb
else
continue;
end
else
if im(y+-2,x+-2) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
end
else
continue;
end
elseif im(y+0,x+-3) < c_b
continue;
else
if im(y+-3,x+1) > cb
if im(y+-2,x+2) > cb
if im(y+2,x+2) > cb
if im(y+-1,x+3) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
end
elseif im(y+-1,x+-3) < c_b
if im(y+-3,x+1) > cb
if im(y+-1,x+3) > cb
if im(y+0,x+3) > cb
if im(y+-2,x+2) > cb
if im(y+3,x+1) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+-2,x+2) > cb
if im(y+0,x+-3) > cb
if im(y+0,x+3) > cb
else
continue;
end
else
continue;
end
else
continue;
end
end
else
if im(y+-2,x+2) > cb
if im(y+0,x+3) > cb
if im(y+-3,x+1) > cb
if im(y+3,x+1) > cb
if im(y+-1,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+2,x+2) > cb
if im(y+3,x+0) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-3,x+1) < c_b
continue;
else
if im(y+0,x+-3) > cb
if im(y+3,x+0) > cb
if im(y+-1,x+3) > cb
if im(y+2,x+-2) > cb
if im(y+2,x+2) > cb
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
elseif im(y+1,x+-3) < c_b
if im(y+0,x+3) > cb
if im(y+1,x+3) < c_b
if im(y+-3,x+-1) < c_b
if im(y+-1,x+-3) < c_b
if im(y+3,x+1) < c_b
if im(y+-3,x+1) > cb||im(y+-3,x+1) < c_b
else
if im(y+-2,x+-2) < c_b
if im(y+3,x+-1) < c_b
if im(y+2,x+2) < c_b
if im(y+0,x+-3) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+0,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+-1,x+-3) > cb
if im(y+-3,x+1) < c_b
if im(y+-2,x+2) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+3) < c_b
if im(y+2,x+-2) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
elseif im(y+-1,x+-3) < c_b
if im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
if im(y+0,x+-3) > cb
continue;
elseif im(y+0,x+-3) < c_b
if im(y+3,x+0) < c_b
if im(y+-1,x+3) > cb
if im(y+1,x+3) < c_b
else
continue;
end
elseif im(y+-1,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
if im(y+-2,x+-2) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
if im(y+-3,x+1) < c_b
if im(y+-1,x+3) < c_b
if im(y+1,x+3) < c_b
if im(y+-2,x+2) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
else
continue;
end
else
if im(y+-2,x+2) < c_b
if im(y+-3,x+1) > cb
elseif im(y+-3,x+1) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+1) < c_b
if im(y+2,x+-2) < c_b
if im(y+-1,x+3) < c_b
if im(y+3,x+0) < c_b
if im(y+2,x+2) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
if im(y+0,x+-3) < c_b
if im(y+2,x+2) < c_b
if im(y+2,x+-2) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+0) < c_b
if im(y+-1,x+3) < c_b
if im(y+3,x+1) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
else
continue;
end
else
if im(y+-3,x+-1) < c_b
if im(y+1,x+3) < c_b
if im(y+3,x+-1) < c_b
if im(y+0,x+-3) < c_b
if im(y+-2,x+-2) < c_b
if im(y+2,x+2) < c_b
if im(y+-1,x+-3) < c_b
if im(y+2,x+-2) < c_b
if im(y+3,x+1) < c_b
if im(y+3,x+0) < c_b
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
else
continue;
end
end
else
continue;
end
end
nc = nc + 1;
if nc > length(cs)
cs(length(cs)*2,1) = 0;
end
cs(nc,1) = x;
cs(nc,2) = y;
end
end
coords = cs([1:nc],:);
|
github
|
rising-turtle/slam_matlab-master
|
getCell.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/DetectionMatching/getCell.m
| 1,456 |
utf_8
|
d3772727968d41dc0620d7764df1aa47
|
%GETCELL Get image cell corresopnding to a given pixel.
function imCell = getCell(u,imGrid)
imCell = ceil(u.*imGrid.numCells./imGrid.imSize);
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
maxParab.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/DetectionMatching/maxParab.m
| 1,525 |
utf_8
|
0d579e9bfdf5048f4c6c8f48955d7b1f
|
% MAXPARAB Get the maximum point of a parabole defined by 3 points.
function xm = maxParab(yc,yl,yr)
a = (yl+yr)/2-yc;
b = (yr-yl)/2;
% c = yc; % not used
if abs(a) > eps
xm = -b/2/a;
else
xm = 0;
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
maxParab2.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/DetectionMatching/maxParab2.m
| 1,494 |
utf_8
|
67e9667499a2e12fd4f877bd316142f0
|
% MAXPARAB2 Maximum point of a 2D parabolloid.
function xm = maxParab2(yc,yl,yr,yu,yd)
% MAXPARAB2(YC,YW,YE,YN,YS)
hm = maxParab(yc,yl,yr);
vm = maxParab(yc,yu,yd);
xm = [hm;vm];
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
moreindatatip.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/Graphics/moreindatatip.m
| 3,321 |
utf_8
|
6ca2377164cb495f4eb5db359677cc17
|
function moreindatatip
% MOREINDATATIP Display index information in the data tip.
%
% Extends the displayed text of the datatip to get the index of the clicked
% point. The extension remains until the figure is deleted. If datatip(s)
% was previously present, a message prompts the user to right-click on the
% figure to delete all datatips in order to switch on the capabilities of
% the datatip.
%
% may 2006
% [email protected]
dcm_obj = datacursormode(gcf);
if ~isempty(findall(gca,'type','hggroup','marker','square'))% if there is datatip, please delete it
info_struct = getCursorInfo(dcm_obj);
xdat=get(info_struct.Target,'xdata');
ydat=get(info_struct.Target,'ydata');
zdat=get(info_struct.Target,'zdata');
if isempty(zdat),zdat=zeros(size(xdat));set(info_struct.Target,'zdata',zdat),end
index=info_struct.DataIndex;
ht=text(xdat(index)*1.05,ydat(index)*1.05,zdat(index)*1.05,...
{'right-click on the figure';'to ''delete all datatips''';'in order to get more'},...
'backgroundcolor',[1,0,0.5],'tag','attention');
end
set(dcm_obj,'enable','on','updatefcn',@myupdatefcn,'displaystyle','datatip')
%-------------------------------------------------------------------------%
function txt = myupdatefcn(empt,event_obj)
% Change the text displayed in the datatip. Note than the actual coordinates
% are displyed rather the position field of the info_struct.
ht=findobj('tag','attention');
if ~isempty(ht),delete(ht),end
dcm_obj = datacursormode(gcf);
info_struct = getCursorInfo(dcm_obj);
xdat=get(info_struct.Target,'xdata');
ydat=get(info_struct.Target,'ydata');
zdat=get(info_struct.Target,'zdata');
index=info_struct.DataIndex;
if isempty(zdat)
txt = {['X: ',num2str(xdat(index))],...
['Y: ',num2str(ydat(index))],...
['index: ',num2str(index)]};
else
txt = {['X: ',num2str(xdat(index))],...
['Y: ',num2str(ydat(index))],...
['Z: ',num2str(zdat(index))],...
['index: ',num2str(index)]};
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
addFrmToTrj.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/Slam/addFrmToTrj.m
| 4,618 |
utf_8
|
530847fdf69755b8c21a29784e40ee12
|
function [Lmk,Trj,Frm,Fac] = addFrmToTrj(Lmk,Trj,Frm,Fac)
% ADDFRMTOTRJ Add frame to trajectory
% [Trj,Frm,Fac] = ADDFRMTOTRJ(Trj,Frm,Fac) Adds a frame to the trajectory
% Trj. It does so by advancing the HEAD pointer in the trajectory Trj,
% and clearing sensitive data in the frame pointed by the new HEAD.
%
% The trajectory is a circular array, so when all positions are full,
% adding a new frame overwrites the oldest one. In such case, all factors
% linking to the discarded frame are cleared.
%
% The added frame is empty, and only its ID is created, distinct to all
% other IDs.
% Advance HEAD
Trj.head = mod(Trj.head, Trj.maxLength) + 1;
% Update TAIL
if Trj.length < Trj.maxLength
% Trj is not yet full. Just lengthen.
Trj.length = Trj.length + 1;
else
% Trj is full. Tail frame will be overwritten !!
% Remove tail frame and cleanup graph
[Lmk,Trj,Frm,Fac] = removeTailFrm(Lmk,Trj,Frm,Fac);
% Advance TAIL
Trj.tail = mod(Trj.tail, Trj.maxLength) + 1;
end
% Complete the new frame with no factors
Frm(Trj.head).used = true;
Frm(Trj.head).id = newId;
Frm(Trj.head).factors = [];
% Query and Block positions in Map
r = newRange(Frm(Trj.head).state.dsize);
blockRange(r);
Frm(Trj.head).state.r = r;
end
function [Lmk,Trj,Frm,Fac] = removeTailFrm(Lmk,Trj,Frm,Fac)
% REMOVETAILFRM Remove tail frame from trajectory.
%
% [Lmk,Trj,Frm,Fac] = REMOVETAILFRM(Lmk,Trj,Frm,Fac) removes the tail
% frame from Trj and cleans up all the information in Lmk(:), Frm(:,:),
% Fac(:) that has been affected.
%
% The motionh factor linking this frams to the next one is convertede to
% an absolute factor.
global Map
% Delete factors from factors lists in Frm and Lmk
factors = Frm(Trj.tail).factors;
for fac = factors
if strcmp(Fac(fac).type, 'motion')
% Convert motion factor to absolute factor
% fprintf('Converting Fac ''%d''.\n', fac)
newTail = Fac(fac).frames(2);
[Frm(newTail),Fac(fac)] = makeAbsFactorFromMotionFactor(Frm(newTail),Fac(fac));
else
% Delete factor after cleaning up graph
for frm = [Fac(fac).frames];
% Remove this factor from frame's factors list
Frm(frm).factors([Frm(frm).factors] == fac) = [];
end
for lmk = [Fac(fac).lmk]
% Remove this factor from landmark's factors list
Lmk(lmk).factors([Lmk(lmk).factors] == fac) = [];
% Delete landmark if no factors support it
if isempty(Lmk(lmk).factors)
% fprintf('Deleting Lmk ''%d''.\n', lmk)
Lmk(lmk).used = false;
Map.used(Lmk(lmk).state.r) = false;
end
end
% Free (and cleanup just in case) factors from tail before advancing
% fprintf('Deleting Fac ''%d''.\n', fac)
Fac(fac).used = false;
Fac(fac).frames = [];
Fac(fac).lmk = [];
end
end
% [Fac(factors).used] = deal(false);
% [Fac(factors).frames] = deal([]);
% [Fac(factors).lmk] = deal([]);
% Clean discarded tail frame
Frm(Trj.tail).used = false;
Frm(Trj.tail).factors = [];
% Unblock positions in Map
Map.used(Frm(Trj.tail).state.r) = false;
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
solveGraphSchur.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/InterfaceLevel/solveGraphSchur.m
| 5,056 |
utf_8
|
5fa972e55263bf248f4c017f2c6decdb
|
function [Rob,Sen,Lmk,Obs,Frm,Fac] = solveGraphSchur(Rob,Sen,Lmk,Obs,Frm,Fac,options)
% SOLVEGRAPHSCHUR Solves the SLAM graph using Schur decomposition.
% [Rob,Sen,Lmk,Obs,Frm,Fac] = solveGraphSchur(Rob,Sen,Lmk,Obs,Frm,Fac)
% solves the graph-SLAM problem using Schur decomposition of the
% Hessian matrix.
%
% IMPORTANT NOTE: This method is illustrative and constitutes the
% motivation for this toolbox. One can achieve better performances, both
% in computing time and possibly in robustness and accuracy, by using
% Matlab's built-in nonlinear optimization tools, such as LSQNONLIN.
%
% See courseSLAM.pdf in the documentation for details about the Schur
% decomposition for solving the graph-SLAM problem.
%
% See also ERRORSTATEJACOBIANS, UPDATESTATES, COMPUTEERROR,
% COMPUTERESIDUAL, COLAMD, '\', MLDIVIDE, LSQNONLIN.
% Copyright 2015- Joan Sola @ IRI-UPC-CSIC.
global Map
% Control of iterations and exit conditions
n_iter = options.niterations; % exit criterion of number of iterations
target_dres = options.target_dres; % exit criterion for error variation
target_res = options.target_res; % exit criterion for current residual
res_old = 1e10; % last iteration's error
% Map states range
Map.mr = find(Map.used);
for it = 1:n_iter
% Compute Jacobians for projection onto the manifold
[Frm,Lmk] = errorStateJacobians(Frm,Lmk);
% Build Hessian H and rhs vector b, in global Map
Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac);
% Get partition ranges
fr = ranges(Frm);
lr = ranges(Lmk);
% Get Schur complement -- The schur complement Spp is the sqrt factor
[Map.sSff, Map.iHll] = schurc(Map.H(Map.mr,Map.mr),lr,fr,1);
% Solve frames subproblem
bf = Map.b(fr) - Map.H(fr,lr) * Map.iHll * Map.b(lr);
y = - Map.sSff'\bf;
Map.x(fr) = Map.sSff\y;
% Solve landmarks subproblem
bl = Map.b(lr) + Map.H(lr,fr) * Map.x(fr);
Map.x(lr) = - Map.iHll * bl;
% Update nominal states
[Rob,Lmk,Frm] = updateStates(Rob,Lmk,Frm);
% Check resulting errors
[res, err_max] = computeResidual(Rob,Sen,Lmk,Obs,Frm,Fac);
dres = res - res_old;
res_old = res;
if ( ( -dres <= target_dres ) || (err_max <= target_res) ) %&& ( abs(derr) < target_derr) )
break;
end
end
end
function Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac)
% BUILDPROBLEM Build least squares problem's matrix H and vector b
% Fac = BUILDPROBLEM(Rob,Sen,Lmk,Obs,Frm,Fac) Builds the least squares
% problem's matrix H and vector b for a solution using sparse Schur
% factorization of H.
global Map
% Reset Hessian and rhs vector
Map.H(Map.mr,Map.mr) = 0;
Map.b(Map.mr) = 0;
% Iterate all factors
for fac = find([Fac.used])
% Extract some pointers
rob = Fac(fac).rob;
sen = Fac(fac).sen;
lmk = Fac(fac).lmk;
frames = Fac(fac).frames;
% Compute factor error, info mat, and Jacobians
[Fac(fac), e, W, ~, J1, J2, r1, r2] = computeError(...
Rob(rob), ...
Sen(sen), ...
Lmk(lmk), ...
Obs(sen,lmk), ...
Frm(frames), ...
Fac(fac));
% Compute sparse Hessian blocks
H_11 = J1' * W * J1;
H_12 = J1' * W * J2;
H_22 = J2' * W * J2;
% Compute rhs vector blocks
b1 = J1' * W * e;
b2 = J2' * W * e;
% Update H and b
Map.H(r1,r1) = Map.H(r1,r1) + H_11;
Map.H(r1,r2) = Map.H(r1,r2) + H_12;
Map.H(r2,r1) = Map.H(r2,r1) + H_12';
Map.H(r2,r2) = Map.H(r2,r2) + H_22;
Map.b(r1,1) = Map.b(r1,1) + b1;
Map.b(r2,1) = Map.b(r2,1) + b2;
end
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
solveGraphQR.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/InterfaceLevel/solveGraphQR.m
| 5,355 |
utf_8
|
5fcc6e754223f6fb664de13631cf0c71
|
function [Rob,Sen,Lmk,Obs,Frm,Fac] = solveGraphQR(Rob,Sen,Lmk,Obs,Frm,Fac,options)
% SOLVEGRAPHQR Solves the SLAM graph using QR decomposition.
% [Rob,Sen,Lmk,Obs,Frm,Fac] = SOLVEGRAPHQR(Rob,Sen,Lmk,Obs,Frm,Fac)
% solves the graph-SLAM problem using QR decomposition of the
% Hessian matrix.
%
% IMPORTANT NOTE: This method is illustrative and constitutes the
% motivation for this toolbox. One can achieve better performances, both
% in computing time and possibly in robustness and accuracy, by using
% Matlab's built-in nonlinear optimization tools, such as LSQNONLIN.
%
% See courseSLAM.pdf in the documentation for details about the QR
% decomposition for solving the graph-SLAM problem.
%
% See also SOLVEGRAPHCHOLESKY, ERRORSTATEJACOBIANS, UPDATESTATES,
% COMPUTEERROR, COMPUTERESIDUAL, COLAMD, '\', MLDIVIDE, LSQNONLIN.
% Copyright 2015- Joan Sola @ IRI-UPC-CSIC.
global Map
% Control of iterations and exit conditions
n_iter = options.niterations; % exit criterion of number of iterations
target_dres = options.target_dres; % exit criterion for error variation
target_res = options.target_res; % exit criterion for current residual
res_old = 1e10; % last iteration's error
% Map states range
Map.mr = find(Map.used);
% Map factors range
errs = [Fac.err];
Map.fr = 1:sum([errs.size]);
for it = 1:n_iter
% Compute Jacobians for projection onto the manifold
[Frm,Lmk] = errorStateJacobians(Frm,Lmk);
% Build Hessian A and rhs vector b, in global Map
Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac);
if it == 1 % do this only once:
% Column permutation
p = colamd(Map.A(Map.fr,Map.mr))';
% Permutated map range
pr = Map.mr(p);
end
% Decomposition
[Map.d, Map.R] = qr(Map.A(Map.fr,pr), Map.b(Map.fr), 0);
% Solve for dx and reorder:
% - dx is Map.x(mr)
% - reordered dx is Map.x(pr)
Map.x(pr) = -Map.R\Map.d; % solve for dx;
% NOTE: Matlab is able to do all the reordering and QR factorization
% for you. If you just use the operator '\', as in 'dx = -A\b', Matlab
% will reorder A, then factor it to get R and d, then solve the
% factored problem, then reorder back the result into dx. Use the
% following line to accomplish this, and comment out the code from line
% 'if it == 1' until here:
%
% Map.x(Map.mr) = -Map.A(Map.fr,Map.mr)\Map.b(Map.fr);
% Update nominal states
[Rob,Lmk,Frm] = updateStates(Rob,Lmk,Frm);
% Check resulting errors
[res, err_max] = computeResidual(Rob,Sen,Lmk,Obs,Frm,Fac);
dres = res - res_old;
res_old = res;
% Test and exit
if ( ( -dres <= target_dres ) || (err_max <= target_res) ) %&& ( abs(derr) < target_derr) )
break;
end
end
end
function Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac)
% BUILDPROBLEM Build least squares problem's matrix A and vector b
% Fac = BUILDPROBLEM(Rob,Sen,Lmk,Obs,Frm,Fac) Builds the least squares
% problem's matrix A and vector b for a solution using sparse QR
% factorization of A.
global Map
% Reset Hessian and rhs vector
Map.A(Map.fr,Map.mr) = 0;
Map.b(Map.fr) = 0;
% Iterate all factors
facCount = 1;
for fac = find([Fac.used])
% Extract some pointers
rob = Fac(fac).rob;
sen = Fac(fac).sen;
lmk = Fac(fac).lmk;
frames = Fac(fac).frames;
% Compute factor error, info mat, and Jacobians
[Fac(fac), e, ~, Wsqrt, J1, J2, r1, r2] = computeError(...
Rob(rob), ...
Sen(sen), ...
Lmk(lmk), ...
Obs(sen,lmk), ...
Frm(frames), ...
Fac(fac));
% row band matrix size
m = numel(e);
mr = (facCount : facCount + m - 1);
% Update A and b
Map.A(mr,r1) = Wsqrt * J1;
Map.A(mr,r2) = Wsqrt * J2;
Map.b(mr,1) = Wsqrt * e;
% Advance to next row band
facCount = facCount + m;
end
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
initNewLmk.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/InterfaceLevel/initNewLmk.m
| 8,393 |
utf_8
|
8fd5044ac20898f18cea65856379af31
|
function [Lmk,Obs,Frm,Fac,lmk] = initNewLmk(Rob, Sen, Raw, Lmk, Obs, Frm, Fac, Opt)
%INITNEWLMK Initialise one landmark.
% [LMK, OBS] = INITNEWLMK(ROB, SEN, RAW, LMK, OBS) initializes one new
% landmark. The landmark is selected by an active-search analysis of the
% Raw data belonging to the current sensor Sen in robot Rob. After
% successful initialization, structures Map, Lmk and Obs are updated.
%
% Input/output structures:
% Rob: the robot
% Sen: the sensor
% Raw: the raw datas issues from Sen
% Lmk: the set of landmarks
% Obs: the observation structure for the sensor Sen
% Frm: The frame from where the Lmk was perceived
% Fac: the factor to be created.
% Opt: the algorithm options
%
% The algorithm can be configured through numerous options stored in
% structure Opt.init. Edit USERDATA_GRAPH to access and modify these
% options.
% Copyright 2015- Joan Sola @ IRI-CSIC-UPC
global Map
% 1. Check that we have space...
% 1a. In Lmk array. Index to first free Idp lmk
lmk = newLmk(Lmk);
if isempty(lmk)
% Lmk structure array full. Unable to initialize new landmark.
return;
end
% 1b. In Fac array. Check for new factor
if (strcmp(Map.type, 'graph') == true)
fac = find([Fac.used] == false, 1, 'first');
if isempty(fac)
% Fac structure array full. Unable to initialize new landmark.
return;
end
end
% 1c. In Map storage vector
% Update rob and sen info from Map or from graph
switch Map.type
case 'ekf'
Rob = map2rob(Rob);
Sen = map2sen(Sen);
case 'graph'
Rob = frm2rob(Rob,Frm);
end
% Type of the lmk to initialize - with error check.
switch Opt.init.initType
case {'hmgPnt'}
lmkSize = 4;
case {'ahmPnt'}
lmkSize = 7;
case {'idpPnt','plkLin'}
lmkSize = 6;
case {'idpLin','aplLin'}
lmkSize = 9;
case {'hmgLin'}
lmkSize = 8;
case {'ahmLin'}
lmkSize = 11;
case {'eucPnt'}
switch Sen.type
case 'pinHoleDepth'
lmkSize = 3;
otherwise
error('??? Unable to initialize lmk type ''%s''. Try using ''idpPnt'' instead.',Opt.init.initType);
end
otherwise
error('??? Unknown landmark type ''%s''.', Opt.init.initType);
end
% % check for free space in the Map.
if (freeSpace() < lmkSize)
% Map full. Unable to initialize landmark.
return
end
% OK, we have space everywhere. Proceed with computations.
% 2. Feature detection
switch Raw.type
case {'simu','dump'}
[lid, app, meas, exp, inn] = simDetectFeat(...
Opt.init.initType, ...
[Lmk([Lmk.used]).id], ...
Raw.data, ...
Sen.par.cov, ...
Sen.par.imSize);
case 'image'
% NYI : Not Yet Implemented. Create detectFeat.m and call:
% [newId, app, meas, exp, inn] = detectFeat(...);
error('??? Raw type ''%s'' not yet implemented.', Raw.type);
otherwise
error('??? Unknown raw type %s.', Raw.type);
end
if ~isempty(meas.y) % a feature was detected --> initialize it
% fill Obs struct before continuing
Obs(lmk).sen = Sen.sen;
Obs(lmk).lmk = lmk;
Obs(lmk).sid = Sen.id;
Obs(lmk).lid = lid;
Obs(lmk).stype = Sen.type;
Obs(lmk).ltype = Opt.init.initType;
Obs(lmk).meas = meas;
Obs(lmk).exp = exp;
Obs(lmk).exp.um = det(inn.Z); % uncertainty measure
Obs(lmk).inn = inn;
Obs(lmk).app.curr = app;
Obs(lmk).app.pred = app;
Obs(lmk).vis = true;
Obs(lmk).measured = true;
Obs(lmk).matched = true;
Obs(lmk).updated = true;
% 3. retro-project feature onto 3D space
[l, L_rf, L_sf, L_obs, L_n, N] = retroProjLmk(Rob,Sen,Obs(lmk),Opt);
% 4. Initialize Lmk
if strcmp(Map.type, 'ekf')
% get new Lmk, covariance and cross-variance.
[P_LL,P_LX] = getNewLmkCovs( ...
Sen.frameInMap, ...
Rob.frame.r, ...
Sen.frame.r, ...
L_rf, ...
L_sf, ...
L_obs, ...
L_n, ...
meas.R, ...
N) ;
% add to Map and get lmk range in Map
Lmk(lmk).state.r = addToMap(l,P_LL,P_LX);
else
% get lmk ranges in Map, and block
r = newRange(Lmk(lmk).state.dsize);
blockRange(r);
% Update ranges and state
Lmk(lmk).state.r = r;
Lmk(lmk).state.x = l;
end
% Fill Lmk structure
Lmk(lmk).lmk = lmk;
Lmk(lmk).id = lid;
Lmk(lmk).type = Opt.init.initType ;
Lmk(lmk).used = true;
Lmk(lmk).factors = [];
Lmk(lmk).sig = app;
Lmk(lmk).nSearch = 1;
Lmk(lmk).nMatch = 1;
Lmk(lmk).nInlier = 1;
% Init off-filter landmark params
[Lmk(lmk),Obs(lmk)] = initLmkParams(Rob,Sen,Lmk(lmk),Obs(lmk));
else
% Detection failed
lmk = [];
end
% 5. Create factor
if (~isempty(lmk) && strcmp(Map.type, 'graph') == true)
[Lmk(lmk), Frm, Fac(fac)] = makeMeasFactor(...
Lmk(lmk), ...
Obs(lmk), ...
Frm, ...
Fac(fac));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [P_LL,P_LX] = getNewLmkCovs(SenFrameInMap, RobFrameR, SenFrameR,...
L_rf, L_sf, L_obs, L_n, R, N)
% GETNEWLMKCOVS return lmk co and cross-variance for initialization.
% [P_LL,P_LX] = GETNEWLMKCOVS( ...
% SENFRAMEINMAP, ...
% ROBFRAMERANGE, ...
% SENFRAMERANGE, ...
% L_RF, ...
% L_SF, ...
% L_OBS, ...
% L_N, ...
% R, ...
% N)
%
% Return the covariance 'Lmk/Lmk' (P_LL) and cross-variance 'Lmk/Map.used'
% (P_LX) given :
% - if the sensor frame is in map (SENFRAMEINMAP).
% - the robot frame range in map (ROBFRAMERANGE).
% - the sensor frame range in map (SENFRAMERANGE).
% - the jacobian 'Lmk/robot frame' (L_RF).
% - the jacobian 'Lmk/sensor frame' (L_SF).
% - the jacobian 'Lmk/observation' (L_OBS).
% - the jacobian 'Lmk/non observable part' (L_N).
% - the observation covariance (R).
% - the observation non observable part covariance (N).
%
% P_LL and P_LX can be placed for example in Map covariance like:
%
% P = | P P_LX' |
% | P_LX P_LL |
%
% (c) 2009 Jean Marie Codol, David Marquez @ LAAS-CNRS
global Map
% Group all map Jacobians and ranges
if SenFrameInMap % if the sensor frame is in the state
mr = [RobFrameR;SenFrameR];
L_m = [L_rf L_sf] ;
else
mr = RobFrameR;
L_m = L_rf ;
end
% co- and cross-variance of map variables (robot and eventually sensor)
P_MM = Map.P(mr,mr) ;
P_MX = Map.P(mr,(Map.used)) ;
% landmark co- and cross-variance
P_LL = ...
L_m * P_MM * L_m' + ... % by map cov
L_obs * R * L_obs' + ... % by observation cov (for pinHole it is a pixel)
L_n * N * L_n' ; % by nom cov
P_LX = L_m*P_MX ;
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
solveGraphCholesky.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/InterfaceLevel/solveGraphCholesky.m
| 5,660 |
utf_8
|
f5d071a8f99dd2cfb377dcae99ec887c
|
function [Rob,Sen,Lmk,Obs,Frm,Fac] = solveGraphCholesky(Rob,Sen,Lmk,Obs,Frm,Fac,options)
% SOLVEGRAPHCHOLESKY Solves the SLAM graph using Cholesky decomposition.
% [Rob,Sen,Lmk,Obs,Frm,Fac] = solveGraphCholesky(Rob,Sen,Lmk,Obs,Frm,Fac)
% solves the graph-SLAM problem using Cholesky decomposition of the
% Hessian matrix.
%
% IMPORTANT NOTE: This method is illustrative and constitutes the
% motivation for this toolbox. One can achieve better performances, both
% in computing time and possibly in robustness and accuracy, by using
% Matlab's built-in nonlinear optimization tools, such as LSQNONLIN.
%
% See courseSLAM.pdf in the documentation for details about the Cholesky
% decomposition for solving the graph-SLAM problem.
%
% See also ERRORSTATEJACOBIANS, UPDATESTATES, COMPUTEERROR,
% COMPUTERESIDUAL, COLAMD, '\', MLDIVIDE, LSQNONLIN.
% Copyright 2015- Joan Sola @ IRI-UPC-CSIC.
global Map
% Control of iterations and exit conditions
n_iter = options.niterations; % exit criterion of number of iterations
target_dres = options.target_dres; % exit criterion for error variation
target_res = options.target_res; % exit criterion for current residual
res_old = 1e10; % last iteration's error
% Map states range
Map.mr = find(Map.used);
for it = 1:n_iter
% fprintf('----------------\nIteration: %d; \n',it)
% Compute Jacobians for projection onto the manifold
[Frm,Lmk] = errorStateJacobians(Frm,Lmk);
% Build Hessian H and rhs vector b, in global Map
Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac);
if it == 1 % do this only once:
% Column permutation
p = colamd(Map.H(Map.mr,Map.mr))';
% Permutated map range
pr = Map.mr(p);
end
% Decomposition
[Map.R, ill] = chol(Map.H(pr,pr));
if ill
error('Ill-conditioned Hessian')
end
% Solve for dx and reorder:
% - dx is Map.x(mr)
% - reordered dx is Map.x(pr)
y = -Map.R'\Map.b(pr); % solve for y
Map.x(pr) = Map.R\y;
% NOTE: Matlab is able to do all the reordering and Cholesky
% factorization for you. If you just use the operator '\', as in
% 'dx = -H\b', Matlab will reorder H, then factor it as R'R, then solve
% the two subproblems, then reorder back the result into dx. Use the
% following line to accomplish this, and comment out the code from line
% 'if it == 1' until here:
%
% Map.x(Map.mr) = -Map.H(Map.mr,Map.mr)\Map.b(Map.mr);
% Update nominal states
[Rob,Lmk,Frm] = updateStates(Rob,Lmk,Frm);
% Check resulting errors
[res, err_max] = computeResidual(Rob,Sen,Lmk,Obs,Frm,Fac);
dres = res - res_old;
res_old = res;
% fprintf('Residual: %.2e; variation: %.2e \n', res, dres)
if ( ( -dres <= target_dres ) || (err_max <= target_res) ) %&& ( abs(derr) < target_derr) )
break;
end
end
end
function Fac = buildProblem(Rob,Sen,Lmk,Obs,Frm,Fac)
% BUILDPROBLEM Build least squares problem's matrix H and vector b
% Fac = BUILDPROBLEM(Rob,Sen,Lmk,Obs,Frm,Fac) Builds the least squares
% problem's matrix H and vector b for a solution using sparse Cholesky
% factorization of H.
global Map
% Reset Hessian and rhs vector
Map.H(Map.mr,Map.mr) = 0;
Map.b(Map.mr) = 0;
% Iterate all factors
for fac = find([Fac.used])
% Extract some pointers
rob = Fac(fac).rob;
sen = Fac(fac).sen;
lmk = Fac(fac).lmk;
frames = Fac(fac).frames;
% Compute factor error, info mat, and Jacobians
[Fac(fac), e, W, ~, J1, J2, r1, r2] = computeError(...
Rob(rob), ...
Sen(sen), ...
Lmk(lmk), ...
Obs(sen,lmk), ...
Frm(frames), ...
Fac(fac));
% Compute sparse Hessian blocks
H_11 = J1' * W * J1;
H_12 = J1' * W * J2;
H_22 = J2' * W * J2;
% Compute rhs vector blocks
b1 = J1' * W * e;
b2 = J2' * W * e;
% Update H and b
Map.H(r1,r1) = Map.H(r1,r1) + H_11;
Map.H(r1,r2) = Map.H(r1,r2) + H_12;
Map.H(r2,r1) = Map.H(r2,r1) + H_12';
Map.H(r2,r2) = Map.H(r2,r2) + H_22;
Map.b(r1,1) = Map.b(r1,1) + b1;
Map.b(r2,1) = Map.b(r2,1) + b2;
end
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
errorAnalysis.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/DataManagement/errorAnalysis.m
| 1,434 |
utf_8
|
30b8cdc0c1a16f01ea47b9385d43e6e1
|
% ERRORANALYSIS Error analysis for slamtb.
function err = errorAnalysis(Rob, SimRob, errfcn)
err = errfcn(Rob, SimRob);
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
chi2.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/Math/chi2.m
| 25,986 |
utf_8
|
316d620ef54a7172615309682fd63d85
|
function chi2 = chi2(n,p)
% CHI2 Chi square distribution
% TH = CHI2(N,P) gives the critical values of the N-dimensional
% Chi-squared distribuiton function for a right-tail probability area P
% Copyright 2009 Joan Sola @ LAAS-CNRS.
[nTab,pTab,Chi2Tab] = chi2tab();
if (n == floor(n))
% values of p
if p < .001
warning('Too small probability. Assuming P=0.001')
p = 0.001;
elseif (p > 0.2) && (p<0.975) && (p~=0.5)
warning('Poor data in table. Inaccurate results. Use P<0.2 or P>0.975.')
elseif p > 0.995
warning('Too big probability. Assuming P=0.995')
p = 0.995;
end
% values of n
if (n > 1000)
error('Chi2 Lookup table only up to N=1000 DOF')
elseif (n > 250) && (mod(n,50)~=0)
warning('Value of N-DOF not found. Innacurate results. Use N in [1:1:250,300:50:1000]')
end
% 2-D interpolation
chi2 = interp2(pTab,nTab,Chi2Tab,p,n);
else
error('Dimension N must be a positive integer value in [1:1000]')
end
end
%% Lookup tables
function [DOF,PRB,TAB] = chi2tab()
PRB = [0.995 0.975 0.20 0.10 0.05 0.025 0.02 0.01 0.005 0.002 0.001];
DOF = [1:250 300:50:1000];
TAB = [...
1 0.0000393 0.000982 1.642 2.706 3.841 5.024 5.412 6.635 7.879 9.550 10.828
2 0.0100 0.0506 3.219 4.605 5.991 7.378 7.824 9.210 10.597 12.429 13.816
3 0.0717 0.216 4.642 6.251 7.815 9.348 9.837 11.345 12.838 14.796 16.266
4 0.207 0.484 5.989 7.779 9.488 11.143 11.668 13.277 14.860 16.924 18.467
5 0.412 0.831 7.289 9.236 11.070 12.833 13.388 15.086 16.750 18.907 20.515
6 0.676 1.237 8.558 10.645 12.592 14.449 15.033 16.812 18.548 20.791 22.458
7 0.989 1.690 9.803 12.017 14.067 16.013 16.622 18.475 20.278 22.601 24.322
8 1.344 2.180 11.030 13.362 15.507 17.535 18.168 20.090 21.955 24.352 26.124
9 1.735 2.700 12.242 14.684 16.919 19.023 19.679 21.666 23.589 26.056 27.877
10 2.156 3.247 13.442 15.987 18.307 20.483 21.161 23.209 25.188 27.722 29.588
11 2.603 3.816 14.631 17.275 19.675 21.920 22.618 24.725 26.757 29.354 31.264
12 3.074 4.404 15.812 18.549 21.026 23.337 24.054 26.217 28.300 30.957 32.909
13 3.565 5.009 16.985 19.812 22.362 24.736 25.472 27.688 29.819 32.535 34.528
14 4.075 5.629 18.151 21.064 23.685 26.119 26.873 29.141 31.319 34.091 36.123
15 4.601 6.262 19.311 22.307 24.996 27.488 28.259 30.578 32.801 35.628 37.697
16 5.142 6.908 20.465 23.542 26.296 28.845 29.633 32.000 34.267 37.146 39.252
17 5.697 7.564 21.615 24.769 27.587 30.191 30.995 33.409 35.718 38.648 40.790
18 6.265 8.231 22.760 25.989 28.869 31.526 32.346 34.805 37.156 40.136 42.312
19 6.844 8.907 23.900 27.204 30.144 32.852 33.687 36.191 38.582 41.610 43.820
20 7.434 9.591 25.038 28.412 31.410 34.170 35.020 37.566 39.997 43.072 45.315
21 8.034 10.283 26.171 29.615 32.671 35.479 36.343 38.932 41.401 44.522 46.797
22 8.643 10.982 27.301 30.813 33.924 36.781 37.659 40.289 42.796 45.962 48.268
23 9.260 11.689 28.429 32.007 35.172 38.076 38.968 41.638 44.181 47.391 49.728
24 9.886 12.401 29.553 33.196 36.415 39.364 40.270 42.980 45.559 48.812 51.179
25 10.520 13.120 30.675 34.382 37.652 40.646 41.566 44.314 46.928 50.223 52.620
26 11.160 13.844 31.795 35.563 38.885 41.923 42.856 45.642 48.290 51.627 54.052
27 11.808 14.573 32.912 36.741 40.113 43.195 44.140 46.963 49.645 53.023 55.476
28 12.461 15.308 34.027 37.916 41.337 44.461 45.419 48.278 50.993 54.411 56.892
29 13.121 16.047 35.139 39.087 42.557 45.722 46.693 49.588 52.336 55.792 58.301
30 13.787 16.791 36.250 40.256 43.773 46.979 47.962 50.892 53.672 57.167 59.703
31 14.458 17.539 37.359 41.422 44.985 48.232 49.226 52.191 55.003 58.536 61.098
32 15.134 18.291 38.466 42.585 46.194 49.480 50.487 53.486 56.328 59.899 62.487
33 15.815 19.047 39.572 43.745 47.400 50.725 51.743 54.776 57.648 61.256 63.870
34 16.501 19.806 40.676 44.903 48.602 51.966 52.995 56.061 58.964 62.608 65.247
35 17.192 20.569 41.778 46.059 49.802 53.203 54.244 57.342 60.275 63.955 66.619
36 17.887 21.336 42.879 47.212 50.998 54.437 55.489 58.619 61.581 65.296 67.985
37 18.586 22.106 43.978 48.363 52.192 55.668 56.730 59.893 62.883 66.633 69.346
38 19.289 22.878 45.076 49.513 53.384 56.896 57.969 61.162 64.181 67.966 70.703
39 19.996 23.654 46.173 50.660 54.572 58.120 59.204 62.428 65.476 69.294 72.055
40 20.707 24.433 47.269 51.805 55.758 59.342 60.436 63.691 66.766 70.618 73.402
41 21.421 25.215 48.363 52.949 56.942 60.561 61.665 64.950 68.053 71.938 74.745
42 22.138 25.999 49.456 54.090 58.124 61.777 62.892 66.206 69.336 73.254 76.084
43 22.859 26.785 50.548 55.230 59.304 62.990 64.116 67.459 70.616 74.566 77.419
44 23.584 27.575 51.639 56.369 60.481 64.201 65.337 68.710 71.893 75.874 78.750
45 24.311 28.366 52.729 57.505 61.656 65.410 66.555 69.957 73.166 77.179 80.077
46 25.041 29.160 53.818 58.641 62.830 66.617 67.771 71.201 74.437 78.481 81.400
47 25.775 29.956 54.906 59.774 64.001 67.821 68.985 72.443 75.704 79.780 82.720
48 26.511 30.755 55.993 60.907 65.171 69.023 70.197 73.683 76.969 81.075 84.037
49 27.249 31.555 57.079 62.038 66.339 70.222 71.406 74.919 78.231 82.367 85.351
50 27.991 32.357 58.164 63.167 67.505 71.420 72.613 76.154 79.490 83.657 86.661
51 28.735 33.162 59.248 64.295 68.669 72.616 73.818 77.386 80.747 84.943 87.968
52 29.481 33.968 60.332 65.422 69.832 73.810 75.021 78.616 82.001 86.227 89.272
53 30.230 34.776 61.414 66.548 70.993 75.002 76.223 79.843 83.253 87.507 90.573
54 30.981 35.586 62.496 67.673 72.153 76.192 77.422 81.069 84.502 88.786 91.872
55 31.735 36.398 63.577 68.796 73.311 77.380 78.619 82.292 85.749 90.061 93.168
56 32.490 37.212 64.658 69.919 74.468 78.567 79.815 83.513 86.994 91.335 94.461
57 33.248 38.027 65.737 71.040 75.624 79.752 81.009 84.733 88.236 92.605 95.751
58 34.008 38.844 66.816 72.160 76.778 80.936 82.201 85.950 89.477 93.874 97.039
59 34.770 39.662 67.894 73.279 77.931 82.117 83.391 87.166 90.715 95.140 98.324
60 35.534 40.482 68.972 74.397 79.082 83.298 84.580 88.379 91.952 96.404 99.607
61 36.301 41.303 70.049 75.514 80.232 84.476 85.767 89.591 93.186 97.665 100.888
62 37.068 42.126 71.125 76.630 81.381 85.654 86.953 90.802 94.419 98.925 102.166
63 37.838 42.950 72.201 77.745 82.529 86.830 88.137 92.010 95.649 100.182 103.442
64 38.610 43.776 73.276 78.860 83.675 88.004 89.320 93.217 96.878 101.437 104.716
65 39.383 44.603 74.351 79.973 84.821 89.177 90.501 94.422 98.105 102.691 105.988
66 40.158 45.431 75.424 81.085 85.965 90.349 91.681 95.626 99.330 103.942 107.258
67 40.935 46.261 76.498 82.197 87.108 91.519 92.860 96.828 100.554 105.192 108.526
68 41.713 47.092 77.571 83.308 88.250 92.689 94.037 98.028 101.776 106.440 109.791
69 42.494 47.924 78.643 84.418 89.391 93.856 95.213 99.228 102.996 107.685 111.055
70 43.275 48.758 79.715 85.527 90.531 95.023 96.388 100.425 104.215 108.929 112.317
71 44.058 49.592 80.786 86.635 91.670 96.189 97.561 101.621 105.432 110.172 113.577
72 44.843 50.428 81.857 87.743 92.808 97.353 98.733 102.816 106.648 111.412 114.835
73 45.629 51.265 82.927 88.850 93.945 98.516 99.904 104.010 107.862 112.651 116.092
74 46.417 52.103 83.997 89.956 95.081 99.678 101.074 105.202 109.074 113.889 117.346
75 47.206 52.942 85.066 91.061 96.217 100.839 102.243 106.393 110.286 115.125 118.599
76 47.997 53.782 86.135 92.166 97.351 101.999 103.410 107.583 111.495 116.359 119.850
77 48.788 54.623 87.203 93.270 98.484 103.158 104.576 108.771 112.704 117.591 121.100
78 49.582 55.466 88.271 94.374 99.617 104.316 105.742 109.958 113.911 118.823 122.348
79 50.376 56.309 89.338 95.476 100.749 105.473 106.906 111.144 115.117 120.052 123.594
80 51.172 57.153 90.405 96.578 101.879 106.629 108.069 112.329 116.321 121.280 124.839
81 51.969 57.998 91.472 97.680 103.010 107.783 109.232 113.512 117.524 122.507 126.083
82 52.767 58.845 92.538 98.780 104.139 108.937 110.393 114.695 118.726 123.733 127.324
83 53.567 59.692 93.604 99.880 105.267 110.090 111.553 115.876 119.927 124.957 128.565
84 54.368 60.540 94.669 100.980 106.395 111.242 112.712 117.057 121.126 126.179 129.804
85 55.170 61.389 95.734 102.079 107.522 112.393 113.871 118.236 122.325 127.401 131.041
86 55.973 62.239 96.799 103.177 108.648 113.544 115.028 119.414 123.522 128.621 132.277
87 56.777 63.089 97.863 104.275 109.773 114.693 116.184 120.591 124.718 129.840 133.512
88 57.582 63.941 98.927 105.372 110.898 115.841 117.340 121.767 125.913 131.057 134.745
89 58.389 64.793 99.991 106.469 112.022 116.989 118.495 122.942 127.106 132.273 135.978
90 59.196 65.647 101.054 107.565 113.145 118.136 119.648 124.116 128.299 133.489 137.208
91 60.005 66.501 102.117 108.661 114.268 119.282 120.801 125.289 129.491 134.702 138.438
92 60.815 67.356 103.179 109.756 115.390 120.427 121.954 126.462 130.681 135.915 139.666
93 61.625 68.211 104.241 110.850 116.511 121.571 123.105 127.633 131.871 137.127 140.893
94 62.437 69.068 105.303 111.944 117.632 122.715 124.255 128.803 133.059 138.337 142.119
95 63.250 69.925 106.364 113.038 118.752 123.858 125.405 129.973 134.247 139.546 143.344
96 64.063 70.783 107.425 114.131 119.871 125.000 126.554 131.141 135.433 140.755 144.567
97 64.878 71.642 108.486 115.223 120.990 126.141 127.702 132.309 136.619 141.962 145.789
98 65.694 72.501 109.547 116.315 122.108 127.282 128.849 133.476 137.803 143.168 147.010
99 66.510 73.361 110.607 117.407 123.225 128.422 129.996 134.642 138.987 144.373 148.230
100 67.328 74.222 111.667 118.498 124.342 129.561 131.142 135.807 140.169 145.577 149.449
101 68.146 75.083 112.726 119.589 125.458 130.700 132.287 136.971 141.351 146.780 150.667
102 68.965 75.946 113.786 120.679 126.574 131.838 133.431 138.134 142.532 147.982 151.884
103 69.785 76.809 114.845 121.769 127.689 132.975 134.575 139.297 143.712 149.183 153.099
104 70.606 77.672 115.903 122.858 128.804 134.111 135.718 140.459 144.891 150.383 154.314
105 71.428 78.536 116.962 123.947 129.918 135.247 136.860 141.620 146.070 151.582 155.528
106 72.251 79.401 118.020 125.035 131.031 136.382 138.002 142.780 147.247 152.780 156.740
107 73.075 80.267 119.078 126.123 132.144 137.517 139.143 143.940 148.424 153.977 157.952
108 73.899 81.133 120.135 127.211 133.257 138.651 140.283 145.099 149.599 155.173 159.162
109 74.724 82.000 121.192 128.298 134.369 139.784 141.423 146.257 150.774 156.369 160.372
110 75.550 82.867 122.250 129.385 135.480 140.917 142.562 147.414 151.948 157.563 161.581
111 76.377 83.735 123.306 130.472 136.591 142.049 143.700 148.571 153.122 158.757 162.788
112 77.204 84.604 124.363 131.558 137.701 143.180 144.838 149.727 154.294 159.950 163.995
113 78.033 85.473 125.419 132.643 138.811 144.311 145.975 150.882 155.466 161.141 165.201
114 78.862 86.342 126.475 133.729 139.921 145.441 147.111 152.037 156.637 162.332 166.406
115 79.692 87.213 127.531 134.813 141.030 146.571 148.247 153.191 157.808 163.523 167.610
116 80.522 88.084 128.587 135.898 142.138 147.700 149.383 154.344 158.977 164.712 168.813
117 81.353 88.955 129.642 136.982 143.246 148.829 150.517 155.496 160.146 165.900 170.016
118 82.185 89.827 130.697 138.066 144.354 149.957 151.652 156.648 161.314 167.088 171.217
119 83.018 90.700 131.752 139.149 145.461 151.084 152.785 157.800 162.481 168.275 172.418
120 83.852 91.573 132.806 140.233 146.567 152.211 153.918 158.950 163.648 169.461 173.617
121 84.686 92.446 133.861 141.315 147.674 153.338 155.051 160.100 164.814 170.647 174.816
122 85.520 93.320 134.915 142.398 148.779 154.464 156.183 161.250 165.980 171.831 176.014
123 86.356 94.195 135.969 143.480 149.885 155.589 157.314 162.398 167.144 173.015 177.212
124 87.192 95.070 137.022 144.562 150.989 156.714 158.445 163.546 168.308 174.198 178.408
125 88.029 95.946 138.076 145.643 152.094 157.839 159.575 164.694 169.471 175.380 179.604
126 88.866 96.822 139.129 146.724 153.198 158.962 160.705 165.841 170.634 176.562 180.799
127 89.704 97.698 140.182 147.805 154.302 160.086 161.834 166.987 171.796 177.743 181.993
128 90.543 98.576 141.235 148.885 155.405 161.209 162.963 168.133 172.957 178.923 183.186
129 91.382 99.453 142.288 149.965 156.508 162.331 164.091 169.278 174.118 180.103 184.379
130 92.222 100.331 143.340 151.045 157.610 163.453 165.219 170.423 175.278 181.282 185.571
131 93.063 101.210 144.392 152.125 158.712 164.575 166.346 171.567 176.438 182.460 186.762
132 93.904 102.089 145.444 153.204 159.814 165.696 167.473 172.711 177.597 183.637 187.953
133 94.746 102.968 146.496 154.283 160.915 166.816 168.600 173.854 178.755 184.814 189.142
134 95.588 103.848 147.548 155.361 162.016 167.936 169.725 174.996 179.913 185.990 190.331
135 96.431 104.729 148.599 156.440 163.116 169.056 170.851 176.138 181.070 187.165 191.520
136 97.275 105.609 149.651 157.518 164.216 170.175 171.976 177.280 182.226 188.340 192.707
137 98.119 106.491 150.702 158.595 165.316 171.294 173.100 178.421 183.382 189.514 193.894
138 98.964 107.372 151.753 159.673 166.415 172.412 174.224 179.561 184.538 190.688 195.080
139 99.809 108.254 152.803 160.750 167.514 173.530 175.348 180.701 185.693 191.861 196.266
140 100.655 109.137 153.854 161.827 168.613 174.648 176.471 181.840 186.847 193.033 197.451
141 101.501 110.020 154.904 162.904 169.711 175.765 177.594 182.979 188.001 194.205 198.635
142 102.348 110.903 155.954 163.980 170.809 176.882 178.716 184.118 189.154 195.376 199.819
143 103.196 111.787 157.004 165.056 171.907 177.998 179.838 185.256 190.306 196.546 201.002
144 104.044 112.671 158.054 166.132 173.004 179.114 180.959 186.393 191.458 197.716 202.184
145 104.892 113.556 159.104 167.207 174.101 180.229 182.080 187.530 192.610 198.885 203.366
146 105.741 114.441 160.153 168.283 175.198 181.344 183.200 188.666 193.761 200.054 204.547
147 106.591 115.326 161.202 169.358 176.294 182.459 184.321 189.802 194.912 201.222 205.727
148 107.441 116.212 162.251 170.432 177.390 183.573 185.440 190.938 196.062 202.390 206.907
149 108.291 117.098 163.300 171.507 178.485 184.687 186.560 192.073 197.211 203.557 208.086
150 109.142 117.985 164.349 172.581 179.581 185.800 187.678 193.208 198.360 204.723 209.265
151 109.994 118.871 165.398 173.655 180.676 186.914 188.797 194.342 199.509 205.889 210.443
152 110.846 119.759 166.446 174.729 181.770 188.026 189.915 195.476 200.657 207.054 211.620
153 111.698 120.646 167.495 175.803 182.865 189.139 191.033 196.609 201.804 208.219 212.797
154 112.551 121.534 168.543 176.876 183.959 190.251 192.150 197.742 202.951 209.383 213.973
155 113.405 122.423 169.591 177.949 185.052 191.362 193.267 198.874 204.098 210.547 215.149
156 114.259 123.312 170.639 179.022 186.146 192.474 194.384 200.006 205.244 211.710 216.324
157 115.113 124.201 171.686 180.094 187.239 193.584 195.500 201.138 206.390 212.873 217.499
158 115.968 125.090 172.734 181.167 188.332 194.695 196.616 202.269 207.535 214.035 218.673
159 116.823 125.980 173.781 182.239 189.424 195.805 197.731 203.400 208.680 215.197 219.846
160 117.679 126.870 174.828 183.311 190.516 196.915 198.846 204.530 209.824 216.358 221.019
161 118.536 127.761 175.875 184.382 191.608 198.025 199.961 205.660 210.968 217.518 222.191
162 119.392 128.651 176.922 185.454 192.700 199.134 201.076 206.790 212.111 218.678 223.363
163 120.249 129.543 177.969 186.525 193.791 200.243 202.190 207.919 213.254 219.838 224.535
164 121.107 130.434 179.016 187.596 194.883 201.351 203.303 209.047 214.396 220.997 225.705
165 121.965 131.326 180.062 188.667 195.973 202.459 204.417 210.176 215.539 222.156 226.876
166 122.823 132.218 181.109 189.737 197.064 203.567 205.530 211.304 216.680 223.314 228.045
167 123.682 133.111 182.155 190.808 198.154 204.675 206.642 212.431 217.821 224.472 229.215
168 124.541 134.003 183.201 191.878 199.244 205.782 207.755 213.558 218.962 225.629 230.383
169 125.401 134.897 184.247 192.948 200.334 206.889 208.867 214.685 220.102 226.786 231.552
170 126.261 135.790 185.293 194.017 201.423 207.995 209.978 215.812 221.242 227.942 232.719
171 127.122 136.684 186.338 195.087 202.513 209.102 211.090 216.938 222.382 229.098 233.887
172 127.983 137.578 187.384 196.156 203.602 210.208 212.201 218.063 223.521 230.253 235.053
173 128.844 138.472 188.429 197.225 204.690 211.313 213.311 219.189 224.660 231.408 236.220
174 129.706 139.367 189.475 198.294 205.779 212.419 214.422 220.314 225.798 232.563 237.385
175 130.568 140.262 190.520 199.363 206.867 213.524 215.532 221.438 226.936 233.717 238.551
176 131.430 141.157 191.565 200.432 207.955 214.628 216.641 222.563 228.074 234.870 239.716
177 132.293 142.053 192.610 201.500 209.042 215.733 217.751 223.687 229.211 236.023 240.880
178 133.157 142.949 193.654 202.568 210.130 216.837 218.860 224.810 230.347 237.176 242.044
179 134.020 143.845 194.699 203.636 211.217 217.941 219.969 225.933 231.484 238.328 243.207
180 134.884 144.741 195.743 204.704 212.304 219.044 221.077 227.056 232.620 239.480 244.370
181 135.749 145.638 196.788 205.771 213.391 220.148 222.185 228.179 233.755 240.632 245.533
182 136.614 146.535 197.832 206.839 214.477 221.251 223.293 229.301 234.891 241.783 246.695
183 137.479 147.432 198.876 207.906 215.563 222.353 224.401 230.423 236.026 242.933 247.857
184 138.344 148.330 199.920 208.973 216.649 223.456 225.508 231.544 237.160 244.084 249.018
185 139.210 149.228 200.964 210.040 217.735 224.558 226.615 232.665 238.294 245.234 250.179
186 140.077 150.126 202.008 211.106 218.820 225.660 227.722 233.786 239.428 246.383 251.339
187 140.943 151.024 203.052 212.173 219.906 226.761 228.828 234.907 240.561 247.532 252.499
188 141.810 151.923 204.095 213.239 220.991 227.863 229.935 236.027 241.694 248.681 253.659
189 142.678 152.822 205.139 214.305 222.076 228.964 231.040 237.147 242.827 249.829 254.818
190 143.545 153.721 206.182 215.371 223.160 230.064 232.146 238.266 243.959 250.977 255.976
191 144.413 154.621 207.225 216.437 224.245 231.165 233.251 239.386 245.091 252.124 257.135
192 145.282 155.521 208.268 217.502 225.329 232.265 234.356 240.505 246.223 253.271 258.292
193 146.150 156.421 209.311 218.568 226.413 233.365 235.461 241.623 247.354 254.418 259.450
194 147.020 157.321 210.354 219.633 227.496 234.465 236.566 242.742 248.485 255.564 260.607
195 147.889 158.221 211.397 220.698 228.580 235.564 237.670 243.860 249.616 256.710 261.763
196 148.759 159.122 212.439 221.763 229.663 236.664 238.774 244.977 250.746 257.855 262.920
197 149.629 160.023 213.482 222.828 230.746 237.763 239.877 246.095 251.876 259.001 264.075
198 150.499 160.925 214.524 223.892 231.829 238.861 240.981 247.212 253.006 260.145 265.231
199 151.370 161.826 215.567 224.957 232.912 239.960 242.084 248.329 254.135 261.290 266.386
200 152.241 162.728 216.609 226.021 233.994 241.058 243.187 249.445 255.264 262.434 267.541
201 153.112 163.630 217.651 227.085 235.077 242.156 244.290 250.561 256.393 263.578 268.695
202 153.984 164.532 218.693 228.149 236.159 243.254 245.392 251.677 257.521 264.721 269.849
203 154.856 165.435 219.735 229.213 237.240 244.351 246.494 252.793 258.649 265.864 271.002
204 155.728 166.338 220.777 230.276 238.322 245.448 247.596 253.908 259.777 267.007 272.155
205 156.601 167.241 221.818 231.340 239.403 246.545 248.698 255.023 260.904 268.149 273.308
206 157.474 168.144 222.860 232.403 240.485 247.642 249.799 256.138 262.031 269.291 274.460
207 158.347 169.047 223.901 233.466 241.566 248.739 250.900 257.253 263.158 270.432 275.612
208 159.221 169.951 224.943 234.529 242.647 249.835 252.001 258.367 264.285 271.574 276.764
209 160.095 170.855 225.984 235.592 243.727 250.931 253.102 259.481 265.411 272.715 277.915
210 160.969 171.759 227.025 236.655 244.808 252.027 254.202 260.595 266.537 273.855 279.066
211 161.843 172.664 228.066 237.717 245.888 253.122 255.302 261.708 267.662 274.995 280.217
212 162.718 173.568 229.107 238.780 246.968 254.218 256.402 262.821 268.788 276.135 281.367
213 163.593 174.473 230.148 239.842 248.048 255.313 257.502 263.934 269.912 277.275 282.517
214 164.469 175.378 231.189 240.904 249.128 256.408 258.601 265.047 271.037 278.414 283.666
215 165.344 176.283 232.230 241.966 250.207 257.503 259.701 266.159 272.162 279.553 284.815
216 166.220 177.189 233.270 243.028 251.286 258.597 260.800 267.271 273.286 280.692 285.964
217 167.096 178.095 234.311 244.090 252.365 259.691 261.898 268.383 274.409 281.830 287.112
218 167.973 179.001 235.351 245.151 253.444 260.785 262.997 269.495 275.533 282.968 288.261
219 168.850 179.907 236.391 246.213 254.523 261.879 264.095 270.606 276.656 284.106 289.408
220 169.727 180.813 237.432 247.274 255.602 262.973 265.193 271.717 277.779 285.243 290.556
221 170.604 181.720 238.472 248.335 256.680 264.066 266.291 272.828 278.902 286.380 291.703
222 171.482 182.627 239.512 249.396 257.758 265.159 267.389 273.939 280.024 287.517 292.850
223 172.360 183.534 240.552 250.457 258.837 266.252 268.486 275.049 281.146 288.653 293.996
224 173.238 184.441 241.592 251.517 259.914 267.345 269.584 276.159 282.268 289.789 295.142
225 174.116 185.348 242.631 252.578 260.992 268.438 270.681 277.269 283.390 290.925 296.288
226 174.995 186.256 243.671 253.638 262.070 269.530 271.777 278.379 284.511 292.061 297.433
227 175.874 187.164 244.711 254.699 263.147 270.622 272.874 279.488 285.632 293.196 298.579
228 176.753 188.072 245.750 255.759 264.224 271.714 273.970 280.597 286.753 294.331 299.723
229 177.633 188.980 246.790 256.819 265.301 272.806 275.066 281.706 287.874 295.465 300.868
230 178.512 189.889 247.829 257.879 266.378 273.898 276.162 282.814 288.994 296.600 302.012
231 179.392 190.797 248.868 258.939 267.455 274.989 277.258 283.923 290.114 297.734 303.156
232 180.273 191.706 249.908 259.998 268.531 276.080 278.354 285.031 291.234 298.867 304.299
233 181.153 192.615 250.947 261.058 269.608 277.171 279.449 286.139 292.353 300.001 305.443
234 182.034 193.524 251.986 262.117 270.684 278.262 280.544 287.247 293.472 301.134 306.586
235 182.915 194.434 253.025 263.176 271.760 279.352 281.639 288.354 294.591 302.267 307.728
236 183.796 195.343 254.063 264.235 272.836 280.443 282.734 289.461 295.710 303.400 308.871
237 184.678 196.253 255.102 265.294 273.911 281.533 283.828 290.568 296.828 304.532 310.013
238 185.560 197.163 256.141 266.353 274.987 282.623 284.922 291.675 297.947 305.664 311.154
239 186.442 198.073 257.179 267.412 276.062 283.713 286.016 292.782 299.065 306.796 312.296
240 187.324 198.984 258.218 268.471 277.138 284.802 287.110 293.888 300.182 307.927 313.437
241 188.207 199.894 259.256 269.529 278.213 285.892 288.204 294.994 301.300 309.058 314.578
242 189.090 200.805 260.295 270.588 279.288 286.981 289.298 296.100 302.417 310.189 315.718
243 189.973 201.716 261.333 271.646 280.362 288.070 290.391 297.206 303.534 311.320 316.859
244 190.856 202.627 262.371 272.704 281.437 289.159 291.484 298.311 304.651 312.450 317.999
245 191.739 203.539 263.409 273.762 282.511 290.248 292.577 299.417 305.767 313.580 319.138
246 192.623 204.450 264.447 274.820 283.586 291.336 293.670 300.522 306.883 314.710 320.278
247 193.507 205.362 265.485 275.878 284.660 292.425 294.762 301.626 307.999 315.840 321.417
248 194.391 206.274 266.523 276.935 285.734 293.513 295.855 302.731 309.115 316.969 322.556
249 195.276 207.186 267.561 277.993 286.808 294.601 296.947 303.835 310.231 318.098 323.694
250 196.161 208.098 268.599 279.050 287.882 295.689 298.039 304.940 311.346 319.227 324.832
300 240.663 253.912 320.397 331.789 341.395 349.874 352.425 359.906 366.844 375.369 381.425
350 285.608 300.064 372.051 384.306 394.626 403.723 406.457 414.474 421.900 431.017 437.488
400 330.903 346.482 423.590 436.649 447.632 457.305 460.211 468.724 476.606 486.274 493.132
450 376.483 393.118 475.035 488.849 500.456 510.670 513.736 522.717 531.026 541.212 548.432
500 422.303 439.936 526.401 540.930 553.127 563.852 567.070 576.493 585.207 595.882 603.446
550 468.328 486.910 577.701 592.909 605.667 616.878 620.241 630.084 639.183 650.324 658.215
600 514.529 534.019 628.943 644.800 658.094 669.769 673.270 683.516 692.982 704.568 712.771
650 560.885 581.245 680.134 696.614 710.421 722.542 726.176 736.807 746.625 758.639 767.141
700 607.380 628.577 731.280 748.359 762.661 775.211 778.972 789.974 800.131 812.556 821.347
750 653.997 676.003 782.386 800.043 814.822 827.785 831.670 843.029 853.514 866.336 875.404
800 700.725 723.513 833.456 851.671 866.911 880.275 884.279 895.984 906.786 919.991 929.329
850 747.554 771.099 884.492 903.249 918.937 932.689 936.808 948.848 959.957 973.534 983.133
900 794.475 818.756 935.499 954.782 970.904 985.032 989.263 1001.630 1013.036 1026.974 1036.826
950 841.480 866.477 986.478 1006.272 1022.816 1037.311 1041.651 1054.334 1066.031 1080.320 1090.418
1000 888.564 914.257 1037.431 1057.724 1074.679 1089.531 1093.977 1106.969 1118.948 1133.579 1143.917];
% remove DOF column
TAB = TAB(:,2:end);
% add the P=0.5 column
PRB = [PRB(1:2) 0.500 PRB(3:end)];
TAB = [TAB(:,1:2) DOF' TAB(:,3:end)];
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
vecnorm.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/Math/vecnorm.m
| 1,655 |
utf_8
|
2ad7cbcde8168283c2f19ee1d7142ae4
|
function [n, N_v] = vecnorm(v)
% VECNORM Vector norm, with Jacobian
% VECNORM(V) is the same as NORM(V)
%
% [n, N_v] = VECNORM(V) returns also the Jacobian.
if nargout == 1
n = sqrt(v'*v);
else
n = sqrt(v'*v);
N_v = v'/n;
end
end
%%
function f()
%%
syms v1 v2 real
v = [v1;v2];
[n,N_v] = vecnorm(v);
N_v - jacobian(n,v)
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
toFrameHmg.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/Points/toFrameHmg.m
| 3,330 |
utf_8
|
09b1d98499875375d82a33c3d3dd2323
|
function [hf,HF_f,HF_h] = toFrameHmg(F,h)
% TOFRAMEHMG To-frame transformation for homogeneous coordinates
% P = TOFRAMEHMG(F,PF) transforms homogeneous point P from the global
% frame to local frame F.
%
% [p,Pf,Ppf] = ... returns the Jacobians wrt F and PF.
% Copyright 2008-2011 Joan Sola @ LAAS-CNRS.
[t,q,R] = splitFrame(F) ;
iF = [R' -R'*t ; 0 0 0 1];
hf = iF*h;
if nargout > 1
[x,y,z] = split(t);
[a,b,c,d] = split(q);
[hx,hy,hz,ht] = split(h);
HF_f = [...
[ -ht*(a^2 + b^2 - c^2 - d^2), (-2)*ht*(a*d + b*c), 2*ht*(a*c - b*d), 2*a*hx - 2*c*hz + 2*d*hy - 2*ht*(a*x - c*z + d*y), 2*b*hx + 2*c*hy + 2*d*hz - 2*ht*(b*x + c*y + d*z), 2*b*hy - 2*a*hz - 2*c*hx + 2*ht*(a*z - b*y + c*x), 2*a*hy + 2*b*hz - 2*d*hx - 2*ht*(a*y + b*z - d*x)]
[ 2*ht*(a*d - b*c), -ht*(a^2 - b^2 + c^2 - d^2), (-2)*ht*(a*b + c*d), 2*a*hy + 2*b*hz - 2*d*hx - 2*ht*(a*y + b*z - d*x), 2*a*hz - 2*b*hy + 2*c*hx - 2*ht*(a*z - b*y + c*x), 2*b*hx + 2*c*hy + 2*d*hz - 2*ht*(b*x + c*y + d*z), 2*c*hz - 2*a*hx - 2*d*hy + 2*ht*(a*x - c*z + d*y)]
[ (-2)*ht*(a*c + b*d), 2*ht*(a*b - c*d), -ht*(a^2 - b^2 - c^2 + d^2), 2*a*hz - 2*b*hy + 2*c*hx - 2*ht*(a*z - b*y + c*x), 2*d*hx - 2*b*hz - 2*a*hy + 2*ht*(a*y + b*z - d*x), 2*a*hx - 2*c*hz + 2*d*hy - 2*ht*(a*x - c*z + d*y), 2*b*hx + 2*c*hy + 2*d*hz - 2*ht*(b*x + c*y + d*z)]
[ 0, 0, 0, 0, 0, 0, 0]];
HF_h = iF;
end
end
%%
function f()
%%
syms x y z a b c d hx hy hz ht real
F.x=[x;y;z;a;b;c;d];
F=updateFrame(F);
h = [hx;hy;hz;ht];
hf = toFrameHmg(F,h)
HF_f = simplify(jacobian(hf,F.x))
HF_h = simplify(jacobian(hf,h))
[hf,HF_f,HF_h] = toFrameHmg(F,h);
simplify(HF_f - jacobian(hf,F.x))
simplify(HF_h - jacobian(hf,h))
%%
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
printGraph.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/HighLevel/printGraph.m
| 2,867 |
utf_8
|
d2905fd327eb5bb75af74239eeda0da4
|
function printGraph(Rob,Sen,Lmk,Trj,Frm,Fac)
global Map
fprintf('--------------------------\n')
sprs = round( ( nnz( Map.H(Map.used,Map.used) ) / sum(Map.used)^2 ) * 100);
fprintf('Map size: %3d; sparse: %d%%\n', sum(Map.used), sprs)
for rob = [Rob.rob]
printRob(Rob(rob),1);
for sen = Rob(rob).sensors
printSen(Sen(sen),2);
end
printTrj(Trj(rob),2);
for i = Trj(rob).head:-1:Trj(rob).head-Trj(rob).length+1
frm = mod(i-1, Trj(rob).maxLength)+1;
printFrm(Frm(frm),3);
for fac = [Frm(frm).factors]
printFac(Fac(fac),4);
end
end
end
for lmk = find([Lmk.used])
printLmk(Lmk(lmk),1);
end
end
function tbs = tabs(k, tb)
if nargin == 1
tb = ' ';
end
tbs = '';
for i = 1:k
tbs = [tbs tb] ;
end
end
function printRob(Rob,ntabs)
fprintf('%sRob: %2d\n', tabs(ntabs), Rob.rob)
end
function printSen(Sen,ntabs)
fprintf('%sSen: %2d\n', tabs(ntabs), Sen.sen)
end
function printLmk(Lmk,ntabs)
fprintf('%sLmk: %2d (%2d)\n', tabs(ntabs), Lmk.lmk, Lmk.id)
end
function printTrj(Trj,ntabs)
fprintf('%sTrj: head <- %s <-tail\n', tabs(ntabs), num2str(mod((Trj.head:-1:Trj.head-Trj.length+1)-1,Trj.maxLength)+1))
end
function printFrm(Frm,ntabs)
fprintf('%sFrm: %2d (%3d)\n', tabs(ntabs), Frm.frm, Frm.id)
end
function printFac(Fac,ntabs)
fprintf('%sFac: %3d, %s', tabs(ntabs), Fac.fac, Fac.type(1:4))
if (isempty(Fac.lmk)) % abs or motion
fprintf(', frm: ')
fprintf('%3d', Fac.frames)
else % measurement
fprintf(', lmk: %2d', Fac.lmk)
end
fprintf('\n')
end
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
github
|
rising-turtle/slam_matlab-master
|
invDistortion.m
|
.m
|
slam_matlab-master/libs_dir/SLAM_courses/slamtb/Observations/invDistortion.m
| 4,597 |
utf_8
|
a894c5170cd896e4c51acc53898dc52e
|
function kc = invDistortion(kd,n,cal,draw)
% INVDISTORTION Radial distortion correction calibration.
%
% Kc = INVDISTORTION(Kd,n) computes the least squares optimal set
% of n parameters of the correction radial distortion function
% for a normalized camera:
%
% r = c(rd) = rd (1 + c2 rd^2 + ... + c2n rd^2n)
%
% that best approximates the inverse of the distortion function
%
% rd = d(r) = r (1 + d2 r^2 + d4 r^4 + ...)
%
% which can be of any length.
%
% Kc = INVDISTORTION(Kd,n,cal) accepts the intrinsic parameters
% of the camera cal = [u_0, v_0, a_u, a_v].
%
% The format of the distortion and correction vectors is
%
% Kd = [d2, d4, d6, ...]
% Kc = [c2, c4, ..., c2n]
%
% Kc = INVDISTORTION(...,DRAW) with DRAW~=0 additionally plots the
% distortion and correction mappings r_d=d(r) and r=c(r_d)
% and the error (r - r_d).
%
% See also PINHOLE, INVPINHOLE.
% Copyright 2008-2009 Joan Sola @ LAAS-CNRS.
if numel(kd) == 0
kc = [];
else
if nargin == 2 || isempty(cal)
cal = [1 1 1 1];
end
% fprintf(' Obtaining correction vector from distortion vector...');
rmax2 = (cal(1)/cal(3))^2 + (cal(2)/cal(4))^2;
rmax = sqrt(rmax2); % maximum radius in normalized coordinates
rdmax = 1.1*rmax;
% N=101 sampling points of d(r)
rc = [0:.01*rdmax:rdmax]; % rc is the undistorted radius vector
rd = c2d(kd,rc); % rd is the distorted radius vector
% 1. non-linear least-squares method (for other than radial distortion)
% comment out for testing against psudo-inverse method
% x0 = zeros(1,n);
% kc = lsqnonlin(@(x) fun(x,rc,rd),x0);
% 2. pseudo-inverse method (indicated for radial distortion)
% we solve the system A*Kc = rc-rd via Kc = pinv(A)*(rc-rd).
A = []; % construction of A for Kc of length n
for i = 1:n
A = [A rd'.^(2*i+1)];
end
B = pinv(A);
kc = (rc-rd)*B'; % All transposed because we are working with row-vectors
% fprintf(' OK.\n');
if nargin == 4 && draw
% normalized error
erc = d2c(kc,rd);
% correction and distortion functions
figure(9)
subplot(3,1,[1 2])
plot(rc,rd,'linewidth',2)
title('Distortion mapping'),xlabel('r'),ylabel('rd'),grid
set(gca,'xlim',[0 rdmax])
hold on
plot(erc,rd,'r--','linewidth',2)
hold off
% error function (in pixels)
subplot(3,1,3)
plot(rc,cal(3)*(rc-erc))
title('Correction error [pix]'),xlabel('r'),ylabel('error'),grid
set(gca,'xlim',[0 rdmax])
% error values
err_max = cal(3)*max (abs(rc-erc));
err_mean = cal(3)*mean(rc-erc);
err_std = cal(3)*std (rc-erc);
fprintf(1,' Errors. Max: %.2f | Mean: %.2f | Std: %.2f pixels.\n',err_max,err_mean,err_std)
end
end
% Necessary functions
% corr- to dis- conversion
function rd = c2d(kd,rc)
c = ones(1,length(rc));
for i=1:length(kd)
c = c+kd(i)*rc.^(2*i);
end
rd = rc.*c;
% dis- to corr- conversion
function rc = d2c(kc,rd)
c = ones(1,length(rd));
for i=1:length(kc)
c = c+kc(i)*rd.^(2*i);
end
rc = rd.*c;
% error function (only for non-linear least squares - normally
% not necessary)
function e = fun(kc,rc,rd)
e = d2c(kc,rd) - rc;
% ========== End of function - Start GPL license ==========
% # START GPL LICENSE
%---------------------------------------------------------------------
%
% This file is part of SLAMTB, a SLAM toolbox for Matlab.
%
% SLAMTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% SLAMTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with SLAMTB. If not, see <http://www.gnu.org/licenses/>.
%
%---------------------------------------------------------------------
% SLAMTB is Copyright:
% Copyright (c) 2008-2010, Joan Sola @ LAAS-CNRS,
% Copyright (c) 2010-2013, Joan Sola,
% Copyright (c) 2014-2015, Joan Sola @ IRI-UPC-CSIC,
% SLAMTB is Copyright 2009
% by Joan Sola, Teresa Vidal-Calleja, David Marquez and Jean Marie Codol
% @ LAAS-CNRS.
% See on top of this file for its particular copyright.
% # END GPL LICENSE
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.