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
|
philippboehmsturm/antx-master
|
flip_lr.m
|
.m
|
antx-master/mritools/others/nii/flip_lr.m
| 3,568 |
utf_8
|
d95b62698d44a65a3c2f02fbabc632ac
|
% When you load any ANALYZE or NIfTI file with 'load_nii.m', and view
% it with 'view_nii.m', you may find that the image is L-R flipped.
% This is because of the confusion of radiological and neurological
% convention in the medical image before NIfTI format is adopted. You
% can find more details from:
%
% http://www.rotman-baycrest.on.ca/~jimmy/UseANALYZE.htm
%
% Sometime, people even want to convert RAS (standard orientation) back
% to LAS orientation to satisfy the legend programs or processes. This
% program is only written for those purpose. So PLEASE BE VERY CAUTIOUS
% WHEN USING THIS 'FLIP_LR.M' PROGRAM.
%
% With 'flip_lr.m', you can convert any ANALYZE or NIfTI (no matter
% 3D or 4D) file to a flipped NIfTI file. This is implemented simply
% by flipping the affine matrix in the NIfTI header. Since the L-R
% orientation is determined there, so the image will be flipped.
%
% Usage: flip_lr(original_fn, flipped_fn, [old_RGB],[tolerance],[preferredForm])
%
% original_fn - filename of the original ANALYZE or NIfTI (3D or 4D) file
%
% flipped_fn - filename of the L-R flipped NIfTI file
%
% old_RGB (optional) - a scale number to tell difference of new RGB24
% from old RGB24. New RGB24 uses RGB triple sequentially for each
% voxel, like [R1 G1 B1 R2 G2 B2 ...]. Analyze 6.0 from AnalyzeDirect
% uses old RGB24, in a way like [R1 R2 ... G1 G2 ... B1 B2 ...] for
% each slices. If the image that you view is garbled, try to set
% old_RGB variable to 1 and try again, because it could be in
% old RGB24. It will be set to 0, if it is default or empty.
%
% tolerance (optional) - distortion allowed for non-orthogonal rotation
% or shearing in NIfTI affine matrix. It will be set to 0.1 (10%),
% if it is default or empty.
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% Example: flip_lr('avg152T1_LR_nifti.nii', 'flipped_lr.nii');
% flip_lr('avg152T1_RL_nifti.nii', 'flipped_rl.nii');
%
% You will find that 'avg152T1_LR_nifti.nii' and 'avg152T1_RL_nifti.nii'
% are the same, and 'flipped_lr.nii' and 'flipped_rl.nii' are also the
% the same, but they are L-R flipped from 'avg152T1_*'.
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function flip_lr(original_fn, flipped_fn, old_RGB, tolerance, preferredForm)
if ~exist('original_fn','var') | ~exist('flipped_fn','var')
error('Usage: flip_lr(original_fn, flipped_fn, [old_RGB],[tolerance])');
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
if ~exist('tolerance','var') | isempty(tolerance)
tolerance = 0.1;
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
nii = load_nii(original_fn, [], [], [], [], old_RGB, tolerance, preferredForm);
M = diag(nii.hdr.dime.pixdim(2:5));
M(1:3,4) = -M(1:3,1:3)*(nii.hdr.hist.originator(1:3)-1)';
M(1,:) = -1*M(1,:);
nii.hdr.hist.sform_code = 1;
nii.hdr.hist.srow_x = M(1,:);
nii.hdr.hist.srow_y = M(2,:);
nii.hdr.hist.srow_z = M(3,:);
save_nii(nii, flipped_fn);
return; % flip_lr
|
github
|
philippboehmsturm/antx-master
|
save_nii.m
|
.m
|
antx-master/mritools/others/nii/save_nii.m
| 9,690 |
utf_8
|
ed292054cab74afaf953455bfbc200aa
|
% Save NIFTI dataset. Support both *.nii and *.hdr/*.img file extension.
% If file extension is not provided, *.hdr/*.img will be used as default.
%
% Usage: save_nii(nii, filename, [old_RGB])
%
% nii.hdr - struct with NIFTI header fields (from load_nii.m or make_nii.m)
%
% nii.img - 3D (or 4D) matrix of NIFTI data.
%
% filename - NIFTI file name.
%
% old_RGB - an optional boolean variable to handle special RGB data
% sequence [R1 R2 ... G1 G2 ... B1 B2 ...] that is used only by
% AnalyzeDirect (Analyze Software). Since both NIfTI and Analyze
% file format use RGB triple [R1 G1 B1 R2 G2 B2 ...] sequentially
% for each voxel, this variable is set to FALSE by default. If you
% would like the saved image only to be opened by AnalyzeDirect
% Software, set old_RGB to TRUE (or 1). It will be set to 0, if it
% is default or empty.
%
% Tip: to change the data type, set nii.hdr.dime.datatype,
% and nii.hdr.dime.bitpix to:
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
% - "old_RGB" related codes in "save_nii.m" are added by Mike Harms (2006.06.28)
%
function save_nii(nii, fileprefix, old_RGB)
if ~exist('nii','var') | isempty(nii) | ~isfield(nii,'hdr') | ...
~isfield(nii,'img') | ~exist('fileprefix','var') | isempty(fileprefix)
error('Usage: save_nii(nii, filename, [old_RGB])');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''save_untouch_nii.m'' for the untouched structure.');
end
if ~exist('old_RGB','var') | isempty(old_RGB)
old_RGB = 0;
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(fileprefix) > 2 & strcmp(fileprefix(end-2:end), '.gz')
if ~strcmp(fileprefix(end-6:end), '.img.gz') & ...
~strcmp(fileprefix(end-6:end), '.hdr.gz') & ...
~strcmp(fileprefix(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
fileprefix = fileprefix(1:end-3);
end
end
filetype = 1;
% Note: fileprefix is actually the filename you want to save
%
if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii')
filetype = 2;
fileprefix(end-3:end)='';
end
if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr')
fileprefix(end-3:end)='';
end
if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img')
fileprefix(end-3:end)='';
end
write_nii(nii, filetype, fileprefix, old_RGB);
% gzip output file if requested
%
if exist('gzFile', 'var')
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
end;
end;
if filetype == 1
% So earlier versions of SPM can also open it with correct originator
%
M=[[diag(nii.hdr.dime.pixdim(2:4)) -[nii.hdr.hist.originator(1:3).*nii.hdr.dime.pixdim(2:4)]'];[0 0 0 1]];
save([fileprefix '.mat'], 'M');
end
return % save_nii
%-----------------------------------------------------------------------------------
function write_nii(nii, filetype, fileprefix, old_RGB)
hdr = nii.hdr;
if isfield(nii,'ext') & ~isempty(nii.ext)
ext = nii.ext;
[ext, esize_total] = verify_nii_ext(ext);
else
ext = [];
end
switch double(hdr.dime.datatype),
case 1,
hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
case 2,
hdr.dime.bitpix = int16(8 ); precision = 'uint8';
case 4,
hdr.dime.bitpix = int16(16); precision = 'int16';
case 8,
hdr.dime.bitpix = int16(32); precision = 'int32';
case 16,
hdr.dime.bitpix = int16(32); precision = 'float32';
case 32,
hdr.dime.bitpix = int16(64); precision = 'float32';
case 64,
hdr.dime.bitpix = int16(64); precision = 'float64';
case 128,
hdr.dime.bitpix = int16(24); precision = 'uint8';
case 256
hdr.dime.bitpix = int16(8 ); precision = 'int8';
case 511,
hdr.dime.bitpix = int16(96); precision = 'float32';
case 512
hdr.dime.bitpix = int16(16); precision = 'uint16';
case 768
hdr.dime.bitpix = int16(32); precision = 'uint32';
case 1024
hdr.dime.bitpix = int16(64); precision = 'int64';
case 1280
hdr.dime.bitpix = int16(64); precision = 'uint64';
case 1792,
hdr.dime.bitpix = int16(128); precision = 'float64';
otherwise
error('This datatype is not supported');
end
hdr.dime.glmax = round(double(max(nii.img(:))));
hdr.dime.glmin = round(double(min(nii.img(:))));
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 352;
if ~isempty(ext)
hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
end
hdr.hist.magic = 'n+1';
save_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
else
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 0;
hdr.hist.magic = 'ni1';
save_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
end
ScanDim = double(hdr.dime.dim(5)); % t
SliceDim = double(hdr.dime.dim(4)); % z
RowDim = double(hdr.dime.dim(3)); % y
PixelDim = double(hdr.dime.dim(2)); % x
SliceSz = double(hdr.dime.pixdim(4));
RowSz = double(hdr.dime.pixdim(3));
PixelSz = double(hdr.dime.pixdim(2));
x = 1:PixelDim;
if filetype == 2 & isempty(ext)
skip_bytes = double(hdr.dime.vox_offset) - 348;
else
skip_bytes = 0;
end
if double(hdr.dime.datatype) == 128
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
if old_RGB
nii.img = permute(nii.img, [1 2 4 3 5 6 7 8]);
else
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
end
if double(hdr.dime.datatype) == 511
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
if old_RGB
nii.img = permute(nii.img, [1 2 4 3 5 6 7 8]);
else
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
real_img = real(nii.img(:))';
nii.img = imag(nii.img(:))';
nii.img = [real_img; nii.img];
end
if skip_bytes
fwrite(fid, zeros(1,skip_bytes), 'uint8');
end
fwrite(fid, nii.img, precision);
% fwrite(fid, nii.img, precision, skip_bytes); % error using skip
fclose(fid);
return; % write_nii
|
github
|
philippboehmsturm/antx-master
|
rri_file_menu.m
|
.m
|
antx-master/mritools/others/nii/rri_file_menu.m
| 4,153 |
utf_8
|
c9faa3905c642854eeed98ab8b02998e
|
% Imbed a file menu to any figure. If file menu exist, it will append
% to the existing file menu. This file menu includes: Copy to clipboard,
% print, save, close etc.
%
% Usage: rri_file_menu(fig);
%
% rri_file_menu(fig,0) means no 'Close' menu.
%
% - Jimmy Shen ([email protected])
%
%--------------------------------------------------------------------
function rri_file_menu(action, varargin)
if isnumeric(action)
fig = action;
action = 'init';
end
% clear the message line,
%
h = findobj(gcf,'Tag','MessageLine');
set(h,'String','');
if ~strcmp(action, 'init')
set(gcbf, 'InvertHardcopy','off');
% set(gcbf, 'PaperPositionMode','auto');
end
switch action
case {'init'}
if nargin > 1
init(fig, 1); % no 'close' menu
else
init(fig, 0);
end
case {'print_fig'}
printdlg(gcbf);
case {'copy_fig'}
copy_fig;
case {'export_fig'}
export_fig;
end
return % rri_file_menu
%------------------------------------------------
%
% Create (or append) File menu
%
function init(fig, no_close)
% search for file menu
%
h_file = [];
menuitems = findobj(fig, 'type', 'uimenu');
for i=1:length(menuitems)
filelabel = get(menuitems(i),'label');
if strcmpi(strrep(filelabel, '&', ''), 'file')
h_file = menuitems(i);
break;
end
end
set(fig, 'menubar', 'none');
if isempty(h_file)
if isempty(menuitems)
h_file = uimenu('parent', fig, 'label', 'File');
else
h_file = uimenu('parent', fig, 'label', 'Copy Figure');
end
h1 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''copy_fig'');', ...
'label','Copy to Clipboard');
else
h1 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''copy_fig'');', ...
'separator','on', ...
'label','Copy to Clipboard');
end
h2 = uimenu(h_file, ...
'callback','pagesetupdlg(gcbf);', ...
'label','Page Setup...');
h2 = uimenu(h_file, ...
'callback','printpreview(gcbf);', ...
'label','Print Preview...');
h2 = uimenu('parent', h_file, ...
'callback','printdlg(gcbf);', ...
'label','Print Figure ...');
h2 = uimenu('parent', h_file, ...
'callback','rri_file_menu(''export_fig'');', ...
'label','Save Figure ...');
arch = computer;
if ~strcmpi(arch(1:2),'PC')
set(h1, 'enable', 'off');
end
if ~no_close
h1 = uimenu('parent', h_file, ...
'callback','close(gcbf);', ...
'separator','on', ...
'label','Close');
end
return; % init
%------------------------------------------------
%
% Copy to clipboard
%
function copy_fig
arch = computer;
if(~strcmpi(arch(1:2),'PC'))
error('copy to clipboard can only be used under MS Windows');
return;
end
print -noui -dbitmap;
return % copy_fig
%------------------------------------------------
%
% Save as an image file
%
function export_fig
curr = pwd;
if isempty(curr)
curr = filesep;
end
[selected_file, selected_path] = rri_select_file(curr,'Save As');
if isempty(selected_file) | isempty(selected_path)
return;
end
filename = [selected_path selected_file];
if(exist(filename,'file')==2) % file exist
dlg_title = 'Confirm File Overwrite';
msg = ['File ',filename,' exist. Are you sure you want to overwrite it?'];
response = questdlg(msg,dlg_title,'Yes','No','Yes');
if(strcmp(response,'No'))
return;
end
end
old_pointer = get(gcbf,'pointer');
set(gcbf,'pointer','watch');
try
saveas(gcbf,filename);
catch
msg = 'ERROR: Cannot save file';
set(findobj(gcf,'Tag','MessageLine'),'String',msg);
end
set(gcbf,'pointer',old_pointer);
return; % export_fig
|
github
|
philippboehmsturm/antx-master
|
reslice_nii.m
|
.m
|
antx-master/mritools/others/nii/reslice_nii.m
| 10,138 |
utf_8
|
ea18d2f994fd5d9989449feaced1e4dd
|
% The basic application of the 'reslice_nii.m' program is to perform
% any 3D affine transform defined by a NIfTI format image.
%
% In addition, the 'reslice_nii.m' program can also be applied to
% generate an isotropic image from either a NIfTI format image or
% an ANALYZE format image.
%
% The resliced NIfTI file will always be in RAS orientation.
%
% This program only supports real integer or floating-point data type.
% For other data type, the program will exit with an error message
% "Transform of this NIFTI data is not supported by the program".
%
% Usage: reslice_nii(old_fn, new_fn, [voxel_size], [verbose], [bg], ...
% [method], [img_idx], [preferredForm]);
%
% old_fn - filename for original NIfTI file
%
% new_fn - filename for resliced NIfTI file
%
% voxel_size (optional) - size of a voxel in millimeter along x y z
% direction for resliced NIfTI file. 'voxel_size' will use
% the minimum voxel_size in original NIfTI header,
% if it is default or empty.
%
% verbose (optional) - 1, 0
% 1: show transforming progress in percentage
% 2: progress will not be displayed
% 'verbose' is 1 if it is default or empty.
%
% bg (optional) - background voxel intensity in any extra corner that
% is caused by 3D interpolation. 0 in most cases. 'bg'
% will be the average of two corner voxel intensities
% in original image volume, if it is default or empty.
%
% method (optional) - 1, 2, or 3
% 1: for Trilinear interpolation
% 2: for Nearest Neighbor interpolation
% 3: for Fischer's Bresenham interpolation
% 'method' is 1 if it is default or empty.
%
% img_idx (optional) - a numerical array of image volume indices. Only
% the specified volumes will be loaded. All available image
% volumes will be loaded, if it is default or empty.
%
% The number of images scans can be obtained from get_nii_frame.m,
% or simply: hdr.dime.dim(5).
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function reslice_nii(old_fn, new_fn, voxel_size, verbose, bg, method, img_idx, preferredForm)
if ~exist('old_fn','var') | ~exist('new_fn','var')
error('Usage: reslice_nii(old_fn, new_fn, [voxel_size], [verbose], [bg], [method], [img_idx])');
end
if ~exist('method','var') | isempty(method)
method = 1;
end
if ~exist('img_idx','var') | isempty(img_idx)
img_idx = [];
end
if ~exist('verbose','var') | isempty(verbose)
verbose = 1;
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
nii = load_nii_no_xform(old_fn, img_idx, 0, preferredForm);
if ~ismember(nii.hdr.dime.datatype, [2,4,8,16,64,256,512,768])
error('Transform of this NIFTI data is not supported by the program.');
end
if ~exist('voxel_size','var') | isempty(voxel_size)
voxel_size = abs(min(nii.hdr.dime.pixdim(2:4)))*ones(1,3);
elseif length(voxel_size) < 3
voxel_size = abs(voxel_size(1))*ones(1,3);
end
if ~exist('bg','var') | isempty(bg)
bg = mean([nii.img(1) nii.img(end)]);
end
old_M = nii.hdr.hist.old_affine;
if nii.hdr.dime.dim(5) > 1
for i = 1:nii.hdr.dime.dim(5)
if verbose
fprintf('Reslicing %d of %d volumes.\n', i, nii.hdr.dime.dim(5));
end
[img(:,:,:,i) M] = ...
affine(nii.img(:,:,:,i), old_M, voxel_size, verbose, bg, method);
end
else
[img M] = affine(nii.img, old_M, voxel_size, verbose, bg, method);
end
new_dim = size(img);
nii.img = img;
nii.hdr.dime.dim(2:4) = new_dim(1:3);
nii.hdr.dime.datatype = 16;
nii.hdr.dime.bitpix = 32;
nii.hdr.dime.pixdim(2:4) = voxel_size(:)';
nii.hdr.dime.glmax = max(img(:));
nii.hdr.dime.glmin = min(img(:));
nii.hdr.hist.qform_code = 0;
nii.hdr.hist.sform_code = 1;
nii.hdr.hist.srow_x = M(1,:);
nii.hdr.hist.srow_y = M(2,:);
nii.hdr.hist.srow_z = M(3,:);
nii.hdr.hist.new_affine = M;
save_nii(nii, new_fn);
return; % reslice_nii
%--------------------------------------------------------------------
function [nii] = load_nii_no_xform(filename, img_idx, old_RGB, preferredForm)
if ~exist('filename','var'),
error('Usage: [nii] = load_nii(filename, [img_idx], [old_RGB])');
end
if ~exist('img_idx','var'), img_idx = []; end
if ~exist('old_RGB','var'), old_RGB = 0; end
if ~exist('preferredForm','var'), preferredForm= 's'; end % Jeff
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);
% Read the header extension
%
% nii.ext = load_nii_ext(filename);
% Read the dataset body
%
[nii.img,nii.hdr] = ...
load_nii_img(nii.hdr,nii.filetype,nii.fileprefix,nii.machine,img_idx,'','','',old_RGB);
% Perform some of sform/qform transform
%
% nii = xform_nii(nii, preferredForm);
% Clean up after gunzip
%
if exist('gzFileName', 'var')
% fix fileprefix so it doesn't point to temp location
%
nii.fileprefix = gzFileName(1:end-7);
rmdir(tmpDir,'s');
end
hdr = nii.hdr;
% NIFTI can have both sform and qform transform. This program
% will check sform_code prior to qform_code by default.
%
% If user specifys "preferredForm", user can then choose the
% priority. - Jeff
%
useForm=[]; % Jeff
if isequal(preferredForm,'S')
if isequal(hdr.hist.sform_code,0)
error('User requires sform, sform not set in header');
else
useForm='s';
end
end % Jeff
if isequal(preferredForm,'Q')
if isequal(hdr.hist.qform_code,0)
error('User requires sform, sform not set in header');
else
useForm='q';
end
end % Jeff
if isequal(preferredForm,'s')
if hdr.hist.sform_code > 0
useForm='s';
elseif hdr.hist.qform_code > 0
useForm='q';
end
end % Jeff
if isequal(preferredForm,'q')
if hdr.hist.qform_code > 0
useForm='q';
elseif hdr.hist.sform_code > 0
useForm='s';
end
end % Jeff
if isequal(useForm,'s')
R = [hdr.hist.srow_x(1:3)
hdr.hist.srow_y(1:3)
hdr.hist.srow_z(1:3)];
T = [hdr.hist.srow_x(4)
hdr.hist.srow_y(4)
hdr.hist.srow_z(4)];
nii.hdr.hist.old_affine = [ [R;[0 0 0]] [T;1] ];
elseif isequal(useForm,'q')
b = hdr.hist.quatern_b;
c = hdr.hist.quatern_c;
d = hdr.hist.quatern_d;
if 1.0-(b*b+c*c+d*d) < 0
if abs(1.0-(b*b+c*c+d*d)) < 1e-5
a = 0;
else
error('Incorrect quaternion values in this NIFTI data.');
end
else
a = sqrt(1.0-(b*b+c*c+d*d));
end
qfac = hdr.dime.pixdim(1);
i = hdr.dime.pixdim(2);
j = hdr.dime.pixdim(3);
k = qfac * hdr.dime.pixdim(4);
R = [a*a+b*b-c*c-d*d 2*b*c-2*a*d 2*b*d+2*a*c
2*b*c+2*a*d a*a+c*c-b*b-d*d 2*c*d-2*a*b
2*b*d-2*a*c 2*c*d+2*a*b a*a+d*d-c*c-b*b];
T = [hdr.hist.qoffset_x
hdr.hist.qoffset_y
hdr.hist.qoffset_z];
nii.hdr.hist.old_affine = [ [R * diag([i j k]);[0 0 0]] [T;1] ];
elseif nii.filetype == 0 & exist([nii.fileprefix '.mat'],'file')
load([nii.fileprefix '.mat']); % old SPM affine matrix
R=M(1:3,1:3);
T=M(1:3,4);
T=R*ones(3,1)+T;
M(1:3,4)=T;
nii.hdr.hist.old_affine = M;
else
M = diag(hdr.dime.pixdim(2:5));
M(1:3,4) = -M(1:3,1:3)*(hdr.hist.originator(1:3)-1)';
M(4,4) = 1;
nii.hdr.hist.old_affine = M;
end
return % load_nii_no_xform
|
github
|
philippboehmsturm/antx-master
|
save_untouch_nii.m
|
.m
|
antx-master/mritools/others/nii/save_untouch_nii.m
| 6,726 |
utf_8
|
cb98e2799abc112dca5b10078bde09bf
|
% Save NIFTI or ANALYZE dataset that is loaded by "load_untouch_nii.m".
% The output image format and file extension will be the same as the
% input one (NIFTI.nii, NIFTI.img or ANALYZE.img). Therefore, any file
% extension that you specified will be ignored.
%
% Usage: save_untouch_nii(nii, filename)
%
% nii - nii structure that is loaded by "load_untouch_nii.m"
%
% filename - NIFTI or ANALYZE file name.
%
% - Jimmy Shen ([email protected])
%
function save_untouch_nii(nii, filename)
if ~exist('nii','var') | isempty(nii) | ~isfield(nii,'hdr') | ...
~isfield(nii,'img') | ~exist('filename','var') | isempty(filename)
error('Usage: save_untouch_nii(nii, filename)');
end
if ~isfield(nii,'untouch') | nii.untouch == 0
error('Usage: please use ''save_nii.m'' for the modified structure.');
end
if isfield(nii.hdr.hist,'magic') & strcmp(nii.hdr.hist.magic(1:3),'ni1')
filetype = 1;
elseif isfield(nii.hdr.hist,'magic') & strcmp(nii.hdr.hist.magic(1:3),'n+1')
filetype = 2;
else
filetype = 0;
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
filename = filename(1:end-3);
end
end
[p,f] = fileparts(filename);
fileprefix = fullfile(p, f);
write_nii(nii, filetype, fileprefix);
% gzip output file if requested
%
if exist('gzFile', 'var')
if filetype == 1
gzip([fileprefix, '.img']);
delete([fileprefix, '.img']);
gzip([fileprefix, '.hdr']);
delete([fileprefix, '.hdr']);
elseif filetype == 2
gzip([fileprefix, '.nii']);
delete([fileprefix, '.nii']);
end;
end;
% % So earlier versions of SPM can also open it with correct originator
% %
% if filetype == 0
% M=[[diag(nii.hdr.dime.pixdim(2:4)) -[nii.hdr.hist.originator(1:3).*nii.hdr.dime.pixdim(2:4)]'];[0 0 0 1]];
% save(fileprefix, 'M');
% elseif filetype == 1
% M=[];
% save(fileprefix, 'M');
%end
return % save_untouch_nii
%-----------------------------------------------------------------------------------
function write_nii(nii, filetype, fileprefix)
hdr = nii.hdr;
if isfield(nii,'ext') & ~isempty(nii.ext)
ext = nii.ext;
[ext, esize_total] = verify_nii_ext(ext);
else
ext = [];
end
switch double(hdr.dime.datatype),
case 1,
hdr.dime.bitpix = int16(1 ); precision = 'ubit1';
case 2,
hdr.dime.bitpix = int16(8 ); precision = 'uint8';
case 4,
hdr.dime.bitpix = int16(16); precision = 'int16';
case 8,
hdr.dime.bitpix = int16(32); precision = 'int32';
case 16,
hdr.dime.bitpix = int16(32); precision = 'float32';
case 32,
hdr.dime.bitpix = int16(64); precision = 'float32';
case 64,
hdr.dime.bitpix = int16(64); precision = 'float64';
case 128,
hdr.dime.bitpix = int16(24); precision = 'uint8';
case 256
hdr.dime.bitpix = int16(8 ); precision = 'int8';
case 512
hdr.dime.bitpix = int16(16); precision = 'uint16';
case 768
hdr.dime.bitpix = int16(32); precision = 'uint32';
case 1024
hdr.dime.bitpix = int16(64); precision = 'int64';
case 1280
hdr.dime.bitpix = int16(64); precision = 'uint64';
case 1792,
hdr.dime.bitpix = int16(128); precision = 'float64';
otherwise
error('This datatype is not supported');
end
% hdr.dime.glmax = round(double(max(nii.img(:))));
% hdr.dime.glmin = round(double(min(nii.img(:))));
if filetype == 2
fid = fopen(sprintf('%s.nii',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.nii.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 352;
if ~isempty(ext)
hdr.dime.vox_offset = hdr.dime.vox_offset + esize_total;
end
hdr.hist.magic = 'n+1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
elseif filetype == 1
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
hdr.dime.vox_offset = 0;
hdr.hist.magic = 'ni1';
save_untouch_nii_hdr(hdr, fid);
if ~isempty(ext)
save_nii_ext(ext, fid);
end
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
else
fid = fopen(sprintf('%s.hdr',fileprefix),'w');
if fid < 0,
msg = sprintf('Cannot open file %s.hdr.',fileprefix);
error(msg);
end
save_untouch0_nii_hdr(hdr, fid);
fclose(fid);
fid = fopen(sprintf('%s.img',fileprefix),'w');
end
ScanDim = double(hdr.dime.dim(5)); % t
SliceDim = double(hdr.dime.dim(4)); % z
RowDim = double(hdr.dime.dim(3)); % y
PixelDim = double(hdr.dime.dim(2)); % x
SliceSz = double(hdr.dime.pixdim(4));
RowSz = double(hdr.dime.pixdim(3));
PixelSz = double(hdr.dime.pixdim(2));
x = 1:PixelDim;
if filetype == 2 & isempty(ext)
skip_bytes = double(hdr.dime.vox_offset) - 348;
else
skip_bytes = 0;
end
if double(hdr.dime.datatype) == 128
% RGB planes are expected to be in the 4th dimension of nii.img
%
if(size(nii.img,4)~=3)
error(['The NII structure does not appear to have 3 RGB color planes in the 4th dimension']);
end
nii.img = permute(nii.img, [4 1 2 3 5 6 7 8]);
end
% For complex float32 or complex float64, voxel values
% include [real, imag]
%
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792
real_img = real(nii.img(:))';
nii.img = imag(nii.img(:))';
nii.img = [real_img; nii.img];
end
if skip_bytes
fwrite(fid, zeros(1,skip_bytes), 'uint8');
end
fwrite(fid, nii.img, precision);
% fwrite(fid, nii.img, precision, skip_bytes); % error using skip
fclose(fid);
return; % write_nii
|
github
|
philippboehmsturm/antx-master
|
view_nii.m
|
.m
|
antx-master/mritools/others/nii/view_nii.m
| 144,481 |
utf_8
|
8ea68ec34d3a6bec721497afb56cfb54
|
% VIEW_NII: Create or update a 3-View (Front, Top, Side) of the
% brain data that is specified by nii structure
%
% Usage: status = view_nii([h], nii, [option]) or
% status = view_nii(h, [option])
%
% Where, h is the figure on which the 3-View will be plotted;
% nii is the brain data in NIFTI format;
% option is a struct that configures the view plotted, can be:
%
% option.command = 'init'
% option.command = 'update'
% option.command = 'clearnii'
% option.command = 'updatenii'
% option.command = 'updateimg' (nii is nii.img here)
%
% option.usecolorbar = 0 | [1]
% option.usepanel = 0 | [1]
% option.usecrosshair = 0 | [1]
% option.usestretch = 0 | [1]
% option.useimagesc = 0 | [1]
% option.useinterp = [0] | 1
%
% option.setarea = [x y w h] | [0.05 0.05 0.9 0.9]
% option.setunit = ['vox'] | 'mm'
% option.setviewpoint = [x y z] | [origin]
% option.setscanid = [t] | [1]
% option.setcrosshaircolor = [r g b] | [1 0 0]
% option.setcolorindex = From 1 to 9 (default is 2 or 3)
% option.setcolormap = (Mx3 matrix, 0 <= val <= 1)
% option.setcolorlevel = No more than 256 (default 256)
% option.sethighcolor = []
% option.setcbarminmax = []
% option.setvalue = []
% option.glblocminmax = []
% option.setbuttondown = ''
% option.setcomplex = [0] | 1 | 2
%
% Options description in detail:
% ==============================
%
% 1. command: A char string that can control program.
%
% init: If option.command='init', the program will display
% a 3-View plot on the figure specified by figure h
% or on a new figure. If there is already a 3-View
% plot on the figure, please use option.command =
% 'updatenii' (see detail below); otherwise, the
% new 3-View plot will superimpose on the old one.
% If there is no option provided, the program will
% assume that this is an initial plot. If the figure
% handle is omitted, the program knows that it is
% an initial plot.
%
% update: If there is no command specified, and a figure
% handle of the existing 3-View plot is provided,
% the program will choose option.command='update'
% to update the 3-View plot with some new option
% items.
%
% clearnii: Clear 3-View plot on specific figure
%
% updatenii: If a new nii is going to be loaded on a fig
% that has already 3-View plot on it, use this
% command to clear existing 3-View plot, and then
% display with new nii. So, the new nii will not
% superimpose on the existing one. All options
% for 'init' can be used for 'updatenii'.
%
% updateimg: If a new 3D matrix with the same dimension
% is going to be loaded, option.command='updateimg'
% can be used as a light-weighted 'updatenii, since
% it only updates the 3 slices with new values.
% inputing argument nii should be a 3D matrix
% (nii.img) instead of nii struct. No other option
% should be used together with 'updateimg' to keep
% this command as simple as possible.
%
%
% 2. usecolorbar: If specified and usecolorbar=0, the program
% will not include the colorbar in plot area; otherwise,
% a colorbar will be included in plot area.
%
% 3. usepanel: If specified and usepanel=0, the control panel
% at lower right cornor will be invisible; otherwise,
% it will be visible.
%
% 4. usecrosshair: If specified and usecrosshair=0, the crosshair
% will be invisible; otherwise, it will be visible.
%
% 5. usestretch: If specified and usestretch=0, the 3 slices will
% not be stretched, and will be displayed according to
% the actual voxel size; otherwise, the 3 slices will be
% stretched to the edge.
%
% 6. useimagesc: If specified and useimagesc=0, images data will
% be used directly to match the colormap (like 'image'
% command); otherwise, image data will be scaled to full
% colormap with 'imagesc' command in Matlab.
%
% 7. useinterp: If specified and useinterp=1, the image will be
% displayed using interpolation. Otherwise, it will be
% displayed like mosaic, and each tile stands for a
% pixel. This option does not apply to 'setvalue' option
% is set.
%
%
% 8. setarea: 3-View plot will be displayed on this specific
% region. If it is not specified, program will set the
% plot area to [0.05 0.05 0.9 0.9].
%
% 9. setunit: It can be specified to setunit='voxel' or 'mm'
% and the view will change the axes unit of [X Y Z]
% accordingly.
%
% 10. setviewpoint: If specified, [X Y Z] values will be used
% to set the viewpoint of 3-View plot.
%
% 11. setscanid: If specified, [t] value will be used to display
% the specified image scan in NIFTI data.
%
% 12. setcrosshaircolor: If specified, [r g b] value will be used
% for Crosshair Color. Otherwise, red will be the default.
%
% 13. setcolorindex: If specified, the 3-View will choose the
% following colormap: 2 - Bipolar; 3 - Gray; 4 - Jet;
% 5 - Cool; 6 - Bone; 7 - Hot; 8 - Copper; 9 - Pink;
% If not specified, it will choose 3 - Gray if all data
% values are not less than 0; otherwise, it will choose
% 2 - Bipolar if there is value less than 0. (Contrast
% control can only apply to 3 - Gray colormap.
%
% 14. setcolormap: 3-View plot will use it as a customized colormap.
% It is a 3-column matrix with value between 0 and 1. If
% using MS-Windows version of Matlab, the number of rows
% can not be more than 256, because of Matlab limitation.
% When colormap is used, setcolorlevel option will be
% disabled automatically.
%
% 15. setcolorlevel: If specified (must be no more than 256, and
% cannot be used for customized colormap), row number of
% colormap will be squeezed down to this level; otherwise,
% it will assume that setcolorlevel=256.
%
% 16. sethighcolor: If specified, program will squeeze down the
% colormap, and allocate sethighcolor (an Mx3 matrix)
% to high-end portion of the colormap. The sum of M and
% setcolorlevel should be less than 256. If setcolormap
% option is used, sethighcolor will be inserted on top
% of the setcolormap, and the setcolorlevel option will
% be disabled automatically.
%
% 17. setcbarminmax: if specified, the [min max] will be used to
% set the min and max of the colorbar, which does not
% include any data for highcolor.
%
% 18. setvalue: If specified, setvalue.val (with the same size as
% the source data on solution points) in the source area
% setvalue.idx will be superimposed on the current nii
% image. So, the size of setvalue.val should be equal to
% the size of setvalue.idx. To use this feature, it needs
% single or double nii structure for background image.
%
% 19. glblocminmax: If specified, pgm will use glblocminmax to
% calculate the colormap, instead of minmax of image.
%
% 20. setbuttondown: If specified, pgm will evaluate the command
% after a click or slide action is invoked to the new
% view point.
%
% 21. setcomplex: This option will decide how complex data to be
% displayed: 0 - Real part of complex data; 1 - Imaginary
% part of complex data; 2 - Modulus (magnitude) of complex
% data; If not specified, it will be set to 0 (Real part
% of complex data as default option. This option only apply
% when option.command is set to 'init or 'updatenii'.
%
%
% Additional Options for 'update' command:
% =======================================
%
% option.enablecursormove = [1] | 0
% option.enableviewpoint = 0 | [1]
% option.enableorigin = 0 | [1]
% option.enableunit = 0 | [1]
% option.enablecrosshair = 0 | [1]
% option.enablehistogram = 0 | [1]
% option.enablecolormap = 0 | [1]
% option.enablecontrast = 0 | [1]
% option.enablebrightness = 0 | [1]
% option.enableslider = 0 | [1]
% option.enabledirlabel = 0 | [1]
%
%
% e.g.:
% nii = load_nii('T1'); % T1.img/hdr
% view_nii(nii);
%
% or
%
% h = figure('unit','normal','pos', [0.18 0.08 0.64 0.85]);
% opt.setarea = [0.05 0.05 0.9 0.9];
% view_nii(h, nii, opt);
%
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function status = view_nii(varargin)
if nargin < 1
error('Please check inputs using ''help view_nii''');
end;
nii = '';
opt = '';
command = '';
usecolorbar = [];
usepanel = [];
usecrosshair = '';
usestretch = [];
useimagesc = [];
useinterp = [];
setarea = [];
setunit = '';
setviewpoint = [];
setscanid = [];
setcrosshaircolor = [];
setcolorindex = '';
setcolormap = 'NA';
setcolorlevel = [];
sethighcolor = 'NA';
setcbarminmax = [];
setvalue = [];
glblocminmax = [];
setbuttondown = '';
setcomplex = 0;
status = [];
if ishandle(varargin{1}) % plot on top of this figure
fig = varargin{1};
if nargin < 2
command = 'update'; % just to get 3-View status
end
if nargin == 2
if ~isstruct(varargin{2})
error('2nd parameter should be either nii struct or option struct');
end
opt = varargin{2};
if isfield(opt,'hdr') & isfield(opt,'img')
nii = opt;
elseif isfield(opt, 'command') & (strcmpi(opt.command,'init') ...
| strcmpi(opt.command,'updatenii') ...
| strcmpi(opt.command,'updateimg') )
error('Option here cannot contain "init", "updatenii", or "updateimg" comand');
end
end
if nargin == 3
nii = varargin{2};
opt = varargin{3};
if ~isstruct(opt)
error('3rd parameter should be option struct');
end
if ~isfield(opt,'command') | ~strcmpi(opt.command,'updateimg')
if ~isstruct(nii) | ~isfield(nii,'hdr') | ~isfield(nii,'img')
error('2nd parameter should be nii struct');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''load_nii.m'' to load the structure.');
end
end
end
set(fig, 'menubar', 'none');
elseif ischar(varargin{1}) % call back by event
command = lower(varargin{1});
fig = gcbf;
else % start nii with a new figure
nii = varargin{1};
if ~isstruct(nii) | ~isfield(nii,'hdr') | ~isfield(nii,'img')
error('1st parameter should be either a figure handle or nii struct');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''load_nii.m'' to load the structure.');
end
if nargin > 1
opt = varargin{2};
if isfield(opt, 'command') & ~strcmpi(opt.command,'init')
error('Option here must use "init" comand');
end
end
command = 'init';
fig = figure('unit','normal','position',[0.15 0.08 0.70 0.85]);
view_nii_menu(fig);
rri_file_menu(fig);
end
if ~isempty(opt)
if isfield(opt,'command')
command = lower(opt.command);
end
if isempty(command)
command = 'update';
end
if isfield(opt,'usecolorbar')
usecolorbar = opt.usecolorbar;
end
if isfield(opt,'usepanel')
usepanel = opt.usepanel;
end
if isfield(opt,'usecrosshair')
usecrosshair = opt.usecrosshair;
end
if isfield(opt,'usestretch')
usestretch = opt.usestretch;
end
if isfield(opt,'useimagesc')
useimagesc = opt.useimagesc;
end
if isfield(opt,'useinterp')
useinterp = opt.useinterp;
end
if isfield(opt,'setarea')
setarea = opt.setarea;
end
if isfield(opt,'setunit')
setunit = opt.setunit;
end
if isfield(opt,'setviewpoint')
setviewpoint = opt.setviewpoint;
end
if isfield(opt,'setscanid')
setscanid = opt.setscanid;
end
if isfield(opt,'setcrosshaircolor')
setcrosshaircolor = opt.setcrosshaircolor;
if ~isempty(setcrosshaircolor) & (~isnumeric(setcrosshaircolor) | ~isequal(size(setcrosshaircolor),[1 3]) | min(setcrosshaircolor(:))<0 | max(setcrosshaircolor(:))>1)
error('Crosshair Color should be a 1x3 matrix with value between 0 and 1');
end
end
if isfield(opt,'setcolorindex')
setcolorindex = round(opt.setcolorindex);
if ~isnumeric(setcolorindex) | setcolorindex < 1 | setcolorindex > 9
error('Colorindex should be a number between 1 and 9');
end
end
if isfield(opt,'setcolormap')
setcolormap = opt.setcolormap;
if ~isempty(setcolormap) & (~isnumeric(setcolormap) | size(setcolormap,2) ~= 3 | min(setcolormap(:))<0 | max(setcolormap(:))>1)
error('Colormap should be a Mx3 matrix with value between 0 and 1');
end
end
if isfield(opt,'setcolorlevel')
setcolorlevel = round(opt.setcolorlevel);
if ~isnumeric(setcolorlevel) | setcolorlevel > 256 | setcolorlevel < 1
error('Colorlevel should be a number between 1 and 256');
end
end
if isfield(opt,'sethighcolor')
sethighcolor = opt.sethighcolor;
if ~isempty(sethighcolor) & (~isnumeric(sethighcolor) | size(sethighcolor,2) ~= 3 | min(sethighcolor(:))<0 | max(sethighcolor(:))>1)
error('Highcolor should be a Mx3 matrix with value between 0 and 1');
end
end
if isfield(opt,'setcbarminmax')
setcbarminmax = opt.setcbarminmax;
if isempty(setcbarminmax) | ~isnumeric(setcbarminmax) | length(setcbarminmax) ~= 2
error('Colorbar MinMax should contain 2 values: [min max]');
end
end
if isfield(opt,'setvalue')
setvalue = opt.setvalue;
if isempty(setvalue) | ~isstruct(setvalue) | ...
~isfield(opt.setvalue,'idx') | ~isfield(opt.setvalue,'val')
error('setvalue should be a struct contains idx and val');
end
if length(opt.setvalue.idx(:)) ~= length(opt.setvalue.val(:))
error('length of idx and val fields should be the same');
end
if ~strcmpi(class(opt.setvalue.idx),'single')
opt.setvalue.idx = single(opt.setvalue.idx);
end
if ~strcmpi(class(opt.setvalue.val),'single')
opt.setvalue.val = single(opt.setvalue.val);
end
end
if isfield(opt,'glblocminmax')
glblocminmax = opt.glblocminmax;
end
if isfield(opt,'setbuttondown')
setbuttondown = opt.setbuttondown;
end
if isfield(opt,'setcomplex')
setcomplex = opt.setcomplex;
end
end
switch command
case {'init'}
set(fig, 'InvertHardcopy','off');
set(fig, 'PaperPositionMode','auto');
fig = init(nii, fig, setarea, setunit, setviewpoint, setscanid, setbuttondown, ...
setcolorindex, setcolormap, setcolorlevel, sethighcolor, setcbarminmax, ...
usecolorbar, usepanel, usecrosshair, usestretch, useimagesc, useinterp, ...
setvalue, glblocminmax, setcrosshaircolor, setcomplex);
% get status
%
status = get_status(fig);
case {'update'}
nii_view = getappdata(fig,'nii_view');
h = fig;
if isempty(nii_view)
error('The figure should already contain a 3-View plot.');
end
if ~isempty(opt)
% Order of the following update matters.
%
update_shape(h, setarea, usecolorbar, usestretch, useimagesc);
update_useinterp(h, useinterp);
update_useimagesc(h, useimagesc);
update_usepanel(h, usepanel);
update_colorindex(h, setcolorindex);
update_colormap(h, setcolormap);
update_highcolor(h, sethighcolor, setcolorlevel);
update_cbarminmax(h, setcbarminmax);
update_unit(h, setunit);
update_viewpoint(h, setviewpoint);
update_scanid(h, setscanid);
update_buttondown(h, setbuttondown);
update_crosshaircolor(h, setcrosshaircolor);
update_usecrosshair(h, usecrosshair);
% Enable/Disable object
%
update_enable(h, opt);
end
% get status
%
status = get_status(h);
case {'updateimg'}
if ~exist('nii','var')
msg = sprintf('Please input a 3D matrix brain data');
error(msg);
end
% Note: nii is not nii, nii should be a 3D matrix here
%
if ~isnumeric(nii)
msg = sprintf('2nd parameter should be a 3D matrix, not nii struct');
error(msg);
end
nii_view = getappdata(fig,'nii_view');
if isempty(nii_view)
error('The figure should already contain a 3-View plot.');
end
img = nii;
update_img(img, fig, opt);
% get status
%
status = get_status(fig);
case {'updatenii'}
nii_view = getappdata(fig,'nii_view');
if isempty(nii_view)
error('The figure should already contain a 3-View plot.');
end
if ~isstruct(nii) | ~isfield(nii,'hdr') | ~isfield(nii,'img')
error('2nd parameter should be nii struct');
end
if isfield(nii,'untouch') & nii.untouch == 1
error('Usage: please use ''load_nii.m'' to load the structure.');
end
opt.command = 'clearnii';
view_nii(fig, opt);
opt.command = 'init';
view_nii(fig, nii, opt);
% get status
%
status = get_status(fig);
case {'clearnii'}
nii_view = getappdata(fig,'nii_view');
handles = struct2cell(nii_view.handles);
for i=1:length(handles)
if ishandle(handles{i}) % in case already del by parent
delete(handles{i});
end
end
rmappdata(fig,'nii_view');
buttonmotion = get(fig,'windowbuttonmotion');
mymotion = '; view_nii(''move_cursor'');';
buttonmotion = strrep(buttonmotion, mymotion, '');
set(fig, 'windowbuttonmotion', buttonmotion);
case {'axial_image','coronal_image','sagittal_image'}
switch command
case 'axial_image', view = 'axi'; axi = 0; cor = 1; sag = 1;
case 'coronal_image', view = 'cor'; axi = 1; cor = 0; sag = 1;
case 'sagittal_image', view = 'sag'; axi = 1; cor = 1; sag = 0;
end
nii_view = getappdata(fig,'nii_view');
nii_view = get_slice_position(nii_view,view);
if isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
% CData must be double() for Matlab 6.5 for Windows
%
if axi,
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg) & nii_view.useinterp
Saxi = squeeze(nii_view.bgimg(:,:,nii_view.slices.axi));
set(nii_view.handles.axial_bg,'CData',double(Saxi)');
end
if isfield(nii_view.handles,'axial_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Saxi = squeeze(img(:,:,nii_view.slices.axi,:,nii_view.scanid));
Saxi = permute(Saxi, [2 1 3]);
else
Saxi = squeeze(img(:,:,nii_view.slices.axi,nii_view.scanid));
Saxi = Saxi';
end
set(nii_view.handles.axial_image,'CData',double(Saxi));
end
if isfield(nii_view.handles,'axial_slider'),
set(nii_view.handles.axial_slider,'Value',nii_view.slices.axi);
end;
end
if cor,
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg) & nii_view.useinterp
Scor = squeeze(nii_view.bgimg(:,nii_view.slices.cor,:));
set(nii_view.handles.coronal_bg,'CData',double(Scor)');
end
if isfield(nii_view.handles,'coronal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Scor = squeeze(img(:,nii_view.slices.cor,:,:,nii_view.scanid));
Scor = permute(Scor, [2 1 3]);
else
Scor = squeeze(img(:,nii_view.slices.cor,:,nii_view.scanid));
Scor = Scor';
end
set(nii_view.handles.coronal_image,'CData',double(Scor));
end
if isfield(nii_view.handles,'coronal_slider'),
slider_val = nii_view.dims(2) - nii_view.slices.cor + 1;
set(nii_view.handles.coronal_slider,'Value',slider_val);
end;
end;
if sag,
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg) & nii_view.useinterp
Ssag = squeeze(nii_view.bgimg(nii_view.slices.sag,:,:));
set(nii_view.handles.sagittal_bg,'CData',double(Ssag)');
end
if isfield(nii_view.handles,'sagittal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Ssag = squeeze(img(nii_view.slices.sag,:,:,:,nii_view.scanid));
Ssag = permute(Ssag, [2 1 3]);
else
Ssag = squeeze(img(nii_view.slices.sag,:,:,nii_view.scanid));
Ssag = Ssag';
end
set(nii_view.handles.sagittal_image,'CData',double(Ssag));
end
if isfield(nii_view.handles,'sagittal_slider'),
set(nii_view.handles.sagittal_slider,'Value',nii_view.slices.sag);
end;
end;
update_nii_view(nii_view);
if ~isempty(nii_view.buttondown)
eval(nii_view.buttondown);
end
case {'axial_slider','coronal_slider','sagittal_slider'},
switch command
case 'axial_slider', view = 'axi'; axi = 1; cor = 0; sag = 0;
case 'coronal_slider', view = 'cor'; axi = 0; cor = 1; sag = 0;
case 'sagittal_slider', view = 'sag'; axi = 0; cor = 0; sag = 1;
end
nii_view = getappdata(fig,'nii_view');
nii_view = get_slider_position(nii_view);
if isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
if axi,
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg) & nii_view.useinterp
Saxi = squeeze(nii_view.bgimg(:,:,nii_view.slices.axi));
set(nii_view.handles.axial_bg,'CData',double(Saxi)');
end
if isfield(nii_view.handles,'axial_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Saxi = squeeze(img(:,:,nii_view.slices.axi,:,nii_view.scanid));
Saxi = permute(Saxi, [2 1 3]);
else
Saxi = squeeze(img(:,:,nii_view.slices.axi,nii_view.scanid));
Saxi = Saxi';
end
set(nii_view.handles.axial_image,'CData',double(Saxi));
end
if isfield(nii_view.handles,'axial_slider'),
set(nii_view.handles.axial_slider,'Value',nii_view.slices.axi);
end
end
if cor,
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg) & nii_view.useinterp
Scor = squeeze(nii_view.bgimg(:,nii_view.slices.cor,:));
set(nii_view.handles.coronal_bg,'CData',double(Scor)');
end
if isfield(nii_view.handles,'coronal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Scor = squeeze(img(:,nii_view.slices.cor,:,:,nii_view.scanid));
Scor = permute(Scor, [2 1 3]);
else
Scor = squeeze(img(:,nii_view.slices.cor,:,nii_view.scanid));
Scor = Scor';
end
set(nii_view.handles.coronal_image,'CData',double(Scor));
end
if isfield(nii_view.handles,'coronal_slider'),
slider_val = nii_view.dims(2) - nii_view.slices.cor + 1;
set(nii_view.handles.coronal_slider,'Value',slider_val);
end
end
if sag,
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg) & nii_view.useinterp
Ssag = squeeze(nii_view.bgimg(nii_view.slices.sag,:,:));
set(nii_view.handles.sagittal_bg,'CData',double(Ssag)');
end
if isfield(nii_view.handles,'sagittal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Ssag = squeeze(img(nii_view.slices.sag,:,:,:,nii_view.scanid));
Ssag = permute(Ssag, [2 1 3]);
else
Ssag = squeeze(img(nii_view.slices.sag,:,:,nii_view.scanid));
Ssag = Ssag';
end
set(nii_view.handles.sagittal_image,'CData',double(Ssag));
end
if isfield(nii_view.handles,'sagittal_slider'),
set(nii_view.handles.sagittal_slider,'Value',nii_view.slices.sag);
end
end
update_nii_view(nii_view);
if ~isempty(nii_view.buttondown)
eval(nii_view.buttondown);
end
case {'impos_edit'}
nii_view = getappdata(fig,'nii_view');
impos = str2num(get(nii_view.handles.impos,'string'));
if isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
if isempty(impos) | ~all(size(impos) == [1 3])
msg = 'Please use 3 numbers to represent X,Y and Z';
msgbox(msg,'Error');
return;
end
slices.sag = round(impos(1));
slices.cor = round(impos(2));
slices.axi = round(impos(3));
nii_view = convert2voxel(nii_view,slices);
nii_view = check_slices(nii_view);
impos(1) = nii_view.slices.sag;
impos(2) = nii_view.dims(2) - nii_view.slices.cor + 1;
impos(3) = nii_view.slices.axi;
if isfield(nii_view.handles,'sagittal_slider'),
set(nii_view.handles.sagittal_slider,'Value',impos(1));
end
if isfield(nii_view.handles,'coronal_slider'),
set(nii_view.handles.coronal_slider,'Value',impos(2));
end
if isfield(nii_view.handles,'axial_slider'),
set(nii_view.handles.axial_slider,'Value',impos(3));
end
nii_view = get_slider_position(nii_view);
update_nii_view(nii_view);
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg) & nii_view.useinterp
Saxi = squeeze(nii_view.bgimg(:,:,nii_view.slices.axi));
set(nii_view.handles.axial_bg,'CData',double(Saxi)');
end
if isfield(nii_view.handles,'axial_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Saxi = squeeze(img(:,:,nii_view.slices.axi,:,nii_view.scanid));
Saxi = permute(Saxi, [2 1 3]);
else
Saxi = squeeze(img(:,:,nii_view.slices.axi,nii_view.scanid));
Saxi = Saxi';
end
set(nii_view.handles.axial_image,'CData',double(Saxi));
end
if isfield(nii_view.handles,'axial_slider'),
set(nii_view.handles.axial_slider,'Value',nii_view.slices.axi);
end
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg) & nii_view.useinterp
Scor = squeeze(nii_view.bgimg(:,nii_view.slices.cor,:));
set(nii_view.handles.coronal_bg,'CData',double(Scor)');
end
if isfield(nii_view.handles,'coronal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Scor = squeeze(img(:,nii_view.slices.cor,:,:,nii_view.scanid));
Scor = permute(Scor, [2 1 3]);
else
Scor = squeeze(img(:,nii_view.slices.cor,:,nii_view.scanid));
Scor = Scor';
end
set(nii_view.handles.coronal_image,'CData',double(Scor));
end
if isfield(nii_view.handles,'coronal_slider'),
slider_val = nii_view.dims(2) - nii_view.slices.cor + 1;
set(nii_view.handles.coronal_slider,'Value',slider_val);
end
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg) & nii_view.useinterp
Ssag = squeeze(nii_view.bgimg(nii_view.slices.sag,:,:));
set(nii_view.handles.sagittal_bg,'CData',double(Ssag)');
end
if isfield(nii_view.handles,'sagittal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Ssag = squeeze(img(nii_view.slices.sag,:,:,:,nii_view.scanid));
Ssag = permute(Ssag, [2 1 3]);
else
Ssag = squeeze(img(nii_view.slices.sag,:,:,nii_view.scanid));
Ssag = Ssag';
end
set(nii_view.handles.sagittal_image,'CData',double(Ssag));
end
if isfield(nii_view.handles,'sagittal_slider'),
set(nii_view.handles.sagittal_slider,'Value',nii_view.slices.sag);
end
axes(nii_view.handles.axial_axes);
axes(nii_view.handles.coronal_axes);
axes(nii_view.handles.sagittal_axes);
if ~isempty(nii_view.buttondown)
eval(nii_view.buttondown);
end
case 'coordinates',
nii_view = getappdata(fig,'nii_view');
set_image_value(nii_view);
case 'crosshair',
nii_view = getappdata(fig,'nii_view');
if get(nii_view.handles.xhair,'value') == 2 % off
set(nii_view.axi_xhair.lx,'visible','off');
set(nii_view.axi_xhair.ly,'visible','off');
set(nii_view.cor_xhair.lx,'visible','off');
set(nii_view.cor_xhair.ly,'visible','off');
set(nii_view.sag_xhair.lx,'visible','off');
set(nii_view.sag_xhair.ly,'visible','off');
else
set(nii_view.axi_xhair.lx,'visible','on');
set(nii_view.axi_xhair.ly,'visible','on');
set(nii_view.cor_xhair.lx,'visible','on');
set(nii_view.cor_xhair.ly,'visible','on');
set(nii_view.sag_xhair.lx,'visible','on');
set(nii_view.sag_xhair.ly,'visible','on');
set(nii_view.handles.axial_axes,'selected','on');
set(nii_view.handles.axial_axes,'selected','off');
set(nii_view.handles.coronal_axes,'selected','on');
set(nii_view.handles.coronal_axes,'selected','off');
set(nii_view.handles.sagittal_axes,'selected','on');
set(nii_view.handles.sagittal_axes,'selected','off');
end
case 'xhair_color',
old_color = get(gcbo,'user');
new_color = uisetcolor(old_color);
update_crosshaircolor(fig, new_color);
case {'color','contrast_def'}
nii_view = getappdata(fig,'nii_view');
if nii_view.numscan == 1
if get(nii_view.handles.colorindex,'value') == 2
set(nii_view.handles.contrast,'value',128);
elseif get(nii_view.handles.colorindex,'value') == 3
set(nii_view.handles.contrast,'value',1);
end
end
[custom_color_map, custom_colorindex] = change_colormap(fig);
if strcmpi(command, 'color')
setcolorlevel = nii_view.colorlevel;
if ~isempty(custom_color_map) % isfield(nii_view, 'color_map')
setcolormap = custom_color_map; % nii_view.color_map;
else
setcolormap = [];
end
if isfield(nii_view, 'highcolor')
sethighcolor = nii_view.highcolor;
else
sethighcolor = [];
end
redraw_cbar(fig, setcolorlevel, setcolormap, sethighcolor);
if nii_view.numscan == 1 & ...
(custom_colorindex < 2 | custom_colorindex > 3)
contrastopt.enablecontrast = 0;
else
contrastopt.enablecontrast = 1;
end
update_enable(fig, contrastopt);
end
case {'neg_color','brightness','contrast'}
change_colormap(fig);
case {'brightness_def'}
nii_view = getappdata(fig,'nii_view');
set(nii_view.handles.brightness,'value',0);
change_colormap(fig);
case 'hist_plot'
hist_plot(fig);
case 'hist_eq'
hist_eq(fig);
case 'move_cursor'
move_cursor(fig);
case 'edit_change_scan'
change_scan('edit_change_scan');
case 'slider_change_scan'
change_scan('slider_change_scan');
end
return; % view_nii
%----------------------------------------------------------------
function fig = init(nii, fig, area, setunit, setviewpoint, setscanid, buttondown, ...
colorindex, color_map, colorlevel, highcolor, cbarminmax, ...
usecolorbar, usepanel, usecrosshair, usestretch, useimagesc, ...
useinterp, setvalue, glblocminmax, setcrosshaircolor, ...
setcomplex)
% Support data type COMPLEX64 & COMPLEX128
%
if nii.hdr.dime.datatype == 32 | nii.hdr.dime.datatype == 1792
switch setcomplex,
case 0,
nii.img = real(nii.img);
case 1,
nii.img = imag(nii.img);
case 2,
if isa(nii.img, 'double')
nii.img = abs(double(nii.img));
else
nii.img = single(abs(double(nii.img)));
end
end
end
if isempty(area)
area = [0.05 0.05 0.9 0.9];
end
if isempty(setscanid)
setscanid = 1;
else
setscanid = round(setscanid);
if setscanid < 1
setscanid = 1;
end
if setscanid > nii.hdr.dime.dim(5)
setscanid = nii.hdr.dime.dim(5);
end
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
usecolorbar = 0;
elseif isempty(usecolorbar)
usecolorbar = 1;
end
if isempty(usepanel)
usepanel = 1;
end
if isempty(usestretch)
usestretch = 1;
end
if isempty(useimagesc)
useimagesc = 1;
end
if isempty(useinterp)
useinterp = 0;
end
if isempty(colorindex)
tmp = min(nii.img(:,:,:,setscanid));
if min(tmp(:)) < 0
colorindex = 2;
setcrosshaircolor = [1 1 0];
else
colorindex = 3;
end
end
if isempty(color_map) | ischar(color_map)
color_map = [];
else
colorindex = 1;
end
bgimg = [];
if ~isempty(glblocminmax)
minvalue = glblocminmax(1);
maxvalue = glblocminmax(2);
else
minvalue = nii.img(:,:,:,setscanid);
minvalue = double(minvalue(:));
minvalue = min(minvalue(~isnan(minvalue)));
maxvalue = nii.img(:,:,:,setscanid);
maxvalue = double(maxvalue(:));
maxvalue = max(maxvalue(~isnan(maxvalue)));
end
if ~isempty(setvalue)
if ~isempty(glblocminmax)
minvalue = glblocminmax(1);
maxvalue = glblocminmax(2);
else
minvalue = double(min(setvalue.val));
maxvalue = double(max(setvalue.val));
end
bgimg = double(nii.img);
minbg = double(min(bgimg(:)));
maxbg = double(max(bgimg(:)));
bgimg = scale_in(bgimg, minbg, maxbg, 55) + 200; % scale to 201~256
% 56 level for brain structure
%
% highcolor = [zeros(1,3);gray(55)];
highcolor = gray(56);
cbarminmax = [minvalue maxvalue];
if useinterp
% scale signal data to 1~200
%
nii.img = repmat(nan, size(nii.img));
nii.img(setvalue.idx) = setvalue.val;
% 200 level for source image
%
bgimg = single(scale_out(bgimg, cbarminmax(1), cbarminmax(2), 199));
else
bgimg(setvalue.idx) = NaN;
minbg = double(min(bgimg(:)));
maxbg = double(max(bgimg(:)));
bgimg(setvalue.idx) = minbg;
% bgimg must be normalized to [201 256]
%
bgimg = 55 * (bgimg-min(bgimg(:))) / (max(bgimg(:))-min(bgimg(:))) + 201;
bgimg(setvalue.idx) = 0;
% scale signal data to 1~200
%
nii.img = zeros(size(nii.img));
nii.img(setvalue.idx) = scale_in(setvalue.val, minvalue, maxvalue, 199);
nii.img = nii.img + bgimg;
bgimg = [];
nii.img = scale_out(nii.img, cbarminmax(1), cbarminmax(2), 199);
minvalue = double(nii.img(:));
minvalue = min(minvalue(~isnan(minvalue)));
maxvalue = double(nii.img(:));
maxvalue = max(maxvalue(~isnan(maxvalue)));
if ~isempty(glblocminmax) % maxvalue is gray
minvalue = glblocminmax(1);
end
end
colorindex = 2;
setcrosshaircolor = [1 1 0];
end
if isempty(highcolor) | ischar(highcolor)
highcolor = [];
num_highcolor = 0;
else
num_highcolor = size(highcolor,1);
end
if isempty(colorlevel)
colorlevel = 256 - num_highcolor;
end
if usecolorbar
cbar_area = area;
cbar_area(1) = area(1) + area(3)*0.93;
cbar_area(3) = area(3)*0.04;
area(3) = area(3)*0.9; % 90% used for main axes
else
cbar_area = [];
end
% init color (gray) scaling to make sure the slice clim take the
% global clim [min(nii.img(:)) max(nii.img(:))]
%
if isempty(bgimg)
clim = [minvalue maxvalue];
else
clim = [minvalue double(max(bgimg(:)))];
end
if clim(1) == clim(2)
clim(2) = clim(1) + 0.000001;
end
if isempty(cbarminmax)
cbarminmax = [minvalue maxvalue];
end
xdim = size(nii.img, 1);
ydim = size(nii.img, 2);
zdim = size(nii.img, 3);
dims = [xdim ydim zdim];
voxel_size = abs(nii.hdr.dime.pixdim(2:4)); % vol in mm
if any(voxel_size <= 0)
voxel_size(find(voxel_size <= 0)) = 1;
end
origin = abs(nii.hdr.hist.originator(1:3));
if isempty(origin) | all(origin == 0) % according to SPM
origin = (dims+1)/2;
end;
origin = round(origin);
if any(origin > dims) % simulate fMRI
origin(find(origin > dims)) = dims(find(origin > dims));
end
if any(origin <= 0)
origin(find(origin <= 0)) = 1;
end
nii_view.dims = dims;
nii_view.voxel_size = voxel_size;
nii_view.origin = origin;
nii_view.slices.sag = 1;
nii_view.slices.cor = 1;
nii_view.slices.axi = 1;
if xdim > 1, nii_view.slices.sag = origin(1); end
if ydim > 1, nii_view.slices.cor = origin(2); end
if zdim > 1, nii_view.slices.axi = origin(3); end
nii_view.area = area;
nii_view.fig = fig;
nii_view.nii = nii; % image data
nii_view.bgimg = bgimg; % background
nii_view.setvalue = setvalue;
nii_view.minvalue = minvalue;
nii_view.maxvalue = maxvalue;
nii_view.numscan = nii.hdr.dime.dim(5);
nii_view.scanid = setscanid;
Font.FontUnits = 'point';
Font.FontSize = 12;
% create axes for colorbar
%
[cbar_axes cbarminmax_axes] = create_cbar_axes(fig, cbar_area);
if isempty(cbar_area)
nii_view.cbar_area = [];
else
nii_view.cbar_area = cbar_area;
end
% create axes for top/front/side view
%
vol_size = voxel_size .* dims;
[top_ax, front_ax, side_ax] ...
= create_ax(fig, area, vol_size, usestretch);
top_pos = get(top_ax,'position');
front_pos = get(front_ax,'position');
side_pos = get(side_ax,'position');
% Sagittal Slider
%
x = side_pos(1);
y = top_pos(2) + top_pos(4);
w = side_pos(3);
h = (front_pos(2) - y) / 2;
y = y + h;
pos = [x y w h];
if xdim > 1,
slider_step(1) = 1/(xdim);
slider_step(2) = 1.00001/(xdim);
handles.sagittal_slider = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment','center',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Sagittal slice navigation',...
'Min',1,'Max',xdim,'SliderStep',slider_step, ...
'Value',nii_view.slices.sag,...
'Callback','view_nii(''sagittal_slider'');');
set(handles.sagittal_slider,'position',pos); % linux66
end
% Coronal Slider
%
x = top_pos(1);
y = top_pos(2) + top_pos(4);
w = top_pos(3);
h = (front_pos(2) - y) / 2;
y = y + h;
pos = [x y w h];
if ydim > 1,
slider_step(1) = 1/(ydim);
slider_step(2) = 1.00001/(ydim);
slider_val = nii_view.dims(2) - nii_view.slices.cor + 1;
handles.coronal_slider = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment','center',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Coronal slice navigation',...
'Min',1,'Max',ydim,'SliderStep',slider_step, ...
'Value',slider_val,...
'Callback','view_nii(''coronal_slider'');');
set(handles.coronal_slider,'position',pos); % linux66
end
% Axial Slider
%
% x = front_pos(1) + front_pos(3);
% y = front_pos(2);
% w = side_pos(1) - x;
% h = front_pos(4);
x = top_pos(1);
y = area(2);
w = top_pos(3);
h = top_pos(2) - y;
pos = [x y w h];
if zdim > 1,
slider_step(1) = 1/(zdim);
slider_step(2) = 1.00001/(zdim);
handles.axial_slider = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment','center',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Axial slice navigation',...
'Min',1,'Max',zdim,'SliderStep',slider_step, ...
'Value',nii_view.slices.axi,...
'Callback','view_nii(''axial_slider'');');
set(handles.axial_slider,'position',pos); % linux66
end
% plot info view
%
% info_pos = [side_pos([1,3]); top_pos([2,4])];
% info_pos = info_pos(:);
gap = side_pos(1)-(top_pos(1)+top_pos(3));
info_pos(1) = side_pos(1) + gap;
info_pos(2) = area(2);
info_pos(3) = side_pos(3) - gap;
info_pos(4) = top_pos(2) + top_pos(4) - area(2) - gap;
num_inputline = 10;
inputline_space =info_pos(4) / num_inputline;
% for any info_area change, update_usestretch should also be changed
% Image Intensity Value at Cursor
%
x = info_pos(1);
y = info_pos(2);
w = info_pos(3)*0.5;
h = inputline_space*0.6;
pos = [x y w h];
handles.Timvalcur = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Value at cursor:');
if usepanel
set(handles.Timvalcur, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.imvalcur = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String',' ');
if usepanel
set(handles.imvalcur, 'visible', 'on');
end
% Position at Cursor
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.Timposcur = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','[X Y Z] at cursor:');
if usepanel
set(handles.Timposcur, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.imposcur = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String',' ','Value',[0 0 0]);
if usepanel
set(handles.imposcur, 'visible', 'on');
end
% Image Intensity Value at Mouse Click
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.Timval = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Value at crosshair:');
if usepanel
set(handles.Timval, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.imval = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String',' ');
if usepanel
set(handles.imval, 'visible', 'on');
end
% Viewpoint Position at Mouse Click
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.Timpos = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','[X Y Z] at crosshair:');
if usepanel
set(handles.Timpos, 'visible', 'on');
end
x = x + w + 0.005;
y = y - 0.008;
w = info_pos(3)*0.5;
h = inputline_space*0.9;
pos = [x y w h];
handles.impos = uicontrol('Parent',fig,'Style','edit', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'Callback','view_nii(''impos_edit'');', ...
'TooltipString','Viewpoint Location in Axes Unit', ...
'visible','off', ...
'String',' ','Value',[0 0 0]);
if usepanel
set(handles.impos, 'visible', 'on');
end
% Origin Position
%
x = info_pos(1);
y = y + inputline_space*1.2;
w = info_pos(3)*0.5;
h = inputline_space*0.6;
pos = [x y w h];
handles.Torigin = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','[X Y Z] at origin:');
if usepanel
set(handles.Torigin, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.origin = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'right',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String',' ','Value',[0 0 0]);
if usepanel
set(handles.origin, 'visible', 'on');
end
if 0
% Voxel Unit
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
handles.Tcoord = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Axes Unit:');
if usepanel
set(handles.Tcoord, 'visible', 'on');
end
x = x + w + 0.005;
w = info_pos(3)*0.5 - 0.005;
pos = [x y w h];
Font.FontSize = 8;
handles.coord = uicontrol('Parent',fig,'Style','popupmenu', ...
'Units','Normalized', Font, ...
'Position',pos, ...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'TooltipString','Choose Voxel or Millimeter',...
'String',{'Voxel','Millimeter'},...
'visible','off', ...
'Callback','view_nii(''coordinates'');');
% 'TooltipString','Choose Voxel, MNI or Talairach Coordinates',...
% 'String',{'Voxel','MNI (mm)','Talairach (mm)'},...
Font.FontSize = 12;
if usepanel
set(handles.coord, 'visible', 'on');
end
end
% Crosshair
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.4;
pos = [x y w h];
handles.Txhair = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Crosshair:');
if usepanel
set(handles.Txhair, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.2;
h = inputline_space*0.7;
pos = [x y w h];
Font.FontSize = 8;
handles.xhair_color = uicontrol('Parent',fig,'Style','push', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Crosshair Color',...
'User',[1 0 0],...
'String','Color',...
'visible','off', ...
'Callback','view_nii(''xhair_color'');');
if usepanel
set(handles.xhair_color, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.7;
w = info_pos(3)*0.3;
pos = [x y w h];
handles.xhair = uicontrol('Parent',fig,'Style','popupmenu', ...
'Units','Normalized', Font, ...
'Position',pos, ...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'TooltipString','Display or Hide Crosshair',...
'String',{'On','Off'},...
'visible','off', ...
'Callback','view_nii(''crosshair'');');
if usepanel
set(handles.xhair, 'visible', 'on');
end
% Histogram & Color
%
x = info_pos(1);
w = info_pos(3)*0.45;
h = inputline_space * 1.5;
pos = [x, y+inputline_space*0.9, w, h];
handles.hist_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
% set(handles.hist_frame, 'visible', 'on');
end
handles.coord_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
set(handles.coord_frame, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.475;
w = info_pos(3)*0.525;
h = inputline_space * 1.5;
pos = [x, y+inputline_space*0.9, w, h];
handles.color_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
set(handles.color_frame, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space*1.2;
w = info_pos(3)*0.2;
h = inputline_space*0.7;
pos = [x y w h];
Font.FontSize = 8;
handles.hist_eq = uicontrol('Parent',fig,'Style','toggle', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Histogram Equalization',...
'String','Hist EQ',...
'visible','off', ...
'Callback','view_nii(''hist_eq'');');
if usepanel
% set(handles.hist_eq, 'visible', 'on');
end
x = x + w;
w = info_pos(3)*0.2;
pos = [x y w h];
handles.hist_plot = uicontrol('Parent',fig,'Style','push', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Histogram Plot',...
'String','Hist Plot',...
'visible','off', ...
'Callback','view_nii(''hist_plot'');');
if usepanel
% set(handles.hist_plot, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.025;
w = info_pos(3)*0.4;
pos = [x y w h];
handles.coord = uicontrol('Parent',fig,'Style','popupmenu', ...
'Units','Normalized', Font, ...
'Position',pos, ...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'TooltipString','Choose Voxel or Millimeter',...
'String',{'Voxel','Millimeter'},...
'visible','off', ...
'Callback','view_nii(''coordinates'');');
% 'TooltipString','Choose Voxel, MNI or Talairach Coordinates',...
% 'String',{'Voxel','MNI (mm)','Talairach (mm)'},...
if usepanel
set(handles.coord, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.2;
pos = [x y w h];
handles.neg_color = uicontrol('Parent',fig,'Style','toggle', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Negative Colormap',...
'String','Negative',...
'visible','off', ...
'Callback','view_nii(''neg_color'');');
if usepanel
set(handles.neg_color, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.neg_color, 'enable', 'off');
end
x = info_pos(1) + info_pos(3)*0.7;
w = info_pos(3)*0.275;
pos = [x y w h];
handles.colorindex = uicontrol('Parent',fig,'Style','popupmenu', ...
'Units','Normalized', Font, ...
'Position',pos, ...
'BackgroundColor', [1 1 1], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'TooltipString','Change Colormap',...
'String',{'Custom','Bipolar','Gray','Jet','Cool','Bone','Hot','Copper','Pink'},...
'value', colorindex, ...
'visible','off', ...
'Callback','view_nii(''color'');');
if usepanel
set(handles.colorindex, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.colorindex, 'enable', 'off');
end
x = info_pos(1) + info_pos(3)*0.1;
y = y + inputline_space;
w = info_pos(3)*0.28;
h = inputline_space*0.6;
pos = [x y w h];
Font.FontSize = 8;
handles.Thist = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Histogram');
handles.Tcoord = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Axes Unit');
if usepanel
% set(handles.Thist, 'visible', 'on');
set(handles.Tcoord, 'visible', 'on');
end
x = info_pos(1) + info_pos(3)*0.60;
w = info_pos(3)*0.28;
pos = [x y w h];
handles.Tcolor = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Colormap');
if usepanel
set(handles.Tcolor, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.Tcolor, 'enable', 'off');
end
% Contrast Frame
%
x = info_pos(1);
w = info_pos(3)*0.45;
h = inputline_space * 2;
pos = [x, y+inputline_space*0.8, w, h];
handles.contrast_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
set(handles.contrast_frame, 'visible', 'on');
end
if colorindex < 2 | colorindex > 3
set(handles.contrast_frame, 'visible', 'off');
end
% Brightness Frame
%
x = info_pos(1) + info_pos(3)*0.475;
w = info_pos(3)*0.525;
pos = [x, y+inputline_space*0.8, w, h];
handles.brightness_frame = uicontrol('Parent',fig, ...
'Units','normal', ...
'BackgroundColor',[0.8 0.8 0.8], ...
'Position',pos, ...
'visible','off', ...
'Style','frame');
if usepanel
set(handles.brightness_frame, 'visible', 'on');
end
% Contrast
%
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space;
w = info_pos(3)*0.4;
h = inputline_space*0.6;
pos = [x y w h];
Font.FontSize = 12;
slider_step(1) = 5/255;
slider_step(2) = 5.00001/255;
handles.contrast = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Change contrast',...
'Min',1,'Max',256,'SliderStep',slider_step, ...
'Value',1, ...
'visible','off', ...
'Callback','view_nii(''contrast'');');
if usepanel
set(handles.contrast, 'visible', 'on');
end
if (nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511) & nii_view.numscan <= 1
set(handles.contrast, 'enable', 'off');
end
if nii_view.numscan > 1
set(handles.contrast, 'min', 1, 'max', nii_view.numscan, ...
'sliderstep',[1/(nii_view.numscan-1) 1.00001/(nii_view.numscan-1)], ...
'Callback', 'view_nii(''slider_change_scan'');');
elseif colorindex < 2 | colorindex > 3
set(handles.contrast, 'visible', 'off');
elseif colorindex == 2
set(handles.contrast,'value',128);
end
set(handles.contrast,'position',pos); % linux66
% Brightness
%
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.475;
pos = [x y w h];
Font.FontSize = 12;
slider_step(1) = 1/50;
slider_step(2) = 1.00001/50;
handles.brightness = uicontrol('Parent',fig, ...
'Style','slider','Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor',[0.5 0.5 0.5],'ForegroundColor',[0 0 0],...
'BusyAction','queue',...
'TooltipString','Change brightness',...
'Min',-1,'Max',1,'SliderStep',slider_step, ...
'Value',0, ...
'visible','off', ...
'Callback','view_nii(''brightness'');');
if usepanel
set(handles.brightness, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.brightness, 'enable', 'off');
end
set(handles.brightness,'position',pos); % linux66
% Contrast text/def
%
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space;
w = info_pos(3)*0.22;
pos = [x y w h];
handles.Tcontrast = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Contrast:');
if usepanel
set(handles.Tcontrast, 'visible', 'on');
end
if (nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511) & nii_view.numscan <= 1
set(handles.Tcontrast, 'enable', 'off');
end
if nii_view.numscan > 1
set(handles.Tcontrast, 'string', 'Scan ID:');
set(handles.contrast, 'TooltipString', 'Change Scan ID');
elseif colorindex < 2 | colorindex > 3
set(handles.Tcontrast, 'visible', 'off');
end
x = x + w;
w = info_pos(3)*0.18;
pos = [x y w h];
Font.FontSize = 8;
handles.contrast_def = uicontrol('Parent',fig,'Style','push', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Restore initial contrast',...
'String','Reset',...
'visible','off', ...
'Callback','view_nii(''contrast_def'');');
if usepanel
set(handles.contrast_def, 'visible', 'on');
end
if (nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511) & nii_view.numscan <= 1
set(handles.contrast_def, 'enable', 'off');
end
if nii_view.numscan > 1
set(handles.contrast_def, 'style', 'edit', 'background', 'w', ...
'TooltipString','Scan (or volume) index in the time series',...
'string', '1', 'Callback', 'view_nii(''edit_change_scan'');');
elseif colorindex < 2 | colorindex > 3
set(handles.contrast_def, 'visible', 'off');
end
% Brightness text/def
%
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.295;
pos = [x y w h];
Font.FontSize = 12;
handles.Tbrightness = uicontrol('Parent',fig,'Style','text', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'left',...
'BackgroundColor', [0.8 0.8 0.8], 'ForegroundColor', [0 0 0],...
'BusyAction','queue',...
'visible','off', ...
'String','Brightness:');
if usepanel
set(handles.Tbrightness, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.Tbrightness, 'enable', 'off');
end
x = x + w;
w = info_pos(3)*0.18;
pos = [x y w h];
Font.FontSize = 8;
handles.brightness_def = uicontrol('Parent',fig,'Style','push', ...
'Units','Normalized', Font, ...
'Position',pos, 'HorizontalAlignment', 'center',...
'TooltipString','Restore initial brightness',...
'String','Reset',...
'visible','off', ...
'Callback','view_nii(''brightness_def'');');
if usepanel
set(handles.brightness_def, 'visible', 'on');
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(handles.brightness_def, 'enable', 'off');
end
% init image handles
%
handles.axial_image = [];
handles.coronal_image = [];
handles.sagittal_image = [];
% plot axial view
%
if ~isempty(nii_view.bgimg)
bg_slice = squeeze(bgimg(:,:,nii_view.slices.axi));
h1 = plot_view(fig, xdim, ydim, top_ax, bg_slice', clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
handles.axial_bg = h1;
else
handles.axial_bg = [];
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
img_slice = squeeze(nii.img(:,:,nii_view.slices.axi,:,setscanid));
img_slice = permute(img_slice, [2 1 3]);
else
img_slice = squeeze(nii.img(:,:,nii_view.slices.axi,setscanid));
img_slice = img_slice';
end
h1 = plot_view(fig, xdim, ydim, top_ax, img_slice, clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
set(h1,'buttondown','view_nii(''axial_image'');');
handles.axial_image = h1;
handles.axial_axes = top_ax;
if size(img_slice,1) == 1 | size(img_slice,2) == 1
set(top_ax,'visible','off');
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider, 'visible', 'off');
end
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider, 'visible', 'off');
end
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider, 'visible', 'off');
end
end
% plot coronal view
%
if ~isempty(nii_view.bgimg)
bg_slice = squeeze(bgimg(:,nii_view.slices.cor,:));
h1 = plot_view(fig, xdim, zdim, front_ax, bg_slice', clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
handles.coronal_bg = h1;
else
handles.coronal_bg = [];
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
img_slice = squeeze(nii.img(:,nii_view.slices.cor,:,:,setscanid));
img_slice = permute(img_slice, [2 1 3]);
else
img_slice = squeeze(nii.img(:,nii_view.slices.cor,:,setscanid));
img_slice = img_slice';
end
h1 = plot_view(fig, xdim, zdim, front_ax, img_slice, clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
set(h1,'buttondown','view_nii(''coronal_image'');');
handles.coronal_image = h1;
handles.coronal_axes = front_ax;
if size(img_slice,1) == 1 | size(img_slice,2) == 1
set(front_ax,'visible','off');
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider, 'visible', 'off');
end
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider, 'visible', 'off');
end
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider, 'visible', 'off');
end
end
% plot sagittal view
%
if ~isempty(nii_view.bgimg)
bg_slice = squeeze(bgimg(nii_view.slices.sag,:,:));
h1 = plot_view(fig, ydim, zdim, side_ax, bg_slice', clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
handles.sagittal_bg = h1;
else
handles.sagittal_bg = [];
end
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
img_slice = squeeze(nii.img(nii_view.slices.sag,:,:,:,setscanid));
img_slice = permute(img_slice, [2 1 3]);
else
img_slice = squeeze(nii.img(nii_view.slices.sag,:,:,setscanid));
img_slice = img_slice';
end
h1 = plot_view(fig, ydim, zdim, side_ax, img_slice, clim, cbarminmax, ...
handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, nii_view.numscan);
set(h1,'buttondown','view_nii(''sagittal_image'');');
set(side_ax,'Xdir', 'reverse');
handles.sagittal_image = h1;
handles.sagittal_axes = side_ax;
if size(img_slice,1) == 1 | size(img_slice,2) == 1
set(side_ax,'visible','off');
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider, 'visible', 'off');
end
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider, 'visible', 'off');
end
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider, 'visible', 'off');
end
end
[top1_label, top2_label, side1_label, side2_label] = ...
dir_label(fig, top_ax, front_ax, side_ax);
% store label handles
%
handles.top1_label = top1_label;
handles.top2_label = top2_label;
handles.side1_label = side1_label;
handles.side2_label = side2_label;
% plot colorbar
%
if ~isempty(cbar_axes) & ~isempty(cbarminmax_axes)
if 0
if isempty(color_map)
level = colorlevel + num_highcolor;
else
level = size([color_map; highcolor], 1);
end
end
if isempty(color_map)
level = colorlevel;
else
level = size([color_map], 1);
end
niiclass = class(nii.img);
h1 = plot_cbar(fig, cbar_axes, cbarminmax_axes, cbarminmax, ...
level, handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, niiclass, nii_view.numscan);
handles.cbar_image = h1;
handles.cbar_axes = cbar_axes;
handles.cbarminmax_axes = cbarminmax_axes;
end
nii_view.handles = handles; % store handles
nii_view.usepanel = usepanel; % whole panel at low right cornor
nii_view.usestretch = usestretch; % stretch display of voxel_size
nii_view.useinterp = useinterp; % use interpolation
nii_view.colorindex = colorindex; % store colorindex variable
nii_view.buttondown = buttondown; % command after button down click
nii_view.cbarminmax = cbarminmax; % store min max value for colorbar
set_coordinates(nii_view,useinterp); % coord unit
if ~isfield(nii_view, 'axi_xhair') | ...
~isfield(nii_view, 'cor_xhair') | ...
~isfield(nii_view, 'sag_xhair')
nii_view.axi_xhair = []; % top cross hair
nii_view.cor_xhair = []; % front cross hair
nii_view.sag_xhair = []; % side cross hair
end
if ~isempty(color_map)
nii_view.color_map = color_map;
end
if ~isempty(colorlevel)
nii_view.colorlevel = colorlevel;
end
if ~isempty(highcolor)
nii_view.highcolor = highcolor;
end
update_nii_view(nii_view);
if ~isempty(setunit)
update_unit(fig, setunit);
end
if ~isempty(setviewpoint)
update_viewpoint(fig, setviewpoint);
end
if ~isempty(setcrosshaircolor)
update_crosshaircolor(fig, setcrosshaircolor);
end
if ~isempty(usecrosshair)
update_usecrosshair(fig, usecrosshair);
end
nii_menu = getappdata(fig, 'nii_menu');
if ~isempty(nii_menu)
if nii.hdr.dime.datatype == 128 | nii.hdr.dime.datatype == 511
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on','enable','off');
elseif useinterp
set(nii_menu.Minterp,'Userdata',0,'Label','Interp off');
else
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on');
end
end
windowbuttonmotion = get(fig, 'windowbuttonmotion');
windowbuttonmotion = [windowbuttonmotion '; view_nii(''move_cursor'');'];
set(fig, 'windowbuttonmotion', windowbuttonmotion);
return; % init
%----------------------------------------------------------------
function fig = update_img(img, fig, opt)
nii_menu = getappdata(fig,'nii_menu');
if ~isempty(nii_menu)
set(nii_menu.Mzoom,'Userdata',1,'Label','Zoom on');
set(fig,'pointer','arrow');
zoom off;
end
nii_view = getappdata(fig,'nii_view');
change_interp = 0;
if isfield(opt, 'useinterp') & opt.useinterp ~= nii_view.useinterp
nii_view.useinterp = opt.useinterp;
change_interp = 1;
end
setscanid = 1;
if isfield(opt, 'setscanid')
setscanid = round(opt.setscanid);
if setscanid < 1
setscanid = 1;
end
if setscanid > nii_view.numscan
setscanid = nii_view.numscan;
end
end
if isfield(opt, 'glblocminmax') & ~isempty(opt.glblocminmax)
minvalue = opt.glblocminmax(1);
maxvalue = opt.glblocminmax(2);
else
minvalue = img(:,:,:,setscanid);
minvalue = double(minvalue(:));
minvalue = min(minvalue(~isnan(minvalue)));
maxvalue = img(:,:,:,setscanid);
maxvalue = double(maxvalue(:));
maxvalue = max(maxvalue(~isnan(maxvalue)));
end
if isfield(opt, 'setvalue')
setvalue = opt.setvalue;
if isfield(opt, 'glblocminmax') & ~isempty(opt.glblocminmax)
minvalue = opt.glblocminmax(1);
maxvalue = opt.glblocminmax(2);
else
minvalue = double(min(setvalue.val));
maxvalue = double(max(setvalue.val));
end
bgimg = double(img);
minbg = double(min(bgimg(:)));
maxbg = double(max(bgimg(:)));
bgimg = scale_in(bgimg, minbg, maxbg, 55) + 200; % scale to 201~256
cbarminmax = [minvalue maxvalue];
if nii_view.useinterp
% scale signal data to 1~200
%
img = repmat(nan, size(img));
img(setvalue.idx) = setvalue.val;
% 200 level for source image
%
bgimg = single(scale_out(bgimg, cbarminmax(1), cbarminmax(2), 199));
else
bgimg(setvalue.idx) = NaN;
minbg = double(min(bgimg(:)));
maxbg = double(max(bgimg(:)));
bgimg(setvalue.idx) = minbg;
% bgimg must be normalized to [201 256]
%
bgimg = 55 * (bgimg-min(bgimg(:))) / (max(bgimg(:))-min(bgimg(:))) + 201;
bgimg(setvalue.idx) = 0;
% scale signal data to 1~200
%
img = zeros(size(img));
img(setvalue.idx) = scale_in(setvalue.val, minvalue, maxvalue, 199);
img = img + bgimg;
bgimg = [];
img = scale_out(img, cbarminmax(1), cbarminmax(2), 199);
minvalue = double(min(img(:)));
maxvalue = double(max(img(:)));
if isfield(opt,'glblocminmax') & ~isempty(opt.glblocminmax)
minvalue = opt.glblocminmax(1);
end
end
nii_view.bgimg = bgimg;
nii_view.setvalue = setvalue;
else
cbarminmax = [minvalue maxvalue];
end
update_cbarminmax(fig, cbarminmax);
nii_view.cbarminmax = cbarminmax;
nii_view.nii.img = img;
nii_view.minvalue = minvalue;
nii_view.maxvalue = maxvalue;
nii_view.scanid = setscanid;
change_colormap(fig);
% init color (gray) scaling to make sure the slice clim take the
% global clim [min(nii.img(:)) max(nii.img(:))]
%
if isempty(nii_view.bgimg)
clim = [minvalue maxvalue];
else
clim = [minvalue double(max(nii_view.bgimg(:)))];
end
if clim(1) == clim(2)
clim(2) = clim(1) + 0.000001;
end
if strcmpi(get(nii_view.handles.axial_image,'cdatamapping'), 'direct')
useimagesc = 0;
else
useimagesc = 1;
end
if ~isempty(nii_view.bgimg) % with interpolation
Saxi = squeeze(nii_view.bgimg(:,:,nii_view.slices.axi));
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg)
set(nii_view.handles.axial_bg,'CData',double(Saxi)');
else
axes(nii_view.handles.axial_axes);
if useimagesc
nii_view.handles.axial_bg = surface(zeros(size(Saxi')),double(Saxi'),'edgecolor','none','facecolor','interp');
else
nii_view.handles.axial_bg = surface(zeros(size(Saxi')),double(Saxi'),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
order = get(gca,'child');
order(find(order == nii_view.handles.axial_bg)) = [];
order = [order; nii_view.handles.axial_bg];
set(gca, 'child', order);
end
end
if isfield(nii_view.handles,'axial_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Saxi = squeeze(nii_view.nii.img(:,:,nii_view.slices.axi,:,setscanid));
Saxi = permute(Saxi, [2 1 3]);
else
Saxi = squeeze(nii_view.nii.img(:,:,nii_view.slices.axi,setscanid));
Saxi = Saxi';
end
set(nii_view.handles.axial_image,'CData',double(Saxi));
end
set(nii_view.handles.axial_axes,'CLim',clim);
if ~isempty(nii_view.bgimg)
Scor = squeeze(nii_view.bgimg(:,nii_view.slices.cor,:));
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg)
set(nii_view.handles.coronal_bg,'CData',double(Scor)');
else
axes(nii_view.handles.coronal_axes);
if useimagesc
nii_view.handles.coronal_bg = surface(zeros(size(Scor')),double(Scor'),'edgecolor','none','facecolor','interp');
else
nii_view.handles.coronal_bg = surface(zeros(size(Scor')),double(Scor'),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
order = get(gca,'child');
order(find(order == nii_view.handles.coronal_bg)) = [];
order = [order; nii_view.handles.coronal_bg];
set(gca, 'child', order);
end
end
if isfield(nii_view.handles,'coronal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Scor = squeeze(nii_view.nii.img(:,nii_view.slices.cor,:,:,setscanid));
Scor = permute(Scor, [2 1 3]);
else
Scor = squeeze(nii_view.nii.img(:,nii_view.slices.cor,:,setscanid));
Scor = Scor';
end
set(nii_view.handles.coronal_image,'CData',double(Scor));
end
set(nii_view.handles.coronal_axes,'CLim',clim);
if ~isempty(nii_view.bgimg)
Ssag = squeeze(nii_view.bgimg(nii_view.slices.sag,:,:));
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg)
set(nii_view.handles.sagittal_bg,'CData',double(Ssag)');
else
axes(nii_view.handles.sagittal_axes);
if useimagesc
nii_view.handles.sagittal_bg = surface(zeros(size(Ssag')),double(Ssag'),'edgecolor','none','facecolor','interp');
else
nii_view.handles.sagittal_bg = surface(zeros(size(Ssag')),double(Ssag'),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
order = get(gca,'child');
order(find(order == nii_view.handles.sagittal_bg)) = [];
order = [order; nii_view.handles.sagittal_bg];
set(gca, 'child', order);
end
end
if isfield(nii_view.handles,'sagittal_image'),
if nii_view.nii.hdr.dime.datatype == 128 | nii_view.nii.hdr.dime.datatype == 511
Ssag = squeeze(nii_view.nii.img(nii_view.slices.sag,:,:,:,setscanid));
Ssag = permute(Ssag, [2 1 3]);
else
Ssag = squeeze(nii_view.nii.img(nii_view.slices.sag,:,:,setscanid));
Ssag = Ssag';
end
set(nii_view.handles.sagittal_image,'CData',double(Ssag));
end
set(nii_view.handles.sagittal_axes,'CLim',clim);
update_nii_view(nii_view);
if isfield(opt, 'setvalue')
if ~isfield(nii_view,'highcolor') | ~isequal(size(nii_view.highcolor),[56 3])
% 55 level for brain structure (paded 0 for highcolor level 1, i.e. normal level 201, to make 56 highcolor)
%
update_highcolor(fig, [zeros(1,3);gray(55)], []);
end
if nii_view.colorindex ~= 2
update_colorindex(fig, 2);
end
old_color = get(nii_view.handles.xhair_color,'user');
if isequal(old_color, [1 0 0])
update_crosshaircolor(fig, [1 1 0]);
end
% if change_interp
% update_useinterp(fig, nii_view.useinterp);
% end
end
if change_interp
update_useinterp(fig, nii_view.useinterp);
end
return; % update_img
%----------------------------------------------------------------
function [top_pos, front_pos, side_pos] = ...
axes_pos(fig,area,vol_size,usestretch)
set(fig,'unit','pixel');
fig_pos = get(fig,'position');
gap_x = 15/fig_pos(3); % width of vertical scrollbar
gap_y = 15/fig_pos(4); % width of horizontal scrollbar
a = (area(3) - gap_x * 1.3) * fig_pos(3) / (vol_size(1) + vol_size(2)); % no crosshair lost in zoom
b = (area(4) - gap_y * 3) * fig_pos(4) / (vol_size(2) + vol_size(3));
c = min([a b]); % make sure 'ax' is inside 'area'
top_w = vol_size(1) * c / fig_pos(3);
side_w = vol_size(2) * c / fig_pos(3);
top_h = vol_size(2) * c / fig_pos(4);
side_h = vol_size(3) * c / fig_pos(4);
side_x = area(1) + top_w + gap_x * 1.3; % no crosshair lost in zoom
side_y = area(2) + top_h + gap_y * 3;
if usestretch
if a > b % top touched ceiling, use b
d = (area(3) - gap_x * 1.3) / (top_w + side_w); % no crosshair lost in zoom
top_w = top_w * d;
side_w = side_w * d;
side_x = area(1) + top_w + gap_x * 1.3; % no crosshair lost in zoom
else
d = (area(4) - gap_y * 3) / (top_h + side_h);
top_h = top_h * d;
side_h = side_h * d;
side_y = area(2) + top_h + gap_y * 3;
end
end
top_pos = [area(1) area(2)+gap_y top_w top_h];
front_pos = [area(1) side_y top_w side_h];
side_pos = [side_x side_y side_w side_h];
set(fig,'unit','normal');
return; % axes_pos
%----------------------------------------------------------------
function [top_ax, front_ax, side_ax] ...
= create_ax(fig, area, vol_size, usestretch)
cur_fig = gcf; % save h_wait fig
figure(fig);
[top_pos, front_pos, side_pos] = ...
axes_pos(fig,area,vol_size,usestretch);
nii_view = getappdata(fig, 'nii_view');
if isempty(nii_view)
top_ax = axes('position', top_pos);
front_ax = axes('position', front_pos);
side_ax = axes('position', side_pos);
else
top_ax = nii_view.handles.axial_axes;
front_ax = nii_view.handles.coronal_axes;
side_ax = nii_view.handles.sagittal_axes;
set(top_ax, 'position', top_pos);
set(front_ax, 'position', front_pos);
set(side_ax, 'position', side_pos);
end
figure(cur_fig);
return; % create_ax
%----------------------------------------------------------------
function [cbar_axes, cbarminmax_axes] = create_cbar_axes(fig, cbar_area, nii_view)
if isempty(cbar_area) % without_cbar
cbar_axes = [];
cbarminmax_axes = [];
return;
end
cur_fig = gcf; % save h_wait fig
figure(fig);
if ~exist('nii_view', 'var')
nii_view = getappdata(fig, 'nii_view');
end
if isempty(nii_view) | ~isfield(nii_view.handles,'cbar_axes') | isempty(nii_view.handles.cbar_axes)
cbarminmax_axes = axes('position', cbar_area);
cbar_axes = axes('position', cbar_area);
else
cbarminmax_axes = nii_view.handles.cbarminmax_axes;
cbar_axes = nii_view.handles.cbar_axes;
set(cbarminmax_axes, 'position', cbar_area);
set(cbar_axes, 'position', cbar_area);
end
figure(cur_fig);
return; % create_cbar_axes
%----------------------------------------------------------------
function h1 = plot_view(fig, x, y, img_ax, img_slice, clim, ...
cbarminmax, handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, useinterp, numscan)
h1 = [];
if x > 1 & y > 1,
axes(img_ax);
nii_view = getappdata(fig, 'nii_view');
if isempty(nii_view)
% set colormap first
%
nii.handles = handles;
nii.handles.axial_axes = img_ax;
nii.colorindex = colorindex;
nii.color_map = color_map;
nii.colorlevel = colorlevel;
nii.highcolor = highcolor;
nii.numscan = numscan;
change_colormap(fig, nii, colorindex, cbarminmax);
if useinterp
if useimagesc
h1 = surface(zeros(size(img_slice)),double(img_slice),'edgecolor','none','facecolor','interp');
else
h1 = surface(zeros(size(img_slice)),double(img_slice),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
set(gca,'clim',clim);
else
if useimagesc
h1 = imagesc(img_slice,clim);
else
h1 = image(img_slice);
end
set(gca,'clim',clim);
end
else
h1 = nii_view.handles.axial_image;
if ~isequal(get(h1,'parent'), img_ax)
h1 = nii_view.handles.coronal_image;
end
if ~isequal(get(h1,'parent'), img_ax)
h1 = nii_view.handles.sagittal_image;
end
set(h1, 'cdata', double(img_slice));
set(h1, 'xdata', 1:size(img_slice,2));
set(h1, 'ydata', 1:size(img_slice,1));
end
set(img_ax,'YDir','normal','XLimMode','manual','YLimMode','manual',...
'ClimMode','manual','visible','off', ...
'xtick',[],'ytick',[], 'clim', clim);
end
return; % plot_view
%----------------------------------------------------------------
function h1 = plot_cbar(fig, cbar_axes, cbarminmax_axes, cbarminmax, ...
level, handles, useimagesc, colorindex, color_map, ...
colorlevel, highcolor, niiclass, numscan, nii_view)
cbar_image = [1:level]';
% In a uint8 or uint16 indexed image, 0 points to the first row
% in the colormap
%
if 0 % strcmpi(niiclass,'uint8') | strcmpi(niiclass,'uint16')
% we use single for display anyway
ylim = [0, level-1];
else
ylim = [1, level];
end
axes(cbarminmax_axes);
plot([0 0], cbarminmax, 'w');
axis tight;
set(cbarminmax_axes,'YDir','normal', ...
'XLimMode','manual','YLimMode','manual','YColor',[0 0 0], ...
'XColor',[0 0 0],'xtick',[],'YAxisLocation','right');
ylimb = get(cbarminmax_axes,'ylim');
ytickb = get(cbarminmax_axes,'ytick');
ytick=(ylim(2)-ylim(1))*(ytickb-ylimb(1))/(ylimb(2)-ylimb(1))+ylim(1);
axes(cbar_axes);
if ~exist('nii_view', 'var')
nii_view = getappdata(fig, 'nii_view');
end
if isempty(nii_view) | ~isfield(nii_view.handles,'cbar_image') | isempty(nii_view.handles.cbar_image)
% set colormap first
%
nii.handles = handles;
nii.colorindex = colorindex;
nii.color_map = color_map;
nii.colorlevel = colorlevel;
nii.highcolor = highcolor;
nii.numscan = numscan;
change_colormap(fig, nii, colorindex, cbarminmax);
h1 = image([0,1], [ylim(1),ylim(2)], cbar_image);
else
h1 = nii_view.handles.cbar_image;
set(h1, 'cdata', double(cbar_image));
end
set(cbar_axes,'YDir','normal','XLimMode','manual', ...
'YLimMode','manual','YColor',[0 0 0],'XColor',[0 0 0],'xtick',[], ...
'YAxisLocation','right','ylim',ylim,'ytick',ytick,'yticklabel','');
return; % plot_cbar
%----------------------------------------------------------------
function set_coordinates(nii_view,useinterp)
imgPlim.vox = nii_view.dims;
imgNlim.vox = [1 1 1];
if useinterp
xdata_ax = [imgNlim.vox(1) imgPlim.vox(1)];
ydata_ax = [imgNlim.vox(2) imgPlim.vox(2)];
zdata_ax = [imgNlim.vox(3) imgPlim.vox(3)];
else
xdata_ax = [imgNlim.vox(1)-0.5 imgPlim.vox(1)+0.5];
ydata_ax = [imgNlim.vox(2)-0.5 imgPlim.vox(2)+0.5];
zdata_ax = [imgNlim.vox(3)-0.5 imgPlim.vox(3)+0.5];
end
if isfield(nii_view.handles,'axial_image') & ~isempty(nii_view.handles.axial_image)
set(nii_view.handles.axial_axes,'Xlim',xdata_ax);
set(nii_view.handles.axial_axes,'Ylim',ydata_ax);
end;
if isfield(nii_view.handles,'coronal_image') & ~isempty(nii_view.handles.coronal_image)
set(nii_view.handles.coronal_axes,'Xlim',xdata_ax);
set(nii_view.handles.coronal_axes,'Ylim',zdata_ax);
end;
if isfield(nii_view.handles,'sagittal_image') & ~isempty(nii_view.handles.sagittal_image)
set(nii_view.handles.sagittal_axes,'Xlim',ydata_ax);
set(nii_view.handles.sagittal_axes,'Ylim',zdata_ax);
end;
return % set_coordinates
%----------------------------------------------------------------
function set_image_value(nii_view),
% get coordinates of selected voxel and the image intensity there
%
sag = round(nii_view.slices.sag);
cor = round(nii_view.slices.cor);
axi = round(nii_view.slices.axi);
if 0 % isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
if nii_view.nii.hdr.dime.datatype == 128
imgvalue = [double(img(sag,cor,axi,1,nii_view.scanid)) double(img(sag,cor,axi,2,nii_view.scanid)) double(img(sag,cor,axi,3,nii_view.scanid))];
set(nii_view.handles.imval,'Value',imgvalue);
set(nii_view.handles.imval,'String',sprintf('%7.4g %7.4g %7.4g',imgvalue));
elseif nii_view.nii.hdr.dime.datatype == 511
R = double(img(sag,cor,axi,1,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
G = double(img(sag,cor,axi,2,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
B = double(img(sag,cor,axi,3,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
imgvalue = [double(img(sag,cor,axi,1,nii_view.scanid)) double(img(sag,cor,axi,2,nii_view.scanid)) double(img(sag,cor,axi,3,nii_view.scanid))];
set(nii_view.handles.imval,'Value',imgvalue);
imgvalue = [R G B];
set(nii_view.handles.imval,'String',sprintf('%7.4g %7.4g %7.4g',imgvalue));
else
imgvalue = double(img(sag,cor,axi,nii_view.scanid));
set(nii_view.handles.imval,'Value',imgvalue);
if isnan(imgvalue) | imgvalue > nii_view.cbarminmax(2)
imgvalue = 0;
end
set(nii_view.handles.imval,'String',sprintf('%.6g',imgvalue));
end
% Now update the coordinates of the selected voxel
nii_view = update_imgXYZ(nii_view);
if get(nii_view.handles.coord,'value') == 1,
sag = nii_view.imgXYZ.vox(1);
cor = nii_view.imgXYZ.vox(2);
axi = nii_view.imgXYZ.vox(3);
org = nii_view.origin;
elseif get(nii_view.handles.coord,'value') == 2,
sag = nii_view.imgXYZ.mm(1);
cor = nii_view.imgXYZ.mm(2);
axi = nii_view.imgXYZ.mm(3);
org = [0 0 0];
elseif get(nii_view.handles.coord,'value') == 3,
sag = nii_view.imgXYZ.tal(1);
cor = nii_view.imgXYZ.tal(2);
axi = nii_view.imgXYZ.tal(3);
org = [0 0 0];
end
set(nii_view.handles.impos,'Value',[sag,cor,axi]);
if get(nii_view.handles.coord,'value') == 1,
string = sprintf('%7.0f %7.0f %7.0f',sag,cor,axi);
org_str = sprintf('%7.0f %7.0f %7.0f', org(1), org(2), org(3));
else
string = sprintf('%7.1f %7.1f %7.1f',sag,cor,axi);
org_str = sprintf('%7.1f %7.1f %7.1f', org(1), org(2), org(3));
end;
set(nii_view.handles.impos,'String',string);
set(nii_view.handles.origin, 'string', org_str);
return % set_image_value
%----------------------------------------------------------------
function nii_view = get_slice_position(nii_view,view),
% obtain slices that is in correct unit, then update slices
%
slices = nii_view.slices;
switch view,
case 'sag',
currentpoint = get(nii_view.handles.sagittal_axes,'CurrentPoint');
slices.cor = currentpoint(1,1);
slices.axi = currentpoint(1,2);
case 'cor',
currentpoint = get(nii_view.handles.coronal_axes,'CurrentPoint');
slices.sag = currentpoint(1,1);
slices.axi = currentpoint(1,2);
case 'axi',
currentpoint = get(nii_view.handles.axial_axes,'CurrentPoint');
slices.sag = currentpoint(1,1);
slices.cor = currentpoint(1,2);
end
% update nii_view.slices with the updated slices
%
nii_view.slices.axi = round(slices.axi);
nii_view.slices.cor = round(slices.cor);
nii_view.slices.sag = round(slices.sag);
return % get_slice_position
%----------------------------------------------------------------
function nii_view = get_slider_position(nii_view),
[nii_view.slices.sag,nii_view.slices.cor,nii_view.slices.axi] = deal(0);
if isfield(nii_view.handles,'sagittal_slider'),
if ishandle(nii_view.handles.sagittal_slider),
nii_view.slices.sag = ...
round(get(nii_view.handles.sagittal_slider,'Value'));
end
end
if isfield(nii_view.handles,'coronal_slider'),
if ishandle(nii_view.handles.coronal_slider),
nii_view.slices.cor = ...
round(nii_view.dims(2) - ...
get(nii_view.handles.coronal_slider,'Value') + 1);
end
end
if isfield(nii_view.handles,'axial_slider'),
if ishandle(nii_view.handles.axial_slider),
nii_view.slices.axi = ...
round(get(nii_view.handles.axial_slider,'Value'));
end
end
nii_view = check_slices(nii_view);
return % get_slider_position
%----------------------------------------------------------------
function nii_view = update_imgXYZ(nii_view),
nii_view.imgXYZ.vox = ...
[nii_view.slices.sag,nii_view.slices.cor,nii_view.slices.axi];
nii_view.imgXYZ.mm = ...
(nii_view.imgXYZ.vox - nii_view.origin) .* nii_view.voxel_size;
% nii_view.imgXYZ.tal = mni2tal(nii_view.imgXYZ.mni);
return % update_imgXYZ
%----------------------------------------------------------------
function nii_view = convert2voxel(nii_view,slices),
if get(nii_view.handles.coord,'value') == 1,
% [slices.axi, slices.cor, slices.sag] are in vox
%
nii_view.slices.axi = round(slices.axi);
nii_view.slices.cor = round(slices.cor);
nii_view.slices.sag = round(slices.sag);
elseif get(nii_view.handles.coord,'value') == 2,
% [slices.axi, slices.cor, slices.sag] are in mm
%
xpix = nii_view.voxel_size(1);
ypix = nii_view.voxel_size(2);
zpix = nii_view.voxel_size(3);
nii_view.slices.axi = round(slices.axi / zpix + nii_view.origin(3));
nii_view.slices.cor = round(slices.cor / ypix + nii_view.origin(2));
nii_view.slices.sag = round(slices.sag / xpix + nii_view.origin(1));
elseif get(nii_view.handles.coord,'value') == 3,
% [slices.axi, slices.cor, slices.sag] are in talairach
%
xpix = nii_view.voxel_size(1);
ypix = nii_view.voxel_size(2);
zpix = nii_view.voxel_size(3);
xyz_tal = [slices.sag, slices.cor, slices.axi];
xyz_mni = tal2mni(xyz_tal);
nii_view.slices.axi = round(xyz_mni(3) / zpix + nii_view.origin(3));
nii_view.slices.cor = round(xyz_mni(2) / ypix + nii_view.origin(2));
nii_view.slices.sag = round(xyz_mni(1) / xpix + nii_view.origin(1));
end
return % convert2voxel
%----------------------------------------------------------------
function nii_view = check_slices(nii_view),
img = nii_view.nii.img;
[ SagSize, CorSize, AxiSize, TimeSize ] = size(img);
if nii_view.slices.sag > SagSize, nii_view.slices.sag = SagSize; end;
if nii_view.slices.sag < 1, nii_view.slices.sag = 1; end;
if nii_view.slices.cor > CorSize, nii_view.slices.cor = CorSize; end;
if nii_view.slices.cor < 1, nii_view.slices.cor = 1; end;
if nii_view.slices.axi > AxiSize, nii_view.slices.axi = AxiSize; end;
if nii_view.slices.axi < 1, nii_view.slices.axi = 1; end;
if nii_view.scanid > TimeSize, nii_view.scanid = TimeSize; end;
if nii_view.scanid < 1, nii_view.scanid = 1; end;
return % check_slices
%----------------------------------------------------------------
%
% keep this function small, since it will be called for every click
%
function nii_view = update_nii_view(nii_view)
% add imgXYZ into nii_view struct
%
nii_view = check_slices(nii_view);
nii_view = update_imgXYZ(nii_view);
% update xhair
%
p_axi = nii_view.imgXYZ.vox([1 2]);
p_cor = nii_view.imgXYZ.vox([1 3]);
p_sag = nii_view.imgXYZ.vox([2 3]);
nii_view.axi_xhair = ...
rri_xhair(p_axi, nii_view.axi_xhair, nii_view.handles.axial_axes);
nii_view.cor_xhair = ...
rri_xhair(p_cor, nii_view.cor_xhair, nii_view.handles.coronal_axes);
nii_view.sag_xhair = ...
rri_xhair(p_sag, nii_view.sag_xhair, nii_view.handles.sagittal_axes);
setappdata(nii_view.fig, 'nii_view', nii_view);
set_image_value(nii_view);
return; % update_nii_view
%----------------------------------------------------------------
function hist_plot(fig)
nii_view = getappdata(fig,'nii_view');
if isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
img = double(img(:));
if length(unique(round(img))) == length(unique(img))
is_integer = 1;
range = max(img) - min(img) + 1;
figure; hist(img, range);
set(gca, 'xlim', [-range/5, max(img)]);
else
is_integer = 0;
figure; hist(img);
end
xlabel('Voxel Intensity');
ylabel('Voxel Numbers for Each Intensity');
set(gcf, 'NumberTitle','off','Name','Histogram Plot');
return; % hist_plot
%----------------------------------------------------------------
function hist_eq(fig)
nii_view = getappdata(fig,'nii_view');
old_pointer = get(fig,'Pointer');
set(fig,'Pointer','watch');
if get(nii_view.handles.hist_eq,'value')
max_img = double(max(nii_view.nii.img(:)));
tmp = double(nii_view.nii.img) / max_img; % normalize for histeq
tmp = histeq(tmp(:));
nii_view.disp = reshape(tmp, size(nii_view.nii.img));
min_disp = min(nii_view.disp(:));
nii_view.disp = (nii_view.disp - min_disp); % range having eq hist
nii_view.disp = nii_view.disp * max_img / max(nii_view.disp(:));
nii_view.disp = single(nii_view.disp);
else
if isfield(nii_view, 'disp')
nii_view.disp = nii_view.nii.img;
else
set(fig,'Pointer',old_pointer);
return;
end
end
% update axial view
%
img_slice = squeeze(double(nii_view.disp(:,:,nii_view.slices.axi)));
h1 = nii_view.handles.axial_image;
set(h1, 'cdata', double(img_slice)');
% update coronal view
%
img_slice = squeeze(double(nii_view.disp(:,nii_view.slices.cor,:)));
h1 = nii_view.handles.coronal_image;
set(h1, 'cdata', double(img_slice)');
% update sagittal view
%
img_slice = squeeze(double(nii_view.disp(nii_view.slices.sag,:,:)));
h1 = nii_view.handles.sagittal_image;
set(h1, 'cdata', double(img_slice)');
% remove disp field if un-check 'histeq' button
%
if ~get(nii_view.handles.hist_eq,'value') & isfield(nii_view, 'disp')
nii_view = rmfield(nii_view, 'disp');
end
update_nii_view(nii_view);
set(fig,'Pointer',old_pointer);
return; % hist_eq
%----------------------------------------------------------------
function [top1_label, top2_label, side1_label, side2_label] = ...
dir_label(fig, top_ax, front_ax, side_ax)
nii_view = getappdata(fig,'nii_view');
top_pos = get(top_ax,'position');
front_pos = get(front_ax,'position');
side_pos = get(side_ax,'position');
top_gap_x = (side_pos(1)-top_pos(1)-top_pos(3)) / (2*top_pos(3));
top_gap_y = (front_pos(2)-top_pos(2)-top_pos(4)) / (2*top_pos(4));
side_gap_x = (side_pos(1)-top_pos(1)-top_pos(3)) / (2*side_pos(3));
side_gap_y = (front_pos(2)-top_pos(2)-top_pos(4)) / (2*side_pos(4));
top1_label_pos = [0, 1]; % rot0
top2_label_pos = [1, 0]; % rot90
side1_label_pos = [1, - side_gap_y]; % rot0
side2_label_pos = [0, 0]; % rot90
if isempty(nii_view)
axes(top_ax);
top1_label = text(double(top1_label_pos(1)),double(top1_label_pos(2)), ...
'== X =>', ...
'vertical', 'bottom', ...
'unit', 'normal', 'fontsize', 8);
axes(top_ax);
top2_label = text(double(top2_label_pos(1)),double(top2_label_pos(2)), ...
'== Y =>', ...
'rotation', 90, 'vertical', 'top', ...
'unit', 'normal', 'fontsize', 8);
axes(side_ax);
side1_label = text(double(side1_label_pos(1)),double(side1_label_pos(2)), ...
'<= Y ==', ...
'horizontal', 'right', 'vertical', 'top', ...
'unit', 'normal', 'fontsize', 8);
axes(side_ax);
side2_label = text(double(side2_label_pos(1)),double(side2_label_pos(2)), ...
'== Z =>', ...
'rotation', 90, 'vertical', 'bottom', ...
'unit', 'normal', 'fontsize', 8);
else
top1_label = nii_view.handles.top1_label;
top2_label = nii_view.handles.top2_label;
side1_label = nii_view.handles.side1_label;
side2_label = nii_view.handles.side2_label;
set(top1_label, 'position', [top1_label_pos 0]);
set(top2_label, 'position', [top2_label_pos 0]);
set(side1_label, 'position', [side1_label_pos 0]);
set(side2_label, 'position', [side2_label_pos 0]);
end
return; % dir_label
%----------------------------------------------------------------
function update_enable(h, opt);
nii_view = getappdata(h,'nii_view');
handles = nii_view.handles;
if isfield(opt,'enablecursormove')
if opt.enablecursormove
v = 'on';
else
v = 'off';
end
set(handles.Timposcur, 'visible', v);
set(handles.imposcur, 'visible', v);
set(handles.Timvalcur, 'visible', v);
set(handles.imvalcur, 'visible', v);
end
if isfield(opt,'enableviewpoint')
if opt.enableviewpoint
v = 'on';
else
v = 'off';
end
set(handles.Timpos, 'visible', v);
set(handles.impos, 'visible', v);
set(handles.Timval, 'visible', v);
set(handles.imval, 'visible', v);
end
if isfield(opt,'enableorigin')
if opt.enableorigin
v = 'on';
else
v = 'off';
end
set(handles.Torigin, 'visible', v);
set(handles.origin, 'visible', v);
end
if isfield(opt,'enableunit')
if opt.enableunit
v = 'on';
else
v = 'off';
end
set(handles.Tcoord, 'visible', v);
set(handles.coord_frame, 'visible', v);
set(handles.coord, 'visible', v);
end
if isfield(opt,'enablecrosshair')
if opt.enablecrosshair
v = 'on';
else
v = 'off';
end
set(handles.Txhair, 'visible', v);
set(handles.xhair_color, 'visible', v);
set(handles.xhair, 'visible', v);
end
if isfield(opt,'enablehistogram')
if opt.enablehistogram
v = 'on';
vv = 'off';
else
v = 'off';
vv = 'on';
end
set(handles.Tcoord, 'visible', vv);
set(handles.coord_frame, 'visible', vv);
set(handles.coord, 'visible', vv);
set(handles.Thist, 'visible', v);
set(handles.hist_frame, 'visible', v);
set(handles.hist_eq, 'visible', v);
set(handles.hist_plot, 'visible', v);
end
if isfield(opt,'enablecolormap')
if opt.enablecolormap
v = 'on';
else
v = 'off';
end
set(handles.Tcolor, 'visible', v);
set(handles.color_frame, 'visible', v);
set(handles.neg_color, 'visible', v);
set(handles.colorindex, 'visible', v);
end
if isfield(opt,'enablecontrast')
if opt.enablecontrast
v = 'on';
else
v = 'off';
end
set(handles.Tcontrast, 'visible', v);
set(handles.contrast_frame, 'visible', v);
set(handles.contrast_def, 'visible', v);
set(handles.contrast, 'visible', v);
end
if isfield(opt,'enablebrightness')
if opt.enablebrightness
v = 'on';
else
v = 'off';
end
set(handles.Tbrightness, 'visible', v);
set(handles.brightness_frame, 'visible', v);
set(handles.brightness_def, 'visible', v);
set(handles.brightness, 'visible', v);
end
if isfield(opt,'enabledirlabel')
if opt.enabledirlabel
v = 'on';
else
v = 'off';
end
set(handles.top1_label, 'visible', v);
set(handles.top2_label, 'visible', v);
set(handles.side1_label, 'visible', v);
set(handles.side2_label, 'visible', v);
end
if isfield(opt,'enableslider')
if opt.enableslider
v = 'on';
else
v = 'off';
end
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider, 'visible', v);
end
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider, 'visible', v);
end
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider, 'visible', v);
end
end
return; % update_enable
%----------------------------------------------------------------
function update_usepanel(fig, usepanel)
if isempty(usepanel)
return;
end
if usepanel
opt.enablecursormove = 1;
opt.enableviewpoint = 1;
opt.enableorigin = 1;
opt.enableunit = 1;
opt.enablecrosshair = 1;
% opt.enablehistogram = 1;
opt.enablecolormap = 1;
opt.enablecontrast = 1;
opt.enablebrightness = 1;
else
opt.enablecursormove = 0;
opt.enableviewpoint = 0;
opt.enableorigin = 0;
opt.enableunit = 0;
opt.enablecrosshair = 0;
% opt.enablehistogram = 0;
opt.enablecolormap = 0;
opt.enablecontrast = 0;
opt.enablebrightness = 0;
end
update_enable(fig, opt);
nii_view = getappdata(fig,'nii_view');
nii_view.usepanel = usepanel;
setappdata(fig,'nii_view',nii_view);
return; % update_usepanel
%----------------------------------------------------------------
function update_usecrosshair(fig, usecrosshair)
if isempty(usecrosshair)
return;
end
if usecrosshair
v=1;
else
v=2;
end
nii_view = getappdata(fig,'nii_view');
set(nii_view.handles.xhair,'value',v);
opt.command = 'crosshair';
view_nii(fig, opt);
return; % update_usecrosshair
%----------------------------------------------------------------
function update_usestretch(fig, usestretch)
nii_view = getappdata(fig,'nii_view');
handles = nii_view.handles;
fig = nii_view.fig;
area = nii_view.area;
vol_size = nii_view.voxel_size .* nii_view.dims;
% Three Axes & label
%
[top_ax, front_ax, side_ax] = ...
create_ax(fig, area, vol_size, usestretch);
dir_label(fig, top_ax, front_ax, side_ax);
top_pos = get(top_ax,'position');
front_pos = get(front_ax,'position');
side_pos = get(side_ax,'position');
% Sagittal Slider
%
x = side_pos(1);
y = top_pos(2) + top_pos(4);
w = side_pos(3);
h = (front_pos(2) - y) / 2;
y = y + h;
pos = [x y w h];
if isfield(handles,'sagittal_slider') & ishandle(handles.sagittal_slider)
set(handles.sagittal_slider,'position',pos);
end
% Coronal Slider
%
x = top_pos(1);
y = top_pos(2) + top_pos(4);
w = top_pos(3);
h = (front_pos(2) - y) / 2;
y = y + h;
pos = [x y w h];
if isfield(handles,'coronal_slider') & ishandle(handles.coronal_slider)
set(handles.coronal_slider,'position',pos);
end
% Axial Slider
%
x = top_pos(1);
y = area(2);
w = top_pos(3);
h = top_pos(2) - y;
pos = [x y w h];
if isfield(handles,'axial_slider') & ishandle(handles.axial_slider)
set(handles.axial_slider,'position',pos);
end
% plot info view
%
% info_pos = [side_pos([1,3]); top_pos([2,4])];
% info_pos = info_pos(:);
gap = side_pos(1)-(top_pos(1)+top_pos(3));
info_pos(1) = side_pos(1) + gap;
info_pos(2) = area(2);
info_pos(3) = side_pos(3) - gap;
info_pos(4) = top_pos(2) + top_pos(4) - area(2) - gap;
num_inputline = 10;
inputline_space =info_pos(4) / num_inputline;
% Image Intensity Value at Cursor
%
x = info_pos(1);
y = info_pos(2);
w = info_pos(3)*0.5;
h = inputline_space*0.6;
pos = [x y w h];
set(handles.Timvalcur,'position',pos);
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.imvalcur,'position',pos);
% Position at Cursor
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.Timposcur,'position',pos);
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.imposcur,'position',pos);
% Image Intensity Value at Mouse Click
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.Timval,'position',pos);
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.imval,'position',pos);
% Viewpoint Position at Mouse Click
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.Timpos,'position',pos);
x = x + w + 0.005;
y = y - 0.008;
w = info_pos(3)*0.5;
h = inputline_space*0.9;
pos = [x y w h];
set(handles.impos,'position',pos);
% Origin Position
%
x = info_pos(1);
y = y + inputline_space*1.2;
w = info_pos(3)*0.5;
h = inputline_space*0.6;
pos = [x y w h];
set(handles.Torigin,'position',pos);
x = x + w;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.origin,'position',pos);
if 0
% Axes Unit
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.5;
pos = [x y w h];
set(handles.Tcoord,'position',pos);
x = x + w + 0.005;
w = info_pos(3)*0.5 - 0.005;
pos = [x y w h];
set(handles.coord,'position',pos);
end
% Crosshair
%
x = info_pos(1);
y = y + inputline_space;
w = info_pos(3)*0.4;
pos = [x y w h];
set(handles.Txhair,'position',pos);
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.2;
h = inputline_space*0.7;
pos = [x y w h];
set(handles.xhair_color,'position',pos);
x = info_pos(1) + info_pos(3)*0.7;
w = info_pos(3)*0.3;
pos = [x y w h];
set(handles.xhair,'position',pos);
% Histogram & Color
%
x = info_pos(1);
w = info_pos(3)*0.45;
h = inputline_space * 1.5;
pos = [x, y+inputline_space*0.9, w, h];
set(handles.hist_frame,'position',pos);
set(handles.coord_frame,'position',pos);
x = info_pos(1) + info_pos(3)*0.475;
w = info_pos(3)*0.525;
h = inputline_space * 1.5;
pos = [x, y+inputline_space*0.9, w, h];
set(handles.color_frame,'position',pos);
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space*1.2;
w = info_pos(3)*0.2;
h = inputline_space*0.7;
pos = [x y w h];
set(handles.hist_eq,'position',pos);
x = x + w;
w = info_pos(3)*0.2;
pos = [x y w h];
set(handles.hist_plot,'position',pos);
x = info_pos(1) + info_pos(3)*0.025;
w = info_pos(3)*0.4;
pos = [x y w h];
set(handles.coord,'position',pos);
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.2;
pos = [x y w h];
set(handles.neg_color,'position',pos);
x = info_pos(1) + info_pos(3)*0.7;
w = info_pos(3)*0.275;
pos = [x y w h];
set(handles.colorindex,'position',pos);
x = info_pos(1) + info_pos(3)*0.1;
y = y + inputline_space;
w = info_pos(3)*0.28;
h = inputline_space*0.6;
pos = [x y w h];
set(handles.Thist,'position',pos);
set(handles.Tcoord,'position',pos);
x = info_pos(1) + info_pos(3)*0.60;
w = info_pos(3)*0.28;
pos = [x y w h];
set(handles.Tcolor,'position',pos);
% Contrast Frame
%
x = info_pos(1);
w = info_pos(3)*0.45;
h = inputline_space * 2;
pos = [x, y+inputline_space*0.8, w, h];
set(handles.contrast_frame,'position',pos);
% Brightness Frame
%
x = info_pos(1) + info_pos(3)*0.475;
w = info_pos(3)*0.525;
pos = [x, y+inputline_space*0.8, w, h];
set(handles.brightness_frame,'position',pos);
% Contrast
%
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space;
w = info_pos(3)*0.4;
h = inputline_space*0.6;
pos = [x y w h];
set(handles.contrast,'position',pos);
% Brightness
%
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.475;
pos = [x y w h];
set(handles.brightness,'position',pos);
% Contrast text/def
%
x = info_pos(1) + info_pos(3)*0.025;
y = y + inputline_space;
w = info_pos(3)*0.22;
pos = [x y w h];
set(handles.Tcontrast,'position',pos);
x = x + w;
w = info_pos(3)*0.18;
pos = [x y w h];
set(handles.contrast_def,'position',pos);
% Brightness text/def
%
x = info_pos(1) + info_pos(3)*0.5;
w = info_pos(3)*0.295;
pos = [x y w h];
set(handles.Tbrightness,'position',pos);
x = x + w;
w = info_pos(3)*0.18;
pos = [x y w h];
set(handles.brightness_def,'position',pos);
return; % update_usestretch
%----------------------------------------------------------------
function update_useinterp(fig, useinterp)
if isempty(useinterp)
return;
end
nii_menu = getappdata(fig, 'nii_menu');
if ~isempty(nii_menu)
if get(nii_menu.Minterp,'user')
set(nii_menu.Minterp,'Userdata',0,'Label','Interp off');
else
set(nii_menu.Minterp,'Userdata',1,'Label','Interp on');
end
end
nii_view = getappdata(fig, 'nii_view');
nii_view.useinterp = useinterp;
if ~isempty(nii_view.handles.axial_image)
if strcmpi(get(nii_view.handles.axial_image,'cdatamapping'), 'direct')
useimagesc = 0;
else
useimagesc = 1;
end
elseif ~isempty(nii_view.handles.coronal_image)
if strcmpi(get(nii_view.handles.coronal_image,'cdatamapping'), 'direct')
useimagesc = 0;
else
useimagesc = 1;
end
else
if strcmpi(get(nii_view.handles.sagittal_image,'cdatamapping'), 'direct')
useimagesc = 0;
else
useimagesc = 1;
end
end
if ~isempty(nii_view.handles.axial_image)
img_slice = get(nii_view.handles.axial_image, 'cdata');
delete(nii_view.handles.axial_image);
axes(nii_view.handles.axial_axes);
clim = get(gca,'clim');
if useinterp
if useimagesc
nii_view.handles.axial_image = surface(zeros(size(img_slice)),double(img_slice),'edgecolor','none','facecolor','interp');
else
nii_view.handles.axial_image = surface(zeros(size(img_slice)),double(img_slice),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
else
if useimagesc
nii_view.handles.axial_image = imagesc('cdata',img_slice);
else
nii_view.handles.axial_image = image('cdata',img_slice);
end
end
set(gca,'clim',clim);
order = get(gca,'child');
order(find(order == nii_view.handles.axial_image)) = [];
order = [order; nii_view.handles.axial_image];
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg)
order(find(order == nii_view.handles.axial_bg)) = [];
order = [order; nii_view.handles.axial_bg];
end
set(gca, 'child', order);
if ~useinterp
if isfield(nii_view.handles,'axial_bg') & ~isempty(nii_view.handles.axial_bg)
delete(nii_view.handles.axial_bg);
nii_view.handles.axial_bg = [];
end
end
set(nii_view.handles.axial_image,'buttondown','view_nii(''axial_image'');');
end
if ~isempty(nii_view.handles.coronal_image)
img_slice = get(nii_view.handles.coronal_image, 'cdata');
delete(nii_view.handles.coronal_image);
axes(nii_view.handles.coronal_axes);
clim = get(gca,'clim');
if useinterp
if useimagesc
nii_view.handles.coronal_image = surface(zeros(size(img_slice)),double(img_slice),'edgecolor','none','facecolor','interp');
else
nii_view.handles.coronal_image = surface(zeros(size(img_slice)),double(img_slice),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
else
if useimagesc
nii_view.handles.coronal_image = imagesc('cdata',img_slice);
else
nii_view.handles.coronal_image = image('cdata',img_slice);
end
end
set(gca,'clim',clim);
order = get(gca,'child');
order(find(order == nii_view.handles.coronal_image)) = [];
order = [order; nii_view.handles.coronal_image];
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg)
order(find(order == nii_view.handles.coronal_bg)) = [];
order = [order; nii_view.handles.coronal_bg];
end
set(gca, 'child', order);
if ~useinterp
if isfield(nii_view.handles,'coronal_bg') & ~isempty(nii_view.handles.coronal_bg)
delete(nii_view.handles.coronal_bg);
nii_view.handles.coronal_bg = [];
end
end
set(nii_view.handles.coronal_image,'buttondown','view_nii(''coronal_image'');');
end
if ~isempty(nii_view.handles.sagittal_image)
img_slice = get(nii_view.handles.sagittal_image, 'cdata');
delete(nii_view.handles.sagittal_image);
axes(nii_view.handles.sagittal_axes);
clim = get(gca,'clim');
if useinterp
if useimagesc
nii_view.handles.sagittal_image = surface(zeros(size(img_slice)),double(img_slice),'edgecolor','none','facecolor','interp');
else
nii_view.handles.sagittal_image = surface(zeros(size(img_slice)),double(img_slice),'cdatamapping','direct','edgecolor','none','facecolor','interp');
end
else
if useimagesc
nii_view.handles.sagittal_image = imagesc('cdata',img_slice);
else
nii_view.handles.sagittal_image = image('cdata',img_slice);
end
end
set(gca,'clim',clim);
order = get(gca,'child');
order(find(order == nii_view.handles.sagittal_image)) = [];
order = [order; nii_view.handles.sagittal_image];
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg)
order(find(order == nii_view.handles.sagittal_bg)) = [];
order = [order; nii_view.handles.sagittal_bg];
end
set(gca, 'child', order);
if ~useinterp
if isfield(nii_view.handles,'sagittal_bg') & ~isempty(nii_view.handles.sagittal_bg)
delete(nii_view.handles.sagittal_bg);
nii_view.handles.sagittal_bg = [];
end
end
set(nii_view.handles.sagittal_image,'buttondown','view_nii(''sagittal_image'');');
end
if ~useinterp
nii_view.bgimg = [];
end
set_coordinates(nii_view,useinterp);
setappdata(fig, 'nii_view', nii_view);
return; % update_useinterp
%----------------------------------------------------------------
function update_useimagesc(fig, useimagesc)
if isempty(useimagesc)
return;
end
if useimagesc
v='scaled';
else
v='direct';
end
nii_view = getappdata(fig,'nii_view');
handles = nii_view.handles;
if isfield(handles,'cbar_image') & ishandle(handles.cbar_image)
% set(handles.cbar_image,'cdatamapping',v);
end
set(handles.axial_image,'cdatamapping',v);
set(handles.coronal_image,'cdatamapping',v);
set(handles.sagittal_image,'cdatamapping',v);
return; % update_useimagesc
%----------------------------------------------------------------
function update_shape(fig, area, usecolorbar, usestretch, useimagesc)
nii_view = getappdata(fig,'nii_view');
if isempty(usestretch) % no change, get usestretch
stretchchange = 0;
usestretch = nii_view.usestretch;
else % change, set usestretch
stretchchange = 1;
nii_view.usestretch = usestretch;
end
if isempty(area) % no change, get area
areachange = 0;
area = nii_view.area;
elseif ~isempty(nii_view.cbar_area) % change, set area & cbar_area
areachange = 1;
cbar_area = area;
cbar_area(1) = area(1) + area(3)*0.93;
cbar_area(3) = area(3)*0.04;
area(3) = area(3)*0.9; % 90% used for main axes
[cbar_axes cbarminmax_axes] = create_cbar_axes(fig, cbar_area);
nii_view.area = area;
nii_view.cbar_area = cbar_area;
else % change, set area only
areachange = 1;
nii_view.area = area;
end
% Add colorbar
%
if ~isempty(usecolorbar) & usecolorbar & isempty(nii_view.cbar_area)
colorbarchange = 1;
cbar_area = area;
cbar_area(1) = area(1) + area(3)*0.93;
cbar_area(3) = area(3)*0.04;
area(3) = area(3)*0.9; % 90% used for main axes
% create axes for colorbar
%
[cbar_axes cbarminmax_axes] = create_cbar_axes(fig, cbar_area);
nii_view.area = area;
nii_view.cbar_area = cbar_area;
% useimagesc follows axial image
%
if isempty(useimagesc)
if strcmpi(get(nii_view.handles.axial_image,'cdatamap'),'scaled')
useimagesc = 1;
else
useimagesc = 0;
end
end
if isfield(nii_view, 'highcolor') & ~isempty(highcolor)
num_highcolor = size(nii_view.highcolor,1);
else
num_highcolor = 0;
end
if isfield(nii_view, 'colorlevel') & ~isempty(nii_view.colorlevel)
colorlevel = nii_view.colorlevel;
else
colorlevel = 256 - num_highcolor;
end
if isfield(nii_view, 'color_map')
color_map = nii_view.color_map;
else
color_map = [];
end
if isfield(nii_view, 'highcolor')
highcolor = nii_view.highcolor;
else
highcolor = [];
end
% plot colorbar
%
if 0
if isempty(color_map)
level = colorlevel + num_highcolor;
else
level = size([color_map; highcolor], 1);
end
end
if isempty(color_map)
level = colorlevel;
else
level = size([color_map], 1);
end
cbar_image = [1:level]';
niiclass = class(nii_view.nii.img);
h1 = plot_cbar(fig, cbar_axes, cbarminmax_axes, nii_view.cbarminmax, ...
level, nii_view.handles, useimagesc, nii_view.colorindex, ...
color_map, colorlevel, highcolor, niiclass, nii_view.numscan);
nii_view.handles.cbar_image = h1;
nii_view.handles.cbar_axes = cbar_axes;
nii_view.handles.cbarminmax_axes = cbar_axes;
% remove colorbar
%
elseif ~isempty(usecolorbar) & ~usecolorbar & ~isempty(nii_view.cbar_area)
colorbarchange = 1;
area(3) = area(3) / 0.9;
nii_view.area = area;
nii_view.cbar_area = [];
nii_view.handles = rmfield(nii_view.handles,'cbar_image');
delete(nii_view.handles.cbarminmax_axes);
nii_view.handles = rmfield(nii_view.handles,'cbarminmax_axes');
delete(nii_view.handles.cbar_axes);
nii_view.handles = rmfield(nii_view.handles,'cbar_axes');
else
colorbarchange = 0;
end
if colorbarchange | stretchchange | areachange
setappdata(fig,'nii_view',nii_view);
update_usestretch(fig, usestretch);
end
return; % update_shape
%----------------------------------------------------------------
function update_unit(fig, setunit)
if isempty(setunit)
return;
end
if strcmpi(setunit,'mm') | strcmpi(setunit,'millimeter') | strcmpi(setunit,'mni')
v = 2;
% elseif strcmpi(setunit,'tal') | strcmpi(setunit,'talairach')
% v = 3;
elseif strcmpi(setunit,'vox') | strcmpi(setunit,'voxel')
v = 1;
else
v = 1;
end
nii_view = getappdata(fig,'nii_view');
set(nii_view.handles.coord, 'value', v);
set_image_value(nii_view);
return; % update_unit
%----------------------------------------------------------------
function update_viewpoint(fig, setviewpoint)
if isempty(setviewpoint)
return;
end
nii_view = getappdata(fig,'nii_view');
if length(setviewpoint) ~= 3
error('Viewpoint position should contain [x y z]');
end
set(nii_view.handles.impos,'string',num2str(setviewpoint));
opt.command = 'impos_edit';
view_nii(fig, opt);
set(nii_view.handles.axial_axes,'selected','on');
set(nii_view.handles.axial_axes,'selected','off');
set(nii_view.handles.coronal_axes,'selected','on');
set(nii_view.handles.coronal_axes,'selected','off');
set(nii_view.handles.sagittal_axes,'selected','on');
set(nii_view.handles.sagittal_axes,'selected','off');
return; % update_viewpoint
%----------------------------------------------------------------
function update_scanid(fig, setscanid)
if isempty(setscanid)
return;
end
nii_view = getappdata(fig,'nii_view');
if setscanid < 1
setscanid = 1;
end
if setscanid > nii_view.numscan
setscanid = nii_view.numscan;
end
set(nii_view.handles.contrast_def,'string',num2str(setscanid));
set(nii_view.handles.contrast,'value',setscanid);
opt.command = 'updateimg';
opt.setscanid = setscanid;
view_nii(fig, nii_view.nii.img, opt);
return; % update_scanid
%----------------------------------------------------------------
function update_crosshaircolor(fig, new_color)
if isempty(new_color)
return;
end
nii_view = getappdata(fig,'nii_view');
xhair_color = nii_view.handles.xhair_color;
set(xhair_color,'user',new_color);
set(nii_view.axi_xhair.lx,'color',new_color);
set(nii_view.axi_xhair.ly,'color',new_color);
set(nii_view.cor_xhair.lx,'color',new_color);
set(nii_view.cor_xhair.ly,'color',new_color);
set(nii_view.sag_xhair.lx,'color',new_color);
set(nii_view.sag_xhair.ly,'color',new_color);
return; % update_crosshaircolor
%----------------------------------------------------------------
function update_colorindex(fig, colorindex)
if isempty(colorindex)
return;
end
nii_view = getappdata(fig,'nii_view');
nii_view.colorindex = colorindex;
setappdata(fig, 'nii_view', nii_view);
set(nii_view.handles.colorindex,'value',colorindex);
opt.command = 'color';
view_nii(fig, opt);
return; % update_colorindex
%----------------------------------------------------------------
function redraw_cbar(fig, colorlevel, color_map, highcolor)
nii_view = getappdata(fig,'nii_view');
if isempty(nii_view.cbar_area)
return;
end
colorindex = nii_view.colorindex;
if isempty(highcolor)
num_highcolor = 0;
else
num_highcolor = size(highcolor,1);
end
if isempty(colorlevel)
colorlevel=256;
end
if colorindex == 1
colorlevel = size(color_map, 1);
end
% level = colorlevel + num_highcolor;
level = colorlevel;
cbar_image = [1:level]';
cbar_area = nii_view.cbar_area;
% useimagesc follows axial image
%
if strcmpi(get(nii_view.handles.axial_image,'cdatamap'),'scaled')
useimagesc = 1;
else
useimagesc = 0;
end
niiclass = class(nii_view.nii.img);
delete(nii_view.handles.cbar_image);
delete(nii_view.handles.cbar_axes);
delete(nii_view.handles.cbarminmax_axes);
[nii_view.handles.cbar_axes nii_view.handles.cbarminmax_axes] = ...
create_cbar_axes(fig, cbar_area, []);
nii_view.handles.cbar_image = plot_cbar(fig, ...
nii_view.handles.cbar_axes, nii_view.handles.cbarminmax_axes, ...
nii_view.cbarminmax, level, nii_view.handles, useimagesc, ...
colorindex, color_map, colorlevel, highcolor, niiclass, ...
nii_view.numscan, []);
setappdata(fig, 'nii_view', nii_view);
return; % redraw_cbar
%----------------------------------------------------------------
function update_buttondown(fig, setbuttondown)
if isempty(setbuttondown)
return;
end
nii_view = getappdata(fig,'nii_view');
nii_view.buttondown = setbuttondown;
setappdata(fig, 'nii_view', nii_view);
return; % update_buttondown
%----------------------------------------------------------------
function update_cbarminmax(fig, cbarminmax)
if isempty(cbarminmax)
return;
end
nii_view = getappdata(fig, 'nii_view');
if ~isfield(nii_view.handles, 'cbarminmax_axes')
return;
end
nii_view.cbarminmax = cbarminmax;
setappdata(fig, 'nii_view', nii_view);
axes(nii_view.handles.cbarminmax_axes);
plot([0 0], cbarminmax, 'w');
axis tight;
set(nii_view.handles.cbarminmax_axes,'YDir','normal', ...
'XLimMode','manual','YLimMode','manual','YColor',[0 0 0], ...
'XColor',[0 0 0],'xtick',[],'YAxisLocation','right');
ylim = get(nii_view.handles.cbar_axes,'ylim');
ylimb = get(nii_view.handles.cbarminmax_axes,'ylim');
ytickb = get(nii_view.handles.cbarminmax_axes,'ytick');
ytick=(ylim(2)-ylim(1))*(ytickb-ylimb(1))/(ylimb(2)-ylimb(1))+ylim(1);
axes(nii_view.handles.cbar_axes);
set(nii_view.handles.cbar_axes,'YDir','normal','XLimMode','manual', ...
'YLimMode','manual','YColor',[0 0 0],'XColor',[0 0 0],'xtick',[], ...
'YAxisLocation','right','ylim',ylim,'ytick',ytick,'yticklabel','');
return; % update_cbarminmax
%----------------------------------------------------------------
function update_highcolor(fig, highcolor, colorlevel)
nii_view = getappdata(fig,'nii_view');
if ischar(highcolor) & (isempty(colorlevel) | nii_view.colorindex == 1)
return;
end
if ~ischar(highcolor)
nii_view.highcolor = highcolor;
if isempty(highcolor)
nii_view = rmfield(nii_view, 'highcolor');
end
else
highcolor = [];
end
if isempty(colorlevel) | nii_view.colorindex == 1
nii_view.colorlevel = nii_view.colorlevel - size(highcolor,1);
else
nii_view.colorlevel = colorlevel;
end
setappdata(fig, 'nii_view', nii_view);
if isfield(nii_view,'color_map')
color_map = nii_view.color_map;
else
color_map = [];
end
redraw_cbar(fig, nii_view.colorlevel, color_map, highcolor);
change_colormap(fig);
return; % update_highcolor
%----------------------------------------------------------------
function update_colormap(fig, color_map)
if ischar(color_map)
return;
end
nii_view = getappdata(fig,'nii_view');
nii = nii_view.nii;
minvalue = nii_view.minvalue;
if isempty(color_map)
if minvalue < 0
colorindex = 2;
else
colorindex = 3;
end
nii_view = rmfield(nii_view, 'color_map');
setappdata(fig,'nii_view',nii_view);
update_colorindex(fig, colorindex);
return;
else
colorindex = 1;
nii_view.color_map = color_map;
nii_view.colorindex = colorindex;
setappdata(fig,'nii_view',nii_view);
set(nii_view.handles.colorindex,'value',colorindex);
end
colorlevel = nii_view.colorlevel;
if isfield(nii_view, 'highcolor')
highcolor = nii_view.highcolor;
else
highcolor = [];
end
redraw_cbar(fig, colorlevel, color_map, highcolor);
change_colormap(fig);
opt.enablecontrast = 0;
update_enable(fig, opt);
return; % update_colormap
%----------------------------------------------------------------
function status = get_status(h);
nii_view = getappdata(h,'nii_view');
status.fig = h;
status.area = nii_view.area;
if isempty(nii_view.cbar_area)
status.usecolorbar = 0;
else
status.usecolorbar = 1;
width = status.area(3) / 0.9;
status.area(3) = width;
end
if strcmpi(get(nii_view.handles.imval,'visible'), 'on')
status.usepanel = 1;
else
status.usepanel = 0;
end
if get(nii_view.handles.xhair,'value') == 1
status.usecrosshair = 1;
else
status.usecrosshair = 0;
end
status.usestretch = nii_view.usestretch;
if strcmpi(get(nii_view.handles.axial_image,'cdatamapping'), 'direct')
status.useimagesc = 0;
else
status.useimagesc = 1;
end
status.useinterp = nii_view.useinterp;
if get(nii_view.handles.coord,'value') == 1
status.unit = 'vox';
elseif get(nii_view.handles.coord,'value') == 2
status.unit = 'mm';
elseif get(nii_view.handles.coord,'value') == 3
status.unit = 'tal';
end
status.viewpoint = get(nii_view.handles.impos,'value');
status.scanid = nii_view.scanid;
status.intensity = get(nii_view.handles.imval,'value');
status.colorindex = get(nii_view.handles.colorindex,'value');
if isfield(nii_view,'color_map')
status.colormap = nii_view.color_map;
else
status.colormap = [];
end
status.colorlevel = nii_view.colorlevel;
if isfield(nii_view,'highcolor')
status.highcolor = nii_view.highcolor;
else
status.highcolor = [];
end
status.cbarminmax = nii_view.cbarminmax;
status.buttondown = nii_view.buttondown;
return; % get_status
%----------------------------------------------------------------
function [custom_color_map, colorindex] ...
= change_colormap(fig, nii, colorindex, cbarminmax)
custom_color_map = [];
if ~exist('nii', 'var')
nii_view = getappdata(fig,'nii_view');
else
nii_view = nii;
end
if ~exist('colorindex', 'var')
colorindex = get(nii_view.handles.colorindex,'value');
end
if ~exist('cbarminmax', 'var')
cbarminmax = nii_view.cbarminmax;
end
if isfield(nii_view, 'highcolor') & ~isempty(nii_view.highcolor)
highcolor = nii_view.highcolor;
num_highcolor = size(highcolor,1);
else
highcolor = [];
num_highcolor = 0;
end
% if isfield(nii_view, 'colorlevel') & ~isempty(nii_view.colorlevel)
if nii_view.colorlevel < 256
num_color = nii_view.colorlevel;
else
num_color = 256 - num_highcolor;
end
contrast = [];
if colorindex == 3 % for gray
if nii_view.numscan > 1
contrast = 1;
else
contrast = (num_color-1)*(get(nii_view.handles.contrast,'value')-1)/255+1;
contrast = floor(contrast);
end
elseif colorindex == 2 % for bipolar
if nii_view.numscan > 1
contrast = 128;
else
contrast = get(nii_view.handles.contrast,'value');
end
end
if isfield(nii_view,'color_map') & ~isempty(nii_view.color_map)
color_map = nii_view.color_map;
custom_color_map = color_map;
elseif colorindex == 1
[f p] = uigetfile('*.txt', 'Input colormap text file');
if p==0
colorindex = nii_view.colorindex;
set(nii_view.handles.colorindex,'value',colorindex);
return;
end;
try
custom_color_map = load(fullfile(p,f));
loadfail = 0;
catch
loadfail = 1;
end
if loadfail | isempty(custom_color_map) | size(custom_color_map,2)~=3 ...
| min(custom_color_map(:)) < 0 | max(custom_color_map(:)) > 1
msg = 'Colormap should be a Mx3 matrix with value between 0 and 1';
msgbox(msg,'Error in colormap file');
colorindex = nii_view.colorindex;
set(nii_view.handles.colorindex,'value',colorindex);
return;
end
color_map = custom_color_map;
nii_view.color_map = color_map;
end
switch colorindex
case {2}
color_map = bipolar(num_color, cbarminmax(1), cbarminmax(2), contrast);
case {3}
color_map = gray(num_color - contrast + 1);
case {4}
color_map = jet(num_color);
case {5}
color_map = cool(num_color);
case {6}
color_map = bone(num_color);
case {7}
color_map = hot(num_color);
case {8}
color_map = copper(num_color);
case {9}
color_map = pink(num_color);
end
nii_view.colorindex = colorindex;
if ~exist('nii', 'var')
setappdata(fig,'nii_view',nii_view);
end
if colorindex == 3
color_map = [zeros(contrast,3); color_map(2:end,:)];
end
if get(nii_view.handles.neg_color,'value') & isempty(highcolor)
color_map = flipud(color_map);
elseif get(nii_view.handles.neg_color,'value') & ~isempty(highcolor)
highcolor = flipud(highcolor);
end
brightness = get(nii_view.handles.brightness,'value');
color_map = brighten(color_map, brightness);
color_map = [color_map; highcolor];
set(fig, 'colormap', color_map);
return; % change_colormap
%----------------------------------------------------------------
function move_cursor(fig)
nii_view = getappdata(fig, 'nii_view');
if isempty(nii_view)
return;
end
axi = get(nii_view.handles.axial_axes, 'pos');
cor = get(nii_view.handles.coronal_axes, 'pos');
sag = get(nii_view.handles.sagittal_axes, 'pos');
curr = get(fig, 'currentpoint');
if curr(1) >= axi(1) & curr(1) <= axi(1)+axi(3) & ...
curr(2) >= axi(2) & curr(2) <= axi(2)+axi(4)
curr = get(nii_view.handles.axial_axes, 'current');
sag = curr(1,1);
cor = curr(1,2);
axi = nii_view.slices.axi;
elseif curr(1) >= cor(1) & curr(1) <= cor(1)+cor(3) & ...
curr(2) >= cor(2) & curr(2) <= cor(2)+cor(4)
curr = get(nii_view.handles.coronal_axes, 'current');
sag = curr(1,1);
cor = nii_view.slices.cor;
axi = curr(1,2);
elseif curr(1) >= sag(1) & curr(1) <= sag(1)+sag(3) & ...
curr(2) >= sag(2) & curr(2) <= sag(2)+sag(4)
curr = get(nii_view.handles.sagittal_axes, 'current');
sag = nii_view.slices.sag;
cor = curr(1,1);
axi = curr(1,2);
else
set(nii_view.handles.imvalcur,'String',' ');
set(nii_view.handles.imposcur,'String',' ');
return;
end
sag = round(sag);
cor = round(cor);
axi = round(axi);
if sag < 1
sag = 1;
elseif sag > nii_view.dims(1)
sag = nii_view.dims(1);
end
if cor < 1
cor = 1;
elseif cor > nii_view.dims(2)
cor = nii_view.dims(2);
end
if axi < 1
axi = 1;
elseif axi > nii_view.dims(3)
axi = nii_view.dims(3);
end
if 0 % isfield(nii_view, 'disp')
img = nii_view.disp;
else
img = nii_view.nii.img;
end
if nii_view.nii.hdr.dime.datatype == 128
imgvalue = [double(img(sag,cor,axi,1,nii_view.scanid)) double(img(sag,cor,axi,2,nii_view.scanid)) double(img(sag,cor,axi,3,nii_view.scanid))];
set(nii_view.handles.imvalcur,'String',sprintf('%7.4g %7.4g %7.4g',imgvalue));
elseif nii_view.nii.hdr.dime.datatype == 511
R = double(img(sag,cor,axi,1,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
G = double(img(sag,cor,axi,2,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
B = double(img(sag,cor,axi,3,nii_view.scanid)) * (nii_view.nii.hdr.dime.glmax - ...
nii_view.nii.hdr.dime.glmin) + nii_view.nii.hdr.dime.glmin;
imgvalue = [R G B];
set(nii_view.handles.imvalcur,'String',sprintf('%7.4g %7.4g %7.4g',imgvalue));
else
imgvalue = double(img(sag,cor,axi,nii_view.scanid));
if isnan(imgvalue) | imgvalue > nii_view.cbarminmax(2)
imgvalue = 0;
end
set(nii_view.handles.imvalcur,'String',sprintf('%.6g',imgvalue));
end
nii_view.slices.sag = sag;
nii_view.slices.cor = cor;
nii_view.slices.axi = axi;
nii_view = update_imgXYZ(nii_view);
if get(nii_view.handles.coord,'value') == 1,
sag = nii_view.imgXYZ.vox(1);
cor = nii_view.imgXYZ.vox(2);
axi = nii_view.imgXYZ.vox(3);
elseif get(nii_view.handles.coord,'value') == 2,
sag = nii_view.imgXYZ.mm(1);
cor = nii_view.imgXYZ.mm(2);
axi = nii_view.imgXYZ.mm(3);
elseif get(nii_view.handles.coord,'value') == 3,
sag = nii_view.imgXYZ.tal(1);
cor = nii_view.imgXYZ.tal(2);
axi = nii_view.imgXYZ.tal(3);
end
if get(nii_view.handles.coord,'value') == 1,
string = sprintf('%7.0f %7.0f %7.0f',sag,cor,axi);
else
string = sprintf('%7.1f %7.1f %7.1f',sag,cor,axi);
end;
set(nii_view.handles.imposcur,'String',string);
return; % move_cursor
%----------------------------------------------------------------
function change_scan(hdl_str)
fig = gcbf;
nii_view = getappdata(fig,'nii_view');
if strcmpi(hdl_str, 'edit_change_scan') % edit
hdl = nii_view.handles.contrast_def;
setscanid = round(str2num(get(hdl, 'string')));
else % slider
hdl = nii_view.handles.contrast;
setscanid = round(get(hdl, 'value'));
end
update_scanid(fig, setscanid);
return; % change_scan
%----------------------------------------------------------------
function val = scale_in(val, minval, maxval, range)
% scale value into range
%
val = range*(double(val)-double(minval))/(double(maxval)-double(minval))+1;
return; % scale_in
%----------------------------------------------------------------
function val = scale_out(val, minval, maxval, range)
% according to [minval maxval] and range of color levels (e.g. 199)
% scale val back from any thing between 1~256 to a small number that
% is corresonding to [minval maxval].
%
val = (double(val)-1)*(double(maxval)-double(minval))/range+double(minval);
return; % scale_out
|
github
|
philippboehmsturm/antx-master
|
mat_into_hdr.m
|
.m
|
antx-master/mritools/others/nii/mat_into_hdr.m
| 2,691 |
utf_8
|
847d96698f45f7c5e7decbb3a0c3187f
|
%MAT_INTO_HDR The old versions of SPM (any version before SPM5) store
% an affine matrix of the SPM Reoriented image into a matlab file
% (.mat extension). The file name of this SPM matlab file is the
% same as the SPM Reoriented image file (.img/.hdr extension).
%
% This program will convert the ANALYZE 7.5 SPM Reoriented image
% file into NIfTI format, and integrate the affine matrix in the
% SPM matlab file into its header file (.hdr extension).
%
% WARNING: Before you run this program, please save the header
% file (.hdr extension) into another file name or into another
% folder location, because all header files (.hdr extension)
% will be overwritten after they are converted into NIfTI
% format.
%
% Usage: mat_into_hdr(filename);
%
% filename: file name(s) with .hdr or .mat file extension, like:
% '*.hdr', or '*.mat', or a single .hdr or .mat file.
% e.g. mat_into_hdr('T1.hdr')
% mat_into_hdr('*.mat')
%
% - Jimmy Shen ([email protected])
%
%-------------------------------------------------------------------------
function mat_into_hdr(files)
pn = fileparts(files);
file_lst = dir(files);
file_lst = {file_lst.name};
file1 = file_lst{1};
[p n e]= fileparts(file1);
for i=1:length(file_lst)
[p n e]= fileparts(file_lst{i});
disp(['working on file ', num2str(i) ,' of ', num2str(length(file_lst)), ': ', n,e]);
process=1;
if isequal(e,'.hdr')
mat=fullfile(pn, [n,'.mat']);
hdr=fullfile(pn, file_lst{i});
if ~exist(mat,'file')
warning(['Cannot find file "',mat , '". File "', n, e, '" will not be processed.']);
process=0;
end
elseif isequal(e,'.mat')
hdr=fullfile(pn, [n,'.hdr']);
mat=fullfile(pn, file_lst{i});
if ~exist(hdr,'file')
warning(['Can not find file "',hdr , '". File "', n, e, '" will not be processed.']);
process=0;
end
else
warning(['Input file must have .mat or .hdr extension. File "', n, e, '" will not be processed.']);
process=0;
end
if process
load(mat);
R=M(1:3,1:3);
T=M(1:3,4);
T=R*ones(3,1)+T;
M(1:3,4)=T;
[h filetype fileprefix machine]=load_nii_hdr(hdr);
h.hist.qform_code=0;
h.hist.sform_code=1;
h.hist.srow_x=M(1,:);
h.hist.srow_y=M(2,:);
h.hist.srow_z=M(3,:);
h.hist.magic='ni1';
fid = fopen(hdr,'w',machine);
save_nii_hdr(h,fid);
fclose(fid);
end
end
return; % mat_into_hdr
|
github
|
philippboehmsturm/antx-master
|
xform_nii.m
|
.m
|
antx-master/mritools/others/nii/xform_nii.m
| 18,628 |
utf_8
|
e39c421e7f117cbc81c56e9d023774a3
|
% internal function
% 'xform_nii.m' is an internal function called by "load_nii.m", so
% you do not need run this program by yourself. It does simplified
% NIfTI sform/qform affine transform, and supports some of the
% affine transforms, including translation, reflection, and
% orthogonal rotation (N*90 degree).
%
% For other affine transforms, e.g. any degree rotation, shearing
% etc. you will have to use the included 'reslice_nii.m' program
% to reslice the image volume. 'reslice_nii.m' is not called by
% any other program, and you have to run 'reslice_nii.m' explicitly
% for those NIfTI files that you want to reslice them.
%
% Since 'xform_nii.m' does not involve any interpolation or any
% slice change, the original image volume is supposed to be
% untouched, although it is translated, reflected, or even
% orthogonally rotated, based on the affine matrix in the
% NIfTI header.
%
% However, the affine matrix in the header of a lot NIfTI files
% contain slightly non-orthogonal rotation. Therefore, optional
% input parameter 'tolerance' is used to allow some distortion
% in the loaded image for any non-orthogonal rotation or shearing
% of NIfTI affine matrix. If you set 'tolerance' to 0, it means
% that you do not allow any distortion. If you set 'tolerance' to
% 1, it means that you do not care any distortion. The image will
% fail to be loaded if it can not be tolerated. The tolerance will
% be set to 0.1 (10%), if it is default or empty.
%
% Because 'reslice_nii.m' has to perform 3D interpolation, it can
% be slow depending on image size and affine matrix in the header.
%
% After you perform the affine transform, the 'nii' structure
% generated from 'xform_nii.m' or new NIfTI file created from
% 'reslice_nii.m' will be in RAS orientation, i.e. X axis from
% Left to Right, Y axis from Posterior to Anterior, and Z axis
% from Inferior to Superior.
%
% NOTE: This function should be called immediately after load_nii.
%
% Usage: [ nii ] = xform_nii(nii, [tolerance], [preferredForm])
%
% nii - NIFTI structure (returned from load_nii)
%
% tolerance (optional) - distortion allowed for non-orthogonal rotation
% or shearing in NIfTI affine matrix. It will be set to 0.1 (10%),
% if it is default or empty.
%
% preferredForm (optional) - selects which transformation from voxels
% to RAS coordinates; values are s,q,S,Q. Lower case s,q indicate
% "prefer sform or qform, but use others if preferred not present".
% Upper case indicate the program is forced to use the specificied
% tranform or fail loading. 'preferredForm' will be 's', if it is
% default or empty. - Jeff Gunter
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function nii = xform_nii(nii, tolerance, preferredForm)
% save a copy of the header as it was loaded. This is the
% header before any sform, qform manipulation is done.
%
nii.original.hdr = nii.hdr;
if ~exist('tolerance','var') | isempty(tolerance)
tolerance = 0.1;
elseif(tolerance<=0)
tolerance = eps;
end
if ~exist('preferredForm','var') | isempty(preferredForm)
preferredForm= 's'; % Jeff
end
% if scl_slope field is nonzero, then each voxel value in the
% dataset should be scaled as: y = scl_slope * x + scl_inter
% I bring it here because hdr will be modified by change_hdr.
%
if nii.hdr.dime.scl_slope ~= 0 & ...
ismember(nii.hdr.dime.datatype, [2,4,8,16,64,256,512,768]) & ...
(nii.hdr.dime.scl_slope ~= 1 | nii.hdr.dime.scl_inter ~= 0)
nii.img = ...
nii.hdr.dime.scl_slope * double(nii.img) + nii.hdr.dime.scl_inter;
if nii.hdr.dime.datatype == 64
nii.hdr.dime.datatype = 64;
nii.hdr.dime.bitpix = 64;
else
nii.img = single(nii.img);
nii.hdr.dime.datatype = 16;
nii.hdr.dime.bitpix = 32;
end
nii.hdr.dime.glmax = max(double(nii.img(:)));
nii.hdr.dime.glmin = min(double(nii.img(:)));
% set scale to non-use, because it is applied in xform_nii
%
nii.hdr.dime.scl_slope = 0;
end
% However, the scaling is to be ignored if datatype is DT_RGB24.
% If datatype is a complex type, then the scaling is to be applied
% to both the real and imaginary parts.
%
if nii.hdr.dime.scl_slope ~= 0 & ...
ismember(nii.hdr.dime.datatype, [32,1792])
nii.img = ...
nii.hdr.dime.scl_slope * double(nii.img) + nii.hdr.dime.scl_inter;
if nii.hdr.dime.datatype == 32
nii.img = single(nii.img);
end
nii.hdr.dime.glmax = max(double(nii.img(:)));
nii.hdr.dime.glmin = min(double(nii.img(:)));
% set scale to non-use, because it is applied in xform_nii
%
nii.hdr.dime.scl_slope = 0;
end
% There is no need for this program to transform Analyze data
%
if nii.filetype == 0 & exist([nii.fileprefix '.mat'],'file')
load([nii.fileprefix '.mat']); % old SPM affine matrix
R=M(1:3,1:3);
T=M(1:3,4);
T=R*ones(3,1)+T;
M(1:3,4)=T;
nii.hdr.hist.qform_code=0;
nii.hdr.hist.sform_code=1;
nii.hdr.hist.srow_x=M(1,:);
nii.hdr.hist.srow_y=M(2,:);
nii.hdr.hist.srow_z=M(3,:);
elseif nii.filetype == 0
nii.hdr.hist.rot_orient = [];
nii.hdr.hist.flip_orient = [];
return; % no sform/qform for Analyze format
end
hdr = nii.hdr;
[hdr,orient]=change_hdr(hdr,tolerance,preferredForm);
% flip and/or rotate image data
%
if ~isequal(orient, [1 2 3])
old_dim = hdr.dime.dim([2:4]);
% More than 1 time frame
%
if ndims(nii.img) > 3
pattern = 1:prod(old_dim);
else
pattern = [];
end
if ~isempty(pattern)
pattern = reshape(pattern, old_dim);
end
% calculate for rotation after flip
%
rot_orient = mod(orient + 2, 3) + 1;
% do flip:
%
flip_orient = orient - rot_orient;
for i = 1:3
if flip_orient(i)
if ~isempty(pattern)
pattern = flipdim(pattern, i);
else
nii.img = flipdim(nii.img, i);
end
end
end
% get index of orient (rotate inversely)
%
[tmp rot_orient] = sort(rot_orient);
new_dim = old_dim;
new_dim = new_dim(rot_orient);
hdr.dime.dim([2:4]) = new_dim;
new_pixdim = hdr.dime.pixdim([2:4]);
new_pixdim = new_pixdim(rot_orient);
hdr.dime.pixdim([2:4]) = new_pixdim;
% re-calculate originator
%
tmp = hdr.hist.originator([1:3]);
tmp = tmp(rot_orient);
flip_orient = flip_orient(rot_orient);
for i = 1:3
if flip_orient(i) & ~isequal(tmp(i), 0)
tmp(i) = new_dim(i) - tmp(i) + 1;
end
end
hdr.hist.originator([1:3]) = tmp;
hdr.hist.rot_orient = rot_orient;
hdr.hist.flip_orient = flip_orient;
% do rotation:
%
if ~isempty(pattern)
pattern = permute(pattern, rot_orient);
pattern = pattern(:);
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792 | ...
hdr.dime.datatype == 128 | hdr.dime.datatype == 511
tmp = reshape(nii.img(:,:,:,1), [prod(new_dim) hdr.dime.dim(5:8)]);
tmp = tmp(pattern, :);
nii.img(:,:,:,1) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);
tmp = reshape(nii.img(:,:,:,2), [prod(new_dim) hdr.dime.dim(5:8)]);
tmp = tmp(pattern, :);
nii.img(:,:,:,2) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
tmp = reshape(nii.img(:,:,:,3), [prod(new_dim) hdr.dime.dim(5:8)]);
tmp = tmp(pattern, :);
nii.img(:,:,:,3) = reshape(tmp, [new_dim hdr.dime.dim(5:8)]);
end
else
nii.img = reshape(nii.img, [prod(new_dim) hdr.dime.dim(5:8)]);
nii.img = nii.img(pattern, :);
nii.img = reshape(nii.img, [new_dim hdr.dime.dim(5:8)]);
end
else
if hdr.dime.datatype == 32 | hdr.dime.datatype == 1792 | ...
hdr.dime.datatype == 128 | hdr.dime.datatype == 511
nii.img(:,:,:,1) = permute(nii.img(:,:,:,1), rot_orient);
nii.img(:,:,:,2) = permute(nii.img(:,:,:,2), rot_orient);
if hdr.dime.datatype == 128 | hdr.dime.datatype == 511
nii.img(:,:,:,3) = permute(nii.img(:,:,:,3), rot_orient);
end
else
nii.img = permute(nii.img, rot_orient);
end
end
else
hdr.hist.rot_orient = [];
hdr.hist.flip_orient = [];
end
nii.hdr = hdr;
return; % xform_nii
%-----------------------------------------------------------------------
function [hdr, orient] = change_hdr(hdr, tolerance, preferredForm)
orient = [1 2 3];
affine_transform = 1;
% NIFTI can have both sform and qform transform. This program
% will check sform_code prior to qform_code by default.
%
% If user specifys "preferredForm", user can then choose the
% priority. - Jeff
%
useForm=[]; % Jeff
if isequal(preferredForm,'S')
if isequal(hdr.hist.sform_code,0)
error('User requires sform, sform not set in header');
else
useForm='s';
end
end % Jeff
if isequal(preferredForm,'Q')
if isequal(hdr.hist.qform_code,0)
error('User requires qform, qform not set in header');
else
useForm='q';
end
end % Jeff
if isequal(preferredForm,'s')
if hdr.hist.sform_code > 0
useForm='s';
elseif hdr.hist.qform_code > 0
useForm='q';
end
end % Jeff
if isequal(preferredForm,'q')
if hdr.hist.qform_code > 0
useForm='q';
elseif hdr.hist.sform_code > 0
useForm='s';
end
end % Jeff
if isequal(useForm,'s')
R = [hdr.hist.srow_x(1:3)
hdr.hist.srow_y(1:3)
hdr.hist.srow_z(1:3)];
T = [hdr.hist.srow_x(4)
hdr.hist.srow_y(4)
hdr.hist.srow_z(4)];
if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
hdr.hist.old_affine = [ [R;[0 0 0]] [T;1] ];
R_sort = sort(abs(R(:)));
R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;
hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];
if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
msg = [char(10) char(10) ' Non-orthogonal rotation or shearing '];
msg = [msg 'found inside the affine matrix' char(10)];
msg = [msg ' in this NIfTI file. You have 3 options:' char(10) char(10)];
msg = [msg ' 1. Using included ''reslice_nii.m'' program to reslice the NIfTI' char(10)];
msg = [msg ' file. I strongly recommand this, because it will not cause' char(10)];
msg = [msg ' negative effect, as long as you remember not to do slice' char(10)];
msg = [msg ' time correction after using ''reslice_nii.m''.' char(10) char(10)];
msg = [msg ' 2. Using included ''load_untouch_nii.m'' program to load image' char(10)];
msg = [msg ' without applying any affine geometric transformation or' char(10)];
msg = [msg ' voxel intensity scaling. This is only for people who want' char(10)];
msg = [msg ' to do some image processing regardless of image orientation' char(10)];
msg = [msg ' and to save data back with the same NIfTI header.' char(10) char(10)];
msg = [msg ' 3. Increasing the tolerance to allow more distortion in loaded' char(10)];
msg = [msg ' image, but I don''t suggest this.' char(10) char(10)];
msg = [msg ' To get help, please type:' char(10) char(10) ' help reslice_nii.m' char(10)];
msg = [msg ' help load_untouch_nii.m' char(10) ' help load_nii.m'];
error(msg);
end
end
elseif isequal(useForm,'q')
b = hdr.hist.quatern_b;
c = hdr.hist.quatern_c;
d = hdr.hist.quatern_d;
if 1.0-(b*b+c*c+d*d) < 0
if abs(1.0-(b*b+c*c+d*d)) < 1e-5
a = 0;
else
error('Incorrect quaternion values in this NIFTI data.');
end
else
a = sqrt(1.0-(b*b+c*c+d*d));
end
qfac = hdr.dime.pixdim(1);
if qfac==0, qfac = 1; end
i = hdr.dime.pixdim(2);
j = hdr.dime.pixdim(3);
k = qfac * hdr.dime.pixdim(4);
R = [a*a+b*b-c*c-d*d 2*b*c-2*a*d 2*b*d+2*a*c
2*b*c+2*a*d a*a+c*c-b*b-d*d 2*c*d-2*a*b
2*b*d-2*a*c 2*c*d+2*a*b a*a+d*d-c*c-b*b];
T = [hdr.hist.qoffset_x
hdr.hist.qoffset_y
hdr.hist.qoffset_z];
% qforms are expected to generate rotation matrices R which are
% det(R) = 1; we'll make sure that happens.
%
% now we make the same checks as were done above for sform data
% BUT we do it on a transform that is in terms of voxels not mm;
% after we figure out the angles and squash them to closest
% rectilinear direction. After that, the voxel sizes are then
% added.
%
% This part is modified by Jeff Gunter.
%
if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
% det(R) == 0 is not a common trigger for this ---
% R(find(R)) is a list of non-zero elements in R; if that
% is straight (not oblique) then it should be the same as
% columnwise summation. Could just as well have checked the
% lengths of R(find(R)) and sum(R)' (which should be 3)
%
hdr.hist.old_affine = [ [R * diag([i j k]);[0 0 0]] [T;1] ];
R_sort = sort(abs(R(:)));
R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;
R = R * diag([i j k]);
hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];
if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
msg = [char(10) char(10) ' Non-orthogonal rotation or shearing '];
msg = [msg 'found inside the affine matrix' char(10)];
msg = [msg ' in this NIfTI file. You have 3 options:' char(10) char(10)];
msg = [msg ' 1. Using included ''reslice_nii.m'' program to reslice the NIfTI' char(10)];
msg = [msg ' file. I strongly recommand this, because it will not cause' char(10)];
msg = [msg ' negative effect, as long as you remember not to do slice' char(10)];
msg = [msg ' time correction after using ''reslice_nii.m''.' char(10) char(10)];
msg = [msg ' 2. Using included ''load_untouch_nii.m'' program to load image' char(10)];
msg = [msg ' without applying any affine geometric transformation or' char(10)];
msg = [msg ' voxel intensity scaling. This is only for people who want' char(10)];
msg = [msg ' to do some image processing regardless of image orientation' char(10)];
msg = [msg ' and to save data back with the same NIfTI header.' char(10) char(10)];
msg = [msg ' 3. Increasing the tolerance to allow more distortion in loaded' char(10)];
msg = [msg ' image, but I don''t suggest this.' char(10) char(10)];
msg = [msg ' To get help, please type:' char(10) char(10) ' help reslice_nii.m' char(10)];
msg = [msg ' help load_untouch_nii.m' char(10) ' help load_nii.m'];
error(msg);
end
else
R = R * diag([i j k]);
end % 1st det(R)
else
affine_transform = 0; % no sform or qform transform
end
if affine_transform == 1
voxel_size = abs(sum(R,1));
inv_R = inv(R);
originator = inv_R*(-T)+1;
orient = get_orient(inv_R);
% modify pixdim and originator
%
hdr.dime.pixdim(2:4) = voxel_size;
hdr.hist.originator(1:3) = originator;
% set sform or qform to non-use, because they have been
% applied in xform_nii
%
hdr.hist.qform_code = 0;
hdr.hist.sform_code = 0;
end
% apply space_unit to pixdim if not 1 (mm)
%
space_unit = get_units(hdr);
if space_unit ~= 1
hdr.dime.pixdim(2:4) = hdr.dime.pixdim(2:4) * space_unit;
% set space_unit of xyzt_units to millimeter, because
% voxel_size has been re-scaled
%
hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,1,0));
hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,2,1));
hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,3,0));
end
hdr.dime.pixdim = abs(hdr.dime.pixdim);
return; % change_hdr
%-----------------------------------------------------------------------
function orient = get_orient(R)
orient = [];
for i = 1:3
switch find(R(i,:)) * sign(sum(R(i,:)))
case 1
orient = [orient 1]; % Left to Right
case 2
orient = [orient 2]; % Posterior to Anterior
case 3
orient = [orient 3]; % Inferior to Superior
case -1
orient = [orient 4]; % Right to Left
case -2
orient = [orient 5]; % Anterior to Posterior
case -3
orient = [orient 6]; % Superior to Inferior
end
end
return; % get_orient
%-----------------------------------------------------------------------
function [space_unit, time_unit] = get_units(hdr)
switch bitand(hdr.dime.xyzt_units, 7) % mask with 0x07
case 1
space_unit = 1e+3; % meter, m
case 3
space_unit = 1e-3; % micrometer, um
otherwise
space_unit = 1; % millimeter, mm
end
switch bitand(hdr.dime.xyzt_units, 56) % mask with 0x38
case 16
time_unit = 1e-3; % millisecond, ms
case 24
time_unit = 1e-6; % microsecond, us
otherwise
time_unit = 1; % second, s
end
return; % get_units
|
github
|
philippboehmsturm/antx-master
|
make_ana.m
|
.m
|
antx-master/mritools/others/nii/make_ana.m
| 5,665 |
utf_8
|
37d574b277823f941138c9548127d720
|
% Make ANALYZE 7.5 data structure specified by a 3D or 4D matrix.
% Optional parameters can also be included, such as: voxel_size,
% origin, datatype, and description.
%
% Once the ANALYZE structure is made, it can be saved into ANALYZE 7.5
% format data file using "save_untouch_nii" command (for more detail,
% type: help save_untouch_nii).
%
% Usage: ana = make_ana(img, [voxel_size], [origin], [datatype], [description])
%
% Where:
%
% img: a 3D matrix [x y z], or a 4D matrix with time
% series [x y z t]. When image is in RGB format,
% make sure that the size of 4th dimension is
% always 3 (i.e. [R G B]). In that case, make
% sure that you must specify RGB datatype to 128.
%
% voxel_size (optional): Voxel size in millimeter for each
% dimension. Default is [1 1 1].
%
% origin (optional): The AC origin. Default is [0 0 0].
%
% datatype (optional): Storage data type:
% 2 - uint8, 4 - int16, 8 - int32, 16 - float32,
% 64 - float64, 128 - RGB24
% Default will use the data type of 'img' matrix
% For RGB image, you must specify it to 128.
%
% description (optional): Description of data. Default is ''.
%
% e.g.:
% origin = [33 44 13]; datatype = 64;
% ana = make_ana(img, [], origin, datatype); % default voxel_size
%
% ANALYZE 7.5 format: http://www.rotman-baycrest.on.ca/~jimmy/ANALYZE75.pdf
%
% - Jimmy Shen ([email protected])
%
function ana = make_ana(varargin)
ana.img = varargin{1};
dims = size(ana.img);
dims = [4 dims ones(1,8)];
dims = dims(1:8);
voxel_size = [0 ones(1,3) zeros(1,4)];
origin = zeros(1,5);
descrip = '';
switch class(ana.img)
case 'uint8'
datatype = 2;
case 'int16'
datatype = 4;
case 'int32'
datatype = 8;
case 'single'
datatype = 16;
case 'double'
datatype = 64;
otherwise
error('Datatype is not supported by make_ana.');
end
if nargin > 1 & ~isempty(varargin{2})
voxel_size(2:4) = double(varargin{2});
end
if nargin > 2 & ~isempty(varargin{3})
origin(1:3) = double(varargin{3});
end
if nargin > 3 & ~isempty(varargin{4})
datatype = double(varargin{4});
if datatype == 128 | datatype == 511
dims(5) = [];
dims = [dims 1];
end
end
if nargin > 4 & ~isempty(varargin{5})
descrip = varargin{5};
end
if ndims(ana.img) > 4
error('NIfTI only allows a maximum of 4 Dimension matrix.');
end
maxval = round(double(max(ana.img(:))));
minval = round(double(min(ana.img(:))));
ana.hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval);
ana.filetype = 0;
ana.ext = [];
ana.untouch = 1;
switch ana.hdr.dime.datatype
case 2
ana.img = uint8(ana.img);
case 4
ana.img = int16(ana.img);
case 8
ana.img = int32(ana.img);
case 16
ana.img = single(ana.img);
case 64
ana.img = double(ana.img);
case 128
ana.img = uint8(ana.img);
otherwise
error('Datatype is not supported by make_ana.');
end
return; % make_ana
%---------------------------------------------------------------------
function hdr = make_header(dims, voxel_size, origin, datatype, ...
descrip, maxval, minval)
hdr.hk = header_key;
hdr.dime = image_dimension(dims, voxel_size, datatype, maxval, minval);
hdr.hist = data_history(origin, descrip);
return; % make_header
%---------------------------------------------------------------------
function hk = header_key
hk.sizeof_hdr = 348; % must be 348!
hk.data_type = '';
hk.db_name = '';
hk.extents = 0;
hk.session_error = 0;
hk.regular = 'r';
hk.hkey_un0 = '0';
return; % header_key
%---------------------------------------------------------------------
function dime = image_dimension(dims, voxel_size, datatype, maxval, minval)
dime.dim = dims;
dime.vox_units = 'mm';
dime.cal_units = '';
dime.unused1 = 0;
dime.datatype = datatype;
switch dime.datatype
case 2,
dime.bitpix = 8; precision = 'uint8';
case 4,
dime.bitpix = 16; precision = 'int16';
case 8,
dime.bitpix = 32; precision = 'int32';
case 16,
dime.bitpix = 32; precision = 'float32';
case 64,
dime.bitpix = 64; precision = 'float64';
case 128
dime.bitpix = 24; precision = 'uint8';
otherwise
error('Datatype is not supported by make_ana.');
end
dime.dim_un0 = 0;
dime.pixdim = voxel_size;
dime.vox_offset = 0;
dime.roi_scale = 1;
dime.funused1 = 0;
dime.funused2 = 0;
dime.cal_max = 0;
dime.cal_min = 0;
dime.compressed = 0;
dime.verified = 0;
dime.glmax = maxval;
dime.glmin = minval;
return; % image_dimension
%---------------------------------------------------------------------
function hist = data_history(origin, descrip)
hist.descrip = descrip;
hist.aux_file = 'none';
hist.orient = 0;
hist.originator = origin;
hist.generated = '';
hist.scannum = '';
hist.patient_id = '';
hist.exp_date = '';
hist.exp_time = '';
hist.hist_un0 = '';
hist.views = 0;
hist.vols_added = 0;
hist.start_field = 0;
hist.field_skip = 0;
hist.omax = 0;
hist.omin = 0;
hist.smax = 0;
hist.smin = 0;
return; % data_history
|
github
|
philippboehmsturm/antx-master
|
extra_nii_hdr.m
|
.m
|
antx-master/mritools/others/nii/extra_nii_hdr.m
| 8,085 |
utf_8
|
4f76a8a66736025a0acf3efa15a2d2aa
|
% Decode extra NIFTI header information into hdr.extra
%
% Usage: hdr = extra_nii_hdr(hdr)
%
% hdr can be obtained from load_nii_hdr
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function hdr = extra_nii_hdr(hdr)
switch hdr.dime.datatype
case 1
extra.NIFTI_DATATYPES = 'DT_BINARY';
case 2
extra.NIFTI_DATATYPES = 'DT_UINT8';
case 4
extra.NIFTI_DATATYPES = 'DT_INT16';
case 8
extra.NIFTI_DATATYPES = 'DT_INT32';
case 16
extra.NIFTI_DATATYPES = 'DT_FLOAT32';
case 32
extra.NIFTI_DATATYPES = 'DT_COMPLEX64';
case 64
extra.NIFTI_DATATYPES = 'DT_FLOAT64';
case 128
extra.NIFTI_DATATYPES = 'DT_RGB24';
case 256
extra.NIFTI_DATATYPES = 'DT_INT8';
case 512
extra.NIFTI_DATATYPES = 'DT_UINT16';
case 768
extra.NIFTI_DATATYPES = 'DT_UINT32';
case 1024
extra.NIFTI_DATATYPES = 'DT_INT64';
case 1280
extra.NIFTI_DATATYPES = 'DT_UINT64';
case 1536
extra.NIFTI_DATATYPES = 'DT_FLOAT128';
case 1792
extra.NIFTI_DATATYPES = 'DT_COMPLEX128';
case 2048
extra.NIFTI_DATATYPES = 'DT_COMPLEX256';
otherwise
extra.NIFTI_DATATYPES = 'DT_UNKNOWN';
end
switch hdr.dime.intent_code
case 2
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_CORREL';
case 3
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_TTEST';
case 4
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_FTEST';
case 5
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_ZSCORE';
case 6
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_CHISQ';
case 7
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_BETA';
case 8
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_BINOM';
case 9
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_GAMMA';
case 10
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_POISSON';
case 11
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_NORMAL';
case 12
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_FTEST_NONC';
case 13
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_CHISQ_NONC';
case 14
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LOGISTIC';
case 15
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LAPLACE';
case 16
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_UNIFORM';
case 17
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_TTEST_NONC';
case 18
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_WEIBULL';
case 19
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_CHI';
case 20
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_INVGAUSS';
case 21
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_EXTVAL';
case 22
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_PVAL';
case 23
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LOGPVAL';
case 24
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LOG10PVAL';
case 1001
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_ESTIMATE';
case 1002
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_LABEL';
case 1003
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_NEURONAME';
case 1004
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_GENMATRIX';
case 1005
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_SYMMATRIX';
case 1006
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_DISPVECT';
case 1007
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_VECTOR';
case 1008
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_POINTSET';
case 1009
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_TRIANGLE';
case 1010
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_QUATERNION';
case 1011
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_DIMLESS';
otherwise
extra.NIFTI_INTENT_CODES = 'NIFTI_INTENT_NONE';
end
extra.NIFTI_INTENT_NAMES = hdr.hist.intent_name;
if hdr.hist.sform_code > 0
switch hdr.hist.sform_code
case 1
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_SCANNER_ANAT';
case 2
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_ALIGNED_ANAT';
case 3
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_TALAIRACH';
case 4
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_MNI_152';
otherwise
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
end
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
elseif hdr.hist.qform_code > 0
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
switch hdr.hist.qform_code
case 1
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_SCANNER_ANAT';
case 2
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_ALIGNED_ANAT';
case 3
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_TALAIRACH';
case 4
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_MNI_152';
otherwise
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
end
else
extra.NIFTI_SFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
extra.NIFTI_QFORM_CODES = 'NIFTI_XFORM_UNKNOWN';
end
switch bitand(hdr.dime.xyzt_units, 7) % mask with 0x07
case 1
extra.NIFTI_SPACE_UNIT = 'NIFTI_UNITS_METER';
case 2
extra.NIFTI_SPACE_UNIT = 'NIFTI_UNITS_MM'; % millimeter
case 3
extra.NIFTI_SPACE_UNIT = 'NIFTI_UNITS_MICRO';
otherwise
extra.NIFTI_SPACE_UNIT = 'NIFTI_UNITS_UNKNOWN';
end
switch bitand(hdr.dime.xyzt_units, 56) % mask with 0x38
case 8
extra.NIFTI_TIME_UNIT = 'NIFTI_UNITS_SEC';
case 16
extra.NIFTI_TIME_UNIT = 'NIFTI_UNITS_MSEC';
case 24
extra.NIFTI_TIME_UNIT = 'NIFTI_UNITS_USEC'; % microsecond
otherwise
extra.NIFTI_TIME_UNIT = 'NIFTI_UNITS_UNKNOWN';
end
switch hdr.dime.xyzt_units
case 32
extra.NIFTI_SPECTRAL_UNIT = 'NIFTI_UNITS_HZ';
case 40
extra.NIFTI_SPECTRAL_UNIT = 'NIFTI_UNITS_PPM'; % part per million
case 48
extra.NIFTI_SPECTRAL_UNIT = 'NIFTI_UNITS_RADS'; % radians per second
otherwise
extra.NIFTI_SPECTRAL_UNIT = 'NIFTI_UNITS_UNKNOWN';
end
% MRI-specific spatial and temporal information
%
dim_info = hdr.hk.dim_info;
extra.NIFTI_FREQ_DIM = bitand(dim_info, 3);
extra.NIFTI_PHASE_DIM = bitand(bitshift(dim_info, -2), 3);
extra.NIFTI_SLICE_DIM = bitand(bitshift(dim_info, -4), 3);
% Check slice code
%
switch hdr.dime.slice_code
case 1
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_SEQ_INC'; % sequential increasing
case 2
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_SEQ_DEC'; % sequential decreasing
case 3
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_ALT_INC'; % alternating increasing
case 4
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_ALT_DEC'; % alternating decreasing
case 5
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_ALT_INC2'; % ALT_INC # 2
case 6
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_ALT_DEC2'; % ALT_DEC # 2
otherwise
extra.NIFTI_SLICE_ORDER = 'NIFTI_SLICE_UNKNOWN';
end
% Check NIFTI version
%
if ~isempty(hdr.hist.magic) & strcmp(hdr.hist.magic(1),'n') & ...
( strcmp(hdr.hist.magic(2),'i') | strcmp(hdr.hist.magic(2),'+') ) & ...
str2num(hdr.hist.magic(3)) >= 1 & str2num(hdr.hist.magic(3)) <= 9
extra.NIFTI_VERSION = str2num(hdr.hist.magic(3));
else
extra.NIFTI_VERSION = 0;
end
% Check if data stored in the same file (*.nii) or separate
% files (*.hdr/*.img)
%
if isempty(hdr.hist.magic)
extra.NIFTI_ONEFILE = 0;
else
extra.NIFTI_ONEFILE = strcmp(hdr.hist.magic(2), '+');
end
% Swap has been taken care of by checking whether sizeof_hdr is
% 348 (machine is 'ieee-le' or 'ieee-be' etc)
%
% extra.NIFTI_NEEDS_SWAP = (hdr.dime.dim(1) < 0 | hdr.dime.dim(1) > 7);
% Check NIFTI header struct contains a 5th (vector) dimension
%
if hdr.dime.dim(1) > 4 & hdr.dime.dim(6) > 1
extra.NIFTI_5TH_DIM = hdr.dime.dim(6);
else
extra.NIFTI_5TH_DIM = 0;
end
hdr.extra = extra;
return; % extra_nii_hdr
|
github
|
philippboehmsturm/antx-master
|
rri_xhair.m
|
.m
|
antx-master/mritools/others/nii/rri_xhair.m
| 2,300 |
utf_8
|
95954b8cd43e01fba5c4b2f335be1780
|
% rri_xhair: create a pair of full_cross_hair at point [x y] in
% axes h_ax, and return xhair struct
%
% Usage: xhair = rri_xhair([x y], xhair, h_ax);
%
% If omit xhair, rri_xhair will create a pair of xhair; otherwise,
% rri_xhair will update the xhair. If omit h_ax, current axes will
% be used.
%
% 24-nov-2003 jimmy ([email protected])
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xhair = rri_xhair(varargin)
if nargin == 0
error('Please enter a point position as first argument');
return;
end
if nargin > 0
p = varargin{1};
if ~isnumeric(p) | length(p) ~= 2
error('Invalid point position');
return;
else
xhair = [];
end
end
if nargin > 1
xhair = varargin{2};
if ~isempty(xhair)
if ~isstruct(xhair)
error('Invalid xhair struct');
return;
elseif ~isfield(xhair,'lx') | ~isfield(xhair,'ly')
error('Invalid xhair struct');
return;
elseif ~ishandle(xhair.lx) | ~ishandle(xhair.ly)
error('Invalid xhair struct');
return;
end
lx = xhair.lx;
ly = xhair.ly;
else
lx = [];
ly = [];
end
end
if nargin > 2
h_ax = varargin{3};
if ~ishandle(h_ax)
error('Invalid axes handle');
return;
elseif ~strcmp(lower(get(h_ax,'type')), 'axes')
error('Invalid axes handle');
return;
end
else
h_ax = gca;
end
x_range = get(h_ax,'xlim');
y_range = get(h_ax,'ylim');
if ~isempty(xhair)
set(lx, 'ydata', [p(2) p(2)]);
set(ly, 'xdata', [p(1) p(1)]);
set(h_ax, 'selected', 'on');
set(h_ax, 'selected', 'off');
else
figure(get(h_ax,'parent'));
axes(h_ax);
xhair.lx = line('xdata', x_range, 'ydata', [p(2) p(2)], ...
'zdata', [11 11], 'color', [1 0 0], 'hittest', 'off');
xhair.ly = line('xdata', [p(1) p(1)], 'ydata', y_range, ...
'zdata', [11 11], 'color', [1 0 0], 'hittest', 'off');
end
set(h_ax,'xlim',x_range);
set(h_ax,'ylim',y_range);
return;
|
github
|
philippboehmsturm/antx-master
|
save_untouch_nii_hdr.m
|
.m
|
antx-master/mritools/others/nii/save_untouch_nii_hdr.m
| 8,721 |
utf_8
|
0d396eaeebb6114f24d56ab74a8299cf
|
% internal function
% - Jimmy Shen ([email protected])
function save_nii_hdr(hdr, fid)
if ~isequal(hdr.hk.sizeof_hdr,348),
error('hdr.hk.sizeof_hdr must be 348.');
end
write_header(hdr, fid);
return; % save_nii_hdr
%---------------------------------------------------------------------
function write_header(hdr, fid)
% Original header structures
% struct dsr /* dsr = hdr */
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
header_key(fid, hdr.hk);
image_dimension(fid, hdr.dime);
data_history(fid, hdr.hist);
% check the file size is 348 bytes
%
fbytes = ftell(fid);
if ~isequal(fbytes,348),
msg = sprintf('Header size is not 348 bytes.');
warning(msg);
end
return; % write_header
%---------------------------------------------------------------------
function header_key(fid, hk)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348.
% data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars from left
% fwrite(fid, data_type(1:10), 'uchar');
pad = zeros(1, 10-length(hk.data_type));
hk.data_type = [hk.data_type char(pad)];
fwrite(fid, hk.data_type(1:10), 'uchar');
% db_name = sprintf('%-18s', hk.db_name); % ensure it is 18 chars from left
% fwrite(fid, db_name(1:18), 'uchar');
pad = zeros(1, 18-length(hk.db_name));
hk.db_name = [hk.db_name char(pad)];
fwrite(fid, hk.db_name(1:18), 'uchar');
fwrite(fid, hk.extents(1), 'int32');
fwrite(fid, hk.session_error(1), 'int16');
fwrite(fid, hk.regular(1), 'uchar'); % might be uint8
% fwrite(fid, hk.hkey_un0(1), 'uchar');
% fwrite(fid, hk.hkey_un0(1), 'uint8');
fwrite(fid, hk.dim_info(1), 'uchar');
return; % header_key
%---------------------------------------------------------------------
function image_dimension(fid, dime)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width
% pixdim[2] - voxel height
% pixdim[3] - interslice distance
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
fwrite(fid, dime.dim(1:8), 'int16');
fwrite(fid, dime.intent_p1(1), 'float32');
fwrite(fid, dime.intent_p2(1), 'float32');
fwrite(fid, dime.intent_p3(1), 'float32');
fwrite(fid, dime.intent_code(1), 'int16');
fwrite(fid, dime.datatype(1), 'int16');
fwrite(fid, dime.bitpix(1), 'int16');
fwrite(fid, dime.slice_start(1), 'int16');
fwrite(fid, dime.pixdim(1:8), 'float32');
fwrite(fid, dime.vox_offset(1), 'float32');
fwrite(fid, dime.scl_slope(1), 'float32');
fwrite(fid, dime.scl_inter(1), 'float32');
fwrite(fid, dime.slice_end(1), 'int16');
fwrite(fid, dime.slice_code(1), 'uchar');
fwrite(fid, dime.xyzt_units(1), 'uchar');
fwrite(fid, dime.cal_max(1), 'float32');
fwrite(fid, dime.cal_min(1), 'float32');
fwrite(fid, dime.slice_duration(1), 'float32');
fwrite(fid, dime.toffset(1), 'float32');
fwrite(fid, dime.glmax(1), 'int32');
fwrite(fid, dime.glmin(1), 'int32');
return; % image_dimension
%---------------------------------------------------------------------
function data_history(fid, hist)
% Original header structures
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
% descrip = sprintf('%-80s', hist.descrip); % 80 chars from left
% fwrite(fid, descrip(1:80), 'uchar');
pad = zeros(1, 80-length(hist.descrip));
hist.descrip = [hist.descrip char(pad)];
fwrite(fid, hist.descrip(1:80), 'uchar');
% aux_file = sprintf('%-24s', hist.aux_file); % 24 chars from left
% fwrite(fid, aux_file(1:24), 'uchar');
pad = zeros(1, 24-length(hist.aux_file));
hist.aux_file = [hist.aux_file char(pad)];
fwrite(fid, hist.aux_file(1:24), 'uchar');
fwrite(fid, hist.qform_code, 'int16');
fwrite(fid, hist.sform_code, 'int16');
fwrite(fid, hist.quatern_b, 'float32');
fwrite(fid, hist.quatern_c, 'float32');
fwrite(fid, hist.quatern_d, 'float32');
fwrite(fid, hist.qoffset_x, 'float32');
fwrite(fid, hist.qoffset_y, 'float32');
fwrite(fid, hist.qoffset_z, 'float32');
fwrite(fid, hist.srow_x(1:4), 'float32');
fwrite(fid, hist.srow_y(1:4), 'float32');
fwrite(fid, hist.srow_z(1:4), 'float32');
% intent_name = sprintf('%-16s', hist.intent_name); % 16 chars from left
% fwrite(fid, intent_name(1:16), 'uchar');
pad = zeros(1, 16-length(hist.intent_name));
hist.intent_name = [hist.intent_name char(pad)];
fwrite(fid, hist.intent_name(1:16), 'uchar');
% magic = sprintf('%-4s', hist.magic); % 4 chars from left
% fwrite(fid, magic(1:4), 'uchar');
pad = zeros(1, 4-length(hist.magic));
hist.magic = [hist.magic char(pad)];
fwrite(fid, hist.magic(1:4), 'uchar');
return; % data_history
|
github
|
philippboehmsturm/antx-master
|
expand_nii_scan.m
|
.m
|
antx-master/mritools/others/nii/expand_nii_scan.m
| 1,381 |
utf_8
|
0715d668d046bcc608ea78cd0c2089bd
|
% Expand a multiple-scan NIFTI file into multiple single-scan NIFTI files
%
% Usage: expand_nii_scan(multi_scan_filename, [img_idx], [path_to_save])
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function expand_nii_scan(filename, img_idx, newpath)
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
else
gzFile = 1;
end
end
if ~exist('newpath','var') | isempty(newpath), newpath = pwd; end
if ~exist('img_idx','var') | isempty(img_idx), img_idx = 1:get_nii_frame(filename); end
for i=img_idx
nii_i = load_untouch_nii(filename, i);
fn = [nii_i.fileprefix '_' sprintf('%04d',i)];
pnfn = fullfile(newpath, fn);
if exist('gzFile', 'var')
pnfn = [pnfn '.nii.gz'];
end
save_untouch_nii(nii_i, pnfn);
end
return; % expand_nii_scan
|
github
|
philippboehmsturm/antx-master
|
load_untouch_header_only.m
|
.m
|
antx-master/mritools/others/nii/load_untouch_header_only.m
| 7,255 |
utf_8
|
f1210f851ab6610e7656121194cb5c8b
|
% Load NIfTI / Analyze header without applying any appropriate affine
% geometric transform or voxel intensity scaling. It is equivalent to
% hdr field when using load_untouch_nii to load dataset. Support both
% *.nii and *.hdr file extension. If file extension is not provided,
% *.hdr will be used as default.
%
% Usage: [header, ext, filetype, machine] = load_untouch_header_only(filename)
%
% filename - NIfTI / Analyze file name.
%
% Returned values:
%
% header - struct with NIfTI / Analyze header fields.
%
% ext - NIfTI extension if it is not empty.
%
% filetype - 0 for Analyze format (*.hdr/*.img);
% 1 for NIFTI format in 2 files (*.hdr/*.img);
% 2 for NIFTI format in 1 file (*.nii).
%
% machine - a string, see below for details. The default here is 'ieee-le'.
%
% 'native' or 'n' - local machine format - the default
% 'ieee-le' or 'l' - IEEE floating point with little-endian
% byte ordering
% 'ieee-be' or 'b' - IEEE floating point with big-endian
% byte ordering
% 'vaxd' or 'd' - VAX D floating point and VAX ordering
% 'vaxg' or 'g' - VAX G floating point and VAX ordering
% 'cray' or 'c' - Cray floating point with big-endian
% byte ordering
% 'ieee-le.l64' or 'a' - IEEE floating point with little-endian
% byte ordering and 64 bit long data type
% 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte
% ordering and 64 bit long data type.
%
% Part of this file is copied and modified from:
% http://www.mathworks.com/matlabcentral/fileexchange/1878-mri-analyze-tools
%
% NIFTI data format can be found on: http://nifti.nimh.nih.gov
%
% - Jimmy Shen ([email protected])
%
function [hdr, ext, filetype, machine] = load_untouch_header_only(filename)
if ~exist('filename','var')
error('Usage: [header, ext, filetype, machine] = load_untouch_header_only(filename)');
end
v = version;
% Check file extension. If .gz, unpack it into temp folder
%
if length(filename) > 2 & strcmp(filename(end-2:end), '.gz')
if ~strcmp(filename(end-6:end), '.img.gz') & ...
~strcmp(filename(end-6:end), '.hdr.gz') & ...
~strcmp(filename(end-6:end), '.nii.gz')
error('Please check filename.');
end
if str2num(v(1:3)) < 7.1 | ~usejava('jvm')
error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.');
elseif strcmp(filename(end-6:end), '.img.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.hdr.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.hdr.gz')
filename1 = filename;
filename2 = filename;
filename2(end-6:end) = '';
filename2 = [filename2, '.img.gz'];
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename1 = gunzip(filename1, tmpDir);
filename2 = gunzip(filename2, tmpDir);
filename = char(filename1); % convert from cell to string
elseif strcmp(filename(end-6:end), '.nii.gz')
tmpDir = tempname;
mkdir(tmpDir);
gzFileName = filename;
filename = gunzip(filename, tmpDir);
filename = char(filename); % convert from cell to string
end
end
% Read the dataset header
%
[hdr, filetype, fileprefix, machine] = load_nii_hdr(filename);
if filetype == 0
hdr = load_untouch0_nii_hdr(fileprefix, machine);
ext = [];
else
hdr = load_untouch_nii_hdr(fileprefix, machine, filetype);
% Read the header extension
%
ext = load_nii_ext(filename);
end
% Set bitpix according to datatype
%
% /*Acceptable values for datatype are*/
%
% 0 None (Unknown bit per voxel) % DT_NONE, DT_UNKNOWN
% 1 Binary (ubit1, bitpix=1) % DT_BINARY
% 2 Unsigned char (uchar or uint8, bitpix=8) % DT_UINT8, NIFTI_TYPE_UINT8
% 4 Signed short (int16, bitpix=16) % DT_INT16, NIFTI_TYPE_INT16
% 8 Signed integer (int32, bitpix=32) % DT_INT32, NIFTI_TYPE_INT32
% 16 Floating point (single or float32, bitpix=32) % DT_FLOAT32, NIFTI_TYPE_FLOAT32
% 32 Complex, 2 float32 (Use float32, bitpix=64) % DT_COMPLEX64, NIFTI_TYPE_COMPLEX64
% 64 Double precision (double or float64, bitpix=64) % DT_FLOAT64, NIFTI_TYPE_FLOAT64
% 128 uint8 RGB (Use uint8, bitpix=24) % DT_RGB24, NIFTI_TYPE_RGB24
% 256 Signed char (schar or int8, bitpix=8) % DT_INT8, NIFTI_TYPE_INT8
% 511 Single RGB (Use float32, bitpix=96) % DT_RGB96, NIFTI_TYPE_RGB96
% 512 Unsigned short (uint16, bitpix=16) % DT_UNINT16, NIFTI_TYPE_UNINT16
% 768 Unsigned integer (uint32, bitpix=32) % DT_UNINT32, NIFTI_TYPE_UNINT32
% 1024 Signed long long (int64, bitpix=64) % DT_INT64, NIFTI_TYPE_INT64
% 1280 Unsigned long long (uint64, bitpix=64) % DT_UINT64, NIFTI_TYPE_UINT64
% 1536 Long double, float128 (Unsupported, bitpix=128) % DT_FLOAT128, NIFTI_TYPE_FLOAT128
% 1792 Complex128, 2 float64 (Use float64, bitpix=128) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
% 2048 Complex256, 2 float128 (Unsupported, bitpix=256) % DT_COMPLEX128, NIFTI_TYPE_COMPLEX128
%
switch hdr.dime.datatype
case 1,
hdr.dime.bitpix = 1; precision = 'ubit1';
case 2,
hdr.dime.bitpix = 8; precision = 'uint8';
case 4,
hdr.dime.bitpix = 16; precision = 'int16';
case 8,
hdr.dime.bitpix = 32; precision = 'int32';
case 16,
hdr.dime.bitpix = 32; precision = 'float32';
case 32,
hdr.dime.bitpix = 64; precision = 'float32';
case 64,
hdr.dime.bitpix = 64; precision = 'float64';
case 128,
hdr.dime.bitpix = 24; precision = 'uint8';
case 256
hdr.dime.bitpix = 8; precision = 'int8';
case 511
hdr.dime.bitpix = 96; precision = 'float32';
case 512
hdr.dime.bitpix = 16; precision = 'uint16';
case 768
hdr.dime.bitpix = 32; precision = 'uint32';
case 1024
hdr.dime.bitpix = 64; precision = 'int64';
case 1280
hdr.dime.bitpix = 64; precision = 'uint64';
case 1792,
hdr.dime.bitpix = 128; precision = 'float64';
otherwise
error('This datatype is not supported');
end
tmp = hdr.dime.dim(2:end);
tmp(find(tmp < 1)) = 1;
hdr.dime.dim(2:end) = tmp;
% Clean up after gunzip
%
if exist('gzFileName', 'var')
rmdir(tmpDir,'s');
end
return % load_untouch_header_only
|
github
|
philippboehmsturm/antx-master
|
bipolar.m
|
.m
|
antx-master/mritools/others/nii/bipolar.m
| 2,239 |
utf_8
|
c860ec93d96b6ab636c985280d79958d
|
%BIPOLAR returns an M-by-3 matrix containing a blue-red colormap, in
% in which red stands for positive, blue stands for negative,
% and white stands for 0.
%
% Usage: cmap = bipolar(M, lo, hi, contrast); or cmap = bipolar;
%
% cmap: output M-by-3 matrix for BIPOLAR colormap.
% M: number of shades in the colormap. By default, it is the
% same length as the current colormap.
% lo: the lowest value to represent.
% hi: the highest value to represent.
%
% Inspired from the LORETA PASCAL program:
% http://www.unizh.ch/keyinst/NewLORETA
%
% [email protected]
%
%----------------------------------------------------------------
function cmap = bipolar(M, lo, hi, contrast)
if ~exist('contrast','var')
contrast = 128;
end
if ~exist('lo','var')
lo = -1;
end
if ~exist('hi','var')
hi = 1;
end
if ~exist('M','var')
cmap = colormap;
M = size(cmap,1);
end
steepness = 10 ^ (1 - (contrast-1)/127);
pos_infs = 1e-99;
neg_infs = -1e-99;
doubleredc = [];
doublebluec = [];
if lo >= 0 % all positive
if lo == 0
lo = pos_infs;
end
for i=linspace(hi/M, hi, M)
t = exp(log(i/hi)*steepness);
doubleredc = [doubleredc; [(1-t)+t,(1-t)+0,(1-t)+0]];
end
cmap = doubleredc;
elseif hi <= 0 % all negative
if hi == 0
hi = neg_infs;
end
for i=linspace(abs(lo)/M, abs(lo), M)
t = exp(log(i/abs(lo))*steepness);
doublebluec = [doublebluec; [(1-t)+0,(1-t)+0,(1-t)+t]];
end
cmap = flipud(doublebluec);
else
if hi > abs(lo)
maxc = hi;
else
maxc = abs(lo);
end
for i=linspace(maxc/M, hi, round(M*hi/(hi-lo)))
t = exp(log(i/maxc)*steepness);
doubleredc = [doubleredc; [(1-t)+t,(1-t)+0,(1-t)+0]];
end
for i=linspace(maxc/M, abs(lo), round(M*abs(lo)/(hi-lo)))
t = exp(log(i/maxc)*steepness);
doublebluec = [doublebluec; [(1-t)+0,(1-t)+0,(1-t)+t]];
end
cmap = [flipud(doublebluec); doubleredc];
end
return; % bipolar
|
github
|
philippboehmsturm/antx-master
|
save_nii_hdr.m
|
.m
|
antx-master/mritools/others/nii/save_nii_hdr.m
| 9,497 |
utf_8
|
66a99df0cb0f3c1f44c6e36dcd13cddf
|
% internal function
% - Jimmy Shen ([email protected])
function save_nii_hdr(hdr, fid)
if ~exist('hdr','var') | ~exist('fid','var')
error('Usage: save_nii_hdr(hdr, fid)');
end
if ~isequal(hdr.hk.sizeof_hdr,348),
error('hdr.hk.sizeof_hdr must be 348.');
end
if hdr.hist.qform_code == 0 & hdr.hist.sform_code == 0
hdr.hist.sform_code = 1;
hdr.hist.srow_x(1) = hdr.dime.pixdim(2);
hdr.hist.srow_x(2) = 0;
hdr.hist.srow_x(3) = 0;
hdr.hist.srow_y(1) = 0;
hdr.hist.srow_y(2) = hdr.dime.pixdim(3);
hdr.hist.srow_y(3) = 0;
hdr.hist.srow_z(1) = 0;
hdr.hist.srow_z(2) = 0;
hdr.hist.srow_z(3) = hdr.dime.pixdim(4);
hdr.hist.srow_x(4) = (1-hdr.hist.originator(1))*hdr.dime.pixdim(2);
hdr.hist.srow_y(4) = (1-hdr.hist.originator(2))*hdr.dime.pixdim(3);
hdr.hist.srow_z(4) = (1-hdr.hist.originator(3))*hdr.dime.pixdim(4);
end
write_header(hdr, fid);
return; % save_nii_hdr
%---------------------------------------------------------------------
function write_header(hdr, fid)
% Original header structures
% struct dsr /* dsr = hdr */
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
header_key(fid, hdr.hk);
image_dimension(fid, hdr.dime);
data_history(fid, hdr.hist);
% check the file size is 348 bytes
%
fbytes = ftell(fid);
if ~isequal(fbytes,348),
msg = sprintf('Header size is not 348 bytes.');
warning(msg);
end
return; % write_header
%---------------------------------------------------------------------
function header_key(fid, hk)
fseek(fid,0,'bof');
% Original header structures
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char dim_info; % char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348.
% data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars from left
% fwrite(fid, data_type(1:10), 'uchar');
pad = zeros(1, 10-length(hk.data_type));
hk.data_type = [hk.data_type char(pad)];
fwrite(fid, hk.data_type(1:10), 'uchar');
% db_name = sprintf('%-18s', hk.db_name); % ensure it is 18 chars from left
% fwrite(fid, db_name(1:18), 'uchar');
pad = zeros(1, 18-length(hk.db_name));
hk.db_name = [hk.db_name char(pad)];
fwrite(fid, hk.db_name(1:18), 'uchar');
fwrite(fid, hk.extents(1), 'int32');
fwrite(fid, hk.session_error(1), 'int16');
fwrite(fid, hk.regular(1), 'uchar'); % might be uint8
% fwrite(fid, hk.hkey_un0(1), 'uchar');
% fwrite(fid, hk.hkey_un0(1), 'uint8');
fwrite(fid, hk.dim_info(1), 'uchar');
return; % header_key
%---------------------------------------------------------------------
function image_dimension(fid, dime)
% Original header structures
% struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% float intent_p1; % char vox_units[4]; /* 16 + 4 */
% float intent_p2; % char cal_units[8]; /* 20 + 4 */
% float intent_p3; % char cal_units[8]; /* 24 + 4 */
% short int intent_code; % short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int slice_start; % short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width
% pixdim[2] - voxel height
% pixdim[3] - interslice distance
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float scl_slope; % float roi_scale; /* 72 + 4 */
% float scl_inter; % float funused1; /* 76 + 4 */
% short slice_end; % float funused2; /* 80 + 2 */
% char slice_code; % float funused2; /* 82 + 1 */
% char xyzt_units; % float funused2; /* 83 + 1 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% float slice_duration; % int compressed; /* 92 + 4 */
% float toffset; % int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
fwrite(fid, dime.dim(1:8), 'int16');
fwrite(fid, dime.intent_p1(1), 'float32');
fwrite(fid, dime.intent_p2(1), 'float32');
fwrite(fid, dime.intent_p3(1), 'float32');
fwrite(fid, dime.intent_code(1), 'int16');
fwrite(fid, dime.datatype(1), 'int16');
fwrite(fid, dime.bitpix(1), 'int16');
fwrite(fid, dime.slice_start(1), 'int16');
fwrite(fid, dime.pixdim(1:8), 'float32');
fwrite(fid, dime.vox_offset(1), 'float32');
fwrite(fid, dime.scl_slope(1), 'float32');
fwrite(fid, dime.scl_inter(1), 'float32');
fwrite(fid, dime.slice_end(1), 'int16');
fwrite(fid, dime.slice_code(1), 'uchar');
fwrite(fid, dime.xyzt_units(1), 'uchar');
fwrite(fid, dime.cal_max(1), 'float32');
fwrite(fid, dime.cal_min(1), 'float32');
fwrite(fid, dime.slice_duration(1), 'float32');
fwrite(fid, dime.toffset(1), 'float32');
fwrite(fid, dime.glmax(1), 'int32');
fwrite(fid, dime.glmin(1), 'int32');
return; % image_dimension
%---------------------------------------------------------------------
function data_history(fid, hist)
% Original header structures
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% short int qform_code; /* 104 + 2 */
% short int sform_code; /* 106 + 2 */
% float quatern_b; /* 108 + 4 */
% float quatern_c; /* 112 + 4 */
% float quatern_d; /* 116 + 4 */
% float qoffset_x; /* 120 + 4 */
% float qoffset_y; /* 124 + 4 */
% float qoffset_z; /* 128 + 4 */
% float srow_x[4]; /* 132 + 16 */
% float srow_y[4]; /* 148 + 16 */
% float srow_z[4]; /* 164 + 16 */
% char intent_name[16]; /* 180 + 16 */
% char magic[4]; % int smin; /* 196 + 4 */
% }; /* total=200 bytes */
% descrip = sprintf('%-80s', hist.descrip); % 80 chars from left
% fwrite(fid, descrip(1:80), 'uchar');
pad = zeros(1, 80-length(hist.descrip));
hist.descrip = [hist.descrip char(pad)];
fwrite(fid, hist.descrip(1:80), 'uchar');
% aux_file = sprintf('%-24s', hist.aux_file); % 24 chars from left
% fwrite(fid, aux_file(1:24), 'uchar');
pad = zeros(1, 24-length(hist.aux_file));
hist.aux_file = [hist.aux_file char(pad)];
fwrite(fid, hist.aux_file(1:24), 'uchar');
fwrite(fid, hist.qform_code, 'int16');
fwrite(fid, hist.sform_code, 'int16');
fwrite(fid, hist.quatern_b, 'float32');
fwrite(fid, hist.quatern_c, 'float32');
fwrite(fid, hist.quatern_d, 'float32');
fwrite(fid, hist.qoffset_x, 'float32');
fwrite(fid, hist.qoffset_y, 'float32');
fwrite(fid, hist.qoffset_z, 'float32');
fwrite(fid, hist.srow_x(1:4), 'float32');
fwrite(fid, hist.srow_y(1:4), 'float32');
fwrite(fid, hist.srow_z(1:4), 'float32');
% intent_name = sprintf('%-16s', hist.intent_name); % 16 chars from left
% fwrite(fid, intent_name(1:16), 'uchar');
pad = zeros(1, 16-length(hist.intent_name));
hist.intent_name = [hist.intent_name char(pad)];
fwrite(fid, hist.intent_name(1:16), 'uchar');
% magic = sprintf('%-4s', hist.magic); % 4 chars from left
% fwrite(fid, magic(1:4), 'uchar');
pad = zeros(1, 4-length(hist.magic));
hist.magic = [hist.magic char(pad)];
fwrite(fid, hist.magic(1:4), 'uchar');
return; % data_history
|
github
|
philippboehmsturm/antx-master
|
skullstrip_pcnn3d.m
|
.m
|
antx-master/mritools/others/PCNN3D/skullstrip_pcnn3d.m
| 1,473 |
utf_8
|
9caa6079dcad36d4cb8d74d33386ce79
|
function skullstrip_pcnn3d(t2file, fileout, mode )
if 0
skullstrip_pcnn3d(fullfile(pwd,'t2_aa.nii'), fullfile(pwd, '_test1.nii' ), 'mask' )
skullstrip_pcnn3d(fullfile(pwd,'t2_aa.nii'), fullfile(pwd, '_test2.nii' ), 'skullstrip' )
end
warning off;
% tmpfile=fullfile(fileparts(t2file),'__temp4skullstrip.nii')
% copyfile(t2file,tmpfile,'f')
% spm_reslice(tmpfile)
[bb vox]=world_bb(t2file);
% outfile=resize_img5(imname,outname, Voxdim, BB, ismask, interpmethod, dt)
% [ha a]=rgetnii('T2.nii');
[ha a]= rgetnii(t2file);
brainSize= [100 550];
niter = 100;
radelem =4;
vdim=abs(vox);%abs(diag(ha.mat(1:3,1:3))');
%[I_border, gi] = PCNN3D( a , 4 , vdim, brainSize );
[args ,I_border, gi] = evalc('PCNN3D( a , radelem , vdim, brainSize );');
disp(args);
%get Guess for best iteration.
ix=strfind(args,'Guess for best iteration is ');
ix2=strfind(args,'.');
ank=ix2(min(find(ix2>ix)));
id=str2num(regexprep(args(ix:ank-1),'\D',''));
if 0
gi(find(gi<brainSize(1) | gi>brainSize(2)))=nan ;%set nan outside brainsize
id= find(diff(gi)==nanmin(diff(gi))); %find plateau
id=min(id);
end
r=I_border{id};
% r=I_border{35}
for i=1:length(r)
b=full(r{i});
if i==1; x=zeros(size(a));end
x(:,:,i)=b;
end
if strcmp(mode, 'mask')
m=x;
elseif strcmp(mode, 'skullstrip')
m=x.*a;
end
% rsavenii('_msk',ha,m);
rsavenii(fileout,ha,m);
close(gcf);
|
github
|
philippboehmsturm/antx-master
|
screencapture.m
|
.m
|
antx-master/mritools/others/ScreenCapture/screencapture.m
| 37,131 |
utf_8
|
221211bbef30a51283574e24a0c5fb2a
|
function imageData = screencapture(varargin)
% screencapture - get a screen-capture of a figure frame, component handle, or screen area rectangle
%
% ScreenCapture gets a screen-capture of any Matlab GUI handle (including desktop,
% figure, axes, image or uicontrol), or a specified area rectangle located relative to
% the specified handle. Screen area capture is possible by specifying the root (desktop)
% handle (=0). The output can be either to an image file or to a Matlab matrix (useful
% for displaying via imshow() or for further processing) or to the system clipboard.
% This utility also enables adding a toolbar button for easy interactive screen-capture.
%
% Syntax:
% imageData = screencapture(handle, position, target, 'PropName',PropValue, ...)
%
% Input Parameters:
% handle - optional handle to be used for screen-capture origin.
% If empty/unsupplied then current figure (gcf) will be used.
% position - optional position array in pixels: [x,y,width,height].
% If empty/unsupplied then the handle's position vector will be used.
% If both handle and position are empty/unsupplied then the position
% will be retrieved via interactive mouse-selection.
% If handle is an image, then position is in data (not pixel) units, so the
% captured region remains the same after figure/axes resize (like imcrop)
% target - optional filename for storing the screen-capture, or the
% 'clipboard'/'printer' strings.
% If empty/unsupplied then no output to file will be done.
% The file format will be determined from the extension (JPG/PNG/...).
% Supported formats are those supported by the imwrite function.
% 'PropName',PropValue -
% optional list of property pairs (e.g., 'target','myImage.png','pos',[10,20,30,40],'handle',gca)
% PropNames may be abbreviated and are case-insensitive.
% PropNames may also be given in whichever order.
% Supported PropNames are:
% - 'handle' (default: gcf handle)
% - 'position' (default: gcf position array)
% - 'target' (default: '')
% - 'toolbar' (figure handle; default: gcf)
% this adds a screen-capture button to the figure's toolbar
% If this parameter is specified, then no screen-capture
% will take place and the returned imageData will be [].
%
% Output parameters:
% imageData - image data in a format acceptable by the imshow function
% If neither target nor imageData were specified, the user will be
% asked to interactively specify the output file.
%
% Examples:
% imageData = screencapture; % interactively select screen-capture rectangle
% imageData = screencapture(hListbox); % capture image of a uicontrol
% imageData = screencapture(0, [20,30,40,50]); % capture a small desktop region
% imageData = screencapture(gcf,[20,30,40,50]); % capture a small figure region
% imageData = screencapture(gca,[10,20,30,40]); % capture a small axes region
% imshow(imageData); % display the captured image in a matlab figure
% imwrite(imageData,'myImage.png'); % save the captured image to file
% img = imread('cameraman.tif');
% hImg = imshow(img);
% screencapture(hImg,[60,35,140,80]); % capture a region of an image
% screencapture(gcf,[],'myFigure.jpg'); % capture the entire figure into file
% screencapture(gcf,[],'clipboard'); % capture the entire figure into clipboard
% screencapture(gcf,[],'printer'); % print the entire figure
% screencapture('handle',gcf,'target','myFigure.jpg'); % same as previous, save to file
% screencapture('handle',gcf,'target','clipboard'); % same as previous, copy to clipboard
% screencapture('handle',gcf,'target','printer'); % same as previous, send to printer
% screencapture('toolbar',gcf); % adds a screen-capture button to gcf's toolbar
% screencapture('toolbar',[],'target','sc.bmp'); % same with default output filename
%
% Technical description:
% http://UndocumentedMatlab.com/blog/screencapture-utility/
%
% Bugs and suggestions:
% Please send to Yair Altman (altmany at gmail dot com)
%
% See also:
% imshow, imwrite, print
%
% Release history:
% 1.17 2016-05-16: Fix annoying warning about JavaFrame property becoming obsolete someday (yes, we know...)
% 1.16 2016-04-19: Fix for deployed application suggested by Dwight Bartholomew
% 1.10 2014-11-25: Added the 'print' target
% 1.9 2014-11-25: Fix for saving GIF files
% 1.8 2014-11-16: Fixes for R2014b
% 1.7 2014-04-28: Fixed bug when capturing interactive selection
% 1.6 2014-04-22: Only enable image formats when saving to an unspecified file via uiputfile
% 1.5 2013-04-18: Fixed bug in capture of non-square image; fixes for Win64
% 1.4 2013-01-27: Fixed capture of Desktop (root); enabled rbbox anywhere on desktop (not necesarily in a Matlab figure); enabled output to clipboard (based on Jiro Doke's imclipboard utility); edge-case fixes; added Java compatibility check
% 1.3 2012-07-23: Capture current object (uicontrol/axes/figure) if w=h=0 (e.g., by clicking a single point); extra input args sanity checks; fix for docked windows and image axes; include axes labels & ticks by default when capturing axes; use data-units position vector when capturing images; many edge-case fixes
% 1.2 2011-01-16: another performance boost (thanks to Jan Simon); some compatibility fixes for Matlab 6.5 (untested)
% 1.1 2009-06-03: Handle missing output format; performance boost (thanks to Urs); fix minor root-handle bug; added toolbar button option
% 1.0 2009-06-02: First version posted on <a href="http://www.mathworks.com/matlabcentral/fileexchange/authors/27420">MathWorks File Exchange</a>
% License to use and modify this code is granted freely to all interested, as long as the original author is
% referenced and attributed as such. The original author maintains the right to be solely associated with this work.
% Programmed and Copyright by Yair M. Altman: altmany(at)gmail.com
% $Revision: 1.17 $ $Date: 2016/05/16 17:59:36 $
% Ensure that java awt is enabled...
if ~usejava('awt')
error('YMA:screencapture:NeedAwt','ScreenCapture requires Java to run.');
end
% Ensure that our Java version supports the Robot class (requires JVM 1.3+)
try
robot = java.awt.Robot; %#ok<NASGU>
catch
uiwait(msgbox({['Your Matlab installation is so old that its Java engine (' version('-java') ...
') does not have a java.awt.Robot class. '], ' ', ...
'Without this class, taking a screen-capture is impossible.', ' ', ...
'So, either install JVM 1.3 or higher, or use a newer Matlab release.'}, ...
'ScreenCapture', 'warn'));
if nargout, imageData = []; end
return;
end
% Process optional arguments
paramsStruct = processArgs(varargin{:});
% If toolbar button requested, add it and exit
if ~isempty(paramsStruct.toolbar)
% Add the toolbar button
addToolbarButton(paramsStruct);
% Return the figure to its pre-undocked state (when relevant)
redockFigureIfRelevant(paramsStruct);
% Exit immediately (do NOT take a screen-capture)
if nargout, imageData = []; end
return;
end
% Convert position from handle-relative to desktop Java-based pixels
[paramsStruct, msgStr] = convertPos(paramsStruct);
% Capture the requested screen rectangle using java.awt.Robot
imgData = getScreenCaptureImageData(paramsStruct.position);
% Return the figure to its pre-undocked state (when relevant)
redockFigureIfRelevant(paramsStruct);
% Save image data in file or clipboard, if specified
if ~isempty(paramsStruct.target)
if strcmpi(paramsStruct.target,'clipboard')
if ~isempty(imgData)
imclipboard(imgData);
else
msgbox('No image area selected - not copying image to clipboard','ScreenCapture','warn');
end
elseif strncmpi(paramsStruct.target,'print',5) % 'print' or 'printer'
if ~isempty(imgData)
hNewFig = figure('visible','off');
imshow(imgData);
print(hNewFig);
delete(hNewFig);
else
msgbox('No image area selected - not printing screenshot','ScreenCapture','warn');
end
else % real filename
if ~isempty(imgData)
imwrite(imgData,paramsStruct.target);
else
msgbox(['No image area selected - not saving image file ' paramsStruct.target],'ScreenCapture','warn');
end
end
end
% Return image raster data to user, if requested
if nargout
imageData = imgData;
% If neither output formats was specified (neither target nor output data)
elseif isempty(paramsStruct.target) & ~isempty(imgData) %#ok ML6
% Ask the user to specify a file
%error('YMA:screencapture:noOutput','No output specified for ScreenCapture: specify the output filename and/or output data');
%format = '*.*';
formats = imformats;
for idx = 1 : numel(formats)
ext = sprintf('*.%s;',formats(idx).ext{:});
format(idx,1:2) = {ext(1:end-1), formats(idx).description}; %#ok<AGROW>
end
[filename,pathname] = uiputfile(format,'Save screen capture as');
if ~isequal(filename,0) & ~isequal(pathname,0) %#ok Matlab6 compatibility
try
filename = fullfile(pathname,filename);
imwrite(imgData,filename);
catch % possibly a GIF file that requires indexed colors
[imgData,map] = rgb2ind(imgData,256);
imwrite(imgData,map,filename);
end
else
% TODO - copy to clipboard
end
end
% Display msgStr, if relevant
if ~isempty(msgStr)
uiwait(msgbox(msgStr,'ScreenCapture'));
drawnow; pause(0.05); % time for the msgbox to disappear
end
return; % debug breakpoint
%% Process optional arguments
function paramsStruct = processArgs(varargin)
% Get the properties in either direct or P-V format
[regParams, pvPairs] = parseparams(varargin);
% Now process the optional P-V params
try
% Initialize
paramName = [];
paramsStruct = [];
paramsStruct.handle = [];
paramsStruct.position = [];
paramsStruct.target = '';
paramsStruct.toolbar = [];
paramsStruct.wasDocked = 0; % no false available in ML6
paramsStruct.wasInteractive = 0; % no false available in ML6
% Parse the regular (non-named) params in recption order
if ~isempty(regParams) & (isempty(regParams{1}) | ishandle(regParams{1}(1))) %#ok ML6
paramsStruct.handle = regParams{1};
regParams(1) = [];
end
if ~isempty(regParams) & isnumeric(regParams{1}) & (length(regParams{1}) == 4) %#ok ML6
paramsStruct.position = regParams{1};
regParams(1) = [];
end
if ~isempty(regParams) & ischar(regParams{1}) %#ok ML6
paramsStruct.target = regParams{1};
end
% Parse the optional param PV pairs
supportedArgs = {'handle','position','target','toolbar'};
while ~isempty(pvPairs)
% Disregard empty propNames (may be due to users mis-interpretting the syntax help)
while ~isempty(pvPairs) & isempty(pvPairs{1}) %#ok ML6
pvPairs(1) = [];
end
if isempty(pvPairs)
break;
end
% Ensure basic format is valid
paramName = '';
if ~ischar(pvPairs{1})
error('YMA:screencapture:invalidProperty','Invalid property passed to ScreenCapture');
elseif length(pvPairs) == 1
if isempty(paramsStruct.target)
paramsStruct.target = pvPairs{1};
break;
else
error('YMA:screencapture:noPropertyValue',['No value specified for property ''' pvPairs{1} '''']);
end
end
% Process parameter values
paramName = pvPairs{1};
if strcmpi(paramName,'filename') % backward compatibility
paramName = 'target';
end
paramValue = pvPairs{2};
pvPairs(1:2) = [];
idx = find(strncmpi(paramName,supportedArgs,length(paramName)));
if ~isempty(idx)
%paramsStruct.(lower(supportedArgs{idx(1)})) = paramValue; % incompatible with ML6
paramsStruct = setfield(paramsStruct, lower(supportedArgs{idx(1)}), paramValue); %#ok ML6
% If 'toolbar' param specified, then it cannot be left empty - use gcf
if strncmpi(paramName,'toolbar',length(paramName)) & isempty(paramsStruct.toolbar) %#ok ML6
paramsStruct.toolbar = getCurrentFig;
end
elseif isempty(paramsStruct.target)
paramsStruct.target = paramName;
pvPairs = {paramValue, pvPairs{:}}; %#ok (more readable this way, although a bit less efficient...)
else
supportedArgsStr = sprintf('''%s'',',supportedArgs{:});
error('YMA:screencapture:invalidProperty','%s \n%s', ...
'Invalid property passed to ScreenCapture', ...
['Supported property names are: ' supportedArgsStr(1:end-1)]);
end
end % loop pvPairs
catch
if ~isempty(paramName), paramName = [' ''' paramName '''']; end
error('YMA:screencapture:invalidProperty','Error setting ScreenCapture property %s:\n%s',paramName,lasterr); %#ok<LERR>
end
%end % processArgs
%% Convert position from handle-relative to desktop Java-based pixels
function [paramsStruct, msgStr] = convertPos(paramsStruct)
msgStr = '';
try
% Get the screen-size for later use
screenSize = get(0,'ScreenSize');
% Get the containing figure's handle
hParent = paramsStruct.handle;
if isempty(paramsStruct.handle)
paramsStruct.hFigure = getCurrentFig;
hParent = paramsStruct.hFigure;
else
paramsStruct.hFigure = ancestor(paramsStruct.handle,'figure');
end
% To get the acurate pixel position, the figure window must be undocked
try
if strcmpi(get(paramsStruct.hFigure,'WindowStyle'),'docked')
set(paramsStruct.hFigure,'WindowStyle','normal');
drawnow; pause(0.25);
paramsStruct.wasDocked = 1; % no true available in ML6
end
catch
% never mind - ignore...
end
% The figure (if specified) must be in focus
if ~isempty(paramsStruct.hFigure) & ishandle(paramsStruct.hFigure) %#ok ML6
isFigureValid = 1; % no true available in ML6
figure(paramsStruct.hFigure);
else
isFigureValid = 0; % no false available in ML6
end
% Flush all graphic events to ensure correct rendering
drawnow; pause(0.01);
% No handle specified
wasPositionGiven = 1; % no true available in ML6
if isempty(paramsStruct.handle)
% Set default handle, if not supplied
paramsStruct.handle = paramsStruct.hFigure;
% If position was not specified, get it interactively using RBBOX
if isempty(paramsStruct.position)
[paramsStruct.position, jFrameUsed, msgStr] = getInteractivePosition(paramsStruct.hFigure); %#ok<ASGLU> jFrameUsed is unused
paramsStruct.wasInteractive = 1; % no true available in ML6
wasPositionGiven = 0; % no false available in ML6
end
elseif ~ishandle(paramsStruct.handle)
% Handle was supplied - ensure it is a valid handle
error('YMA:screencapture:invalidHandle','Invalid handle passed to ScreenCapture');
elseif isempty(paramsStruct.position)
% Handle was supplied but position was not, so use the handle's position
paramsStruct.position = getPixelPos(paramsStruct.handle);
paramsStruct.position(1:2) = 0;
wasPositionGiven = 0; % no false available in ML6
elseif ~isnumeric(paramsStruct.position) | (length(paramsStruct.position) ~= 4) %#ok ML6
% Both handle & position were supplied - ensure a valid pixel position vector
error('YMA:screencapture:invalidPosition','Invalid position vector passed to ScreenCapture: \nMust be a [x,y,w,h] numeric pixel array');
end
% Capture current object (uicontrol/axes/figure) if w=h=0 (single-click in interactive mode)
if paramsStruct.position(3)<=0 | paramsStruct.position(4)<=0 %#ok ML6
%TODO - find a way to single-click another Matlab figure (the following does not work)
%paramsStruct.position = getPixelPos(ancestor(hittest,'figure'));
paramsStruct.position = getPixelPos(paramsStruct.handle);
paramsStruct.position(1:2) = 0;
paramsStruct.wasInteractive = 0; % no false available in ML6
wasPositionGiven = 0; % no false available in ML6
end
% First get the parent handle's desktop-based Matlab pixel position
parentPos = [0,0,0,0];
dX = 0;
dY = 0;
dW = 0;
dH = 0;
if ~isFigure(hParent)
% Get the reguested component's pixel position
parentPos = getPixelPos(hParent, 1); % no true available in ML6
% Axes position inaccuracy estimation
deltaX = 3;
deltaY = -1;
% Fix for images
if isImage(hParent) % | (isAxes(hParent) & strcmpi(get(hParent,'YDir'),'reverse')) %#ok ML6
% Compensate for resized image axes
hAxes = get(hParent,'Parent');
if all(get(hAxes,'DataAspectRatio')==1) % sanity check: this is the normal behavior
% Note 18/4/2013: the following fails for non-square images
%actualImgSize = min(parentPos(3:4));
%dX = (parentPos(3) - actualImgSize) / 2;
%dY = (parentPos(4) - actualImgSize) / 2;
%parentPos(3:4) = actualImgSize;
% The following should work for all types of images
actualImgSize = size(get(hParent,'CData'));
dX = (parentPos(3) - min(parentPos(3),actualImgSize(2))) / 2;
dY = (parentPos(4) - min(parentPos(4),actualImgSize(1))) / 2;
parentPos(3:4) = actualImgSize([2,1]);
%parentPos(3) = max(parentPos(3),actualImgSize(2));
%parentPos(4) = max(parentPos(4),actualImgSize(1));
end
% Fix user-specified img positions (but not auto-inferred ones)
if wasPositionGiven
% In images, use data units rather than pixel units
% Reverse the YDir
ymax = max(get(hParent,'YData'));
paramsStruct.position(2) = ymax - paramsStruct.position(2) - paramsStruct.position(4);
% Note: it would be best to use hgconvertunits, but:
% ^^^^ (1) it fails on Matlab 6, and (2) it doesn't accept Data units
%paramsStruct.position = hgconvertunits(hFig, paramsStruct.position, 'Data', 'pixel', hParent); % fails!
xLims = get(hParent,'XData');
yLims = get(hParent,'YData');
xPixelsPerData = parentPos(3) / (diff(xLims) + 1);
yPixelsPerData = parentPos(4) / (diff(yLims) + 1);
paramsStruct.position(1) = round((paramsStruct.position(1)-xLims(1)) * xPixelsPerData);
paramsStruct.position(2) = round((paramsStruct.position(2)-yLims(1)) * yPixelsPerData + 2*dY);
paramsStruct.position(3) = round( paramsStruct.position(3) * xPixelsPerData);
paramsStruct.position(4) = round( paramsStruct.position(4) * yPixelsPerData);
% Axes position inaccuracy estimation
if strcmpi(computer('arch'),'win64')
deltaX = 7;
deltaY = -7;
else
deltaX = 3;
deltaY = -3;
end
else % axes/image position was auto-infered (entire image)
% Axes position inaccuracy estimation
if strcmpi(computer('arch'),'win64')
deltaX = 6;
deltaY = -6;
else
deltaX = 2;
deltaY = -2;
end
dW = -2*dX;
dH = -2*dY;
end
end
%hFig = ancestor(hParent,'figure');
hParent = paramsStruct.hFigure;
elseif paramsStruct.wasInteractive % interactive figure rectangle
% Compensate for 1px rbbox inaccuracies
deltaX = 2;
deltaY = -2;
else % non-interactive figure
% Compensate 4px figure boundaries = difference betweeen OuterPosition and Position
deltaX = -1;
deltaY = 1;
end
%disp(paramsStruct.position) % for debugging
% Now get the pixel position relative to the monitor
figurePos = getPixelPos(hParent);
desktopPos = figurePos + parentPos;
% Now convert to Java-based pixels based on screen size
% Note: multiple monitors are automatically handled correctly, since all
% ^^^^ Java positions are relative to the main monitor's top-left corner
javaX = desktopPos(1) + paramsStruct.position(1) + deltaX + dX;
javaY = screenSize(4) - desktopPos(2) - paramsStruct.position(2) - paramsStruct.position(4) + deltaY + dY;
width = paramsStruct.position(3) + dW;
height = paramsStruct.position(4) + dH;
paramsStruct.position = round([javaX, javaY, width, height]);
%paramsStruct.position
% Ensure the figure is at the front so it can be screen-captured
if isFigureValid
figure(hParent);
drawnow;
pause(0.02);
end
catch
% Maybe root/desktop handle (root does not have a 'Position' prop so getPixelPos croaks
if isequal(double(hParent),0) % =root/desktop handle; handles case of hParent=[]
javaX = paramsStruct.position(1) - 1;
javaY = screenSize(4) - paramsStruct.position(2) - paramsStruct.position(4) - 1;
paramsStruct.position = [javaX, javaY, paramsStruct.position(3:4)];
end
end
%end % convertPos
%% Interactively get the requested capture rectangle
function [positionRect, jFrameUsed, msgStr] = getInteractivePosition(hFig)
msgStr = '';
try
% First try the invisible-figure approach, in order to
% enable rbbox outside any existing figure boundaries
f = figure('units','pixel','pos',[-100,-100,10,10],'HitTest','off');
drawnow; pause(0.01);
oldWarn = warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
jf = get(handle(f),'JavaFrame');
warning(oldWarn);
try
jWindow = jf.fFigureClient.getWindow;
catch
try
jWindow = jf.fHG1Client.getWindow;
catch
jWindow = jf.getFigurePanelContainer.getParent.getTopLevelAncestor;
end
end
com.sun.awt.AWTUtilities.setWindowOpacity(jWindow,0.05); %=nearly transparent (not fully so that mouse clicks are captured)
jWindow.setMaximized(1); % no true available in ML6
jFrameUsed = 1; % no true available in ML6
msg = {'Mouse-click and drag a bounding rectangle for screen-capture ' ...
... %'or single-click any Matlab figure to capture the entire figure.' ...
};
catch
% Something failed, so revert to a simple rbbox on a visible figure
try delete(f); drawnow; catch, end %Cleanup...
jFrameUsed = 0; % no false available in ML6
msg = {'Mouse-click within any Matlab figure and then', ...
'drag a bounding rectangle for screen-capture,', ...
'or single-click to capture the entire figure'};
end
uiwait(msgbox(msg,'ScreenCapture'));
k = waitforbuttonpress; %#ok k is unused
%hFig = getCurrentFig;
%p1 = get(hFig,'CurrentPoint');
positionRect = rbbox;
%p2 = get(hFig,'CurrentPoint');
if jFrameUsed
jFrameOrigin = getPixelPos(f);
delete(f); drawnow;
try
figOrigin = getPixelPos(hFig);
catch % empty/invalid hFig handle
figOrigin = [0,0,0,0];
end
else
if isempty(hFig)
jFrameOrigin = getPixelPos(gcf);
else
jFrameOrigin = [0,0,0,0];
end
figOrigin = [0,0,0,0];
end
positionRect(1:2) = positionRect(1:2) + jFrameOrigin(1:2) - figOrigin(1:2);
if prod(positionRect(3:4)) > 0
msgStr = sprintf('%dx%d area captured',positionRect(3),positionRect(4));
end
%end % getInteractivePosition
%% Get current figure (even if its handle is hidden)
function hFig = getCurrentFig
oldState = get(0,'showHiddenHandles');
set(0,'showHiddenHandles','on');
hFig = get(0,'CurrentFigure');
set(0,'showHiddenHandles',oldState);
%end % getCurrentFig
%% Get ancestor figure - used for old Matlab versions that don't have a built-in ancestor()
function hObj = ancestor(hObj,type)
if ~isempty(hObj) & ishandle(hObj) %#ok for Matlab 6 compatibility
try
hObj = get(hObj,'Ancestor');
catch
% never mind...
end
try
%if ~isa(handle(hObj),type) % this is best but always returns 0 in Matlab 6!
%if ~isprop(hObj,'type') | ~strcmpi(get(hObj,'type'),type) % no isprop() in ML6!
try
objType = get(hObj,'type');
catch
objType = '';
end
if ~strcmpi(objType,type)
try
parent = get(handle(hObj),'parent');
catch
parent = hObj.getParent; % some objs have no 'Parent' prop, just this method...
end
if ~isempty(parent) % empty parent means root ancestor, so exit
hObj = ancestor(parent,type);
end
end
catch
% never mind...
end
end
%end % ancestor
%% Get position of an HG object in specified units
function pos = getPos(hObj,field,units)
% Matlab 6 did not have hgconvertunits so use the old way...
oldUnits = get(hObj,'units');
if strcmpi(oldUnits,units) % don't modify units unless we must!
pos = get(hObj,field);
else
set(hObj,'units',units);
pos = get(hObj,field);
set(hObj,'units',oldUnits);
end
%end % getPos
%% Get pixel position of an HG object - for Matlab 6 compatibility
function pos = getPixelPos(hObj,varargin)
persistent originalObj
try
stk = dbstack;
if ~strcmp(stk(2).name,'getPixelPos')
originalObj = hObj;
end
if isFigure(hObj) %| isAxes(hObj)
%try
pos = getPos(hObj,'OuterPosition','pixels');
else %catch
% getpixelposition is unvectorized unfortunately!
pos = getpixelposition(hObj,varargin{:});
% add the axes labels/ticks if relevant (plus a tiny margin to fix 2px label/title inconsistencies)
if isAxes(hObj) & ~isImage(originalObj) %#ok ML6
tightInsets = getPos(hObj,'TightInset','pixel');
pos = pos + tightInsets.*[-1,-1,1,1] + [-1,1,1+tightInsets(1:2)];
end
end
catch
try
% Matlab 6 did not have getpixelposition nor hgconvertunits so use the old way...
pos = getPos(hObj,'Position','pixels');
catch
% Maybe the handle does not have a 'Position' prop (e.g., text/line/plot) - use its parent
pos = getPixelPos(get(hObj,'parent'),varargin{:});
end
end
% Handle the case of missing/invalid/empty HG handle
if isempty(pos)
pos = [0,0,0,0];
end
%end % getPixelPos
%% Adds a ScreenCapture toolbar button
function addToolbarButton(paramsStruct)
% Ensure we have a valid toolbar handle
hFig = ancestor(paramsStruct.toolbar,'figure');
if isempty(hFig)
error('YMA:screencapture:badToolbar','the ''Toolbar'' parameter must contain a valid GUI handle');
end
set(hFig,'ToolBar','figure');
hToolbar = findall(hFig,'type','uitoolbar');
if isempty(hToolbar)
error('YMA:screencapture:noToolbar','the ''Toolbar'' parameter must contain a figure handle possessing a valid toolbar');
end
hToolbar = hToolbar(1); % just in case there are several toolbars... - use only the first
% Prepare the camera icon
icon = ['3333333333333333'; ...
'3333333333333333'; ...
'3333300000333333'; ...
'3333065556033333'; ...
'3000000000000033'; ...
'3022222222222033'; ...
'3022220002222033'; ...
'3022203110222033'; ...
'3022201110222033'; ...
'3022204440222033'; ...
'3022220002222033'; ...
'3022222222222033'; ...
'3000000000000033'; ...
'3333333333333333'; ...
'3333333333333333'; ...
'3333333333333333'];
cm = [ 0 0 0; ... % black
0 0.60 1; ... % light blue
0.53 0.53 0.53; ... % light gray
NaN NaN NaN; ... % transparent
0 0.73 0; ... % light green
0.27 0.27 0.27; ... % gray
0.13 0.13 0.13]; % dark gray
cdata = ind2rgb(uint8(icon-'0'),cm);
% If the button does not already exit
hButton = findall(hToolbar,'Tag','ScreenCaptureButton');
tooltip = 'Screen capture';
if ~isempty(paramsStruct.target)
tooltip = [tooltip ' to ' paramsStruct.target];
end
if isempty(hButton)
% Add the button with the icon to the figure's toolbar
hButton = uipushtool(hToolbar, 'CData',cdata, 'Tag','ScreenCaptureButton', 'TooltipString',tooltip, 'ClickedCallback',['screencapture(''' paramsStruct.target ''')']); %#ok unused
else
% Otherwise, simply update the existing button
set(hButton, 'CData',cdata, 'Tag','ScreenCaptureButton', 'TooltipString',tooltip, 'ClickedCallback',['screencapture(''' paramsStruct.target ''')']);
end
%end % addToolbarButton
%% Java-get the actual screen-capture image data
function imgData = getScreenCaptureImageData(positionRect)
if isempty(positionRect) | all(positionRect==0) | positionRect(3)<=0 | positionRect(4)<=0 %#ok ML6
imgData = [];
else
% Use java.awt.Robot to take a screen-capture of the specified screen area
rect = java.awt.Rectangle(positionRect(1), positionRect(2), positionRect(3), positionRect(4));
robot = java.awt.Robot;
jImage = robot.createScreenCapture(rect);
% Convert the resulting Java image to a Matlab image
% Adapted for a much-improved performance from:
% http://www.mathworks.com/support/solutions/data/1-2WPAYR.html
h = jImage.getHeight;
w = jImage.getWidth;
%imgData = zeros([h,w,3],'uint8');
%pixelsData = uint8(jImage.getData.getPixels(0,0,w,h,[]));
%for i = 1 : h
% base = (i-1)*w*3+1;
% imgData(i,1:w,:) = deal(reshape(pixelsData(base:(base+3*w-1)),3,w)');
%end
% Performance further improved based on feedback from Urs Schwartz:
%pixelsData = reshape(typecast(jImage.getData.getDataStorage,'uint32'),w,h).';
%imgData(:,:,3) = bitshift(bitand(pixelsData,256^1-1),-8*0);
%imgData(:,:,2) = bitshift(bitand(pixelsData,256^2-1),-8*1);
%imgData(:,:,1) = bitshift(bitand(pixelsData,256^3-1),-8*2);
% Performance even further improved based on feedback from Jan Simon:
pixelsData = reshape(typecast(jImage.getData.getDataStorage, 'uint8'), 4, w, h);
imgData = cat(3, ...
transpose(reshape(pixelsData(3, :, :), w, h)), ...
transpose(reshape(pixelsData(2, :, :), w, h)), ...
transpose(reshape(pixelsData(1, :, :), w, h)));
end
%end % getInteractivePosition
%% Return the figure to its pre-undocked state (when relevant)
function redockFigureIfRelevant(paramsStruct)
if paramsStruct.wasDocked
try
set(paramsStruct.hFigure,'WindowStyle','docked');
%drawnow;
catch
% never mind - ignore...
end
end
%end % redockFigureIfRelevant
%% Copy screen-capture to the system clipboard
% Adapted from http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard/content/imclipboard.m
function imclipboard(imgData)
% Import necessary Java classes
import java.awt.Toolkit.*
import java.awt.image.BufferedImage
import java.awt.datatransfer.DataFlavor
% Add the necessary Java class (ImageSelection) to the Java classpath
if ~exist('ImageSelection', 'class')
% Obtain the directory of the executable (or of the M-file if not deployed)
%javaaddpath(fileparts(which(mfilename)), '-end');
if isdeployed % Stand-alone mode.
[status, result] = system('path'); %#ok<ASGLU>
MatLabFilePath = char(regexpi(result, 'Path=(.*?);', 'tokens', 'once'));
else % MATLAB mode.
MatLabFilePath = fileparts(mfilename('fullpath'));
end
javaaddpath(MatLabFilePath, '-end');
end
% Get System Clipboard object (java.awt.Toolkit)
cb = getDefaultToolkit.getSystemClipboard; % can't use () in ML6!
% Get image size
ht = size(imgData, 1);
wd = size(imgData, 2);
% Convert to Blue-Green-Red format
imgData = imgData(:, :, [3 2 1]);
% Convert to 3xWxH format
imgData = permute(imgData, [3, 2, 1]);
% Append Alpha data (not used)
imgData = cat(1, imgData, 255*ones(1, wd, ht, 'uint8'));
% Create image buffer
imBuffer = BufferedImage(wd, ht, BufferedImage.TYPE_INT_RGB);
imBuffer.setRGB(0, 0, wd, ht, typecast(imgData(:), 'int32'), 0, wd);
% Create ImageSelection object
% % custom java class
imSelection = ImageSelection(imBuffer);
% Set clipboard content to the image
cb.setContents(imSelection, []);
%end %imclipboard
%% Is the provided handle a figure?
function flag = isFigure(hObj)
flag = isa(handle(hObj),'figure') | isa(hObj,'matlab.ui.Figure');
%end %isFigure
%% Is the provided handle an axes?
function flag = isAxes(hObj)
flag = isa(handle(hObj),'axes') | isa(hObj,'matlab.graphics.axis.Axes');
%end %isFigure
%% Is the provided handle an image?
function flag = isImage(hObj)
flag = isa(handle(hObj),'image') | isa(hObj,'matlab.graphics.primitive.Image');
%end %isFigure
%%%%%%%%%%%%%%%%%%%%%%%%%% TODO %%%%%%%%%%%%%%%%%%%%%%%%%
% find a way in interactive-mode to single-click another Matlab figure for screen-capture
|
github
|
philippboehmsturm/antx-master
|
demo_WindowAPI.m
|
.m
|
antx-master/mritools/others/windowapi/demo_WindowAPI.m
| 7,664 |
utf_8
|
4521f3e55d6634de6a8e4bf7fa63ced1
|
function demo_WindowAPI
% Demo for WindowAPI
% The function WindowAPI has grown to an universal super tool. Unfortunately
% this reduces the readability of the help section. Therefore I've created this
% function to demonstrate the usage of all features.
%
% Author: Jan Simon, Heidelberg, (C) 2008-2016 matlab.THISYEAR(a)nMINUSsimon.de
% $JRev: R-g V:006 Sum:t/JmEwfh8W4x Date:09-Oct-2011 02:42:27 $
% $License: BSD (use/copy/change/redistribute on own risk, mention the author) $
% $File: Tools\UnitTests_\demo_WindowAPI.m $
% Initialize: ==================================================================
delay = 1.0; % Seconds between effects
% Do the work: =================================================================
fprintf('== %s:\n', mfilename);
% Search the compiled C-Mex file:
clear('WindowAPI');
MexVersion = WindowAPI();
whichWindowAPI = which(MexVersion);
if isempty(whichWindowAPI)
error(['JSimon:', mfilename, ':MissingMex'], ...
['*** %s: WindowAPI.mex is not found in the path.\n', ...
' Try to compile it again.'], mfilename);
end
fprintf('Using: %s\n\n', whichWindowAPI);
try
% Create a figure to operate on: --------------------------------------------
% The OpenGL renderer is confused by the alpha blending, so Painters is used:
disp(' Create a figure:');
FigH = figure('Color', ones(1, 3), 'Renderer', 'Painters');
FigPos = get(FigH, 'Position');
axes('Visible', 'off', 'Units', 'normalized', 'Position', [0, 0, 1, 1]);
TextH = text(0.5, 0.5, ' Demo: WindowAPI ', ...
'Units', 'normalized', ...
'FontSize', 20, ...
'HorizontalAlignment', 'center', ...
'BackgroundColor', [0.4, 0.9, 0.0], ...
'Margin', 12);
% Move figure to 2nd monitor - on a single monitor setup this request should
% be ignored silently:
disp(' Try to move figure to 2nd monitor, if existing:');
pause(delay);
WindowAPI(FigH, 'Position', FigPos, 2);
WindowAPI(FigH, 'ToMonitor'); % If 2nd monitor has different size
pause(delay);
% Get info about current monitor:
disp(' Get info of monitor of the figure:');
Info = WindowAPI(FigH, 'Monitor');
disp(Info);
pause(delay);
% Set topmost status:
disp(' Set figure to topmost, no topmost and to front:');
WindowAPI(FigH, 'topmost'); % Command is not case-sensitive
drawnow;
WindowAPI(FigH, 'TopMost', 0);
drawnow;
WindowAPI(FigH, 'front');
drawnow;
% Nicer to have the figure on topmost for the rest of the demo:
WindowAPI(FigH, 'topmost');
% Minimize, maximize:
disp(' Minimize, maximize, restore former size, get current status:');
WindowAPI(FigH, 'minimize');
disp([' ', WindowAPI(FigH, 'GetStatus')]);
pause(delay);
WindowAPI(FigH, 'restore');
disp([' ', WindowAPI(FigH, 'GetStatus')]);
pause(delay);
WindowAPI(FigH, 'maximize');
disp([' ', WindowAPI(FigH, 'GetStatus')]);
pause(delay);
WindowAPI(FigH, 'restore');
pause(delay);
% Get the position:
disp(' Get window position relative to nearest monitor:');
Location = WindowAPI(FigH, 'Position');
disp(Location);
pause(delay);
% Partial maximizing:
disp(' Maximize horizontally or vertically only:');
WindowAPI(FigH, 'xmax');
pause(delay);
WindowAPI(FigH, 'Position', Location.Position, Location.MonitorIndex);
pause(delay);
WindowAPI(FigH, 'ymax');
pause(delay);
disp(' Move back to 1st monitor:');
WindowAPI(FigH, 'Position', Location.Position, 1);
WindowAPI(FigH, 'ToMonitor');
pause(delay);
% Special maximizing such that the inner figure fill the screen:
disp(' Maximize inner figure position to work size:');
disp(' (Taskbar and sidebar are not concealed...)');
WindowAPI(FigH, 'Position', 'work');
pause(delay);
disp(' Maximize inner figure position to full monitor:');
WindowAPI(FigH, 'Position', 'full'); % Complete monitor
pause(delay);
% Maximize the outer position, which is similar to the standard maximization:
disp(' Maximize the outer position of the figure:');
disp(' (The window title and menu bar is visible)');
WindowAPI(FigH, 'OuterPosition', 'work');
pause(delay);
WindowAPI(FigH, 'OuterPosition', 'full'); % Complete monitor
pause(delay);
% Move to screen and test using the HWnd handle:
disp(' Move back to visible area automatically:');
disp(' (OS Window handle "HWnd" is used, not working for inner position!)');
HWnd = WindowAPI(FigH, 'GetHWnd');
WindowAPI(HWnd, 'OuterPosition', [-100, -100, FigPos(3:4)]);
pause(delay);
WindowAPI(HWnd, 'ToMonitor');
pause(delay);
% Short flashing:
disp(' A short flash of the window border:');
WindowAPI(FigH, 'Flash');
% Disable the figure:
disp(' Disable the figure - no user intection possible:');
WindowAPI(FigH, 'Enable', 0);
pause(delay);
WindowAPI(FigH, 'Enable', 1);
disp(' Hide the buttons:');
WindowAPI(FigH, 'Button', false);
pause(delay);
WindowAPI(FigH, 'Button', true);
% If a UICONTROL is activated, the figure does *not* gain the focus back by
% the command "figure(FigH)" in Matlab 5.3 to 2009a (or higher) - in contrary
% to the documentation!
disp(' Set the keyboard focus:');
disp(' (The Matlab command "figure(FigH)" is not relialble)');
WindowAPI(FigH, 'SetFocus');
% Alpha blending and stencil color:
disp(' Semi-transparent sphere without visible figure');
% Painters or ZBuffer as renderer! OpenGL draws black figures sometimes.
AxesH = axes('Units', 'pixels', 'Position', FigPos);
sphere;
set(AxesH, 'Visible', 'off', 'CameraViewAngle', 30);
WindowAPI(FigH, 'Position', 'work');
WindowAPI(FigH, 'Clip'); % No border on neighboring monitors
WindowAPI(FigH, 'topmost');
% NOTE: depending on the graphics hardware not all RGB values are working,
% because the pixel colors can be sampled to 555 or 565 bits, especially on
% laptops. At least 0, and 255 are always regonized, so prefer [255,255,0] or
% similar colors:
StencilRGB = [255, 255, 255];
WindowAPI(FigH, 'Alpha', 0.2, StencilRGB);
for angle = 40:-2:5
set(AxesH, 'CameraViewAngle', angle);
drawnow;
end
disp(' Release the memory used for alpha-blending (important!):');
WindowAPI(FigH, 'Opaque');
delete(AxesH);
% Clip visible region:
disp(' Clip window border ("splash screen"):');
WindowAPI(FigH, 'Position', FigPos);
WindowAPI(FigH, 'Clip');
pause(delay);
disp(' Clip specified rectangle:');
set(TextH, 'Units', 'pixels', 'ButtonDownFcn', @cleanup, ...
'String', ' Click to escape! ', ...
'Margin', 10, ...
'EdgeColor', [0.2, 0.7, 0.0], ...
'LineWidth', 2);
pos = round(get(TextH, 'Extent')) + [-12, -11, 22, 22];
WindowAPI(FigH, 'Clip', pos);
% Lock mouse position:
WindowAPI(FigH, 'LockCursor', pos);
fprintf('\n ready. CLICK ON THE BOX TO DELETE IT!\n\n');
catch
fprintf('\n%s crashed: %s\n\n', mfilename, lasterr);
WindowAPI('UnlockCursor');
delete(FigH);
end
% return;
% ******************************************************************************
function cleanup(ObjH, EventData) %#ok<INUSD>
% Smooth fading.
FigH = ancestor(ObjH, 'figure');
% Unlock the cursor:
WindowAPI(FigH, 'LockCursor', 0);
% or: WindowAPI(FigH, 'LockCursor');
% or: WindowAPI('UnlockCursor');
% Fade out:
for alpha = linspace(1, 0, 20)
WindowAPI(FigH, 'Alpha', alpha);
pause(0.03);
end
delete(gcbf);
fprintf('%s: Goodbye\n', mfilename);
% return;
|
github
|
philippboehmsturm/antx-master
|
spm_uitab.m
|
.m
|
antx-master/xspm8/spm_uitab.m
| 7,695 |
utf_8
|
e80b69279b276644a59f0e838bc07817
|
function [handles] = spm_uitab(hparent,labels,callbacks,...
tag,active,height,tab_height)
% Create tabs in the SPM Graphics window
% FORMAT [handles] = spm_uitab(hfig,labels,callbacks,...
% tag,active,height,tab_height)
% This functiuon creates tabs in the SPM graphics window.
% These tabs may be associated with different sets of axes and uicontrol,
% through the use of callback functions linked to the tabs.
% IN:
% - hparent: the handle of the parent of the tabs (can be the SPM graphics
% windows, or the handle of the uipanel of a former spm_uitab...)
% - labels: a cell array of string containing the labels of the tabs
% - callbacks: a cell array of strings which will be evaluated using the
% 'eval' function when clicking on a tab
% - tag: a string which is the tags associated with the tabs (useful for
% finding them in a window...)
% - active: the index of the active tab when creating the uitabs (default
% = 1, ie the first tab is active)
% - height: the relative height of the tab panels within its parent
% spatial extent (default = 1)
% - tab_height: the relative height of the tabs within its parent spatial
% extent (default = 1)
% OUT:
% - handles: a structure of handles for the differents tab objects.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_uitab.m 3062 2009-04-17 14:07:40Z jean $
Ntabs = length(labels);
if ~exist('callbacks','var') || isempty(callbacks)
for i=1:Ntabs
callbacks{i} = [];
end
end
if ~exist('tag','var') || isempty(tag)
tag = '';
end
if ~exist('active','var') || isempty(active)
active = 1;
end
if ~exist('height','var') || isempty(height)
height = 1;
end
if ~exist('tab_height','var') || isempty(tab_height)
tab_height = 0.025;
end
if ~isequal(get(hparent,'type'),'figure')
set(hparent,'units','normalized')
POS = get(hparent,'position');
pos1 = [POS(1)+0.02,POS(2)+0.01,POS(3)-0.04,POS(4)-(tab_height+0.035)];
dx = 0.1*(POS(3)-0.04)./0.98;
dx2 = [0.04,0.93]*(POS(3)-0.04)./0.98;
else
pos1 = [0.01 0.005 0.98 1-(tab_height+0.01)];
dx = 0.1;
dx2 = [0.04,0.93];
end
pos1(4) = pos1(4).*height;
COLOR = 0.95*[1 1 1];
handles.hp = uipanel(...
'parent',hparent,...
'position',pos1,...
'BorderType','beveledout',...
'BackgroundColor',COLOR,...
'tag',tag);
set(handles.hp,'units','normalized');
xl = pos1(1);
yu = pos1(2) +pos1(4);
ddx = 0.0025;
ddy = 0.005;
dy = tab_height;
if Ntabs > 9
handles.hs(1) = uicontrol(...
'parent',hparent,...'enable','off',...
'style','pushbutton',...
'units','normalized','position',[xl yu dx2(1) dy],...
'SelectionHighlight','off',...
'BackgroundColor',COLOR,...
'callback',@doScroll,...
'value',0,'min',0,'max',Ntabs-9,...
'string','<',...
'tag',tag,...
'BusyAction','cancel',...
'Interruptible','off');
handles.hs(2) = uicontrol(...
'parent',hparent,...
'style','pushbutton',...
'units','normalized','position',[xl+dx2(2) yu 0.05 dy],...
'SelectionHighlight','off',...
'BackgroundColor',COLOR,...
'callback',@doScroll,...
'value',1,'min',1,'max',Ntabs-9,...
'string','>',...
'tag',tag,...
'BusyAction','cancel',...
'Interruptible','off');
set(handles.hs,'units','normalized')
xl = xl + dx2(1);
end
for i =1:min([Ntabs,9])
pos = [xl+dx*(i-1) yu dx dy];
handles.htab(i) = uicontrol(...
'parent',hparent,...
'style','pushbutton',...
'units','normalized','position',pos,...
'SelectionHighlight','off',...
'string',labels{i},...
'BackgroundColor',COLOR,...
'tag',tag);
set(handles.htab(i),'units','normalized')
pos = [xl+dx*(i-1)+ddx yu-ddy dx-2*ddx 2*ddy];
handles.hh(i) = uicontrol(...
'parent',hparent,...
'style','text',...
'units','normalized','position',pos,...
'BackgroundColor',COLOR,...
'tag',tag);
set(handles.hh(i),'units','normalized')
end
try
set(handles.hh(active),'visible','on')
catch
active = 1;
set(handles.hh(active),'visible','on')
end
others = setdiff(1:min([Ntabs,9]),active);
set(handles.htab(active),...
'FontWeight','bold');
set(handles.hh(others),'visible','off');
set(handles.htab(others),...
'ForegroundColor',0.25*[1 1 1]);
ud.handles = handles;
ud.Ntabs = Ntabs;
for i =1:min([Ntabs,9])
ud.ind = i;
ud.callback = callbacks{i};
set(handles.htab(i),'callback',@doChoose,'userdata',ud,...
'BusyAction','cancel',...
'Interruptible','off');
if i > 9
set(handles.htab(i),'visible','off');
end
end
if Ntabs > 9
UD.in = [1:9];
UD.Ntabs = Ntabs;
UD.h = handles;
UD.active = active;
UD.who = -1;
UD.callbacks = callbacks;
UD.labels = labels;
set(handles.hs(1),'userdata',UD,'enable','off');
UD.who = 1;
set(handles.hs(2),'userdata',UD);
end
%==========================================================================
% doChoose
%==========================================================================
function doChoose(o1,o2)
ud = get(o1,'userdata');
% Do nothing if called tab is current (active) tab
if ~strcmp(get(ud.handles.htab(ud.ind),'FontWeight'),'bold')
spm('pointer','watch');
set(ud.handles.hh(ud.ind),'visible','on');
set(ud.handles.htab(ud.ind),...
'ForegroundColor',0*[1 1 1],...
'FontWeight','bold');
others = setdiff(1:length(ud.handles.hh),ud.ind);
set(ud.handles.hh(others),'visible','off');
set(ud.handles.htab(others),...
'ForegroundColor',0.25*[1 1 1],...
'FontWeight','normal');
if ud.Ntabs >9
UD = get(ud.handles.hs(1),'userdata');
UD.active = UD.in(ud.ind);
UD.who = -1;
set(ud.handles.hs(1),'userdata',UD);
UD.who = 1;
set(ud.handles.hs(2),'userdata',UD);
end
drawnow
if ~isempty(ud.callback)
if isa(ud.callback, 'function_handle')
feval(ud.callback);
else
eval(ud.callback);
end
end
drawnow
spm('pointer','arrow');
end
%==========================================================================
% doScroll
%==========================================================================
function doScroll(o1,o2)
ud = get(o1,'userdata');
% active = ud.in(ud.active);
ud.in = ud.in + ud.who;
if min(ud.in) ==1
set(ud.h.hs(1),'enable','off');
set(ud.h.hs(2),'enable','on');
elseif max(ud.in) ==ud.Ntabs
set(ud.h.hs(1),'enable','on');
set(ud.h.hs(2),'enable','off');
else
set(ud.h.hs,'enable','on');
end
UD.handles = ud.h;
UD.Ntabs = ud.Ntabs;
for i = 1:length(ud.in)
UD.ind = i;
UD.callback = ud.callbacks{ud.in(i)};
set(ud.h.htab(i),'userdata',UD,...
'string',ud.labels{ud.in(i)});
if ismember(ud.active,ud.in)
ind = find(ud.in==ud.active);
set(ud.h.hh(ind),'visible','on');
set(ud.h.htab(ind),...
'ForegroundColor',0*[1 1 1],...
'FontWeight','bold');
others = setdiff(1:9,ind);
set(ud.h.hh(others),'visible','off');
set(ud.h.htab(others),...
'ForegroundColor',0.25*[1 1 1],...
'FontWeight','normal');
else
others = 1:9;
set(ud.h.hh(others),'visible','off');
set(ud.h.htab(others),...
'ForegroundColor',0.25*[1 1 1],...
'FontWeight','normal');
end
end
ud.who = -1;
set(ud.h.hs(1),'userdata',ud)
ud.who = 1;
set(ud.h.hs(2),'userdata',ud)
|
github
|
philippboehmsturm/antx-master
|
spm_vb_ppm_anova.m
|
.m
|
antx-master/xspm8/spm_vb_ppm_anova.m
| 3,873 |
utf_8
|
5360b2f4d1d7fe1f61c455b53a468fd5
|
function spm_vb_ppm_anova(SPM)
% Bayesian ANOVA using model comparison
% FORMAT spm_vb_ppm_anova(SPM)
%
% SPM - Data structure corresponding to a full model (ie. one
% containing all experimental conditions).
%
% This function creates images of differences in log evidence
% which characterise the average effect, main effects and interactions
% in a factorial design.
%
% The factorial design is specified in SPM.factor. For a one-way ANOVA
% the images
%
% avg_effect.img
% main_effect.img
%
% are produced. For a two-way ANOVA the following images are produced
%
% avg_effect.img
% main_effect_'factor1'.img
% main_effect_'factor2'.img
% interaction.img
%
% These images can then be thresholded. For example a threshold of 4.6
% corresponds to a posterior effect probability of [exp(4.6)] = 0.999.
% See paper VB4 for more details.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Will Penny
% $Id: spm_vb_ppm_anova.m 1143 2008-02-07 19:33:33Z spm $
disp('Warning: spm_vb_ppm_anova only works for single session data.');
model = spm_vb_models(SPM,SPM.factor);
analysis_dir = pwd;
for m=1:length(model)-1,
model_subdir = ['model_',int2str(m)];
mkdir(analysis_dir,model_subdir);
SPM.swd = fullfile(analysis_dir,model_subdir);
SPM.Sess(1).U = model(m).U;
SPM.Sess(1).U = spm_get_ons(SPM,1);
SPM = spm_fMRI_design(SPM,0); % 0 = don't save SPM.mat
SPM.PPM.update_F = 1; % Compute evidence for each model
SPM.PPM.compute_det_D = 1;
spm_spm_vb(SPM);
end
% Compute differences in contributions to log-evidence images
% to assess main effects and interactions
nf = length(SPM.factor);
if nf==1
% For a single factor
% Average effect
image1 = fullfile(analysis_dir, 'model_1','LogEv.img');
image2 = fullfile(analysis_dir, 'model_2','LogEv.img');
imout = fullfile(analysis_dir, 'avg_effect.img');
img_subtract(image1,image2,imout);
% Main effect of factor
image1 = fullfile(analysis_dir, 'model_2','LogEv.img');
image2 = fullfile(analysis_dir, 'LogEv.img');
imout = fullfile(analysis_dir, 'main_effect.img');
img_subtract(image1,image2,imout);
elseif nf==2
% For two factors
% Average effect
image1 = fullfile(analysis_dir, 'model_1','LogEv.img');
image2 = fullfile(analysis_dir, 'model_2','LogEv.img');
imout = fullfile(analysis_dir, 'avg_effect.img');
img_subtract(image1,image2,imout);
% Main effect of factor 1
image1 = fullfile(analysis_dir, 'model_2','LogEv.img');
image2 = fullfile(analysis_dir, 'model_3','LogEv.img');
imout = fullfile(analysis_dir, ['main_effect_',SPM.factor(1).name,'.img']);
img_subtract(image1,image2,imout);
% Main effect of factor 2
image1 = fullfile(analysis_dir, 'model_2','LogEv.img');
image2 = fullfile(analysis_dir, 'model_4','LogEv.img');
imout = fullfile(analysis_dir, ['main_effect_',SPM.factor(2).name,'.img']);
img_subtract(image1,image2,imout);
% Interaction
image1 = fullfile(analysis_dir, 'model_5','LogEv.img');
image2 = fullfile(analysis_dir, 'LogEv.img');
imout = fullfile(analysis_dir, 'interaction.img');
img_subtract(image1,image2,imout);
end
%-----------------------------------------------------------------------
function img_subtract(image1,image2,image_out)
% Subtract image 1 from image 2 and write to image out
% Note: parameters are names of files
Vi = spm_vol(strvcat(image1,image2));
Vo = struct(...
'fname', image_out,...
'dim', [Vi(1).dim(1:3)],...
'dt', [spm_type('float32') spm_platform('bigend')],...
'mat', Vi(1).mat,...
'descrip', 'Difference in Log Evidence');
f = 'i2-i1';
flags = {0,0,1};
Vo = spm_imcalc(Vi,Vo,f,flags);
|
github
|
philippboehmsturm/antx-master
|
spm_fmri_spm_ui.m
|
.m
|
antx-master/xspm8/spm_fmri_spm_ui.m
| 19,258 |
utf_8
|
8205c5db88ee6848b51de86102b8b0d0
|
function [SPM] = spm_fmri_spm_ui(SPM)
% Setting up the general linear model for fMRI time-series
% FORMAT [SPM] = spm_fmri_spm_ui(SPM)
%
% creates SPM with the following fields
%
% xY: [1x1 struct] - data structure
% nscan: [double] - vector of scans per session
% xBF: [1x1 struct] - Basis function structure (see spm_fMRI_design)
% Sess: [1x1 struct] - Session structure (see spm_fMRI_design)
% xX: [1x1 struct] - Design matrix structure (see spm_fMRI_design)
% xGX: [1x1 struct] - Global variate structure
% xVi: [1x1 struct] - Non-sphericity structure
% xM: [1x1 struct] - Masking structure
% xsDes: [1x1 struct] - Design description structure
%
%
% SPM.xY
% P: [n x ? char] - filenames
% VY: [n x 1 struct] - filehandles
% RT: Repeat time
%
% SPM.xGX
%
% iGXcalc: {'none'|'Scaling'} - Global normalization option
% sGXcalc: 'mean voxel value' - Calculation method
% sGMsca: 'session specific' - Grand mean scaling
% rg: [n x 1 double] - Global estimate
% GM: 100 - Grand mean
% gSF: [n x 1 double] - Global scaling factor
%
% SPM.xVi
% Vi: {[n x n sparse]..} - covariance components
% form: {'none'|'AR(1)'} - form of non-sphericity
%
% SPM.xM
% T: [n x 1 double] - Masking index
% TH: [n x 1 double] - Threshold
% I: 0
% VM: - Mask filehandles
% xs: [1x1 struct] - cellstr description
%
% (see also spm_spm_ui)
%
%__________________________________________________________________________
%
% spm_fmri_spm_ui configures the design matrix, data specification and
% filtering that specify the ensuing statistical analysis. These
% arguments are passed to spm_spm that then performs the actual parameter
% estimation.
%
% The design matrix defines the experimental design and the nature of
% hypothesis testing to be implemented. The design matrix has one row
% for each scan and one column for each effect or explanatory variable.
% (e.g. regressor or stimulus function). The parameters are estimated in
% a least squares sense using the general linear model. Specific profiles
% within these parameters are tested using a linear compound or contrast
% with the T or F statistic. The resulting statistical map constitutes
% an SPM. The SPM{T}/{F} is then characterized in terms of focal or regional
% differences by assuming that (under the null hypothesis) the components of
% the SPM (i.e. residual fields) behave as smooth stationary Gaussian fields.
%
% spm_fmri_spm_ui allows you to (i) specify a statistical model in terms
% of a design matrix, (ii) associate some data with a pre-specified design
% [or (iii) specify both the data and design] and then proceed to estimate
% the parameters of the model.
% Inferences can be made about the ensuing parameter estimates (at a first
% or fixed-effect level) in the results section, or they can be re-entered
% into a second (random-effect) level analysis by treating the session or
% subject-specific [contrasts of] parameter estimates as new summary data.
% Inferences at any level obtain by specifying appropriate T or F contrasts
% in the results section to produce SPMs and tables of p values and statistics.
%
% spm_fmri_spm calls spm_fMRI_design which allows you to configure a
% design matrix in terms of events or epochs.
%
% spm_fMRI_design allows you to build design matrices with separable
% session-specific partitions. Each partition may be the same (in which
% case it is only necessary to specify it once) or different. Responses
% can be either event- or epoch related, The only distinction is the duration
% of the underlying input or stimulus function. Mathematically they are both
% modelled by convolving a series of delta (stick) or box functions (u),
% indicating the onset of an event or epoch with a set of basis
% functions. These basis functions model the hemodynamic convolution,
% applied by the brain, to the inputs. This convolution can be first-order
% or a generalized convolution modelled to second order (if you specify the
% Volterra option). [The same inputs are used by the hemodynamic model or
% or dynamic causal models which model the convolution explicitly in terms of
% hidden state variables (see spm_hdm_ui and spm_dcm_ui).]
% Basis functions can be used to plot estimated responses to single events
% once the parameters (i.e. basis function coefficients) have
% been estimated. The importance of basis functions is that they provide
% a graceful transition between simple fixed response models (like the
% box-car) and finite impulse response (FIR) models, where there is one
% basis function for each scan following an event or epoch onset. The
% nice thing about basis functions, compared to FIR models, is that data
% sampling and stimulus presentation does not have to be synchronized
% thereby allowing a uniform and unbiased sampling of peri-stimulus time.
%
% Event-related designs may be stochastic or deterministic. Stochastic
% designs involve one of a number of trial-types occurring with a
% specified probably at successive intervals in time. These
% probabilities can be fixed (stationary designs) or time-dependent
% (modulated or non-stationary designs). The most efficient designs
% obtain when the probabilities of every trial type are equal.
% A critical issue in stochastic designs is whether to include null events
% If you wish to estimate the evoke response to a specific event
% type (as opposed to differential responses) then a null event must be
% included (even if it is not modelled explicitly).
%
% The choice of basis functions depends upon the nature of the inference
% sought. One important consideration is whether you want to make
% inferences about compounds of parameters (i.e. contrasts). This is
% the case if (i) you wish to use a SPM{T} to look separately at
% activations and deactivations or (ii) you with to proceed to a second
% (random-effect) level of analysis. If this is the case then (for
% event-related studies) use a canonical hemodynamic response function
% (HRF) and derivatives with respect to latency (and dispersion). Unlike
% other bases, contrasts of these effects have a physical interpretation
% and represent a parsimonious way of characterising event-related
% responses. Bases such as a Fourier set require the SPM{F} for
% inference.
%
% See spm_fMRI_design for more details about how designs are specified.
%
% Serial correlations in fast fMRI time-series are dealt with as
% described in spm_spm. At this stage you need to specify the filtering
% that will be applied to the data (and design matrix) to give a
% generalized least squares (GLS) estimate of the parameters required.
% This filtering is important to ensure that the GLS estimate is
% efficient and that the error variance is estimated in an unbiased way.
%
% The serial correlations will be estimated with a ReML (restricted
% maximum likelihood) algorithm using an autoregressive AR(1) model
% during parameter estimation. This estimate assumes the same
% correlation structure for each voxel, within each session. The ReML
% estimates are then used to correct for non-sphericity during inference
% by adjusting the statistics and degrees of freedom appropriately. The
% discrepancy between estimated and actual intrinsic (i.e. prior to
% filtering) correlations are greatest at low frequencies. Therefore
% specification of the high-pass filter is particularly important.
%
% High-pass filtering is implemented at the level of the
% filtering matrix K (as opposed to entering as confounds in the design
% matrix). The default cut-off period is 128 seconds. Use 'explore design'
% to ensure this cut-off is not removing too much experimental variance.
% Note that high-pass filtering uses a residual forming matrix (i.e.
% it is not a convolution) and is simply to a way to remove confounds
% without estimating their parameters explicitly. The constant term
% is also incorporated into this filter matrix.
%
%--------------------------------------------------------------------------
% Refs:
%
% Friston KJ, Holmes A, Poline J-B, Grasby PJ, Williams SCR, Frackowiak
% RSJ & Turner R (1995) Analysis of fMRI time-series revisited. NeuroImage
% 2:45-53
%
% Worsley KJ and Friston KJ (1995) Analysis of fMRI time-series revisited -
% again. NeuroImage 2:178-181
%
% Friston KJ, Frith CD, Frackowiak RSJ, & Turner R (1995) Characterising
% dynamic brain responses with fMRI: A multivariate approach NeuroImage -
% 2:166-172
%
% Frith CD, Turner R & Frackowiak RSJ (1995) Characterising evoked
% hemodynamics with fMRI Friston KJ, NeuroImage 2:157-165
%
% Josephs O, Turner R and Friston KJ (1997) Event-related fMRI, Hum. Brain
% Map. 0:00-00
%
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston, Jean-Baptiste Poline & Christian Buchel
% $Id: spm_fmri_spm_ui.m 4421 2011-08-04 11:34:28Z guillaume $
SVNid = '$Rev: 4421 $';
%-GUI setup
%--------------------------------------------------------------------------
[Finter,Fgraph,CmdLine] = spm('FnUIsetup','fMRI stats model setup',0);
% get design matrix and/or data
%==========================================================================
if ~nargin
str = 'specify design or data';
if spm_input(str,1,'b',{'design','data'},[1 0]);
% specify a design
%------------------------------------------------------------------
if sf_abort, spm_clf(Finter), return, end
SPM = spm_fMRI_design;
spm_fMRI_design_show(SPM);
return
else
% get design
%------------------------------------------------------------------
load(spm_select(1,'^SPM\.mat$','Select SPM.mat'));
end
else
% get design matrix
%----------------------------------------------------------------------
SPM = spm_fMRI_design(SPM);
end
% get Repeat time
%--------------------------------------------------------------------------
try
SPM.xY.RT;
catch
SPM.xY.RT = spm_input('Interscan interval {secs}','+1');
end
% session and scan number
%--------------------------------------------------------------------------
nscan = SPM.nscan;
nsess = length(nscan);
% check data are specified
%--------------------------------------------------------------------------
try
SPM.xY.P;
catch
% get filenames
%----------------------------------------------------------------------
P = [];
for i = 1:nsess
str = sprintf('select scans for session %0.0f',i);
q = spm_select(nscan(i),'image',str);
P = strvcat(P,q);
end
% place in data field
%----------------------------------------------------------------------
SPM.xY.P = P;
end
% Assemble remaining design parameters
%==========================================================================
SPM.SPMid = spm('FnBanner',mfilename,SVNid);
% Global normalization
%--------------------------------------------------------------------------
try
SPM.xGX.iGXcalc;
catch
spm_input('Global intensity normalisation...',1,'d',mfilename)
str = 'remove Global effects';
SPM.xGX.iGXcalc = spm_input(str,'+1','scale|none',{'Scaling' 'None'});
end
SPM.xGX.sGXcalc = 'mean voxel value';
SPM.xGX.sGMsca = 'session specific';
% High-pass filtering and serial correlations
%==========================================================================
% low frequency confounds
%--------------------------------------------------------------------------
try
myLastWarn = 0;
HParam = [SPM.xX.K(:).HParam];
if length(HParam) == 1
HParam = HParam*ones(1,nsess);
elseif length(HParam) ~= nsess
myLastWarn = 1;
error('Continue with manual HPF specification in the catch block');
end
catch
% specify low frequency confounds
%----------------------------------------------------------------------
spm_input('Temporal autocorrelation options','+1','d',mfilename)
switch spm_input('High-pass filter?','+1','b','none|specify');
case 'specify' % default in seconds
%--------------------------------------------------------------
HParam = spm_get_defaults('stats.fmri.hpf')*ones(1,nsess);
str = 'cutoff period (secs)';
HParam = spm_input(str,'+1','e',HParam,[1 nsess]);
case 'none' % Inf seconds (i.e. constant term only)
%--------------------------------------------------------------
HParam = Inf(1,nsess);
end
if myLastWarn
warning('SPM:InvalidHighPassFilterSpec',...
['Different number of High-pass filter values and sessions.\n',...
'HPF filter configured manually. Design setup will proceed.']);
clear myLastWarn
end
end
% create and set filter struct
%--------------------------------------------------------------------------
for i = 1:nsess
K(i) = struct('HParam', HParam(i),...
'row', SPM.Sess(i).row,...
'RT', SPM.xY.RT);
end
SPM.xX.K = spm_filter(K);
% intrinsic autocorrelations (Vi)
%--------------------------------------------------------------------------
try
cVi = SPM.xVi.form;
catch
% Construct Vi structure for non-sphericity ReML estimation
%----------------------------------------------------------------------
str = 'Correct for serial correlations?';
cVi = {'none','AR(1)'};
cVi = spm_input(str,'+1','b',cVi);
end
% create Vi struct
%--------------------------------------------------------------------------
if ~ischar(cVi) % AR coefficient specified
%----------------------------------------------------------------------
SPM.xVi.Vi = spm_Ce(nscan,cVi(1));
cVi = ['AR( ' sprintf('%0.1f ',cVi) ')'];
else
switch lower(cVi)
case 'none' % xVi.V is i.i.d
%--------------------------------------------------------------
SPM.xVi.V = speye(sum(nscan));
cVi = 'i.i.d';
otherwise % otherwise assume AR(0.2) in xVi.Vi
%--------------------------------------------------------------
SPM.xVi.Vi = spm_Ce(nscan,0.2);
cVi = 'AR(0.2)';
end
end
SPM.xVi.form = cVi;
%==========================================================================
% - C O N F I G U R E D E S I G N
%==========================================================================
spm_clf(Finter);
spm('FigName','Configuring, please wait...',Finter,CmdLine);
spm('Pointer','Watch');
% get file identifiers
%==========================================================================
%-Map files
%--------------------------------------------------------------------------
fprintf('%-40s: ','Mapping files') %-#
VY = spm_vol(SPM.xY.P);
fprintf('%30s\n','...done') %-#
%-check internal consistency of images
%--------------------------------------------------------------------------
spm_check_orientations(VY);
%-place in xY
%--------------------------------------------------------------------------
SPM.xY.VY = VY;
%-Compute Global variate
%==========================================================================
GM = 100;
q = length(VY);
g = zeros(q,1);
fprintf('%-40s: %30s','Calculating globals',' ') %-#
for i = 1:q
fprintf('%s%30s',repmat(sprintf('\b'),1,30),sprintf('%4d/%-4d',i,q))%-#
g(i) = spm_global(VY(i));
end
fprintf('%s%30s\n',repmat(sprintf('\b'),1,30),'...done') %-#
% scale if specified (otherwise session specific grand mean scaling)
%--------------------------------------------------------------------------
gSF = GM./g;
if strcmpi(SPM.xGX.iGXcalc,'none')
for i = 1:nsess
gSF(SPM.Sess(i).row) = GM./mean(g(SPM.Sess(i).row));
end
end
%-Apply gSF to memory-mapped scalefactors to implement scaling
%--------------------------------------------------------------------------
for i = 1:q
SPM.xY.VY(i).pinfo(1:2,:) = SPM.xY.VY(i).pinfo(1:2,:)*gSF(i);
end
%-place global variates in global structure
%--------------------------------------------------------------------------
SPM.xGX.rg = g;
SPM.xGX.GM = GM;
SPM.xGX.gSF = gSF;
%-Masking structure automatically set to 80% of mean
%==========================================================================
try
TH = g.*gSF*spm_get_defaults('mask.thresh');
catch
TH = g.*gSF*0.8;
end
SPM.xM = struct('T', ones(q,1),...
'TH', TH,...
'I', 0,...
'VM', {[]},...
'xs', struct('Masking','analysis threshold'));
%-Design description - for saving and display
%==========================================================================
for i = 1:nsess, ntr(i) = length(SPM.Sess(i).U); end
Fstr = sprintf('[min] Cutoff: %d {s}',min([SPM.xX.K(:).HParam]));
SPM.xsDes = struct(...
'Basis_functions', SPM.xBF.name,...
'Number_of_sessions', sprintf('%d',nsess),...
'Trials_per_session', sprintf('%-3d',ntr),...
'Interscan_interval', sprintf('%0.2f {s}',SPM.xY.RT),...
'High_pass_Filter', sprintf('Cutoff: %d {s}',SPM.xX.K(1).HParam),...
'Global_calculation', SPM.xGX.sGXcalc,...
'Grand_mean_scaling', SPM.xGX.sGMsca,...
'Global_normalisation', SPM.xGX.iGXcalc);
%-Save SPM.mat
%==========================================================================
fprintf('%-40s: ','Saving SPM configuration') %-#
if spm_check_version('matlab','7') >=0
save('SPM.mat', 'SPM', '-V6');
else
save('SPM.mat', 'SPM');
end
fprintf('%30s\n','...SPM.mat saved') %-#
%-Display Design report
%==========================================================================
if ~CmdLine
fprintf('%-40s: ','Design reporting') %-#
fname = cat(1,{SPM.xY.VY.fname}');
spm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes)
fprintf('%30s\n','...done') %-#
end
%-End: Cleanup GUI
%==========================================================================
spm_clf(Finter)
spm('FigName','Stats: configured',Finter,CmdLine);
spm('Pointer','Arrow')
%==========================================================================
%- S U B - F U N C T I O N S
%==========================================================================
function abort = sf_abort
%==========================================================================
if exist(fullfile(pwd,'SPM.mat'),'file')
str = { 'Current directory contains existing SPM file:',...
'Continuing will overwrite existing file!'};
abort = spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);
if abort, fprintf('%-40s: %30s\n\n',...
'Abort... (existing SPM files)',spm('time')), end
else
abort = 0;
end
|
github
|
philippboehmsturm/antx-master
|
spm_input.m
|
.m
|
antx-master/xspm8/spm_input.m
| 89,733 |
utf_8
|
57a58b73c9dcef093e755ad4051efd65
|
function varargout = spm_input(varargin)
% Comprehensive graphical and command line input function
% FORMATs (given in Programmers Help)
%_______________________________________________________________________
%
% spm_input handles most forms of interactive user input for SPM.
% (File selection is handled by spm_select.m)
%
% There are five types of input: String, Evaluated, Conditions, Buttons
% and Menus: These prompt for string input; string input which is
% evaluated to give a numerical result; selection of one item from a
% set of buttons; selection of an item from a menu.
%
% - STRING, EVALUATED & CONDITION input -
% For STRING, EVALUATED and CONDITION input types, a prompt is
% displayed adjacent to an editable text entry widget (with a lilac
% background!). Clicking in the entry widget allows editing, pressing
% <RETURN> or <ENTER> enters the result. You must enter something,
% empty answers are not accepted. A default response may be pre-specified
% in the entry widget, which will then be outlined. Clicking the border
% accepts the default value.
%
% Basic editing of the entry widget is supported *without* clicking in
% the widget, provided no other graphics widget has the focus. (If a
% widget has the focus, it is shown highlighted with a thin coloured
% line. Clicking on the window background returns the focus to the
% window, enabling keyboard accelerators.). This enables you to type
% responses to a sequence of questions without having to repeatedly
% click the mouse in the text widgets. Supported are BackSpace and
% Delete, line kill (^U). Other standard ASCII characters are appended
% to the text in the entry widget. Press <RETURN> or <ENTER> to submit
% your response.
%
% A ContextMenu is provided (in the figure background) giving access to
% relevant utilities including the facility to load input from a file
% (see spm_load.m and examples given below): Click the right button on
% the figure background.
%
% For EVALUATED input, the string submitted is evaluated in the base
% MatLab workspace (see MatLab's `eval` command) to give a numerical
% value. This permits the entry of numerics, matrices, expressions,
% functions or workspace variables. I.e.:
% i) - a number, vector or matrix e.g. "[1 2 3 4]"
% "[1:4]"
% "1:4"
% ii) - an expression e.g. "pi^2"
% "exp(-[1:36]/5.321)"
% iii) - a function (that will be invoked) e.g. "spm_load('tmp.dat')"
% (function must be on MATLABPATH) "input_cov(36,5.321)"
% iv) - a variable from the base workspace
% e.g. "tmp"
%
% The last three options provide a great deal of power: spm_load will
% load a matrix from an ASCII data file and return the results. When
% called without an argument, spm_load will pop up a file selection
% dialog. Alternatively, this facility can be gained from the
% ContextMenu. The second example assummes a custom funcion called
% input_cov has been written which expects two arguments, for example
% the following file saved as input_cov.m somewhere on the MATLABPATH
% (~/matlab, the matlab subdirectory of your home area, and the current
% directory, are on the MATLABPATH by default):
%
% function [x] = input_cov(n,decay)
% % data input routine - mono-exponential covariate
% % FORMAT [x] = input_cov(n,decay)
% % n - number of time points
% % decay - decay constant
% x = exp(-[1:n]/decay);
%
% Although this example is trivial, specifying large vectors of
% empirical data (e.g. reaction times for 72 scans) is efficient and
% reliable using this device. In the last option, a variable called tmp
% is picked up from the base workspace. To use this method, set the
% variables in the MatLab base workspace before starting an SPM
% procedure (but after starting the SPM interface). E.g.
% >> tmp=exp(-[1:36]/5.321)
%
% Occasionally a vector of a specific length will be required: This
% will be indicated in the prompt, which will start with "[#]", where
% # is the length of vector(s) required. (If a matrix is entered then
% at least one dimension should equal #.)
%
% Occasionally a specific type of number will be required. This should
% be obvious from the context. If you enter a number of the wrong type,
% you'll be alerted and asked to re-specify. The types are i) Real
% numbers; ii) Integers; iii) Whole numbers [0,1,2,3,...] & iv) Natural
% numbers [1,2,3,...]
%
% CONDITIONS type input is for getting indicator vectors. The features
% of evaluated input described above are complimented as follows:
% v) - a compressed list of digits 0-9 e.g. "12121212"
% ii) - a list of indicator characters e.g. "abababab"
% a-z mapped to 1-26 in alphabetical order, *except* r ("rest")
% which is mapped to zero (case insensitive, [A:Z,a:z] only)
% ...in addition the response is checked to ensure integer condition indices.
% Occasionally a specific number of conditions will be required: This
% will be indicated in the prompt, which will end with (#), where # is
% the number of conditions required.
%
% CONTRAST type input is for getting contrast weight vectors. Enter
% contrasts as row-vectors. Contrast weight vectors will be padded with
% zeros to the correct length, and checked for validity. (Valid
% contrasts are estimable, which are those whose weights vector is in
% the row-space of the design matrix.)
%
% Errors in string evaluation for EVALUATED & CONDITION types are
% handled gracefully, the user notified, and prompted to re-enter.
%
% - BUTTON input -
% For Button input, the prompt is displayed adjacent to a small row of
% buttons. Press the approprate button. The default button (if
% available) has a dark outline. Keyboard accelerators are available
% (provided no graphics widget has the focus): <RETURN> or <ENTER>
% selects the default button (if available). Typing the first character
% of the button label (case insensitive) "presses" that button. (If
% these Keys are not unique, then the integer keys 1,2,... "press" the
% appropriate button.)
%
% The CommandLine variant presents a simple menu of buttons and prompts
% for a selection. Any default response is indicated, and accepted if
% an empty line is input.
%
%
% - MENU input -
% For Menu input, the prompt is displayed in a pull down menu widget.
% Using the mouse, a selection is made by pulling down the widget and
% releasing the mouse on the appropriate response. The default response
% (if set) is marked with an asterisk. Keyboard accelerators are
% available (provided no graphic widget has the focus) as follows: 'f',
% 'n' or 'd' move forward to next response down; 'b', 'p' or 'u' move
% backwards to the previous response up the list; the number keys jump
% to the appropriate response number; <RETURN> or <ENTER> slelects the
% currently displayed response. If a default is available, then
% pressing <RETURN> or <ENTER> when the prompt is displayed jumps to
% the default response.
%
% The CommandLine variant presents a simple menu and prompts for a selection.
% Any default response is indicated, and accepted if an empty line is
% input.
%
%
% - Combination BUTTON/EDIT input -
% In this usage, you will be presented with a set of buttons and an
% editable text widget. Click one of the buttons to choose that option,
% or type your response in the edit widget. Any default response will
% be shown in the edit widget. The edit widget behaves in the same way
% as with the STRING/EVALUATED input, and expects a single number.
% Keypresses edit the text widget (rather than "press" the buttons)
% (provided no other graphics widget has the focus). A default response
% can be selected with the mouse by clicking the thick border of the
% edit widget.
%
%
% - Command line -
% If YPos is 0 or global CMDLINE is true, then the command line is used.
% Negative YPos overrides CMDLINE, ensuring the GUI is used, at
% YPos=abs(YPos). Similarly relative YPos beginning with '!'
% (E.g.YPos='!+1') ensures the GUI is used.
%
% spm_input uses the SPM 'Interactive' window, which is 'Tag'ged
% 'Interactive'. If there is no such window, then the current figure is
% used, or an 'Interactive' window created if no windows are open.
%
%-----------------------------------------------------------------------
% Programers help is contained in the main body of spm_input.m
%-----------------------------------------------------------------------
% See : input.m (MatLab Reference Guide)
% See also : spm_select.m (SPM file selector dialog)
% : spm_input.m (Input wrapper function - handles batch mode)
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm_input.m 6071 2014-06-27 12:52:33Z guillaume $
%=======================================================================
% - FORMAT specifications for programers
%=======================================================================
% generic - [p,YPos] = spm_input(Prompt,YPos,Type,...)
% string - [p,YPos] = spm_input(Prompt,YPos,'s',DefStr)
% string+ - [p,YPos] = spm_input(Prompt,YPos,'s+',DefStr)
% evaluated - [p,YPos] = spm_input(Prompt,YPos,'e',DefStr,n)
% - natural - [p,YPos] = spm_input(Prompt,YPos,'n',DefStr,n,mx)
% - whole - [p,YPos] = spm_input(Prompt,YPos,'w',DefStr,n,mx)
% - integer - [p,YPos] = spm_input(Prompt,YPos,'i',DefStr,n)
% - real - [p,YPos] = spm_input(Prompt,YPos,'r',DefStr,n,mm)
% condition - [p,YPos] = spm_input(Prompt,YPos,'c',DefStr,n,m)
% contrast - [p,YPos] = spm_input(Prompt,YPos,'x',DefStr,n,X)
% permutation- [p,YPos] = spm_input(Prompt,YPos,'p',DefStr,P,n)
% button - [p,YPos] = spm_input(Prompt,YPos,'b',Labels,Values,DefItem)
% button/edit combo's (edit for string or typed scalar evaluated input)
% [p,YPos] = spm_input(Prompt,YPos,'b?1',Labels,Values,DefStr,mx)
% ...where ? in b?1 specifies edit widget type as with string & eval'd input
% - [p,YPos] = spm_input(Prompt,YPos,'n1',DefStr,mx)
% - [p,YPos] = spm_input(Prompt,YPos,'w1',DefStr,mx)
% button dialog
% - [p,YPos] = spm_input(Prompt,YPos,'bd',...
% Labels,Values,DefItem,Title)
% menu - [p,YPos] = spm_input(Prompt,YPos,'m',Labels,Values,DefItem)
% display - spm_input(Message,YPos,'d',Label)
% display - (GUI only) spm_input(Alert,YPos,'d!',Label)
%
% yes/no - [p,YPos] = spm_input(Prompt,YPos,'y/n',Values,DefItem)
% buttons (shortcut) where Labels is a bar delimited string
% - [p,YPos] = spm_input(Prompt,YPos,Labels,Values,DefItem)
%
% NB: Natural numbers are [1:Inf), Whole numbers are [0:Inf)
%
% -- Parameters (input) --
%
% Prompt - prompt string
% - Defaults (missing or empty) to 'Enter an expression'
%
% YPos - (numeric) vertical position {1 - 12}
% - overriden by global CMDLINE
% - 0 for command line
% - negative to force GUI
% - (string) relative vertical position E.g. '+1'
% - relative to last position used
% - overriden by global CMDLINE
% - YPos(1)=='!' forces GUI E.g. '!+1'
% - '_' is a shortcut for the lowest GUI position
% - Defaults (missing or empty) to '+1'
%
% Type - type of interrogation
% - 's'tring
% - 's+' multi-line string
% - p returned as cellstr (nx1 cell array of strings)
% - DefStr can be a cellstr or string matrix
% - 'e'valuated string
% - 'n'atural numbers
% - 'w'hole numbers
% - 'i'ntegers
% - 'r'eals
% - 'c'ondition indicator vector
% - 'x' - contrast entry
% - If n(2) or design matrix X is specified, then
% contrast matrices are padded with zeros to have
% correct length.
% - if design matrix X is specified, then contrasts are
% checked for validity (i.e. in the row-space of X)
% (checking handled by spm_SpUtil)
% - 'b'uttons
% - 'bd' - button dialog: Uses MatLab's questdlg
% - For up to three buttons
% - Prompt can be a cellstr with a long multiline message
% - CmdLine support as with 'b' type
% - button/edit combo's: 'be1','bn1','bw1','bi1','br1'
% - second letter of b?1 specifies type for edit widget
% - 'n1' - single natural number (buttons 1,2,... & edit)
% - 'w1' - single whole number (buttons 0,1,... & edit)
% - 'm'enu pulldown
% - 'y/n' : Yes or No buttons
% (See shortcuts below)
% - bar delimited string : buttons with these labels
% (See shortcuts below)
% - Defaults (missing or empty) to 'e'
%
% DefStr - Default string to be placed in entry widget for string and
% evaluated types
% - Defaults to ''
%
% n ('e', 'c' & 'p' types)
% - Size of matrix requred
% - NaN for 'e' type implies no checking - returns input as evaluated
% - length of n(:) specifies dimension - elements specify size
% - Inf implies no restriction
% - Scalar n expanded to [n,1] (i.e. a column vector)
% (except 'x' contrast type when it's [n,np] for np
% - E.g: [n,1] & [1,n] (scalar n) prompt for an n-vector,
% returned as column or row vector respectively
% [1,Inf] & [Inf,1] prompt for a single vector,
% returned as column or row vector respectively
% [n,Inf] & [Inf,n] prompts for any number of n-vectors,
% returned with row/column dimension n respectively.
% [a,b] prompts for an 2D matrix with row dimension a and
% column dimension b
% [a,Inf,b] prompt for a 3D matrix with row dimension a,
% page dimension b, and any column dimension.
% - 'c' type can only deal with single vectors
% - NaN for 'c' type treated as Inf
% - Defaults (missing or empty) to NaN
%
% n ('x'type)
% - Number of contrasts required by 'x' type (n(1))
% ( n(2) can be used specify length of contrast vectors if )
% ( a design matrix isn't passed )
% - Defaults (missing or empty) to 1 - vector contrast
%
% mx ('n', 'w', 'n1', 'w1', 'bn1' & 'bw1' types)
% - Maximum value (inclusive)
%
% mm ('r' type)
% - Maximum and minimum values (inclusive)
%
% m - Number of unique conditions required by 'c' type
% - Inf implies no restriction
% - Defaults (missing or empty) to Inf - no restriction
%
% P - set (vector) of numbers of which a permutation is required
%
% X - Design matrix for contrast checking in 'x' type
% - Can be either a straight matrix or a space structure (see spm_sp)
% - Column dimension of design matrix specifies length of contrast
% vectors (overriding n(2) is specified).
%
% Title - Title for questdlg in 'bd' type
%
% Labels - Labels for button and menu types.
% - string matrix, one label per row
% - bar delimited string
% E.g. 'AnCova|Scaling|None'
%
% Values - Return values corresponding to Labels for button and menu types
% - j-th row is returned if button / menu item j is selected
% (row vectors are transposed)
% - Defaults (missing or empty) to - (button) Labels
% - ( menu ) menu item numbers
%
% DefItem - Default item number, for button and menu types.
%
% -- Parameters (output) --
% p - results
% YPos - Optional second output argument returns GUI position just used
%
%-----------------------------------------------------------------------
% WINDOWS:
%
% spm_input uses the SPM 'Interactive' 'Tag'ged window. If this isn't
% available and no figures are open, an 'Interactive' SPM window is
% created (`spm('CreateIntWin')`). If figures are available, then the
% current figure is used *unless* it is 'Tag'ged.
%
%-----------------------------------------------------------------------
% SHORTCUTS:
%
% Buttons SHORTCUT - If the Type parameter is a bar delimited string, then
% the Type is taken as 'b' with the specified labels, and the next parameter
% (if specified) is taken for the Values.
%
% Yes/No question shortcut - p = spm_input(Prompt,YPos,'y/n') expands
% to p = spm_input(Prompt,YPos,'b','yes|no',...), enabling easy use of
% spm_input for yes/no dialogue. Values defaults to 'yn', so 'y' or 'n'
% is returned as appropriate.
%
%-----------------------------------------------------------------------
% EXAMPLES:
% ( Specified YPos is overriden if global CMDLINE is )
% ( true, when the command line versions are used. )
%
% p = spm_input
% Command line input of an evaluated string, default prompt.
% p = spm_input('Enter a value',1)
% Evaluated string input, prompted by 'Enter a value', in
% position 1 of the dialog figure.
% p = spm_input(str,'+1','e',0.001)
% Evaluated string input, prompted by contents of string str,
% in next position of the dialog figure.
% Default value of 0.001 offered.
% p = spm_input(str,2,'e',[],5)
% Evaluated string input, prompted by contents of string str,
% in second position of the dialog figure.
% Vector of length 5 required - returned as column vector
% p = spm_input(str,2,'e',[],[Inf,5])
% ...as above, but can enter multiple 5-vectors in a matrix,
% returned with 5-vectors in rows
% p = spm_input(str,0,'c','ababab')
% Condition string input, prompted by contents of string str
% Uses command line interface.
% Default string of 'ababab' offered.
% p = spm_input(str,0,'c','010101')
% As above, but default string of '010101' offered.
% [p,YPos] = spm_input(str,'0','s','Image')
% String input, same position as last used, prompted by str,
% default of 'Image' offered. YPos returns GUI position used.
% p = spm_input(str,'-1','y/n')
% Yes/No buttons for question with prompt str, in position one
% before the last used Returns 'y' or 'n'.
% p = spm_input(str,'-1','y/n',[1,0],2)
% As above, but returns 1 for yes response, 0 for no,
% with 'no' as the default response
% p = spm_input(str,4,'AnCova|Scaling')
% Presents two buttons labelled 'AnCova' & 'Scaling', with
% prompt str, in position 4 of the dialog figure. Returns the
% string on the depresed button, where buttons can be pressed
% with the mouse or by the respective keyboard accelerators
% 'a' & 's' (or 'A' & 'S').
% p = spm_input(str,-4,'b','AnCova|Scaling',[],2)
% As above, but makes "Scaling" the default response, and
% overrides global CMDLINE
% p = spm_input(str,0,'b','AnCova|Scaling|None',[1,2,3])
% Prompts for [A]ncova / [S]caling / [N]one in MatLab command
% window, returns 1, 2, or 3 according to the first character
% of the entered string as one of 'a', 's', or 'n' (case
% insensitive).
% p = spm_input(str,1,'b','AnCova',1)
% Since there's only one button, this just displays the response
% in GUI position 1 (or on the command line if global CMDLINE
% is true), and returns 1.
% p = spm_input(str,'+0','br1','None|Mask',[-Inf,NaN],0.8)
% Presents two buttons labelled "None" & "Mask" (which return
% -Inf & NaN if clicked), together with an editable text widget
% for entry of a single real number. The default of 0.8 is
% initially presented in the edit window, and can be selected by
% pressing return.
% Uses the previous GUI position, unless global CMDLINE is true,
% in which case a command-line equivalent is used.
% p = spm_input(str,'+0','w1')
% Prompts for a single whole number using a combination of
% buttons and edit widget, using the previous GUI position,
% or the command line if global CMDLINE is true.
% p = spm_input(str,'!0','m','Single Subject|Multi Subject|Multi Study')
% Prints the prompt str in a pull down menu containing items
% 'Single Subject', 'Multi Subject' & 'Multi Study'. When OK is
% clicked p is returned as the index of the choice, 1,2, or 3
% respectively. Uses last used position in GUI, irrespective of
% global CMDLINE
% p = spm_input(str,5,'m',...
% 'Single Subject|Multi Subject|Multi Study',...
% ['SS';'MS';'SP'],2)
% As above, but returns strings 'SS', 'MS', or 'SP' according to
% the respective choice, with 'MS; as the default response.
% p = spm_input(str,0,'m',...
% 'Single Subject|Multi Subject|Multi Study',...
% ['SS';'MS';'SP'],2)
% As above, but the menu is presented in the command window
% as a numbered list.
% spm_input('AnCova, GrandMean scaling',0,'d')
% Displays message in a box in the MatLab command window
% [null,YPos]=spm_input('Session 1','+1','d!','fMRI')
% Displays 'fMRI: Session 1' in next GUI position of the
% 'Interactive' window. If CMDLINE is 1, then nothing is done.
% Position used is returned in YPos.
%
%-----------------------------------------------------------------------
% FORMAT h = spm_input(Prompt,YPos,'m!',Labels,cb,UD,XCB);
% GUI PullDown menu utility - creates a pulldown menu in the Interactive window
% FORMAT H = spm_input(Prompt,YPos,'b!',Labels,cb,UD,XCB);
% GUI Buttons utility - creates GUI buttons in the Interactive window
%
% Prompt, YPos, Labels - as with 'm'enu/'b'utton types
% cb - CallBack string
% UD - UserData
% XCB - Extended CallBack handling - allows different CallBack for each item,
% and use of UD in CallBack strings. [Defaults to 1 for PullDown type
% when multiple CallBacks specified, 0 o/w.]
% H - Handle of 'PullDown' uicontrol / 'Button's
%
% In "normal" mode (when XCB is false), this is essentially a utility
% to create a PullDown menu widget or set of buttons in the SPM
% 'Interactive' figure, using positioning and Label definition
% conveniences of the spm_input 'm'enu & 'b'utton types. If Prompt is
% not empty, then the PullDown/Buttons appears on the right, with the
% Prompt on the left, otherwise the PullDown/Buttons use the whole
% width of the Interactive figure. The PopUp's CallBack string is
% specified in cb, and [optional] UserData may be passed as UD.
%
% For buttons, a separate callback can be specified for each button, by
% passing the callbacks corresponding to the Labels as rows of a
% cellstr or string matrix.
%
% This "different CallBacks" facility can also be extended to the
% PullDown type, using the "extended callback" mode (when XCB is
% true). % In addition, in "extended callback", you can use UD to
% refer to the UserData argument in the CallBack strings. (What happens
% is this: The cb & UD are stored as fields in the PopUp's UserData
% structure, and the PopUp's callback is set to spm_input('!m_cb'),
% which reads UD into the functions workspace and eval's the
% appropriate CallBack string. Note that this means that base
% workspace variables are inaccessible (put what you need in UD), and
% that any return arguments from CallBack functions are not passed back
% to the base workspace).
%
%
%-----------------------------------------------------------------------
% UTILITY FUNCTIONS:
%
% FORMAT colour = spm_input('!Colour')
% Returns colour for input widgets, as specified in COLOUR parameter at
% start of code.
% colour - [r,g,b] colour triple
%
% FORMAT [iCond,msg] = spm_input('!iCond',str,n,m)
% Parser for special 'c'ondition type: Handles digit strings and
% strings of indicator chars.
% str - input string
% n - length of condition vector required [defaut Inf - no restriction]
% m - number of conditions required [default Inf - no restrictions]
% iCond - Integer condition indicator vector
% msg - status message
%
% FORMAT hM = spm_input('!InptConMen',Finter,H)
% Sets a basic Input ContextMenu for the figure
% Finter - figure to set menu in
% H - handles of objects to delete on "crash out" option
% hM - handle of UIContextMenu
%
% FORMAT [CmdLine,YPos] = spm_input('!CmdLine',YPos)
% Sorts out whether to use CmdLine or not & canonicalises YPos
% CmdLine - Binary flag
% YPos - Position index
%
% FORMAT Finter = spm_input('!GetWin',F)
% Locates (or creates) figure to work in
% F - Interactive Figure, defaults to 'Interactive'
% Finter - Handle of figure to use
%
% FORMAT [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp)
% Raise window & jump pointer over question
% RRec - Response rectangle of current question
% F - Interactive Figure, Defaults to 'Interactive'
% XDisp - X-displacement of cursor relative to RRec
% PLoc - Pointer location before jumping
% cF - Current figure before making F current.
%
% FORMAT [PLoc,cF] = spm_input('!PointerJumpBack',PLoc,cF)
% Replace pointer and reset CurrentFigure back
% PLoc - Pointer location before jumping
% cF - Previous current figure
%
% FORMAT spm_input('!PrntPrmpt',Prompt,TipStr,Title)
% Print prompt for CmdLine questioning
% Prompt - prompt string, callstr, or string matrix
% TipStr - tip string
% Title - title string
%
% FORMAT [Frec,QRec,PRec,RRec] = spm_input('!InputRects',YPos,rec,F)
% Returns rectangles (pixels) used in GUI
% YPos - Position index
% rec - Rectangle specifier: String, one of 'Frec','QRec','PRec','RRec'
% Defaults to '', which returns them all.
% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')
% FRec - Position of interactive window
% QRec - Position of entire question
% PRec - Position of prompt
% RRec - Position of response
%
% FORMAT spm_input('!DeleteInputObj',F)
% Deltes input objects (only) from figure F
% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')
%
% FORMAT [CPos,hCPos] = spm_input('!CurrentPos',F)
% Returns currently used GUI question positions & their handles
% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')
% CPos - Vector of position indices
% hCPos - (n x CPos) matrix of object handles
%
% FORMAT h = spm_input('!FindInputObj',F)
% Returns handles of input GUI objects in figure F
% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')
% h - vector of object handles
%
% FORMAT [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine)
% Returns next position index, specified by YPos
% YPos - Absolute (integer) or relative (string) position index
% Defaults to '+1'
% F - Interactive Figure, defaults to spm_figure('FindWin','Interactive')
% CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos)
% NPos - Next position index
% CPos & hCPos - as for !CurrentPos
%
% FORMAT NPos = spm_input('!SetNextPos',YPos,F,CmdLine)
% Sets up for input at next position index, specified by YPos. This utility
% function can be used stand-alone to implicitly set the next position
% by clearing positions NPos and greater.
% YPos - Absolute (integer) or relative (string) position index
% Defaults to '+1'
% F - Interactive Figure, defaults to spm_figure('FindWin','Interactive')
% CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos)
% NPos - Next position index
%
% FORMAT MPos = spm_input('!MaxPos',F,FRec3)
% Returns maximum position index for figure F
% F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive')
% Not required if FRec3 is specified
% FRec3 - Length of interactive figure in pixels
%
% FORMAT spm_input('!EditableKeyPressFcn',h,ch)
% KeyPress callback for GUI string / eval input
%
% FORMAT spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch)
% KeyPress callback for GUI buttons
%
% FORMAT spm_input('!PullDownKeyPressFcn',h,ch,DefItem)
% KeyPress callback for GUI pulldown menus
%
% FORMAT spm_input('!m_cb')
% Extended CallBack handler for 'p' PullDown utility type
%
% FORMAT spm_input('!dScroll',h,str)
% Scroll text string in object h
% h - handle of text object
% Prompt - Text to scroll (Defaults to 'UserData' of h)
%
%-----------------------------------------------------------------------
% SUBFUNCTIONS:
%
% FORMAT [Keys,Labs] = sf_labkeys(Labels)
% Make unique character keys for the Labels, ignoring case.
% Used with 'b'utton types.
%
% FORMAT [p,msg] = sf_eEval(str,Type,n,m)
% Common code for evaluating various input types.
%
% FORMAT str = sf_SzStr(n,l)
% Common code to construct prompt strings for pre-specified vector/matrix sizes
%
% FORMAT [p,msg] = sf_SzChk(p,n,msg)
% Common code to check (& canonicalise) sizes of input vectors/matrices
%
%_______________________________________________________________________
% @(#)spm_input.m 2.8 Andrew Holmes 03/03/04
%-Parameters
%=======================================================================
PJump = 1; %-Jumping of pointer to question?
TTips = 1; %-Use ToolTipStrings? (which can be annoying!)
ConCrash = 1; %-Add "crash out" option to 'Interactive'fig.ContextMenu
%-Condition arguments
%=======================================================================
if nargin<1||isempty(varargin{1}), Prompt=''; else Prompt=varargin{1}; end
if ~isempty(Prompt) && ischar(Prompt) && Prompt(1)=='!'
%-Utility functions have Prompt string starting with '!'
Type = Prompt;
else %-Should be an input request: get Type & YPos
if nargin<3||isempty(varargin{3}), Type='e'; else Type=varargin{3}; end
if any(Type=='|'), Type='b|'; end
if nargin<2||isempty(varargin{2}), YPos='+1'; else YPos=varargin{2}; end
[CmdLine,YPos] = spm_input('!CmdLine',YPos);
if ~CmdLine %-Setup for GUI use
%-Locate (or create) figure to work in
Finter = spm_input('!GetWin');
COLOUR = get(Finter,'Color');
%-Find out which Y-position to use, setup for use
YPos = spm_input('!SetNextPos',YPos,Finter,CmdLine);
%-Determine position of objects
[FRec,QRec,PRec,RRec]=spm_input('!InputRects',YPos,'',Finter);
end
end
switch lower(Type)
case {'s','s+','e','n','w','i','r','c','x','p'} %-String and evaluated input
%=======================================================================
%-Condition arguments
if nargin<6||isempty(varargin{6}), m=[]; else m=varargin{6}; end
if nargin<5||isempty(varargin{5}), n=[]; else n=varargin{5}; end
if nargin<4, DefStr=''; else DefStr=varargin{4}; end
if strcmpi(Type,'s+')
%-DefStr should be a cellstr for 's+' type.
if isempty(DefStr), DefStr = {};
else DefStr = cellstr(DefStr); end
DefStr = DefStr(:);
else
%-DefStr needs to be a string
if ~ischar(DefStr), DefStr=num2str(DefStr); end
DefStr = DefStr(:)';
end
strM='';
switch lower(Type) %-Type specific defaults/setup
case 's', TTstr='enter string';
case 's+',TTstr='enter string - multi-line';
case 'e', TTstr='enter expression to evaluate';
case 'n', TTstr='enter expression - natural number(s)';
if ~isempty(m), strM=sprintf(' (in [1,%d])',m); TTstr=[TTstr,strM]; end
case 'w', TTstr='enter expression - whole number(s)';
if ~isempty(m), strM=sprintf(' (in [0,%d])',m); TTstr=[TTstr,strM]; end
case 'i', TTstr='enter expression - integer(s)';
case 'r', TTstr='enter expression - real number(s)';
if ~isempty(m), TTstr=[TTstr,sprintf(' in [%g,%g]',min(m),max(m))]; end
case 'c', TTstr='enter indicator vector e.g. 0101... or abab...';
if ~isempty(m) && isfinite(m), strM=sprintf(' (%d)',m); end
case 'x', TTstr='enter contrast matrix';
case 'p',
if isempty(n), error('permutation of what?'), else P=n(:)'; end
if isempty(m), n = [1,length(P)]; end
m = P;
if isempty(setxor(m,[1:max(m)]))
TTstr=['enter permutation of [1:',num2str(max(m)),']'];
else
TTstr=['enter permutation of [',num2str(m),']'];
end
otherwise
TTstr='enter expression';
end
strN = sf_SzStr(n);
if CmdLine %-Use CmdLine to get answer
%-----------------------------------------------------------------------
spm_input('!PrntPrmpt',[Prompt,strN,strM],TTstr)
%-Do Eval Types in Base workspace, catch errors
switch lower(Type), case 's'
if ~isempty(DefStr)
Prompt=[Prompt,' (Default: ',DefStr,' )'];
end
str = input([Prompt,' : '],'s');
if isempty(str), str=DefStr; end
while isempty(str)
spm('Beep')
fprintf('! %s : enter something!\n',mfilename)
str = input([Prompt,' : '],'s');
if isempty(str), str=DefStr; end
end
p = str; msg = '';
case 's+'
fprintf(['Multi-line input: Type ''.'' on a line',...
' of its own to terminate input.\n'])
if ~isempty(DefStr)
fprintf('Default : (press return to accept)\n')
fprintf(' : %s\n',DefStr{:})
end
fprintf('\n')
str = input('l001 : ','s');
while (isempty(str) || strcmp(str,'.')) && isempty(DefStr)
spm('Beep')
fprintf('! %s : enter something!\n',mfilename)
str = input('l001 : ','s');
end
if isempty(str)
%-Accept default
p = DefStr;
else
%-Got some input, allow entry of additional lines
p = {str};
str = input(sprintf('l%03u : ',length(p)+1),'s');
while ~strcmp(str,'.')
p = [p;{str}];
str = input(sprintf('l%03u : ',length(p)+1),'s');
end
end
msg = '';
otherwise
if ~isempty(DefStr)
Prompt=[Prompt,' (Default: ',DefStr,' )'];
end
str = input([Prompt,' : '],'s');
if isempty(str), str=DefStr; end
[p,msg] = sf_eEval(str,Type,n,m);
while ischar(p)
spm('Beep'), fprintf('! %s : %s\n',mfilename,msg)
str = input([Prompt,' : '],'s');
if isempty(str), str=DefStr; end
[p,msg] = sf_eEval(str,Type,n,m);
end
end
if ~isempty(msg), fprintf('\t%s\n',msg), end
else %-Use GUI to get answer
%-----------------------------------------------------------------------
%-Create text and edit control objects
%---------------------------------------------------------------
hPrmpt = uicontrol(Finter,'Style','Text',...
'String',[strN,Prompt,strM],...
'Tag',['GUIinput_',int2str(YPos)],...
'UserData','',...
'BackgroundColor',COLOUR,...
'HorizontalAlignment','Right',...
'Position',PRec);
if TTips, set(hPrmpt,'ToolTipString',[strN,Prompt,strM]); end
%-Default button surrounding edit widget (if a DefStr given)
%-Callback sets hPrmpt UserData, and EditWidget string, to DefStr
% (Buttons UserData holds handles [hPrmpt,hEditWidget], set later)
cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',...
'get(gcbo,''String'')),',...
'set(get(gcbo,''UserData'')*[0;1],''String'',',...
'get(gcbo,''String''))'];
if ~isempty(DefStr)
if iscellstr(DefStr), str=[DefStr{1},'...'];
else str=DefStr; end
hDef = uicontrol(Finter,'Style','PushButton',...
'String',DefStr,...
'ToolTipString',...
['Click on border to accept default: ' str],...
'Tag',['GUIinput_',int2str(YPos)],...
'UserData',[],...
'BackgroundColor',COLOUR,...
'CallBack',cb,...
'Position',RRec+[-2,-2,+4,+4]);
else
hDef = [];
end
%-Edit widget: Callback puts string into hPrompts UserData
cb = 'set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))';
h = uicontrol(Finter,'Style','Edit',...
'String',DefStr,...
'Max',strcmpi(Type,'s+')+1,...
'Tag',['GUIinput_',int2str(YPos)],...
'UserData',hPrmpt,...
'CallBack',cb,...
'Horizontalalignment','Left',...
'BackgroundColor','w',...
'Position',RRec);
set(hDef,'UserData',[hPrmpt,h])
uifocus(h);
if TTips, set(h,'ToolTipString',TTstr), end
%-Figure ContextMenu for shortcuts
hM = spm_input('!InptConMen',Finter,[hPrmpt,hDef,h]);
cb = [ 'set(get(gcbo,''UserData''),''String'',',...
'[''spm_load('''''',spm_select(1),'''''')'']), ',...
'set(get(get(gcbo,''UserData''),''UserData''),''UserData'',',...
'get(get(gcbo,''UserData''),''String''))'];
uimenu(hM,'Label','load from text file','Separator','on',...
'CallBack',cb,'UserData',h)
%-Bring window to fore & jump pointer to edit widget
[PLoc,cF] = spm_input('!PointerJump',RRec,Finter);
%-Setup FigureKeyPressFcn for editing of entry widget without clicking
set(Finter,'KeyPressFcn',[...
'spm_input(''!EditableKeyPressFcn'',',...
'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',...
'''Style'',''edit''),',...
'get(gcbf,''CurrentCharacter''))'])
%-Wait for edit, do eval Types in Base workspace, catch errors
%---------------------------------------------------------------
waitfor(hPrmpt,'UserData')
if ~ishandle(hPrmpt), error(['Input window cleared whilst waiting ',...
'for response: Bailing out!']), end
str = get(hPrmpt,'UserData');
switch lower(Type), case 's'
p = str; msg = '';
case 's+'
p = cellstr(str); msg = '';
otherwise
[p,msg] = sf_eEval(str,Type,n,m);
while ischar(p)
set(h,'Style','Text',...
'String',msg,'HorizontalAlignment','Center',...
'ForegroundColor','r')
spm('Beep'), pause(2)
set(h,'Style','Edit',...
'String',str,...
'HorizontalAlignment','Left',...
'ForegroundColor','k')
%set(hPrmpt,'UserData','');
waitfor(hPrmpt,'UserData')
if ~ishandle(hPrmpt), error(['Input window cleared ',...
'whilst waiting for response: Bailing out!']),end
str = get(hPrmpt,'UserData');
[p,msg] = sf_eEval(str,Type,n,m);
end
end
%-Fix edit window, clean up, reposition pointer, set CurrentFig back
delete([hM,hDef]), set(Finter,'KeyPressFcn','')
set(h,'Style','Text','HorizontalAlignment','Center',...
'ToolTipString',msg,...
'BackgroundColor',COLOUR)
spm_input('!PointerJumpBack',PLoc,cF)
drawnow
end % (if CmdLine)
%-Return response
%-----------------------------------------------------------------------
varargout = {p,YPos};
case {'b','bd','b|','y/n','be1','bn1','bw1','bi1','br1',...
'-n1','n1','-w1','w1','m'} %-'b'utton & 'm'enu Types
%=======================================================================
%-Condition arguments
switch lower(Type), case {'b','be1','bi1','br1','m'}
m = []; Title = '';
if nargin<6, DefItem=[]; else DefItem=varargin{6}; end
if nargin<5, Values=[]; else Values =varargin{5}; end
if nargin<4, Labels=''; else Labels =varargin{4}; end
case 'bd'
if nargin<7, Title=''; else Title =varargin{7}; end
if nargin<6, DefItem=[]; else DefItem=varargin{6}; end
if nargin<5, Values=[]; else Values =varargin{5}; end
if nargin<4, Labels=''; else Labels =varargin{4}; end
case 'y/n'
Title = '';
if nargin<5, DefItem=[]; else DefItem=varargin{5}; end
if nargin<4, Values=[]; else Values =varargin{4}; end
if isempty(Values), Values='yn'; end
Labels = {'yes','no'};
case 'b|'
Title = '';
if nargin<5, DefItem=[]; else DefItem=varargin{5}; end
if nargin<4, Values=[]; else Values =varargin{4}; end
Labels = varargin{3};
case 'bn1'
if nargin<7, m=[]; else m=varargin{7}; end
if nargin<6, DefItem=[]; else DefItem=varargin{6}; end
if nargin<5, Values=[]; else Values =varargin{5}; end
if nargin<4, Labels=[1:5]'; Values=[1:5]; Type='-n1';
else Labels=varargin{4}; end
case 'bw1'
if nargin<7, m=[]; else m=varargin{7}; end
if nargin<6, DefItem=[]; else DefItem=varargin{6}; end
if nargin<5, Values=[]; else Values =varargin{5}; end
if nargin<4, Labels=[0:4]'; Values=[0:4]; Type='-w1';
else Labels=varargin{4}; end
case {'-n1','n1','-w1','w1'}
if nargin<5, m=[]; else m=varargin{5}; end
if nargin<4, DefItem=[]; else DefItem=varargin{4}; end
switch lower(Type)
case {'n1','-n1'}, Labels=[1:min([5,m])]'; Values=Labels'; Type='-n1';
case {'w1','-w1'}, Labels=[0:min([4,m])]'; Values=Labels'; Type='-w1';
end
end
%-Check some labels were specified
if isempty(Labels), error('No Labels specified'), end
if iscellstr(Labels), Labels=char(Labels); end
%-Convert Labels "option" string to string matrix if required
if ischar(Labels) && any(Labels(:)=='|')
OptStr=Labels;
BarPos=find([OptStr=='|',1]);
Labels=OptStr(1:BarPos(1)-1);
for Bar = 2:sum(OptStr=='|')+1
Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1));
end
end
%-Set default Values for the Labels
if isempty(Values)
if strcmpi(Type,'m')
Values=[1:size(Labels,1)]';
else
Values=Labels;
end
else
%-Make sure Values are in rows
if size(Labels,1)>1 && size(Values,1)==1, Values = Values'; end
%-Check numbers of Labels and Values match
if (size(Labels,1)~=size(Values,1))
error('Labels & Values incompatible sizes'), end
end
%-Numeric Labels to strings
if isnumeric(Labels)
tmp = Labels; Labels = cell(size(tmp,1),1);
for i=1:numel(tmp), Labels{i}=num2str(tmp(i,:)); end
Labels=char(Labels);
end
switch lower(Type), case {'b','bd','b|','y/n'} %-Process button types
%=======================================================================
%-Make unique character keys for the Labels, sort DefItem
%---------------------------------------------------------------
nLabels = size(Labels,1);
[Keys,Labs] = sf_labkeys(Labels);
if ~isempty(DefItem) && any(DefItem==[1:nLabels])
DefKey = Keys(DefItem);
else
DefItem = 0;
DefKey = '';
end
if CmdLine
%-Display question prompt
spm_input('!PrntPrmpt',Prompt,'',Title)
%-Build prompt
%-------------------------------------------------------
if ~isempty(Labs)
Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' '];
for i = 2:nLabels
Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' '];
end
else
Prmpt = ['[',Keys(1),'] '];
for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end
end
if DefItem
Prmpt = [Prmpt,...
' (Default: ',deblank(Labels(DefItem,:)),')'];
end
%-Ask for user response
%-------------------------------------------------------
if nLabels==1
%-Only one choice - auto-pick & display
k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels)
else
str = input([Prmpt,'? '],'s');
if isempty(str), str=DefKey; end
while isempty(str) || ~any(lower(Keys)==lower(str(1)))
if ~isempty(str),fprintf('%c\t!Out of range\n',7),end
str = input([Prmpt,'? '],'s');
if isempty(str), str=DefKey; end
end
k = find(lower(Keys)==lower(str(1)));
end
fprintf('\n')
p = Values(k,:); if ischar(p), p=deblank(p); end
elseif strcmpi(Type,'bd')
if nLabels>3, error('at most 3 labels for GUI ''bd'' type'), end
tmp = cellstr(Labels);
if DefItem
tmp = [tmp; tmp(DefItem)];
Prompt = cellstr(Prompt); Prompt=Prompt(:);
Prompt = [Prompt;{' '};...
{['[default: ',tmp{DefItem},']']}];
else
tmp = [tmp; tmp(1)];
end
k = min(find(strcmp(tmp,...
questdlg(Prompt,sprintf('%s%s: %s...',spm('ver'),...
spm('GetUser',' (%s)'),Title),tmp{:}))));
p = Values(k,:); if ischar(p), p=deblank(p); end
else
Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets
%-Create text and edit control objects
%-'UserData' of prompt contains answer
%-------------------------------------------------------
hPrmpt = uicontrol(Finter,'Style','Text',...
'String',Prompt,...
'Tag',Tag,...
'UserData',[],...
'BackgroundColor',COLOUR,...
'HorizontalAlignment','Right',...
'Position',PRec);
if TTips, set(hPrmpt,'ToolTipString',Prompt); end
if nLabels==1
%-Only one choice - auto-pick
k = 1;
else
%-Draw buttons and process response
dX = RRec(3)/nLabels;
if TTips, str = ['select with mouse or use kbd: ',...
sprintf('%c/',Keys(1:end-1)),Keys(end)];
else str=''; end
%-Store button # in buttons 'UserData' property
%-Store handle of prompt string in buttons 'Max' property
%-Button callback sets UserData of prompt string to
% number of pressed button
cb = ['set(get(gcbo,''UserData''),''UserData'',',...
'get(gcbo,''Max''))'];
H = [];
XDisp = [];
for i=1:nLabels
if i==DefItem
%-Default button, outline it
h = uicontrol(Finter,'Style','Frame',...
'BackGroundColor','k',...
'ForeGroundColor','k',...
'Tag',Tag,...
'Position',...
[RRec(1)+(i-1)*dX ...
RRec(2)-1 dX RRec(4)+2]);
XDisp = (i-1/3)*dX;
H = [H,h];
end
h = uicontrol(Finter,'Style','Pushbutton',...
'String',deblank(Labels(i,:)),...
'ToolTipString',sprintf('%s\n%s',deblank(Labels(i,:)),str),...
'Tag',Tag,...
'Max',i,...
'UserData',hPrmpt,...
'BackgroundColor',COLOUR,...
'Callback',cb,...
'Position',[RRec(1)+(i-1)*dX+1 ...
RRec(2) dX-2 RRec(4)]);
if i == DefItem, uifocus(h); end
H = [H,h];
end
%-Figure ContextMenu for shortcuts
hM = spm_input('!InptConMen',Finter,[hPrmpt,H]);
%-Bring window to fore & jump pointer to default button
[PLoc,cF]=spm_input('!PointerJump',RRec,Finter,XDisp);
%-Callback for KeyPress, to store valid button # in
% UserData of Prompt, DefItem if (DefItem~=0)
% & return (ASCII-13) is pressed
set(Finter,'KeyPressFcn',...
['spm_input(''!ButtonKeyPressFcn'',',...
'findobj(gcf,''Tag'',''',Tag,''',',...
'''Style'',''text''),',...
'''',lower(Keys),''',',num2str(DefItem),',',...
'get(gcbf,''CurrentCharacter''))'])
%-Wait for button press, process results
%-----------------------------------------------
waitfor(hPrmpt,'UserData')
if ~ishandle(hPrmpt)
error(['Input objects cleared whilst ',...
'waiting for response: Bailing out!'])
end
k = get(hPrmpt,'UserData');
%-Clean up
delete([H,hM]), set(Finter,'KeyPressFcn','')
spm_input('!PointerJumpBack',PLoc,cF)
end
%-Display answer
uicontrol(Finter,'Style','Text',...
'String',deblank(Labels(k,:)),...
'Tag',Tag,...
'Horizontalalignment','Center',...
'BackgroundColor',COLOUR,...
'Position',RRec);
drawnow
p = Values(k,:); if ischar(p), p=deblank(p); end
end
case {'be1','bn1','bw1','bi1','br1','-n1','-w1'}
%-Process button/entry combo types
%=======================================================================
if ischar(DefItem), DefStr=DefItem; else DefStr=num2str(DefItem); end
if isempty(m), strM=''; else strM=sprintf(' (<=%d)',m); end
if CmdLine
%-Process default item
%---------------------------------------------------------------
if ~isempty(DefItem)
[DefVal,msg] = sf_eEval(DefStr,Type(2),1);
if ischar(DefVal), error(['Invalid DefItem: ',msg]), end
Labels = strvcat(Labels,DefStr);
Values = [Values;DefVal];
DefItem = size(Labels,1);
end
%-Add option to specify...
Labels = strvcat(Labels,'specify...');
%-Process options
nLabels = size(Labels,1);
[Keys,Labs] = sf_labkeys(Labels);
if ~isempty(DefItem), DefKey = Keys(DefItem); else DefKey = ''; end
%-Print banner prompt
%---------------------------------------------------------------
spm_input('!PrntPrmpt',Prompt) %-Display question prompt
if Type(1)=='-' %-No special buttons - go straight to input
k = size(Labels,1);
else %-Offer buttons, default or "specify..."
%-Build prompt
%-------------------------------------------------------
if ~isempty(Labs)
Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' '];
for i = 2:nLabels
Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' '];
end
else
Prmpt = ['[',Keys(1),'] '];
for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end
end
if DefItem, Prmpt = [Prmpt,...
' (Default: ',deblank(Labels(DefItem,:)),')']; end
%-Ask for user response
%-------------------------------------------------------
if nLabels==1
%-Only one choice - auto-pick & display
k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels)
else
str = input([Prmpt,'? '],'s');
if isempty(str), str=DefKey; end
while isempty(str) || ~any(lower(Keys)==lower(str(1)))
if ~isempty(str),fprintf('%c\t!Invalid response\n',7),end
str = input([Prmpt,'? '],'s');
if isempty(str), str=DefKey; end
end
k = find(lower(Keys)==lower(str(1)));
end
fprintf('\n')
end
%-Process response: prompt for value if "specify..." option chosen
%===============================================================
if k<size(Labels,1)
p = Values(k,:); if ischar(p), p=deblank(p); end
else
%-"specify option chosen: ask user to specify
%-------------------------------------------------------
switch lower(Type(2))
case 's', tstr=' string';
case 'e', tstr='n expression';
case 'n', tstr=' natural number';
case 'w', tstr=' whole number';
case 'i', tstr='n integer';
case 'r', tstr=' real number';
otherwise, tstr='';
end
Prompt = sprintf('%s (a%s%s)',Prompt,tstr,strM);
if ~isempty(DefStr)
Prompt=sprintf('%s\b, default %s)',Prompt,DefStr); end
str = input([Prompt,' : '],'s');
if isempty(str), str=DefStr; end
%-Eval in Base workspace, catch errors
[p,msg] = sf_eEval(str,Type(2),1,m);
while ischar(p)
spm('Beep'), fprintf('! %s : %s\n',mfilename,msg)
str = input([Prompt,' : '],'s');
if isempty(str), str=DefStr; end
[p,msg] = sf_eEval(str,Type(2),1,m);
end
end
else
Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets
nLabels = size(Labels,1); %-#buttons
%-Create text and edit control objects
%-'UserData' of prompt contains answer
%---------------------------------------------------------------
hPrmpt = uicontrol(Finter,'Style','Text',...
'String',[Prompt,strM],...
'Tag',Tag,...
'UserData',[],...
'BackgroundColor',COLOUR,...
'HorizontalAlignment','Right',...
'Position',PRec);
if TTips, set(hPrmpt,'ToolTipString',[Prompt,strM]); end
%-Draw buttons & entry widget, & process response
dX = RRec(3)*(2/3)/nLabels;
%-Store button # in buttons 'UserData'
%-Store handle of prompt string in buttons 'Max' property
%-Callback sets UserData of prompt string to button number.
cb = ['set(get(gcbo,''Max''),''UserData'',get(gcbo,''UserData''))'];
if TTips, str=sprintf('select by mouse or enter value in text widget');
else str=''; end
H = [];
for i=1:nLabels
h = uicontrol(Finter,'Style','Pushbutton',...
'String',deblank(Labels(i,:)),...
'Max',hPrmpt,...
'ToolTipString',sprintf('%s\n%s',deblank(Labels(i,:)),str),...
'Tag',Tag,...
'UserData',i,...
'BackgroundColor',COLOUR,...
'Callback',cb,...
'Position',[RRec(1)+(i-1)*dX+1 RRec(2) dX-2 RRec(4)]);
H = [H,h];
end
%-Default button surrounding edit widget (if a DefStr given)
%-Callback sets hPrmpt UserData, and EditWidget string, to DefStr
% (Buttons UserData holds handles [hPrmpt,hEditWidget], set later)
cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',...
'get(gcbo,''String'')),',...
'set(get(gcbo,''UserData'')*[0;1],''String'',',...
'get(gcbo,''String''))'];
if ~isempty(DefStr)
hDef = uicontrol(Finter,'Style','PushButton',...
'String',DefStr,...
'ToolTipString',['Click on border to accept ',...
'default: ' DefStr],...
'Tag',Tag,...
'UserData',[],...
'CallBack',cb,...
'BackgroundColor',COLOUR,...
'Position',...
[RRec(1)+RRec(3)*(2/3) RRec(2)-2 RRec(3)/3+2 RRec(4)+4]);
H = [H,hDef];
else
hDef = [];
end
%-Edit widget: Callback puts string into hPrompts UserData
cb = ['set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))'];
h = uicontrol(Finter,'Style','Edit',...
'String',DefStr,...
'ToolTipString',str,...
'Tag',Tag,...
'UserData',hPrmpt,...
'CallBack',cb,...
'Horizontalalignment','Center',...
'BackgroundColor','w',...
'Position',...
[RRec(1)+RRec(3)*(2/3)+2 RRec(2) RRec(3)/3-2 RRec(4)]);
set(hDef,'UserData',[hPrmpt,h])
uifocus(h);
H = [H,h];
%-Figure ContextMenu for shortcuts
hM = spm_input('!InptConMen',Finter,[hPrmpt,H]);
%-Bring window to fore & jump pointer to default button
[PLoc,cF] = spm_input('!PointerJump',RRec,Finter,RRec(3)*0.95);
%-Setup FigureKeyPressFcn for editing of entry widget without clicking
set(Finter,'KeyPressFcn',[...
'spm_input(''!EditableKeyPressFcn'',',...
'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',...
'''Style'',''edit''),',...
'get(gcbf,''CurrentCharacter''))'])
%-Wait for button press, process results
%---------------------------------------------------------------
waitfor(hPrmpt,'UserData')
if ~ishandle(hPrmpt), error(['Input objects cleared whilst waiting ',...
'for response: Bailing out!']), end
p = get(hPrmpt,'UserData');
if ~ischar(p)
k = p;
p = Values(k,:); if ischar(p), p=deblank(p); end
else
Labels = strvcat(Labels,'specify...');
k = size(Labels,1);
[p,msg] = sf_eEval(p,Type(2),1,m);
while ischar(p)
set(H,'Visible','off')
h = uicontrol('Style','Text','String',msg,...
'Horizontalalignment','Center',...
'ForegroundColor','r',...
'BackgroundColor',COLOUR,...
'Tag',Tag,'Position',RRec);
spm('Beep')
pause(2), delete(h), set(H,'Visible','on')
set(hPrmpt,'UserData','')
waitfor(hPrmpt,'UserData')
if ~ishandle(hPrmpt), error(['Input objects cleared ',...
'whilst waiting for response: Bailing out!']),end
p = get(hPrmpt,'UserData');
if ischar(p), [p,msg] = sf_eEval(p,Type(2),1,m); end
end
end
%-Clean up
delete([H,hM]), set(Finter,'KeyPressFcn','')
spm_input('!PointerJumpBack',PLoc,cF)
%-Display answer
uicontrol(Finter,'Style','Text',...
'String',num2str(p),...
'Tag',Tag,...
'Horizontalalignment','Center',...
'BackgroundColor',COLOUR,...
'Position',RRec);
drawnow
end % (if CmdLine)
case 'm' %-Process menu type
%=======================================================================
nLabels = size(Labels,1);
if ~isempty(DefItem) && ~any(DefItem==[1:nLabels]), DefItem=[]; end
%-Process pull down menu type
if CmdLine
spm_input('!PrntPrmpt',Prompt)
nLabels = size(Labels,1);
for i = 1:nLabels, fprintf('\t%2d : %s\n',i,Labels(i,:)), end
Prmpt = ['Menu choice (1-',int2str(nLabels),')'];
if DefItem
Prmpt=[Prmpt,' (Default: ',num2str(DefItem),')'];
end
%-Ask for user response
%-------------------------------------------------------
if nLabels==1
%-Only one choice - auto-pick & display
k = 1;
fprintf('Menu choice: 1 - %s\t(only option)',Labels)
else
k = input([Prmpt,' ? ']);
if DefItem && isempty(k), k=DefItem; end
while isempty(k) || ~any([1:nLabels]==k)
if ~isempty(k),fprintf('%c\t!Out of range\n',7),end
k = input([Prmpt,' ? ']);
if DefItem && isempty(k), k=DefItem; end
end
end
fprintf('\n')
else
Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets
if nLabels==1
%-Only one choice - auto-pick
k = 1;
else
Labs=[repmat(' ',nLabels,2),Labels];
if DefItem
Labs(DefItem,1)='*';
H = uicontrol(Finter,'Style','Frame',...
'BackGroundColor','k',...
'ForeGroundColor','k',...
'Position',QRec+[-1,-1,+2,+2]);
else
H = [];
end
cb = ['if (get(gcbo,''Value'')>1),',...
'set(gcbo,''UserData'',''Selected''), end'];
hPopUp = uicontrol(Finter,'Style','PopUp',...
'HorizontalAlignment','Left',...
'ForegroundColor','k',...
'BackgroundColor',COLOUR,...
'String',strvcat([Prompt,'...'],Labs),...
'Tag',Tag,...
'UserData',DefItem,...
'CallBack',cb,...
'Position',QRec);
if TTips
cLabs = cellstr(Labels);
cInd = num2cell(1:nLabels);
scLabs = [cInd; cLabs'];
scLabs = sprintf('%d: %s\n',scLabs{:});
set(hPopUp,'ToolTipString',sprintf(['select with ',...
'mouse or type option number (1-',...
num2str(nLabels),') & press return\n%s'],scLabs));
end
%-Figure ContextMenu for shortcuts
hM = spm_input('!InptConMen',Finter,[hPopUp,H]);
%-Bring window to fore & jump pointer to menu widget
[PLoc,cF] = spm_input('!PointerJump',RRec,Finter);
%-Callback for KeyPresses
cb=['spm_input(''!PullDownKeyPressFcn'',',...
'findobj(gcf,''Tag'',''',Tag,'''),',...
'get(gcf,''CurrentCharacter''))'];
set(Finter,'KeyPressFcn',cb)
%-Wait for menu selection
%-----------------------------------------------
waitfor(hPopUp,'UserData')
if ~ishandle(hPopUp), error(['Input object cleared ',...
'whilst waiting for response: Bailing out!']),end
k = get(hPopUp,'Value')-1;
%-Clean up
delete([H,hM]), set(Finter,'KeyPressFcn','')
set(hPopUp,'Style','Text',...
'Horizontalalignment','Center',...
'String',deblank(Labels(k,:)),...
'BackgroundColor',COLOUR)
spm_input('!PointerJumpBack',PLoc,cF)
end
%-Display answer
uicontrol(Finter,'Style','Text',...
'String',deblank(Labels(k,:)),...
'Tag',Tag,...
'Horizontalalignment','Center',...
'BackgroundColor',COLOUR,...
'Position',QRec);
drawnow
end
p = Values(k,:); if ischar(p), p=deblank(p); end
otherwise, error('unrecognised type')
end % (switch lower(Type) within case {'b','b|','y/n'})
%-Return response
%-----------------------------------------------------------------------
varargout = {p,YPos};
case {'m!','b!'} %-GUI PullDown/Buttons utility
%=======================================================================
% H = spm_input(Prompt,YPos,'p',Labels,cb,UD,XCB)
%-Condition arguments
if nargin<7, XCB = 0; else XCB = varargin{7}; end
if nargin<6, UD = []; else UD = varargin{6}; end
if nargin<5, cb = ''; else cb = varargin{5}; end
if nargin<4, Labels = []; else Labels = varargin{4}; end
if CmdLine, error('Can''t do CmdLine GUI utilities!'), end
if isempty(cb), cb = 'disp(''(CallBack not set)'')'; end
if ischar(cb), cb = cellstr(cb); end
if length(cb)>1 && strcmpi(Type,'m!'), XCB=1; end
if iscellstr(Labels), Labels=char(Labels); end
%-Convert Labels "option" string to string matrix if required
if any(Labels=='|')
OptStr=Labels;
BarPos=find([OptStr=='|',1]);
Labels=OptStr(1:BarPos(1)-1);
for Bar = 2:sum(OptStr=='|')+1
Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1));
end
end
%-Check #CallBacks
if ~( length(cb)==1 || (length(cb)==size(Labels,1)) )
error('Labels & Callbacks size mismatch'), end
%-Draw Prompt
%-----------------------------------------------------------------------
Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets
if ~isempty(Prompt)
uicontrol(Finter,'Style','Text',...
'String',Prompt,...
'Tag',Tag,...
'HorizontalAlignment','Right',...
'BackgroundColor',COLOUR,...
'Position',PRec)
Rec = RRec;
else
Rec = QRec;
end
%-Sort out UserData for extended callbacks (handled by spm_input('!m_cb')
%-----------------------------------------------------------------------
if XCB, if iscell(UD), UD={UD}; end, UD = struct('UD',UD,'cb',{cb}); end
%-Draw PullDown or Buttons
%-----------------------------------------------------------------------
switch lower(Type), case 'm!'
if XCB, UD.cb=cb; cb = {'spm_input(''!m_cb'')'}; end
H = uicontrol(Finter,'Style','PopUp',...
'HorizontalAlignment','Left',...
'ForegroundColor','k',...
'BackgroundColor',COLOUR,...
'String',Labels,...
'Tag',Tag,...
'UserData',UD,...
'CallBack',char(cb),...
'Position',Rec);
case 'b!'
nLabels = size(Labels,1);
dX = Rec(3)/nLabels;
H = [];
for i=1:nLabels
if length(cb)>1, tcb=cb(i); else tcb=cb; end
if XCB, UD.cb=tcb; tcb = {'spm_input(''!m_cb'')'}; end
h = uicontrol(Finter,'Style','Pushbutton',...
'String',deblank(Labels(i,:)),...
'ToolTipString','',...
'Tag',Tag,...
'UserData',UD,...
'BackgroundColor',COLOUR,...
'Callback',char(tcb),...
'Position',[Rec(1)+(i-1)*dX+1 ...
Rec(2) dX-2 Rec(4)]);
H = [H,h];
end
end
%-Bring window to fore & jump pointer to menu widget
[PLoc,cF] = spm_input('!PointerJump',RRec,Finter);
varargout = {H};
case {'d','d!'} %-Display message
%=======================================================================
%-Condition arguments
if nargin<4, Label=''; else Label=varargin{4}; end
if CmdLine && strcmpi(Type,'d')
fprintf('\n +-%s%s+',Label,repmat('-',1,57-length(Label)))
Prompt = [Prompt,' '];
while ~isempty(Prompt)
tmp = length(Prompt);
if tmp>56, tmp=min([max(find(Prompt(1:56)==' ')),56]); end
fprintf('\n | %s%s |',Prompt(1:tmp),repmat(' ',1,56-tmp))
Prompt(1:tmp)=[];
end
fprintf('\n +-%s+\n',repmat('-',1,57))
elseif ~CmdLine
if ~isempty(Label), Prompt = [Label,': ',Prompt]; end
figure(Finter)
%-Create text axes and edit control objects
%---------------------------------------------------------------
h = uicontrol(Finter,'Style','Text',...
'String',Prompt(1:min(length(Prompt),56)),...
'FontWeight','bold',...
'Tag',['GUIinput_',int2str(YPos)],...
'HorizontalAlignment','Left',...
'ForegroundColor','k',...
'BackgroundColor',COLOUR,...
'UserData',Prompt,...
'Position',QRec);
if length(Prompt)>56
pause(1)
set(h,'ToolTipString',Prompt)
spm_input('!dScroll',h)
uicontrol(Finter,'Style','PushButton','String','>',...
'ToolTipString','press to scroll message',...
'Tag',['GUIinput_',int2str(YPos)],...
'UserData',h,...
'CallBack',[...
'set(gcbo,''Visible'',''off''),',...
'spm_input(''!dScroll'',get(gcbo,''UserData'')),',...
'set(gcbo,''Visible'',''on'')'],...
'BackgroundColor',COLOUR,...
'Position',[QRec(1)+QRec(3)-10,QRec(2),15,QRec(4)]);
end
end
if nargout>0, varargout={[],YPos}; end
%=======================================================================
% U T I L I T Y F U N C T I O N S
%=======================================================================
case '!colour'
%=======================================================================
% colour = spm_input('!Colour')
varargout = {COLOUR};
case '!icond'
%=======================================================================
% [iCond,msg] = spm_input('!iCond',str,n,m)
% Parse condition indicator spec strings:
% '2 3 2 3', '0 1 0 1', '2323', '0101', 'abab', 'R A R A'
if nargin<4, m=Inf; else m=varargin{4}; end
if nargin<3, n=NaN; else n=varargin{3}; end
if any(isnan(n(:)))
n=Inf;
elseif (length(n(:))==2 && ~any(n==1)) || length(n(:))>2
error('condition input can only do vectors')
end
if nargin<2, i=''; else i=varargin{2}; end
if isempty(i), varargout={[],'empty input'}; return, end
msg = ''; i=i(:)';
if ischar(i)
if i(1)=='0' && all(ismember(unique(i(:)),char(abs('0'):abs('9'))))
%-Leading zeros in a digit list
msg = sprintf('%s expanded',i);
z = min(find([diff(i=='0'),1]));
i = [zeros(1,z), spm_input('!iCond',i(z+1:end))'];
else
%-Try an eval, for functions & string #s
i = evalin('base',['[',i,']'],'i');
end
end
if ischar(i)
%-Evaluation error from above: see if it's an 'abab' or 'a b a b' type:
[c,null,i] = unique(lower(i(~isspace(i))));
if all(ismember(c,char(abs('a'):abs('z'))))
%-Map characters a-z to 1-26, but let 'r' be zero (rest)
tmp = c-'a'+1; tmp(tmp=='r'-'a'+1)=0;
i = tmp(i);
msg = [sprintf('[%s] mapped to [',c),...
sprintf('%d,',tmp(1:end-1)),...
sprintf('%d',tmp(end)),']'];
else
i = '!'; msg = 'evaluation error';
end
elseif ~all(floor(i(:))==i(:))
i = '!'; msg = 'must be integers';
elseif length(i)==1 && prod(n)>1
msg = sprintf('%d expanded',i);
i = floor(i./10.^[floor(log10(i)+eps):-1:0]);
i = i-[0,10*i(1:end-1)];
end
%-Check size of i & #conditions
if ~ischar(i), [i,msg] = sf_SzChk(i,n,msg); end
if ~ischar(i) && isfinite(m) && length(unique(i))~=m
i = '!'; msg = sprintf('%d conditions required',m);
end
varargout = {i,msg};
case '!inptconmen'
%=======================================================================
% hM = spm_input('!InptConMen',Finter,H)
if nargin<3, H=[]; else H=varargin{3}; end
if nargin<2, varargout={[]}; else Finter=varargin{2}; end
hM = uicontextmenu('Parent',Finter);
uimenu(hM,'Label','help on spm_input',...
'CallBack','spm_help(''spm_input.m'')')
if ConCrash
uimenu(hM,'Label','crash out','Separator','on',...
'CallBack','delete(get(gcbo,''UserData''))',...
'UserData',[hM,H])
end
set(Finter,'UIContextMenu',hM)
varargout={hM};
case '!cmdline'
%=======================================================================
% [CmdLine,YPos] = spm_input('!CmdLine',YPos)
%-Sorts out whether to use CmdLine or not & canonicalises YPos
if nargin<2, YPos=''; else YPos=varargin{2}; end
if isempty(YPos), YPos='+1'; end
CmdLine = [];
%-Special YPos specifications
if ischar(YPos)
if(YPos(1)=='!'), CmdLine=0; YPos(1)=[]; end
elseif YPos==0
CmdLine=1;
elseif YPos<0
CmdLine=0;
YPos=-YPos;
end
CmdLine = spm('CmdLine',CmdLine);
if CmdLine, YPos=0; end
varargout = {CmdLine,YPos};
case '!getwin'
%=======================================================================
% Finter = spm_input('!GetWin',F)
%-Locate (or create) figure to work in (Don't use 'Tag'ged figs)
if nargin<2, F='Interactive'; else F=varargin{2}; end
Finter = spm_figure('FindWin',F);
if isempty(Finter)
if ~isempty(get(0,'Children'))
if isempty(get(gcf,'Tag')), Finter = gcf;
else Finter = spm('CreateIntWin'); end
else Finter = spm('CreateIntWin'); end
end
varargout = {Finter};
case '!pointerjump'
%=======================================================================
% [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp)
%-Raise window & jump pointer over question
if nargin<4, XDisp=[]; else XDisp=varargin{4}; end
if nargin<3, F='Interactive'; else F=varargin{3}; end
if nargin<2, error('Insufficient arguments'), else RRec=varargin{2}; end
F = spm_figure('FindWin',F);
PLoc = get(0,'PointerLocation');
cF = get(0,'CurrentFigure');
if ~isempty(F)
figure(F)
FRec = get(F,'Position');
if isempty(XDisp), XDisp=RRec(3)*4/5; end
if PJump, set(0,'PointerLocation',...
floor([(FRec(1)+RRec(1)+XDisp), (FRec(2)+RRec(2)+RRec(4)/3)]));
end
end
varargout = {PLoc,cF};
case '!pointerjumpback'
%=======================================================================
% spm_input('!PointerJumpBack',PLoc,cF)
%-Replace pointer and reset CurrentFigure back
if nargin<4, cF=[]; else F=varargin{3}; end
if nargin<2, error('Insufficient arguments'), else PLoc=varargin{2}; end
if PJump, set(0,'PointerLocation',PLoc), end
cF = spm_figure('FindWin',cF);
if ~isempty(cF), set(0,'CurrentFigure',cF); end
case '!prntprmpt'
%=======================================================================
% spm_input('!PrntPrmpt',Prompt,TipStr,Title)
%-Print prompt for CmdLine questioning
if nargin<4, Title = ''; else Title = varargin{4}; end
if nargin<3, TipStr = ''; else TipStr = varargin{3}; end
if nargin<2, Prompt = ''; else Prompt = varargin{2}; end
if isempty(Prompt), Prompt='Enter an expression'; end
Prompt = cellstr(Prompt);
if ~isempty(TipStr)
tmp = 8 + length(Prompt{end}) + length(TipStr);
if tmp < 62
TipStr = sprintf('%s(%s)',repmat(' ',1,70-tmp),TipStr);
else
TipStr = sprintf('\n%s(%s)',repmat(' ',1,max(0,70-length(TipStr))),TipStr);
end
end
if isempty(Title)
fprintf('\n%s\n',repmat('~',1,72))
else
fprintf('\n= %s %s\n',Title,repmat('~',1,72-length(Title)-3))
end
fprintf('\t%s',Prompt{1})
for i=2:numel(Prompt), fprintf('\n\t%s',Prompt{i}), end
fprintf('%s\n%s\n',TipStr,repmat('~',1,72))
case '!inputrects'
%=======================================================================
% [Frec,QRec,PRec,RRec,Sz,Se] = spm_input('!InputRects',YPos,rec,F)
if nargin<4, F='Interactive'; else F=varargin{4}; end
if nargin<3, rec=''; else rec=varargin{3}; end
if nargin<2, YPos=1; else YPos=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('Figure not found'), end
Units = get(F,'Units');
set(F,'Units','pixels')
FRec = get(F,'Position');
set(F,'Units',Units);
Xdim = FRec(3); Ydim = FRec(4);
WS = spm('WinScale');
Sz = round(22*min(WS)); %-Height
Pd = Sz/2; %-Pad
Se = 2*round(25*min(WS)/2); %-Seperation
Yo = round(2*min(WS)); %-Y offset for responses
a = 5.5/10;
y = Ydim - Se*YPos;
QRec = [Pd y Xdim-2*Pd Sz]; %-Question
PRec = [Pd y floor(a*Xdim)-2*Pd Sz]; %-Prompt
RRec = [ceil(a*Xdim) y+Yo floor((1-a)*Xdim)-Pd Sz]; %-Response
% MRec = [010 y Xdim-50 Sz]; %-Menu PullDown
% BRec = MRec + [Xdim-50+1, 0+1, 50-Xdim+30, 0]; %-Menu PullDown OK butt
if ~isempty(rec)
varargout = {eval(rec)};
else
varargout = {FRec,QRec,PRec,RRec,Sz,Se};
end
case '!deleteinputobj'
%=======================================================================
% spm_input('!DeleteInputObj',F)
if nargin<2, F='Interactive'; else F=varargin{2}; end
h = spm_input('!FindInputObj',F);
delete(h(h>0))
case {'!currentpos','!findinputobj'}
%=======================================================================
% [CPos,hCPos] = spm_input('!CurrentPos',F)
% h = spm_input('!FindInputObj',F)
% hPos contains handles: Columns contain handles corresponding to Pos
if nargin<2, F='Interactive'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
%-Find tags and YPos positions of 'GUIinput_' 'Tag'ged objects
H = [];
YPos = [];
for h = get(F,'Children')'
tmp = get(h,'Tag');
if ~isempty(tmp)
if strcmp(tmp(1:min(length(tmp),9)),'GUIinput_')
H = [H, h];
YPos = [YPos, eval(tmp(10:end))];
end
end
end
switch lower(Type), case '!findinputobj'
varargout = {H};
case '!currentpos'
if nargout<2
varargout = {max(YPos),[]};
elseif isempty(H)
varargout = {[],[]};
else
%-Sort out
tmp = sort(YPos);
CPos = tmp(find([1,diff(tmp)]));
nPos = length(CPos);
nPerPos = diff(find([1,diff(tmp),1]));
hCPos = zeros(max(nPerPos),nPos);
for i = 1:nPos
hCPos(1:nPerPos(i),i) = H(YPos==CPos(i))';
end
varargout = {CPos,hCPos};
end
end
case '!nextpos'
%=======================================================================
% [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine)
%-Return next position to use
if nargin<3, F='Interactive'; else F=varargin{3}; end
if nargin<2, YPos='+1'; else YPos=varargin{2}; end
if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos);
else CmdLine=varargin{4}; end
F = spm_figure('FindWin',F);
%-Get current positions
if nargout<3
CPos = spm_input('!CurrentPos',F);
hCPos = [];
else
[CPos,hCPos] = spm_input('!CurrentPos',F);
end
if CmdLine
NPos = 0;
else
MPos = spm_input('!MaxPos',F);
if ischar(YPos)
%-Relative YPos
%-Strip any '!' prefix from YPos
if(YPos(1)=='!'), YPos(1)=[]; end
if strncmp(YPos,'_',1)
%-YPos='_' means bottom
YPos=eval(['MPos+',YPos(2:end)],'MPos');
else
YPos = max([0,CPos])+eval(YPos);
end
else
%-Absolute YPos
YPos=abs(YPos);
end
NPos = min(max(1,YPos),MPos);
end
varargout = {NPos,CPos,hCPos};
case '!setnextpos'
%=======================================================================
% NPos = spm_input('!SetNextPos',YPos,F,CmdLine)
%-Set next position to use
if nargin<3, F='Interactive'; else F=varargin{3}; end
if nargin<2, YPos='+1'; else YPos=varargin{2}; end
if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos);
else CmdLine=varargin{4}; end
%-Find out which Y-position to use
[NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine);
%-Delete any previous inputs using positions NPos and after
if any(CPos>=NPos), h=hCPos(:,CPos>=NPos); delete(h(h>0)), end
varargout = {NPos};
case '!maxpos'
%=======================================================================
% MPos = spm_input('!MaxPos',F,FRec3)
%
if nargin<3
if nargin<2, F='Interactive'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F)
FRec3=spm('WinSize','Interactive')*[0;0;0;1];
else
%-Get figure size
Units = get(F,'Units');
set(F,'Units','pixels')
FRec3 = get(F,'Position')*[0;0;0;1];
set(F,'Units',Units);
end
end
Se = round(25*min(spm('WinScale')));
MPos = floor((FRec3-5)/Se);
varargout = {MPos};
case '!editablekeypressfcn'
%=======================================================================
% spm_input('!EditableKeyPressFcn',h,ch,hPrmpt)
if nargin<2, error('Insufficient arguments'), else h=varargin{2}; end
if isempty(h), set(gcbf,'KeyPressFcn','','UserData',[]), return, end
if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else ch=varargin{3};end
if nargin<4, hPrmpt=get(h,'UserData'); else hPrmpt=varargin{4}; end
tmp = get(h,'String');
if isempty(tmp), tmp=''; end
if iscellstr(tmp) && length(tmp)==1; tmp=tmp{:}; end
if isempty(ch) %- shift / control / &c. pressed
return
elseif any(abs(ch)==[32:126]) %-Character
if iscellstr(tmp), return, end
tmp = [tmp, ch];
elseif abs(ch)==21 %- ^U - kill
tmp = '';
elseif any(abs(ch)==[8,127]) %-BackSpace or Delete
if iscellstr(tmp), return, end
if ~isempty(tmp), tmp(length(tmp))=''; end
elseif abs(ch)==13 %-Return pressed
if ~isempty(tmp)
set(hPrmpt,'UserData',get(h,'String'))
end
return
else
%-Illegal character
return
end
set(h,'String',tmp)
case '!buttonkeypressfcn'
%=======================================================================
% spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch)
%-Callback for KeyPress, to store valid button # in UserData of Prompt,
% DefItem if (DefItem~=0) & return (ASCII-13) is pressed
%-Condition arguments
if nargin<2, error('Insufficient arguments'), else h=varargin{2}; end
if isempty(h), set(gcf,'KeyPressFcn','','UserData',[]), return, end
if nargin<3, error('Insufficient arguments'); else Keys=varargin{3}; end
if nargin<4, DefItem=0; else DefItem=varargin{4}; end
if nargin<5, ch=get(gcf,'CurrentCharacter'); else ch=varargin{5}; end
if isempty(ch)
%- shift / control / &c. pressed
return
elseif (DefItem && ch==13)
But = DefItem;
else
But = find(lower(ch)==lower(Keys));
end
if ~isempty(But), set(h,'UserData',But), end
case '!pulldownkeypressfcn'
%=======================================================================
% spm_input('!PullDownKeyPressFcn',h,ch,DefItem)
if nargin<2, error('Insufficient arguments'), else h=varargin{2}; end
if isempty(h), set(gcf,'KeyPressFcn',''), return, end
if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else ch=varargin{3};end
if nargin<4, DefItem=get(h,'UserData'); else ch=varargin{4}; end
Pmax = get(h,'Max');
Pval = get(h,'Value');
if Pmax==1, return, end
if isempty(ch)
%- shift / control / &c. pressed
return
elseif abs(ch)==13
if Pval==1
if DefItem, set(h,'Value',max(2,min(DefItem+1,Pmax))), end
else
set(h,'UserData','Selected')
end
elseif any(ch=='bpu')
%-Move "b"ack "u"p to "p"revious entry
set(h,'Value',max(2,Pval-1))
elseif any(ch=='fnd')
%-Move "f"orward "d"own to "n"ext entry
set(h,'Value',min(Pval+1,Pmax))
elseif any(ch=='123456789')
%-Move to entry n
set(h,'Value',max(2,min(eval(ch)+1,Pmax)))
else
%-Illegal character
end
case '!m_cb' %-CallBack handler for extended CallBack 'p'ullDown type
%=======================================================================
% spm_input('!m_cb')
%-Get PopUp handle and value
h = gcbo;
n = get(h,'Value');
%-Get PopUp's UserData, check cb and UD fields exist, extract cb & UD
tmp = get(h,'UserData');
if ~(isfield(tmp,'cb') && isfield(tmp,'UD'))
error('Invalid UserData structure for spm_input extended callback')
end
cb = tmp.cb;
UD = tmp.UD;
%-Evaluate appropriate CallBack string (ignoring any return arguments)
% NB: Using varargout={eval(cb{n})}; gives an error if the CallBack
% has no return arguments!
if length(cb)==1, eval(char(cb)); else eval(cb{n}); end
case '!dscroll'
%=======================================================================
% spm_input('!dScroll',h,Prompt)
%-Scroll text in object h
if nargin<2, return, else h=varargin{2}; end
if nargin<3, Prompt = get(h,'UserData'); else Prompt=varargin{3}; end
tmp = Prompt;
if length(Prompt)>56
while length(tmp)>56
tic, while(toc<0.1), pause(0.05), end
tmp(1)=[];
set(h,'String',tmp(1:min(length(tmp),56)))
end
pause(1)
set(h,'String',Prompt(1:min(length(Prompt),56)))
end
otherwise
%=======================================================================
error(['Invalid type/action: ',Type])
%=======================================================================
end % (case lower(Type))
%=======================================================================
%- S U B - F U N C T I O N S
%=======================================================================
function [Keys,Labs] = sf_labkeys(Labels)
%=======================================================================
%-Make unique character keys for the Labels, ignoring case
if nargin<1, error('insufficient arguments'), end
if iscellstr(Labels), Labels = char(Labels); end
if isempty(Labels), Keys=''; Labs=''; return, end
Keys=Labels(:,1)';
nLabels = size(Labels,1);
if any(~diff(abs(sort(lower(Keys)))))
if nLabels<10
Keys = sprintf('%d',[1:nLabels]);
elseif nLabels<=26
Keys = sprintf('%c',abs('a')+[0:nLabels-1]);
else
error('Too many buttons!')
end
Labs = Labels;
else
Labs = Labels(:,2:end);
end
function [p,msg] = sf_eEval(str,Type,n,m)
%=======================================================================
%-Evaluation and error trapping of typed input
if nargin<4, m=[]; end
if nargin<3, n=[]; end
if nargin<2, Type='e'; end
if nargin<1, str=''; end
if isempty(str), p='!'; msg='empty input'; return, end
switch lower(Type)
case 's'
p = str; msg = '';
case 'e'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
else
[p,msg] = sf_SzChk(p,n);
end
case 'n'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif any(floor(p(:))~=p(:)|p(:)<1)||~isreal(p)
p='!'; msg='natural number(s) required';
elseif ~isempty(m) && any(p(:)>m)
p='!'; msg=['max value is ',num2str(m)];
else
[p,msg] = sf_SzChk(p,n);
end
case 'w'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif any(floor(p(:))~=p(:)|p(:)<0)||~isreal(p)
p='!'; msg='whole number(s) required';
elseif ~isempty(m) && any(p(:)>m)
p='!'; msg=['max value is ',num2str(m)];
else
[p,msg] = sf_SzChk(p,n);
end
case 'i'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif any(floor(p(:))~=p(:))||~isreal(p)
p='!'; msg='integer(s) required';
else
[p,msg] = sf_SzChk(p,n);
end
case 'p'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif ~isempty(setxor(p(:)',m))
p='!'; msg='invalid permutation';
else
[p,msg] = sf_SzChk(p,n);
end
case 'r'
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
elseif ~isreal(p)
p='!'; msg='real number(s) required';
elseif ~isempty(m) && ( max(p)>max(m) || min(p)<min(m) )
p='!'; msg=sprintf('real(s) in [%g,%g] required',min(m),max(m));
else
[p,msg] = sf_SzChk(p,n);
end
case 'c'
if isempty(m), m=Inf; end
[p,msg] = spm_input('!iCond',str,n,m);
case 'x'
X = m; %-Design matrix/space-structure
if isempty(n), n=1; end
%-Sort out contrast matrix dimensions (contrast vectors in rows)
if length(n)==1, n=[n,Inf]; else n=reshape(n(1:2),1,2); end
if ~isempty(X) % - override n(2) w/ design column dimension
n(2) = spm_SpUtil('size',X,2);
end
p = evalin('base',['[',str,']'],'''!''');
if ischar(p)
msg = 'evaluation error';
else
if isfinite(n(2)) && size(p,2)<n(2)
tmp = n(2) -size(p,2);
p = [p, zeros(size(p,1),tmp)];
if size(p,1)>1, str=' columns'; else str='s'; end
msg = sprintf('right padded with %d zero%s',tmp,str);
else
msg = '';
end
if size(p,2)>n(2)
p='!'; msg=sprintf('too long - only %d prams',n(2));
elseif isfinite(n(1)) && size(p,1)~=n(1)
p='!';
if n(1)==1, msg='vector required';
else msg=sprintf('%d contrasts required',n(1)); end
elseif ~isempty(X) && ~spm_SpUtil('allCon',X,p')
p='!'; msg='invalid contrast';
end
end
otherwise
error('unrecognised type');
end
function str = sf_SzStr(n,l)
%=======================================================================
%-Size info string construction
if nargin<2, l=0; else l=1; end
if nargin<1, error('insufficient arguments'), end
if isempty(n), n=NaN; end
n=n(:); if length(n)==1, n=[n,1]; end, dn=length(n);
if any(isnan(n)) || (prod(n)==1 && dn<=2) || (dn==2 && min(n)==1 && isinf(max(n)))
str = ''; lstr = '';
elseif dn==2 && min(n)==1
str = sprintf('[%d]',max(n)); lstr = [str,'-vector'];
elseif dn==2 && sum(isinf(n))==1
str = sprintf('[%d]',min(n)); lstr = [str,'-vector(s)'];
else
str='';
for i = 1:dn
if isfinite(n(i)), str = sprintf('%s,%d',str,n(i));
else str = sprintf('%s,*',str); end
end
str = ['[',str(2:end),']']; lstr = [str,'-matrix'];
end
if l, str=sprintf('\t%s',lstr); else str=[str,' ']; end
function [p,msg] = sf_SzChk(p,n,msg)
%=======================================================================
%-Size checking
if nargin<3, msg=''; end
if nargin<2, n=[]; end, if isempty(n), n=NaN; else n=n(:)'; end
if nargin<1, error('insufficient arguments'), end
if ischar(p) || any(isnan(n(:))), return, end
if length(n)==1, n=[n,1]; end
dn = length(n);
sp = size(p);
dp = ndims(p);
if dn==2 && min(n)==1
%-[1,1], [1,n], [n,1], [1,Inf], [Inf,1] - vector - allow transpose
%---------------------------------------------------------------
i = min(find(n==max(n)));
if n(i)==1 && max(sp)>1
p='!'; msg='scalar required';
elseif ndims(p)~=2 || ~any(sp==1) || ( isfinite(n(i)) && max(sp)~=n(i) )
%-error: Not2D | not vector | not right length
if isfinite(n(i)), str=sprintf('%d-',n(i)); else str=''; end
p='!'; msg=[str,'vector required'];
elseif sp(i)==1 && n(i)~=1
p=p'; msg=[msg,' (input transposed)'];
end
elseif dn==2 && sum(isinf(n))==1
%-[n,Inf], [Inf,n] - n vector(s) required - allow transposing
%---------------------------------------------------------------
i = find(isfinite(n));
if ndims(p)~=2 || ~any(sp==n(i))
p='!'; msg=sprintf('%d-vector(s) required',min(n));
elseif sp(i)~=n
p=p'; msg=[msg,' (input transposed)'];
end
else
%-multi-dimensional matrix required - check dimensions
%---------------------------------------------------------------
if ndims(p)~=dn || ~all( size(p)==n | isinf(n) )
p = '!'; msg='';
for i = 1:dn
if isfinite(n(i)), msg = sprintf('%s,%d',msg,n(i));
else msg = sprintf('%s,*',msg); end
end
msg = ['[',msg(2:end),']-matrix required'];
end
end
%==========================================================================
function uifocus(h)
try
if strcmpi(get(h, 'Style'), 'PushButton') == 1
uicontrol(gcbo);
else
uicontrol(h);
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_realign.m
|
.m
|
antx-master/xspm8/spm_realign.m
| 18,390 |
utf_8
|
40c5bf8bb41fe8dfc414a2afccf6270d
|
function P = spm_realign(P,flags)
% Estimation of within modality rigid body movement parameters
% FORMAT P = spm_realign(P,flags)
%
% 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:
% 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.
%
% interp - B-spline degree used for interpolation
%
%__________________________________________________________________________
%
% Inputs
% A series of *.img conforming to SPM data format (see 'Data Format').
%
% Outputs
% If no output argument, then an updated voxel to world matrix is written
% to the headers of the images (a .mat file is created for 4D 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:
% rp_*.txt.
%__________________________________________________________________________
%
% The voxel to world mappings.
%
% These are simply 4x4 affine transformation matrices represented in the
% NIFTI headers (see http://nifti.nimh.nih.gov/nifti-1 ).
% These are normally modified by the `realignment' and `coregistration'
% modules. What these matrixes represent 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).
%
% 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 matrices 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.
%__________________________________________________________________________
% Ref:
% Friston KJ, Ashburner J, Frith CD, Poline J-B, Heather JD & Frackowiak
% RSJ (1995) Spatial registration and normalization of images Hum. Brain
% Map. 2:165-189
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_realign.m 6071 2014-06-27 12:52:33Z guillaume $
if nargin==0, return; end;
def_flags = spm_get_defaults('realign.estimate');
def_flags.PW = '';
def_flags.graphics = 1;
def_flags.lkp = 1:6;
if nargin < 2,
flags = def_flags;
else
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags.(fnms{i}) = def_flags.(fnms{i});
end;
end;
end;
if ~iscell(P), tmp = cell(1); tmp{1} = P; P = tmp; end;
for i=1:length(P), if ischar(P{i}), P{i} = spm_vol(P{i}); end; end;
if ~isempty(flags.PW) && ischar(flags.PW), flags.PW = spm_vol(flags.PW); end;
% Remove empty cells
PN = {};
j = 1;
for i=1:length(P),
if ~isempty(P{i}), PN{j} = P{i}; j = j+1; end;
end;
P = PN;
if isempty(P), warning('Nothing to do'); return; end;
if length(P)==1,
P{1} = realign_series(P{1},flags);
if nargout==0, save_parameters(P{1}); end;
else
Ptmp = P{1}(1);
for s=2:numel(P),
Ptmp = [Ptmp ; P{s}(1)];
end;
Ptmp = realign_series(Ptmp,flags);
for s=1:numel(P),
M = Ptmp(s).mat*inv(P{s}(1).mat);
for i=1:numel(P{s}),
P{s}(i).mat = M*P{s}(i).mat;
end;
end;
for s=1:numel(P),
P{s} = realign_series(P{s},flags);
if nargout==0, save_parameters(P{s}); end;
end;
end;
if nargout==0,
% Save Realignment Parameters
%---------------------------------------------------------------------------
for s=1:numel(P),
for i=1:numel(P{s}),
spm_get_space([P{s}(i).fname ',' num2str(P{s}(i).n)], P{s}(i).mat);
end;
end;
end;
if flags.graphics, plot_parameters(P); end;
if length(P)==1, P=P{1}; end;
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 numel(P)<2, return; end;
skip = sqrt(sum(P(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
d = P(1).dim(1:3);
lkp = flags.lkp;
rand('state',0); % want the results to be consistant.
if d(3) < 3,
lkp = [1 2 6];
[x1,x2,x3] = ndgrid(1:skip(1):d(1)-.5, 1:skip(2):d(2)-.5, 1:skip(3):d(3));
x1 = x1 + rand(size(x1))*0.5;
x2 = x2 + rand(size(x2))*0.5;
else
[x1,x2,x3]=ndgrid(1:skip(1):d(1)-.5, 1:skip(2):d(2)-.5, 1:skip(3):d(3)-.5);
x1 = x1 + rand(size(x1))*0.5;
x2 = x2 + rand(size(x2))*0.5;
x3 = x3 + rand(size(x3))*0.5;
end;
x1 = x1(:);
x2 = x2(:);
x3 = x3(:);
% Possibly mask an area of the sample volume.
%-----------------------------------------------------------------------
if ~isempty(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;
% Compute rate of change of chi2 w.r.t changes in parameters (matrix A)
%-----------------------------------------------------------------------
V = smooth_vol(P(1),flags.interp,flags.wrap,flags.fwhm);
deg = [flags.interp*[1 1 1]' flags.wrap(:)];
[G,dG1,dG2,dG3] = spm_bsplins(V,x1,x2,x3,deg);
clear V
A0 = make_A(P(1).mat,x1,x2,x3,dG1,dG2,dG3,wt,lkp);
b = G;
if ~isempty(wt), b = b.*wt; end;
%-----------------------------------------------------------------------
if numel(P) > 2,
% Remove voxels that contribute very little to the final estimate.
% Simulated annealing or something similar could be used to
% eliminate a better choice of voxels - but this way will do for
% now. It basically involves removing the voxels that contribute
% least to the determinant of the inverse covariance matrix.
spm_plot_convergence('Init','Eliminating Unimportant Voxels',...
'Relative quality','Iteration');
Alpha = [A0 b];
Alpha = Alpha'*Alpha;
det0 = det(Alpha);
det1 = det0;
spm_plot_convergence('Set',det1/det0);
while det1/det0 > flags.quality,
dets = zeros(size(A0,1),1);
for i=1:size(A0,1),
tmp = [A0(i,:) b(i)];
dets(i) = det(Alpha - tmp'*tmp);
end;
clear tmp
[junk,msk] = sort(det1-dets);
msk = msk(1:round(length(dets)/10));
A0(msk,:) = []; b(msk,:) = []; G(msk,:) = [];
x1(msk,:) = []; x2(msk,:) = []; x3(msk,:) = [];
dG1(msk,:) = []; dG2(msk,:) = []; dG3(msk,:) = [];
if ~isempty(wt), wt(msk,:) = []; end;
Alpha = [A0 b];
Alpha = Alpha'*Alpha;
det1 = det(Alpha);
spm_plot_convergence('Set',single(det1/det0));
end;
spm_plot_convergence('Clear');
end;
%-----------------------------------------------------------------------
if flags.rtm,
count = ones(size(b));
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.interp,flags.wrap,flags.fwhm);
d = [size(V) 1 1];
d = d(1:3);
ss = Inf;
countdown = -1;
for iter=1:64,
[y1,y2,y3] = coords([0 0 0 0 0 0],P(1).mat,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_bsplins(V, y1(msk),y2(msk),y3(msk),deg);
if ~isempty(wt), F = F.*wt(msk); end;
A = A0(msk,:);
b1 = b(msk);
sc = sum(b1)/sum(F);
b1 = b1-F*sc;
soln = (A'*A)\(A'*b1);
p = [0 0 0 0 0 0 1 1 1 0 0 0];
p(lkp) = p(lkp) + soln';
P(i).mat = inv(spm_matrix(p))*P(i).mat;
pss = ss;
ss = sum(b1.^2)/length(b1);
if (pss-ss)/pss < 1e-8 && countdown == -1, % Stopped converging.
countdown = 2;
end;
if countdown ~= -1,
if countdown==0, break; end;
countdown = countdown -1;
end;
end;
if 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_bsplins(V,y1(msk),y2(msk),y3(msk),deg);
ave(msk) = ave(msk) + G*sc;
grad1(msk) = grad1(msk) + dG1*sc;
grad2(msk) = grad2(msk) + dG2*sc;
grad3(msk) = grad3(msk) + dG3*sc;
end;
spm_progress_bar('Set',i-1);
end;
spm_progress_bar('Clear');
if ~flags.rtm, return; end;
%_______________________________________________________________________
M=P(1).mat;
A0 = make_A(M,x1,x2,x3,grad1./count,grad2./count,grad3./count,wt,lkp);
if ~isempty(wt), b = (ave./count).*wt;
else b = (ave./count); end
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.interp,flags.wrap,flags.fwhm);
d = [size(V) 1 1 1];
ss = Inf;
countdown = -1;
for iter=1:64,
[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_bsplins(V, y1(msk),y2(msk),y3(msk),deg);
if ~isempty(wt), F = F.*wt(msk); end;
A = A0(msk,:);
b1 = b(msk);
sc = sum(b1)/sum(F);
b1 = b1-F*sc;
soln = (A'*A)\(A'*b1);
p = [0 0 0 0 0 0 1 1 1 0 0 0];
p(lkp) = p(lkp) + soln';
P(i).mat = inv(spm_matrix(p))*P(i).mat;
pss = ss;
ss = sum(b1.^2)/length(b1);
if (pss-ss)/pss < 1e-8 && countdown == -1 % Stopped converging.
% Do three final iterations to finish off with
countdown = 2;
end;
if countdown ~= -1
if countdown==0, break; end;
countdown = countdown -1;
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)*inv(spm_matrix(p))*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,hld,wrp,fwhm)
% 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;
d = [hld*[1 1 1]' wrp(:)];
V = spm_bsplinc(P,d);
spm_conv_vol(V,V,x,y,z,-[i j k]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function A = make_A(M,x1,x2,x3,dG1,dG2,dG3,wt,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(numel(x1),length(lkp));
for i=1:length(lkp)
pt = p0;
pt(lkp(i)) = pt(i)+1e-6;
[y1,y2,y3] = coords(pt,M,M,x1,x2,x3);
tmp = sum([y1-x1 y2-x2 y3-x3].*[dG1 dG2 dG3],2)/(-1e-6);
if ~isempty(wt), A(:,i) = tmp.*wt;
else A(:,i) = tmp; end
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.',...
'The Check Reg utility will show you the initial',...
'alignment between the images, which must be',...
'within about 4cm and about 15 degrees in order',...
'for SPM to find the optimal solution.'};
spm('alert*',str,mfilename,sqrt(-1));
error('insufficient image overlap')
%_______________________________________________________________________
%_______________________________________________________________________
function plot_parameters(P)
fg=spm_figure('FindWin','Graphics');
if ~isempty(fg),
P = cat(1,P{:});
if length(P)<2, return; end;
Params = zeros(numel(P),12);
for i=1:numel(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','FontSize',16,'FontWeight','Bold','Visible','on');
x = 0.1;
y = 0.9;
for i = 1:min([numel(P) 12])
text(x,y,[sprintf('%-4.0f',i) P(i).fname],'FontSize',10,'Interpreter','none','Parent',ax);
y = y - 0.08;
end
if numel(P) > 12
text(x,y,'................ etc','FontSize',10,'Parent',ax); end
ax=axes('Position',[0.1 0.35 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on',...
'NextPlot','replacechildren','ColorOrder',[0 0 1;0 0.5 0;1 0 0]);
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, s, 'Location','Best')
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',...
'NextPlot','replacechildren','ColorOrder',[0 0 1;0 0.5 0;1 0 0]);
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, s, 'Location','Best')
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,'rp_'),'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,vr] = spm_fileparts(deblank(PI));
PO = fullfile(pth,[pre nm xt vr]);
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_surf.m
|
.m
|
antx-master/xspm8/spm_surf.m
| 9,740 |
utf_8
|
aa92ddde8b875463a0fefee45e0a1d79
|
function varargout = spm_surf(P,mode,thresh)
% Surface extraction
% FORMAT spm_surf(P,mode,thresh)
%
% P - char array of filenames
% Usually, this will be c1xxx.img & c2xxx.img - grey and white
% matter segments created using the segmentation routine.
% mode - operation mode [1: rendering, 2: surface, 3: both]
% thresh - vector or threshold values for extraction [default: 0.5]
% This is only relevant for extracting surfaces, not rendering.
%
% Generated files (depending on 'mode'):
% A "render_xxx.mat" file can be produced that can be used for
% rendering activations on to, see spm_render.
%
% A "xxx.surf.gii" file can also be written, which is created using
% Matlab's isosurface function.
% This extracted brain surface can be viewed using code something like:
% FV = gifti(spm_select(1,'mesh','Select surface data'));
% FV = export(FV,'patch');
% fg = spm_figure('GetWin','Graphics');
% ax = axes('Parent',fg);
% p = patch(FV, 'Parent',ax,...
% 'FaceColor', [0.8 0.7 0.7], 'FaceVertexCData', [],...
% 'EdgeColor', 'none',...
% 'FaceLighting', 'phong',...
% 'SpecularStrength' ,0.7, 'AmbientStrength', 0.1,...
% 'DiffuseStrength', 0.7, 'SpecularExponent', 10);
% set(0,'CurrentFigure',fg);
% set(fg,'CurrentAxes',ax);
% l = camlight(-40, 20);
% axis image;
% rotate3d on;
%
% FORMAT out = spm_surf(job)
%
% Input
% A job structure with fields
% .data - cell array of filenames
% .mode - operation mode
% .thresh - thresholds for extraction
% Output
% A struct with fields (depending on operation mode)
% .rendfile - cellstring containing render filename
% .surffile - cellstring containing surface filename(s)
%__________________________________________________________________________
%
% This surface extraction is not particularly sophisticated. It simply
% smooths the data slightly and extracts the surface at a threshold of
% 0.5. The input segmentation images can be manually cleaned up first using
% e.g., MRIcron.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_surf.m 4341 2011-06-03 11:24:02Z john $
SVNrev = '$Rev: 4341 $';
spm('FnBanner',mfilename,SVNrev);
spm('FigName','Surface');
%-Get input: filenames 'P'
%--------------------------------------------------------------------------
try
if isstruct(P)
job = P;
P = strvcat(job.data);
mode = job.mode;
thresh = job.thresh;
end
catch
[P, sts] = spm_select([1 Inf],'image','Select images');
if ~sts, varargout = {}; return; end
end
%-Get input: operation mode 'mode'
%--------------------------------------------------------------------------
try
mode;
catch
mode = spm_input('Save','+1','m',...
['Save Rendering|'...
'Save Extracted Surface|'...
'Save Rendering and Surface'],[1 2 3],3);
end
%-Get input: threshold for extraction 'thresh'
%--------------------------------------------------------------------------
try
thresh;
catch
thresh = 0.5;
end
%-Surface extraction
%--------------------------------------------------------------------------
spm('FigName','Surface: working');
spm('Pointer','Watch');
out = do_it(P,mode,thresh);
spm('Pointer','Arrow');
spm('FigName','Surface: done');
if nargout > 0
varargout{1} = out;
end
return;
%==========================================================================
function out = do_it(P,mode,thresh)
V = spm_vol(P);
br = zeros(V(1).dim(1:3));
for i=1:V(1).dim(3),
B = spm_matrix([0 0 i]);
tmp = spm_slice_vol(V(1),B,V(1).dim(1:2),1);
for j=2:length(V),
M = V(j).mat\V(1).mat*B;
tmp = tmp + spm_slice_vol(V(j),M,V(1).dim(1:2),1);
end
br(:,:,i) = tmp;
end
% Build a 3x3x3 seperable smoothing kernel and smooth
%--------------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
spm_conv_vol(br,br,kx,ky,kz,-[1 1 1]);
[pth,nam,ext] = fileparts(V(1).fname);
if any(mode==[1 3])
% Produce rendering
%----------------------------------------------------------------------
out.rendfile{1} = fullfile(pth,['render_' nam '.mat']);
tmp = struct('dat',br,'dim',size(br),'mat',V(1).mat);
renviews(tmp,out.rendfile{1});
end
if any(mode==[2 3])
% Produce extracted surface
%----------------------------------------------------------------------
for k=1:numel(thresh)
[faces,vertices] = isosurface(br,thresh(k));
% Swap around x and y because isosurface does for some
% wierd and wonderful reason.
Mat = V(1).mat(1:3,:)*[0 1 0 0;1 0 0 0;0 0 1 0; 0 0 0 1];
vertices = (Mat*[vertices' ; ones(1,size(vertices,1))])';
if numel(thresh)==1
nam1 = nam;
else
nam1 = sprintf('%s-%d',nam,k);
end
out.surffile{k} = fullfile(pth,[nam1 '.surf.gii']);
save(gifti(struct('faces',faces,'vertices',vertices)),out.surffile{k});
end
end
return;
%==========================================================================
function renviews(V,oname)
% Produce images for rendering activations to
%
% FORMAT renviews(V,oname)
% V - mapped image to render, or alternatively
% a structure of:
% V.dat - 3D array
% V.dim - size of 3D array
% V.mat - affine mapping from voxels to millimeters
% oname - the name of the render.mat file.
%__________________________________________________________________________
%
% Produces a matrix file "render_xxx.mat" which contains everything that
% "spm_render" is likely to need.
%
% Ideally, the input image should contain values in the range of zero
% and one, and be smoothed slightly. A threshold of 0.5 is used to
% distinguish brain from non-brain.
%__________________________________________________________________________
linfun = inline('fprintf([''%-30s%s''],x,[repmat(sprintf(''\b''),1,30)])','x');
linfun('Rendering: ');
linfun('Rendering: Transverse 1..'); rend{1} = make_struct(V,[pi 0 pi/2]);
linfun('Rendering: Transverse 2..'); rend{2} = make_struct(V,[0 0 pi/2]);
linfun('Rendering: Sagittal 1..'); rend{3} = make_struct(V,[0 pi/2 pi]);
linfun('Rendering: Sagittal 2..'); rend{4} = make_struct(V,[0 pi/2 0]);
linfun('Rendering: Coronal 1..'); rend{5} = make_struct(V,[pi/2 pi/2 0]);
linfun('Rendering: Coronal 2..'); rend{6} = make_struct(V,[pi/2 pi/2 pi]);
linfun('Rendering: Save..');
if spm_check_version('matlab','7') >= 0
save(oname,'-V6','rend');
else
save(oname,'rend');
end
linfun(' ');
if ~spm('CmdLine')
disp_renderings(rend);
spm_print;
end
return;
%==========================================================================
function str = make_struct(V,thetas)
[D,M] = matdim(V.dim(1:3),V.mat,thetas);
[ren,dep] = make_pic(V,M*V.mat,D);
str = struct('M',M,'ren',ren,'dep',dep);
return;
%==========================================================================
function [ren,zbuf] = make_pic(V,M,D)
% A bit of a hack to try and make spm_render_vol produce some slightly
% prettier output. It kind of works...
if isfield(V,'dat'), vv = V.dat; else vv = V; end;
[REN, zbuf, X, Y, Z] = spm_render_vol(vv, M, D, [0.5 1]);
fw = max(sqrt(sum(M(1:3,1:3).^2)));
msk = find(zbuf==1024);
brn = ones(size(X));
brn(msk) = 0;
brn = spm_conv(brn,fw);
X(msk) = 0;
Y(msk) = 0;
Z(msk) = 0;
msk = find(brn<0.5);
tmp = brn;
tmp(msk) = 100000;
sX = spm_conv(X,fw)./tmp;
sY = spm_conv(Y,fw)./tmp;
sZ = spm_conv(Z,fw)./tmp;
zbuf = spm_conv(zbuf,fw)./tmp;
zbuf(msk) = 1024;
vec = [-1 1 3]; % The direction of the lighting.
vec = vec/norm(vec);
[t,dx,dy,dz] = spm_sample_vol(vv,sX,sY,sZ,3);
IM = inv(diag([0.5 0.5 1])*M(1:3,1:3))';
ren = IM(1:3,1:3)*[dx(:)' ; dy(:)' ; dz(:)'];
len = sqrt(sum(ren.^2,1))+eps;
ren = [ren(1,:)./len ; ren(2,:)./len ; ren(3,:)./len];
ren = reshape(vec*ren,[size(dx) 1]);
ren(ren<0) = 0;
ren(msk) = ren(msk)-0.2;
ren = ren*0.8+0.2;
mx = max(ren(:));
ren = ren/mx;
return;
%==========================================================================
function disp_renderings(rend)
Fgraph = spm_figure('GetWin','Graphics');
spm_results_ui('Clear',Fgraph);
hght = 0.95;
nrow = ceil(length(rend)/2);
ax=axes('Parent',Fgraph,'units','normalized','Position',[0, 0, 1, hght],'Visible','off');
image(0,'Parent',ax);
set(ax,'YTick',[],'XTick',[]);
for i=1:length(rend),
ren = rend{i}.ren;
ax=axes('Parent',Fgraph,'units','normalized',...
'Position',[rem(i-1,2)*0.5, floor((i-1)/2)*hght/nrow, 0.5, hght/nrow],...
'Visible','off');
image(ren*64,'Parent',ax);
set(ax,'DataAspectRatio',[1 1 1], ...
'PlotBoxAspectRatioMode','auto',...
'YTick',[],'XTick',[],'XDir','normal','YDir','normal');
end
drawnow;
return;
%==========================================================================
function [d,M] = matdim(dim,mat,thetas)
R = spm_matrix([0 0 0 thetas]);
bb = [[1 1 1];dim(1:3)];
c = [ bb(1,1) bb(1,2) bb(1,3) 1
bb(1,1) bb(1,2) bb(2,3) 1
bb(1,1) bb(2,2) bb(1,3) 1
bb(1,1) bb(2,2) bb(2,3) 1
bb(2,1) bb(1,2) bb(1,3) 1
bb(2,1) bb(1,2) bb(2,3) 1
bb(2,1) bb(2,2) bb(1,3) 1
bb(2,1) bb(2,2) bb(2,3) 1]';
tc = diag([2 2 1 1])*R*mat*c;
tc = tc(1:3,:)';
mx = max(tc);
mn = min(tc);
M = spm_matrix(-mn(1:2))*diag([2 2 1 1])*R;
d = ceil(abs(mx(1:2)-mn(1:2)))+1;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_plotScalpData.m
|
.m
|
antx-master/xspm8/spm_eeg_plotScalpData.m
| 11,761 |
utf_8
|
47767f883d6ed147946a3f14900db01d
|
function [ZI,f] = spm_eeg_plotScalpData(Z,pos,ChanLabel,in)
% Display interpolated sensor data on the scalp in a new figure
% FORMAT [ZI,f] = spm_eeg_plotScalpData(Z,pos,ChanLabel,in)
%
% INPUT:
% Z - the data matrix at the sensors
% pos - the positions of the sensors
% ChanLabel - the names of the sensors
% in - a structure containing some informations related to the
% main PRESELECTDATA window. This entry is not necessary
% OUTPUT
% ZI - an image of interpolated data onto the scalp
% f - the handle of the figure which displays the interpolated
% data
%__________________________________________________________________________
%
% This function creates a figure whose purpose is to display an
% interpolation of the sensor data on the scalp (an image)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_plotScalpData.m 4375 2011-06-23 10:00:06Z vladimir $
ParentAxes = [];
f = [];
clim = [min(Z(:))-( max(Z(:))-min(Z(:)) )/63 , max(Z(:))];
figName = 'Image Scalp data';
noButtons = 0;
if nargin < 4 || isempty(in)
in = [];
else
if isfield(in,'min') && ...
isfield(in,'max') && ...
isfield(in,'type')
clim = [in.min, in.max];
dc = abs(diff(clim))./63;
clim(1) = clim(1) - dc;
figName = ['Image Scalp data: ',in.type,' sensors'];
if isfield(in,'trN')
figName = [figName ', trial #',num2str(in.trN),'.'];
end
end
if isfield(in,'ParentAxes')
ParentAxes = in.ParentAxes;
end
if isfield(in,'f')
f = in.f;
end
if isfield(in,'noButtons')
noButtons = ~~in.noButtons;
end
end
if ~isfield(in,'cbar')
in.cbar = 1;
end
if ~isfield(in,'plotpos')
in.plotpos = 1;
end
if size(pos,2) ~= length(ChanLabel)
pos = pos';
end
nD = size(pos,1);
if nD ~= 2
% get 2D positions from 3D positions
xyz = pos;
[pos] = get2Dfrom3D(xyz);
pos = pos';
end
% exclude channels ?
goodChannels = find(~isnan(pos(1,:)));
pos = pos(:,goodChannels);
Z = Z(goodChannels,:);
ChanLabel = ChanLabel(goodChannels);
if ~isempty(in) && isfield(in,'type') && strcmp(in.type, 'MEGPLANAR')
[cZ, cpos, cChanLabel] = combineplanar(Z, pos, ChanLabel);
else
cZ = Z;
cpos = pos;
cChanLabel = ChanLabel;
end
xmin = min(cpos(1,:));
xmax = max(cpos(1,:));
dx = (xmax-xmin)./100;
ymin = min(cpos(2,:));
ymax = max(cpos(2,:));
dy = (ymax-ymin)./100;
x = xmin:dx:xmax;
y = ymin:dy:ymax;
[XI,YI] = meshgrid(x,y);
ZI = griddata(cpos(1,:)',cpos(2,:)',full(double(cZ')),XI,YI);
try
figure(f)
catch
f=figure(...
'name',figName,...
'color',[1 1 1],...
'deleteFcn',@dFcn);
ParentAxes = axes('parent',f);
end
COLOR = get(f,'color');
d.hi = image(flipud(ZI),...
'CDataMapping','scaled',...
'Parent',ParentAxes);
set(ParentAxes,'nextPlot','add',...
'tag','spm_eeg_plotScalpData')
try
if length(unique(ZI)) ~= 1
[C,d.hc] = contour(ParentAxes,flipud(ZI),...
'linecolor',0.5.*ones(3,1));
end
end
caxis(ParentAxes,clim);
col = jet;
col(1,:) = COLOR;
colormap(ParentAxes,col)
if in.cbar
d.cbar = colorbar('peer',ParentAxes);
end
axis(ParentAxes,'off')
axis(ParentAxes,'equal')
axis(ParentAxes,'tight')
fpos = cpos;
fpos(1,:) = fpos(1,:) - xmin;
fpos(2,:) = fpos(2,:) - ymin;
fpos(1,:) = fpos(1,:)./(dx);
fpos(2,:) = fpos(2,:)./(dy);
fpos(2,:) = 100-fpos(2,:); % for display purposes (flipud imagesc)
figure(f);
if in.plotpos
d.hp = plot(ParentAxes,...
fpos(1,:),fpos(2,:),...
'ko');
end
d.ht = text(fpos(1,:),fpos(2,:),cChanLabel,...
'Parent',ParentAxes,...
'visible','off');
axis(ParentAxes,'image')
d.interp.XI = XI;
d.interp.YI = YI;
d.interp.pos = cpos;
d.f = f;
d.pos = fpos;
d.goodChannels = goodChannels;
d.ChanLabel = cChanLabel;
d.origChanLabel = ChanLabel;
d.origpos = pos;
d.ParentAxes = ParentAxes;
d.in = in;
if ~noButtons
d.hsp = uicontrol(f,...
'style','pushbutton',...
'callback',{@dosp},...
'BusyAction','cancel',...
'Interruptible','off',...
'position',[10 50 80 20],...
'string','channel pos');
d.hsn = uicontrol(f,...
'style','pushbutton',...
'callback',{@dosn},...
'BusyAction','cancel',...
'Interruptible','off',...
'position',[10 80 80 20],...
'string','channel names');
end
if ~isempty(in) && isfield(in,'handles')
ud = get(in.handles.hfig,'userdata');
nT = ud.Nsamples;
d.hti = uicontrol(f,...
'style','text',...
'BackgroundColor',COLOR,...
'string',[num2str(in.gridTime(in.x)),' (',in.unit,')'],...
'position',[10 10 120 20]);
d.hts = uicontrol(f,...
'style','slider',...
'Position',[130 10 250 20],...
'min',1,'max',nT,...
'value',in.x,'sliderstep',[1./(nT-1) 1./(nT-1)],...
'callback',{@doChangeTime},...
'BusyAction','cancel',...
'Interruptible','off');
set(d.hti,'userdata',d);
set(d.hts,'userdata',d);
end
if ~noButtons
set(d.hsp,'userdata',d);
set(d.hsn,'userdata',d);
end
set(d.ParentAxes,'userdata',d);
%==========================================================================
% dFcn
%==========================================================================
function dFcn(btn,evd)
hf = findobj('tag','Graphics');
D = get(hf,'userdata');
try delete(D.PSD.handles.hli); end
%==========================================================================
% dosp
%==========================================================================
function dosp(btn,evd)
d = get(btn,'userdata');
switch get(d.hp,'visible');
case 'on'
set(d.hp,'visible','off');
case 'off'
set(d.hp,'visible','on');
end
%==========================================================================
% dosn
%==========================================================================
function dosn(btn,evd)
d = get(btn,'userdata');
switch get(d.ht(1),'visible')
case 'on'
set(d.ht,'visible','off');
case 'off'
set(d.ht,'visible','on');
end
%==========================================================================
%
%==========================================================================
function doChangeTime(btn,evd)
d = get(btn,'userdata');
v = get(btn,'value');
% get data
if ishandle(d.in.handles.hfig)
D = get(d.in.handles.hfig,'userdata');
if ~isfield(d.in,'trN')
trN = 1;
else
trN = d.in.trN;
end
if isfield(D,'data')
Z = D.data.y(d.in.ind,v,trN);
Z = Z(d.goodChannels);
if strcmp(d.in.type, 'MEGPLANAR')
Z = combineplanar(Z, d.origpos, d.origChanLabel);
end
clear ud;
% interpolate data
ZI = griddata(d.interp.pos(1,:),d.interp.pos(2,:),full(double(Z)),d.interp.XI,d.interp.YI);
% update data display
set(d.hi,'Cdata',flipud(ZI));
% update time index display
v = round(v);
set(d.hti,'string',[num2str(d.in.gridTime(v)), ' (', d.in.unit, ')']);
% update display marker position
try;set(d.in.hl,'xdata',[v;v]);end
set(d.ParentAxes,'nextPlot','add')
try
% delete current contour plot
delete(findobj(d.ParentAxes,'type','hggroup'));
% create new one
[C,hc] = contour(d.ParentAxes,flipud(ZI),...
'linecolor',[0.5.*ones(3,1)]);
end
axis(d.ParentAxes,'image')
drawnow
else
error('Did not find the data!')
end
else
error('SPM Graphics Figure has been deleted!')
end
%==========================================================================
% get2Dfrom3D
%==========================================================================
function [xy] = get2Dfrom3D(xyz)
% function [xy] = get2Dfrom3D(xyz)
% This function is used to flatten 3D sensor positions onto the 2D plane
% using a modified spherical projection operation.
% It is used to visualize channel data.
% IN:
% - xyz: the carthesian sensor position in 3D space
% OUT:
% - xy: the (x,y) carthesian coordinates of the sensors after projection
% onto the best-fitting sphere
if size(xyz,2) ~= 3
xyz = xyz';
end
% exclude channels ?
badChannels = find(isnan(xyz(:,1)));
goodChannels = find(isnan(xyz(:,1))~=1);
xyz = xyz(goodChannels,:);
% Fit sphere to 3d sensors and center frame
[C,R,out] = fitSphere(xyz(:,1),xyz(:,2),xyz(:,3));
xyz = xyz - repmat(C,size(xyz,1),1);
% apply transformation using spherical coordinates
[TH,PHI,RAD] = cart2sph(xyz(:,1),xyz(:,2),xyz(:,3));
TH = TH - mean(TH);
[X,Y,Z] = sph2cart(TH,zeros(size(TH)),RAD.*(cos(PHI+pi./2)+1));
xy = [X(:),Y(:)];
%==========================================================================
% combineplanar
%==========================================================================
function [Z, pos, ChanLabel] = combineplanar(Z, pos, ChanLabel)
chanind = zeros(1, numel(ChanLabel));
for i = 1:numel(ChanLabel)
chanind(i) = sscanf(ChanLabel{i}, 'MEG%d');
end
pairs = [];
unpaired = [];
paired = zeros(length(chanind));
for i = 1:length(chanind)
if ~paired(i)
cpair = find(abs(chanind - chanind(i))<2);
if length(cpair) == 1
unpaired = [unpaired cpair];
else
pairs = [pairs; cpair(:)'];
end
paired(cpair) = 1;
end
end
if ~isempty(unpaired)
warning(['Could not pair all channels. Ignoring ' num2str(length(unpaired)) ' unpaired channels.']);
end
Z = sqrt(Z(pairs(:, 1)).^2 + Z(pairs(:, 2)).^2);
pos = (pos(:, pairs(:, 1)) + pos(:, pairs(:, 2)))./2;
ChanLabel = {};
for i = 1:size(pairs,1)
ChanLabel{i} = ['MEG' num2str(min(pairs(i,:))) '+' num2str(max(pairs(i,:)))];
end
%==========================================================================
% fitSphere
%==========================================================================
function [C,R,out] = fitSphere(x,y,z)
% fitSphere Fit sphere.
% A = fitSphere(x,y,z) returns the parameters of the best-fit
% [C,R,out] = fitSphere(x,y,z) returns the center and radius
% sphere to data points in vectors (x,y,z) using Taubin's method.
% IN:
% - x/y/z: 3D carthesian ccordinates
% OUT:
% - C: the center of sphere coordinates
% - R: the radius of the sphere
% - out: an output structure devoted to graphical display of the best fit
% sphere
% Make sugary one and zero vectors
l = ones(length(x),1);
O = zeros(length(x),1);
% Make design mx
D = [(x.*x + y.*y + z.*z) x y z l];
Dx = [2*x l O O O];
Dy = [2*y O l O O];
Dz = [2*z O O l O];
% Create scatter matrices
M = D'*D;
N = Dx'*Dx + Dy'*Dy + Dz'*Dz;
% Extract eigensystem
[v, evalues] = eig(M);
evalues = diag(evalues);
Mrank = sum(evalues > eps*5*norm(M));
if (Mrank == 5)
% Full rank -- min ev corresponds to solution
Minverse = v'*diag(1./evalues)*v;
[v,evalues] = eig(inv(M)*N);
[dmin,dminindex] = max(diag(evalues));
pvec = v(:,dminindex(1))';
else
% Rank deficient -- just extract nullspace of M
pvec = null(M)';
[m,n] = size(pvec);
if m > 1
pvec = pvec(1,:)
end
end
% Convert to (R,C)
if nargout == 1,
if pvec(1) < 0
pvec = -pvec;
end
C = pvec;
else
C = -0.5*pvec(2:4) / pvec(1);
R = sqrt(sum(C*C') - pvec(5)/pvec(1));
end
[X,Y,Z] = sphere;
[TH,PHI,R0] = cart2sph(X,Y,Z);
[X,Y,Z] = sph2cart(TH,PHI,R);
X = X + C(1);
Y = Y + C(2);
Z = Z + C(3);
out.X = X;
out.Y = Y;
out.Z = Z;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_render.m
|
.m
|
antx-master/xspm8/spm_eeg_render.m
| 10,872 |
utf_8
|
52b7ba99932d4227bf2efefcc8766540
|
function [out] = spm_eeg_render(m,options)
% Visualisation routine for the cortical surface
% FORMAT [out] = spm_eeg_render(m,options)
%
% INPUT:
% - m = MATLAB mesh (containing the fields .faces et .vertices) or GIFTI
% format file.
% - options = structure variable:
% .texture = texture to be projected onto the mesh
% .clusters = cortical parcelling (cell variable containing the
% vertex indices of each cluster)
% .clustersName = name of the clusters
% .figname = name to be given to the window
% .ParentAxes = handle of the axes within which the mesh should be
% displayed
% .hfig = handle of existing figure. If this option is provided, then
% visu_maillage_surf adds the (textured) mesh to the figure hfig, and
% a control for its transparancy.
%
% OUTPUT:
% - out: a structure containing the fields:
% .hfra: frame structure for movie building
% .handles: a structure containing the handles of the created
% uicontrols and mesh objects.
% .m: the structure used to create the mesh
%__________________________________________________________________________
%
% This function is a visualization routine, mainly for texture and
% clustering on the cortical surface.
% NB: The texture and the clusters can not be visualized at the same time.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_render.m 3051 2009-04-06 14:47:09Z jean $
%----------------------------------------------------------------------%
%------------- Common features for any visualization ------------------%
%----------------------------------------------------------------------%
% Check mesh format
try
if ischar(m) && exist(m,'file')==2
try m = gifti(m);end
end
m0.faces = m.faces;
m0.vertices = m.vertices;
m = m0;
clear m0;
catch
disp('spm_eeg_render: unknown mesh format!')
return
end
% Default options
handles.fi = figure(...
'visible','off',...
'color',ones(1,3),...
'NumberTitle','Off',...
'Name','Mesh visualization',...
'tag','visu_maillage_surf');
ns = 0;
texture = 'none';
clusters = 'none';
subplotBIN = 0;
addMesh = 0;
tag = '';
visible = 'on';
ParentAxes = axes('parent',handles.fi);
try, options; catch options = [];end
% Now get options
if ~isempty(options)
% get texture if provided
try texture = options.texture;end
% get ParentAxes
try ParentAxes = options.ParentAxes;end
% get tag
try tag = options.tag;end
% get flag for visibility: useful for displaying all objects at once
try visible = options.visible;end
% get custers if provided
try
clusters = options.clusters;
IND = zeros(1,length(m.vertices));
K = length(clusters);
for k = 1:K
IND(clusters{k}) = k+1./K;
end
texture = IND';
end
% get figname if provided
try
set(handles.fi,'NumberTitle','Off','Name',options.figname);
end
% get figure handle (should be parent of ParentAxes)
try
figure(options.hfig)
if isempty(ParentAxes)
ParentAxes = axes('parent',options.hfig,...
'nextplot','add');
end
close(handles.fi);
handles.fi = options.hfig;
addMesh = 1;
try % get number of transparency sliders in current figure...
hh=get(handles.fi,'children');
ns=length(findobj(hh,'userdata','tag_UIC_transparency'));
catch
ns=1;
end
end
end
handles.ParentAxes = ParentAxes;
oldRenderer = get(handles.fi,'renderer');
try
if ismac
set(handles.fi,'renderer','zbuffer');
else
set(handles.fi,'renderer','OpenGL');
end
catch
set(handles.fi,'renderer','OpenGL');
end
% Plot mesh and texture/clusters
if isequal(texture,'none')
figure(handles.fi)
handles.p = patch(m,...
'facecolor', [.5 .5 .5], 'EdgeColor', 'none',...
'FaceLighting','gouraud',...
'parent',ParentAxes,...
'userdata',oldRenderer,...
'visible',visible,...
'tag',tag);
else
texture = texture(:);
figure(handles.fi)
if isequal(length(texture),length(m.vertices))
handles.p = patch(m,...
'facevertexcdata',texture,...
'facecolor','interp',...
'EdgeColor', 'none',...
'FaceLighting','gouraud',...
'parent',ParentAxes,...
'userdata',oldRenderer,...
'visible',visible,...
'tag',tag,...
'deleteFcn',@doDelMesh);
col = colormap(ParentAxes,jet(256));
udd.tex = texture;
udd.cax = caxis(ParentAxes);
else
texture = 'none';
disp('Warning: size of texture does not match number of vertices!')
handles.p = patch(m,'facecolor', [.5 .5 .5], 'EdgeColor', 'none',...
'parent',ParentAxes,...
'userdata',oldRenderer,...
'visible',visible,...
'tag',tag,...
'deleteFcn',@doDelMesh);
end
end
daspect(ParentAxes,[1 1 1]);
axis(ParentAxes,'tight');
axis(ParentAxes,'off')
camva(ParentAxes,'auto');
set(ParentAxes,'view',[25,45]);
% build internal userdata structure
udd.p = handles.p;
%----------------------------------------------------------------------%
%---------------------- GUI tools and buttons -------------------------%
%----------------------------------------------------------------------%
% Transparancy sliders
pos = [20 100 20 245];
pos(1) = pos(1) + ns.*25;
handles.transp = uicontrol(handles.fi,...
'style','slider',...
'position',pos,...
'min',0,...
'max',1,...
'value',1,...
'sliderstep',[0.01 0.05],...
'userdata',handles.p,...
'tooltipstring',['mesh #',num2str(ns+1),' transparency control'],...
'callback',{@doTransp},...
'BusyAction','cancel',...
'Interruptible','off',...
'visible',visible,...
'tag',tag);
set(handles.transp,'units','normalized')
handles.tag = uicontrol(handles.fi,...
'style','text',...
'visible','off',...
'tag',tag,...
'userdata','tag_UIC_transparency');
udd.transp = handles.transp;
% Clustering buttons and popup menu
if ~isequal(clusters,'none')
if subplotBIN
subplot(2,1,1)
end
% set(p,'FaceColor','flat');
col=lines;
nc = floor(256./K);
col = [repmat([0.8157 0.6666 0.5762],nc/2,1);...
kron(col(1:K,:),ones(nc,1))];
if K > 1
col(end-nc/2:end,:) = [];
end
colormap(ParentAxes,col);
tex = zeros(length(m.vertices),length(clusters)+1);
tex(:,1) = texture;
string = cell(length(clusters)+1,1);
string{1} = 'all clusters';
for i = 1:length(clusters)
if ~isfield(options,'clustersName')
string{i+1} = ['cluster ',num2str(i)];
else
string{i+1} = options.clustersName{i};
end
tex(clusters{i},i+1) = 1;
end
udd.tex = tex;
udd.tex0 = tex;
udd.p = handles.p;
udd.col = col;
udd.nc = length(clusters);
handles.pop = uicontrol(handles.fi,...
'style','popupmenu',...
'position',[20 20 100 40],...
'string',string,...
'callback',{@doSelectCluster},...
'BusyAction','cancel',...
'Interruptible','off',...
'visible',visible,'tag',tag);
set(handles.pop,'units','normalized')
handles.sli = uicontrol(handles.fi,...
'style','slider',...
'position',[50 10 30 20],'max',udd.nc,...
'sliderstep',[1./(udd.nc+0) 1./(udd.nc+0)],...
'callback',{@doSwitch2nextCluster},...
'BusyAction','cancel',...
'Interruptible','off',...
'visible',visible,'tag',tag);
set(handles.sli,'units','normalized')
udd.pop = handles.pop;
udd.sli = handles.sli;
set(handles.pop,'userdata',udd);
set(handles.sli,'userdata',udd);
end
% Texture thresholding sliders
if ~isequal(texture,'none') && isequal(clusters,'none')
if subplotBIN
subplot(2,1,1)
end
udd.tex0 = texture;
udd.col = col;
handles.hc = colorbar('peer',ParentAxes);
set(handles.hc,'visible',visible)
increment = 0.01;
% right slider
handles.s1 = uicontrol(handles.fi,...
'style','slider',...
'position',[440 28 20 380],...
'min',0,'max',length(udd.col),'value',0,...
'sliderstep',[increment increment],...
'tooltipstring','texture thresholding control',...
'callback',{@doThresh},...
'BusyAction','cancel',...
'Interruptible','off',...
'visible',visible,'tag',tag);
set(handles.s1,'units','normalized')
udd.s1 = handles.s1;
% left slider
handles.s2 = uicontrol(handles.fi,...
'style','slider',...
'position',[420 28 20 380],...
'min',1,'max',length(udd.col),...
'value',length(udd.col),...
'sliderstep',[increment increment],...
'tooltipstring','texture thresholding control',...
'callback',{@doThresh},...
'BusyAction','cancel',...
'Interruptible','off',...
'visible',visible,'tag',tag);
set(handles.s2,'units','normalized')
udd.s2 = handles.s2;
set(handles.s1,'userdata',udd);
set(handles.s2,'userdata',udd);
end
set(handles.fi,'visible','on');
drawnow
% if ~addMesh
camlight
% end
cameratoolbar(handles.fi,'setmode','orbit')
out.hfra = getframe(gcf);
out.handles = handles;
out.m = m;
%--------- subfunctions : BUTTONS CALLBACKS ------------%
function doDelMesh(btn,evd)
renderer=get(btn,'userdata');
set(gcf,'renderer',renderer);
function doTransp(btn,evd)
v00=get(btn,'value');
p00=get(btn,'userdata');
set(p00,'facealpha',v00);
function doThresh(btn,evd)
udd00 = get(btn,'userdata');
ind00 = round(get(udd00.s1,'value'));
ind200 = round(get(udd00.s2,'value'));
if(ind200>ind00)
udd00.col(1:ind00,:)=0.5*ones(ind00,3);
udd00.col(ind200+1:end,:)=0.5*ones(size(udd00.col(ind200+1:end,:)));
else
udd00.col(ind200:ind00,:)=0.5*ones(size(udd00.col(ind200:ind00,:)));
end
colormap(udd00.col);
udd00.cax = caxis;
function doSelectCluster(btn,evd)
udd00 = get(btn,'userdata');
ind00=get(gcbo,'value');
set(udd00.sli,'value',ind00-1);
set(udd00.p,'facevertexcdata',udd00.tex(:,ind00));
if ind00 == 1
colormap(udd00.col);
else
col00 = colormap(jet);
col00(1:end/2,:)=0.5*ones(size(col00(1:end/2,:)));
colormap(col00);
end
udd00.cax = caxis;
function doSwitch2nextCluster(btn,evd)
v00=get(btn,'value')+1;
udd00=get(gcbo,'userdata');
ind00=min([v00 udd00.nc+1]);
set(udd00.pop,'value',ind00);
set(udd00.p,'facevertexcdata',udd00.tex(:,ind00));
if ind00 == 1
colormap(udd00.col);
else
col00 = colormap(jet);
col00(1:end/2,:)=0.5;
colormap(col00);
end
udd00.cax = caxis;
|
github
|
philippboehmsturm/antx-master
|
spm_write_sn.m
|
.m
|
antx-master/xspm8/spm_write_sn.m
| 19,859 |
utf_8
|
0ea1c7ae2ba1644c71deaf8ae1518452
|
function VO = spm_write_sn(V,prm,flags,extras)
% Write out warped images
% FORMAT VO = spm_write_sn(V,prm,flags,msk)
% V - Images to transform (filenames or volume structure).
% prm - Transformation information (filename or structure).
% flags - flags structure, with fields...
% interp - interpolation method (0-7)
% wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences)
% vox - voxel sizes (3 element vector - in mm)
% Non-finite values mean use template vox.
% bb - bounding box (2x3 matrix - in mm)
% Non-finite values mean use template bb.
% preserve - either 0 or 1. A value of 1 will "modulate"
% the spatially normalised images so that total
% units are preserved, rather than just
% concentrations.
% prefix - Prefix for normalised images. Defaults to 'w'.
% msk - An optional cell array for masking the spatially
% normalised images (see below).
%
% Warped images are written prefixed by "w".
%
% Non-finite vox or bounding box suggests that values should be derived
% from the template image.
%
% Don't use interpolation methods greater than one for data containing
% NaNs.
%__________________________________________________________________________
%
% FORMAT msk = spm_write_sn(V,prm,flags,'mask')
% V - Images to transform (filenames or volume structure).
% prm - Transformation information (filename or structure).
% flags - flags structure, with fields...
% wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences)
% vox - voxel sizes (3 element vector - in mm)
% Non-finite values mean use template vox.
% bb - bounding box (2x3 matrix - in mm)
% Non-finite values mean use template bb.
% msk - a cell array for masking a series of spatially normalised
% images.
%
%
%_________________________________________________________________________
%
% FORMAT VO = spm_write_sn(V,prm,'modulate')
% V - Spatially normalised images to modulate (filenames or
% volume structure).
% prm - Transformation information (filename or structure).
%
% After nonlinear spatial normalization, the relative volumes of some
% brain structures will have decreased, whereas others will increase.
% The resampling of the images preserves the concentration of pixel
% units in the images, so the total counts from structures that have
% reduced volumes after spatial normalization will be reduced by an
% amount proportional to the volume reduction.
%
% This routine rescales images after spatial normalization, so that
% the total counts from any structure are preserved. It was written
% as an optional step in performing voxel based morphometry.
%
%__________________________________________________________________________
% Copyright (C) 1996-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_write_sn.m 4201 2011-02-15 10:52:00Z ged $
if isempty(V), return; end;
if ischar(prm), prm = load(prm); end;
if ischar(V), V = spm_vol(V); end;
if nargin==3 && ischar(flags) && strcmpi(flags,'modulate'),
if nargout==0,
modulate(V,prm);
else
VO = modulate(V,prm);
end;
return;
end;
def_flags = spm_get_defaults('normalise.write');
def_flags.prefix = 'w';
if nargin < 3,
flags = def_flags;
else
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags.(fnms{i}) = def_flags.(fnms{i});
end;
end;
end;
[x,y,z,mat] = get_xyzmat(prm,flags.bb,flags.vox);
if nargin==4,
if ischar(extras) && strcmpi(extras,'mask'),
VO = get_snmask(V,prm,x,y,z,flags.wrap);
return;
end;
if iscell(extras),
msk = extras;
end;
end;
if nargout>0 && length(V)>8,
error('Too many images to save in memory');
end;
if ~exist('msk','var')
msk = get_snmask(V,prm,x,y,z,flags.wrap);
end;
if nargout==0,
if isempty(prm.Tr),
affine_transform(V,prm,x,y,z,mat,flags,msk);
else
nonlin_transform(V,prm,x,y,z,mat,flags,msk);
end;
else
if isempty(prm.Tr),
VO = affine_transform(V,prm,x,y,z,mat,flags,msk);
else
VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk);
end;
end;
return;
%==========================================================================
%==========================================================================
function VO = affine_transform(V,prm,x,y,z,mat,flags,msk)
[X,Y] = ndgrid(x,y);
d = [flags.interp*[1 1 1]' flags.wrap(:)];
spm_progress_bar('Init',numel(V),'Resampling','volumes/slices completed');
for i=1:numel(V),
VO = make_hdr_struct(V(i),x,y,z,mat, flags.prefix);
if flags.preserve
VO.fname = prepend(VO.fname,'m');
end
detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat);
if flags.preserve, VO.pinfo(1:2,:) = VO.pinfo(1:2,:)/detAff; end;
%Dat= zeros(VO.dim(1:3));
Dat = single(0);
Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;
C = spm_bsplinc(V(i),d);
for j=1:length(z), % Cycle over planes
[X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF(1).mat*prm.Affine);
dat = spm_bsplins(C,X2,Y2,Z2,d);
if flags.preserve, dat = dat*detAff; end;
dat(msk{j}) = NaN;
Dat(:,:,j) = single(dat);
if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
if nargout~=0,
VO.pinfo = [1 0]';
VO.dt = [spm_type('float32') spm_platform('bigend')];
VO.dat = Dat;
else
spm_write_vol(VO, Dat);
end;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%==========================================================================
%==========================================================================
function VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk)
[X,Y] = ndgrid(x,y);
Tr = prm.Tr;
BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);
BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);
BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);
if flags.preserve,
DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff');
DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff');
DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff');
end;
d = [flags.interp*[1 1 1]' flags.wrap(:)];
spm_progress_bar('Init',numel(V),'Resampling','volumes completed');
for i=1:numel(V),
VO = make_hdr_struct(V(i),x,y,z,mat, flags.prefix);
if flags.preserve
VO.fname = prepend(VO.fname,'m');
end
detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat);
% Accumulate data
%Dat= zeros(VO.dim(1:3));
Dat = single(0);
Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;
C = spm_bsplinc(V(i),d);
for j=1:length(z), % Cycle over planes
% Nonlinear deformations
%------------------------------------------------------------------
tx = get_2Dtrans(Tr(:,:,:,1),BZ,j);
ty = get_2Dtrans(Tr(:,:,:,2),BZ,j);
tz = get_2Dtrans(Tr(:,:,:,3),BZ,j);
X1 = X + BX*tx*BY';
Y1 = Y + BX*ty*BY';
Z1 = z(j) + BX*tz*BY';
[X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF(1).mat*prm.Affine);
dat = spm_bsplins(C,X2,Y2,Z2,d);
dat(msk{j}) = NaN;
if ~flags.preserve,
Dat(:,:,j) = single(dat);
else
j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY';
j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY';
j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1;
% The determinant of the Jacobian reflects relative volume changes
%-----------------------------------------------------------------
dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff;
Dat(:,:,j) = single(dat);
end;
if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
if nargout==0,
if flags.preserve, VO = rmfield(VO,'pinfo'); end
VO = spm_write_vol(VO,Dat);
else
VO.pinfo = [1 0]';
VO.dt = [spm_type('float32') spm_platform('bigend')];
VO.dat = Dat;
end;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%==========================================================================
%==========================================================================
function VO = modulate(V,prm)
spm_progress_bar('Init',numel(V),'Modulating','volumes completed');
for i=1:numel(V),
VO = V(i);
VO = rmfield(VO,'pinfo');
VO.fname = prepend(VO.fname,'m');
detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat);
%Dat = zeros(VO.dim(1:3));
Dat = single(0);
Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;
[x,y,z,mat] = get_xyzmat(prm,NaN,NaN,VO);
if sum((mat(:)-VO.mat(:)).^2)>1e-7, error('Orientations not compatible'); end;
Tr = prm.Tr;
if isempty(Tr),
for j=1:length(z), % Cycle over planes
dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0);
Dat(:,:,j) = single(dat);
if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
else
BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);
BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);
BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);
DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff');
DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff');
DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff');
for j=1:length(z), % Cycle over planes
tx = get_2Dtrans(Tr(:,:,:,1),BZ,j);
ty = get_2Dtrans(Tr(:,:,:,2),BZ,j);
tz = get_2Dtrans(Tr(:,:,:,3),BZ,j);
j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY';
j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY';
j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1;
% The determinant of the Jacobian reflects relative volume changes
%-----------------------------------------------------------------
dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0);
dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff;
Dat(:,:,j) = single(dat);
if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
end;
if nargout==0,
VO = spm_write_vol(VO,Dat);
else
VO.pinfo = [1 0]';
VO.dt = [spm_type('float32') spm_platform('bigend')];
VO.dat = Dat;
end;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%==========================================================================
%==========================================================================
function VO = make_hdr_struct(V,x,y,z,mat,prefix)
VO = V;
VO.fname = prepend(V.fname,prefix);
VO.mat = mat;
VO.dim(1:3) = [length(x) length(y) length(z)];
VO.pinfo = V.pinfo;
VO.descrip = 'spm - 3D normalized';
return;
%==========================================================================
%==========================================================================
function T2 = get_2Dtrans(T3,B,j)
d = [size(T3) 1 1 1];
tmp = reshape(T3,d(1)*d(2),d(3));
T2 = reshape(tmp*B(j,:)',d(1),d(2));
return;
%==========================================================================
%_______________________________________________________________________
function PO = prepend(PI,pre)
[pth,nm,xt,vr] = spm_fileparts(deblank(PI));
PO = fullfile(pth,[pre nm xt vr]);
return;
%==========================================================================
%==========================================================================
function Mask = getmask(X,Y,Z,dim,wrp)
% Find range of slice
tiny = 5e-2;
Mask = true(size(X));
if ~wrp(1), Mask = Mask & (X >= (1-tiny) & X <= (dim(1)+tiny)); end;
if ~wrp(2), Mask = Mask & (Y >= (1-tiny) & Y <= (dim(2)+tiny)); end;
if ~wrp(3), Mask = Mask & (Z >= (1-tiny) & Z <= (dim(3)+tiny)); end;
return;
%==========================================================================
%==========================================================================
function [X2,Y2,Z2] = mmult(X1,Y1,Z1,Mult)
if length(Z1) == 1,
X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + (Mult(1,3)*Z1 + Mult(1,4));
Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + (Mult(2,3)*Z1 + Mult(2,4));
Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + (Mult(3,3)*Z1 + Mult(3,4));
else
X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4);
Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4);
Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4);
end;
return;
%==========================================================================
%==========================================================================
function msk = get_snmask(V,prm,x,y,z,wrap)
% Generate a mask for where there is data for all images
%--------------------------------------------------------------------------
msk = cell(length(z),1);
t1 = cat(3,V.mat);
t2 = cat(1,V.dim);
t = [reshape(t1,[16 length(V)])' t2(:,1:3)];
Tr = prm.Tr;
[X,Y] = ndgrid(x,y);
BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);
BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);
BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);
if numel(V)>1 && any(any(diff(t,1,1))),
spm_progress_bar('Init',length(z),'Computing available voxels','planes completed');
for j=1:length(z), % Cycle over planes
Count = zeros(length(x),length(y));
if isempty(Tr),
% Generate a mask for where there is data for all images
%--------------------------------------------------------------
for i=1:numel(V),
[X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF(1).mat*prm.Affine);
Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap);
end;
else
% Nonlinear deformations
%--------------------------------------------------------------
X1 = X + BX*get_2Dtrans(Tr(:,:,:,1),BZ,j)*BY';
Y1 = Y + BX*get_2Dtrans(Tr(:,:,:,2),BZ,j)*BY';
Z1 = z(j) + BX*get_2Dtrans(Tr(:,:,:,3),BZ,j)*BY';
% Generate a mask for where there is data for all images
%--------------------------------------------------------------
for i=1:numel(V),
[X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF(1).mat*prm.Affine);
Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap);
end;
end;
msk{j} = uint32(find(Count ~= numel(V)));
spm_progress_bar('Set',j);
end;
spm_progress_bar('Clear');
else
for j=1:length(z), msk{j} = uint32([]); end;
end;
return;
%==========================================================================
%==========================================================================
function [x,y,z,mat] = get_xyzmat(prm,bb,vox,VG)
% The old voxel size and origin notation is used here.
% This requires that the position and orientation
% of the template is transverse. It would not be
% straitforward to account for templates that are
% in different orientations because the basis functions
% would no longer be seperable. The seperable basis
% functions mean that computing the deformation field
% from the parameters is much faster.
% bb = sort(bb);
% vox = abs(vox);
if nargin<4,
VG = prm.VG(1);
if all(~isfinite(bb(:))) && all(~isfinite(vox(:))),
x = 1:VG.dim(1);
y = 1:VG.dim(2);
z = 1:VG.dim(3);
mat = VG.mat;
return;
end
end
[bb0 vox0] = spm_get_bbox(VG, 'old');
if ~all(isfinite(vox(:))), vox = vox0; end;
if ~all(isfinite(bb(:))), bb = bb0; end;
msk = find(vox<0);
bb = sort(bb);
bb(:,msk) = flipud(bb(:,msk));
% Adjust bounding box slightly - so it rounds to closest voxel.
% Comment out if not needed.
%bb(:,1) = round(bb(:,1)/vox(1))*vox(1);
%bb(:,2) = round(bb(:,2)/vox(2))*vox(2);
%bb(:,3) = round(bb(:,3)/vox(3))*vox(3);
M = prm.VG(1).mat;
vxg = sqrt(sum(M(1:3,1:3).^2));
if det(M(1:3,1:3))<0, vxg(1) = -vxg(1); end;
ogn = M\[0 0 0 1]';
ogn = ogn(1:3)';
% Convert range into range of voxels within template image
x = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1);
y = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2);
z = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3);
og = -vxg.*ogn;
% Again, chose whether to round to closest voxel.
%of = -vox.*(round(-bb(1,:)./vox)+1);
of = bb(1,:)-vox;
M1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1];
M2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];
mat = prm.VG(1).mat*inv(M1)*M2;
LEFTHANDED = true;
if (LEFTHANDED && det(mat(1:3,1:3))>0) || (~LEFTHANDED && det(mat(1:3,1:3))<0),
Flp = [-1 0 0 (length(x)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
mat = mat*Flp;
x = flipud(x(:))';
end;
return;
%==========================================================================
%==========================================================================
function VO = write_dets(P,bb,vox)
if nargin==1,
job = P;
P = job.P;
bb = job.bb;
vox = job.vox;
end;
spm_progress_bar('Init',numel(P),'Writing','volumes completed');
for i=1:numel(V),
prm = load(deblank(P{i}));
[x,y,z,mat] = get_xyzmat(prm,bb,vox);
Tr = prm.Tr;
BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1);
BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1);
BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1);
DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff');
DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff');
DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff');
[pth,nam,ext,nm] = spm_fileparts(P{i});
VO = struct('fname',fullfile(pth,['jy_' nam ext nm]),...
'dim',[numel(x),numel(y),numel(z)],...
'dt',[spm_type('float32') spm_platform('bigend')],...
'pinfo',[1 0 0]',...
'mat',mat,...
'n',1,...
'descrip','Jacobian determinants');
VO = spm_create_vol(VO);
detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat);
Dat = single(0);
Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0;
for j=1:length(z), % Cycle over planes
% Nonlinear deformations
tx = get_2Dtrans(Tr(:,:,:,1),BZ,j);
ty = get_2Dtrans(Tr(:,:,:,2),BZ,j);
tz = get_2Dtrans(Tr(:,:,:,3),BZ,j);
%------------------------------------------------------------------
j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY';
j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY';
j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1;
% The determinant of the Jacobian reflects relative volume changes.
%------------------------------------------------------------------
dat = (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff;
Dat(:,:,j) = single(dat);
if numel(P)<5, spm_progress_bar('Set',i-1+j/length(z)); end;
end;
VO = spm_write_vol(VO,Dat);
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%==========================================================================
|
github
|
philippboehmsturm/antx-master
|
spm_DesMtx.m
|
.m
|
antx-master/xspm8/spm_DesMtx.m
| 32,503 |
utf_8
|
3378b7ab974fe4c63802be7041a77998
|
function [X,Pnames,Index,idx,jdx,kdx]=spm_DesMtx(varargin)
% Design matrix construction from factor level and covariate vectors
% FORMAT [X,Pnames] = spm_DesMtx(<FCLevels-Constraint-FCnames> list)
% FORMAT [X,Pnames,Index,idx,jdx,kdx] = spm_DesMtx(FCLevels,Constraint,FCnames)
%
% <FCLevels-Constraints-FCnames>
% - set of arguments specifying a portion of design matrix (see below)
% - FCnames parameter, or Constraint and FCnames parameters, are optional
% - a list of multiple <FCLevels-Constraint-FCnames> triples can be
% specified, where FCnames or Constraint-FCnames may be omitted
% within any triple. The program then works recursively.
%
% X - design matrix
% Pnames - paramater names as (constructed from FCnames) - a cellstr
% Index - integer index of factor levels
% - only returned when computing a single design matrix partition
%
% idx,jdx,kdx - reference vectors mapping I & Index (described below)
% - only returned when computing a single design matrix partition
% for unconstrained factor effects ('-' or '~')
%
% ----------------
% - Utilities:
%
% FORMAT i = spm_DesMtx('pds',v,m,n)
% Patterned data setting function - inspired by MINITAB's "SET" command
% v - base pattern vector
% m - (scalar natural number) #replications of elements of v [default 1]
% n - (scalar natural number) #repeats of pattern [default 1]
% i - resultant pattern vector, with v's elements replicated m times,
% the resulting vector repeated n times.
%
% FORMAT [nX,nPnames] = spm_DesMtx('sca',X1,Pnames1,X2,Pnames2,...)
% Produces a scaled design matrix nX with max(abs(nX(:))<=1, suitable
% for imaging with: image((nX+1)*32)
% X1,X2,... - Design matrix partitions
% Pnames1, Pnames2,... - Corresponding parameter name string mtx/cellstr (opt)
% nX - Scaled design matrix
% nPnames - Concatenated parameter names for columns of nX
%
% FORMAT Fnames = spm_DesMtx('Fnames',Pnames)
% Converts parameter names into suitable filenames
% Pnames - string mtx/cellstr containing parameter names
% Fnames - filenames derived from Pnames. (cellstr)
%
% FORMAT TPnames = spm_DesMtx('TeXnames',Pnames)
% Removes '*'s and '@'s from Pnames, so TPnames suitable for TeX interpretation
% Pnames - string mtx/cellstr containing parameter names
% TPnames - TeX-ified parameter names
%
% FORMAT Map = spm_DesMtx('ParMap',aMap)
% Returns Nx2 cellstr mapping (greek TeX) parameters to English names,
% using the notation established in the SPMcourse notes.
% aMap - (optional) Mx2 cellstr of additional or over-ride mappings
% Map - cellstr of parameter names (col1) and corresponding English names (col2)
%
% FORMAT EPnames = spm_DesMtx('ETeXnames',Pnames,aMap)
% Translates greek (TeX) parameter names into English using mapping given by
% spm_DesMtx('ParMap',aMap)
% Pnames - string mtx/cellstr containing parameter names
% aMap - (optional) Mx2 cellstr of additional or over-ride mappings
% EPnames - cellstr of converted parameter names
%_______________________________________________________________________
%
% Returns design matrix corresponding to given vectors containing
% levels of a factor; two way interactions; covariates (n vectors);
% ready-made sections of design matrix; and factor by covariate
% interactions.
%
% The specification for the design matrix is passed in sets of arguments,
% each set corresponding to a particular Factor/Covariate/&c., specifying
% a section of the design matrix. The set of arguments consists of the
% FCLevels matrix (Factor/Covariate levels), an optional constraint string,
% and an optional (string) name matrix containing the names of the
% Factor/Covariate/&c.
%
% MAIN EFFECTS: For a main effect, or single factor, the FCLevels
% matrix is an integer vector whose values represent the levels of the
% factor. The integer factor levels need not be positive, nor in
% order. In the '~' constraint types (below), a factor level of zero
% is ignored (treated as no effect), and no corresponding column of
% design matrix is created. Effects for the factor levels are entered
% into the design matrix *in increasing order* of the factor levels.
% Check Pnames to find out which columns correspond to which levels of
% the factor.
%
% TWO WAY INTERACTIONS: For a two way interaction effect between two
% factors, the FCLevels matrix is an nx2 integer matrix whose columns
% indicate the levels of the two factors. An effect is included for
% each unique combination of the levels of the two factors. Again,
% factor levels must be integer, though not necessarily positive.
% Zero levels are ignored in the '~' constraint types described below.
%
% CONSTRAINTS: Each FactorLevels vector/matrix may be followed by an
% (optional) ConstraintString.
%
% ConstraintStrings for main effects are:
% '-' - No Constraint
% '~' - Ignore zero level of factor
% (I.e. cornerPoint constraint on zero level,
% (same as '.0', except zero level is always ignored,
% (even if factor only has zero level, in which case
% (an empty DesMtx results and a warning is given
% '+0' - sum-to-zero constraint
% '+0m' - Implicit sum-to-zero constraint
% '.' - CornerPoint constraint
% '.0' - CornerPoint constraint applied to zero factor level
% (warns if there is no zero factor level)
% Constraints for two way interaction effects are
% '-' - No Constraints
% '~' - Ignore zero level of any factor
% (I.e. cornerPoint constraint on zero level,
% (same as '.ij0', except zero levels are always ignored
% '+i0','+j0','+ij0' - sum-to-zero constraints
% '.i', '.j', '.ij' - CornerPoint constraints
% '.i0','.j0','.ij0' - CornerPoint constraints applied to zero factor level
% (warns if there is no zero factor level)
% '+i0m', '+j0m' - Implicit sum-to-zero constraints
%
% With the exception of the "ignore zero" '~' constraint, constraints
% are only applied if there are sufficient factor levels. CornerPoint
% and explicit sum-to-zero Constraints are applied to the last level of
% the factor.
%
% The implicit sum-to-zero constraints "mean correct" appropriate rows
% of the relevant design matrix block. For a main effect, constraint
% '+0m' "mean corrects" the main effect block across columns,
% corresponding to factor effects B_i, where B_i = B'_i - mean(B'_i) :
% The B'_i are the fitted parameters, effectively *relative* factor
% parameters, relative to their mean. This leads to a rank deficient
% design matrix block. If Matlab's pinv, which implements a
% Moore-Penrose pseudoinverse, is used to solve the least squares
% problem, then the solution with smallest L2 norm is found, which has
% mean(B'_i)=0 provided the remainder of the design is unique (design
% matrix blocks of full rank). In this case therefore the B_i are
% identically the B'_i - the mean correction imposes the constraint.
%
%
% COVARIATES: The FCLevels matrix here is an nxc matrix whose columns
% contain the covariate values. An effect is included for each covariate.
% Covariates are identified by ConstraintString 'C'.
%
%
% PRE-SPECIFIED DESIGN BLOCKS: ConstraintString 'X' identifies a
% ready-made bit of design matrix - the effect is the same as 'C'.
%
%
% FACTOR BY COVARIATE INTERACTIONS: are identified by ConstraintString
% 'FxC'. The last column is understood to contain the covariate. Other
% columns are taken to contain integer FactorLevels vectors. The
% (unconstrained) interaction of the factors is interacted with the
% covariate. Zero factor levels are ignored if ConstraintString '~FxC'
% is used.
%
%
% NAMES: Each Factor/Covariate can be 'named', by passing a name
% string. Pass a string matrix, or cell array (vector) of strings,
% with rows (cells) naming the factors/covariates in the respective
% columns of the FCLevels matrix. These names default to <Fac>, <Cov>,
% <Fac1>, <Fac2> &c., and are used in the construction of the Pnames
% parameter names.
% E.g. for an interaction, spm_DesMtx([F1,F2],'+ij0',['subj';'cond'])
% giving parameter names such as subj*cond_{1,2} etc...
%
% Pnames returns a string matrix whose successive rows describe the
% effects parameterised in the corresponding columns of the design
% matrix. `Fac1*Fac2_{2,3}' would refer to the parameter for the
% interaction of the two factors Fac1 & Fac2, at the 2nd level of the
% former and the 3rd level of the latter. Other forms are
% - Simple main effect (level 1) : <Fac>_{1}
% - Three way interaction (level 1,2,3) : <Fac1>*<Fac2>*<Fac3>_{1,2,3}
% - Two way factor interaction by covariate interaction :
% : <Cov>@<Fac1>*<Fac2>_{1,1}
% - Column 3 of prespecified DesMtx block (if unnamed)
% : <X> [1]
% The special characters `_*()[]{}' are recognised by the scaling
% function (spm_DesMtx('sca',...), and should therefore be avoided
% when naming effects and covariates.
%
%
% INDEX: An Integer Index matrix is returned if only a single block of
% design matrix is being computed (single set of parameters). It
% indexes the actual order of the effect levels in the design matrix block.
% (Factor levels are introduced in order, regardless of order of
% appearence in the factor index matrices, so that the parameters
% vector has a sensible order.) This is used to aid recursion.
%
% Similarly idx,jdx & kdx are indexes returned for a single block of
% design matrix consisting of unconstrained factor effects ('-' or '~').
% These indexes map I and Index (in a similar fashion to the `unique`
% function) as follows:
% - idx & jdx are such that I = Index(:,jdx)' and Index = I(idx,:)'
% where vector I is given as a column vector
% - If the "ignore zeros" constraint '~' is used, then kdx indexes the
% non-zero (combinations) of factor levels, such that
% I(kdx,:) = Index(:,jdx)' and Index == I(kdx(idx),:)'
%
% ----------------
%
% The "patterned data setting" (spm_DesMtx('pds'...) is a simple
% utility for setting patterned indicator vectors, inspired by
% MINITAB's "SET" command.
%
% The vector v has it's elements replicated m times, and the resulting
% vector is itself repeated n times, giving a resultant vector i of
% length n*m*length(v)
%
% Examples:
% spm_DesMtx('pds',1:3) % = [1,2,3]
% spm_DesMtx('pds',1:3,2) % = [1,1,2,2,3,3]
% spm_DesMtx('pds',1:3,2,3) % = [1,1,2,2,3,3,1,1,2,2,3,3,1,1,2,2,3,3]
% NB: MINITAB's "SET" command has syntax n(v)m:
%
% ----------------
%
% The design matrix scaling feature is designed to return a scaled
% version of a design matrix, with values in [-1,1], suitable for
% visualisation. Special care is taken to apply the same normalisation
% to blocks of design matrix reflecting a single effect, to preserve
% appropriate relationships between columns. Identification of effects
% corresponding to columns of design matrix portions is via the parameter
% names matrices. The design matrix may be passed in any number of
% parts, provided the corresponding parameter names are given. It is
% assummed that the block representing an effect is contained within a
% single partition. Partitions supplied without corresponding parameter
% names are scaled on a column by column basis, the parameters labelled as
% <UnSpec> in the returned nPnames matrix.
%
% Effects are identified using the special characters `_*()[]{}' used in
% parameter naming as follows: (here ? is a wildcard)
% - ?(?) - general block (column normalised)
% - ?[?] - specific block (block normalised)
% - ?_{?} - main effect or interaction of main effects
% - ?@?_{?} - factor by covariate interaction
% Blocks are identified by looking for runs of parameters of the same type
% with the same names: E.g. a block of main effects for factor 'Fac1'
% would have names like Fac1_{?}.
%
% Scaling is as follows:
% * fMRI blocks are scaled around zero to lie in [-1,1]
% * No scaling is carried out if max(abs(tX(:))) is in [.4,1]
% This protects dummy variables from normalisation, even if
% using implicit sum-to-zero constraints.
% * If the block has a single value, it's replaced by 1's
% * FxC blocks are normalised so the covariate values cover [-1,1]
% but leaving zeros as zero.
% * Otherwise, block is scaled to cover [-1,1].
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm_DesMtx.m 4137 2010-12-15 17:18:32Z guillaume $
%-Parse arguments for recursive construction of design matrices
%=======================================================================
if nargin==0 error('Insufficient arguments'), end
if ischar(varargin{1})
%-Non-recursive action string usage
Constraint=varargin{1};
elseif nargin>=2 && ~(ischar(varargin{2}) || iscell(varargin{2}))
[X1,Pnames1]=spm_DesMtx(varargin{1});
[X2,Pnames2]=spm_DesMtx(varargin{2:end});
X=[X1,X2]; Pnames=[Pnames1;Pnames2];
return
elseif nargin>=3 && ~(ischar(varargin{3}) || iscell(varargin{3}))
[X1,Pnames1]=spm_DesMtx(varargin{1:2});
[X2,Pnames2]=spm_DesMtx(varargin{3:end});
X=[X1,X2]; Pnames=[Pnames1;Pnames2];
return
elseif nargin>=4
[X1,Pnames1]=spm_DesMtx(varargin{1:3});
[X2,Pnames2]=spm_DesMtx(varargin{4:end});
X=[X1,X2]; Pnames=[Pnames1;Pnames2];
return
else
%-If I is a vector, make it a column vector
I=varargin{1}; if size(I,1)==1, I=I'; end
%-Sort out constraint and Factor/Covariate name parameters
if nargin<2, Constraint='-'; else Constraint=varargin{2}; end
if isempty(I), Constraint='mt'; end
if nargin<3, FCnames={}; else FCnames=varargin{3}; end
if char(FCnames), FCnames=cellstr(FCnames); end
end
switch Constraint, case 'mt' %-Empty I case
%=======================================================================
X = [];
Pnames = {};
Index = [];
case {'C','X'} %-Covariate effect, or ready-made design matrix
%=======================================================================
%-I contains a covariate (C), or is to be inserted "as is" (X)
X = I;
%-Construct parameter name index
%-----------------------------------------------------------------------
if isempty(FCnames)
if strcmp(Constraint,'C'), FCnames={'<Cov>'}; else FCnames={'<X>'}; end
end
if length(FCnames)==1 && size(X,2)>1
Pnames = cell(size(X,2),1);
for i=1:size(X,2)
Pnames{i} = sprintf('%s [%d]',FCnames{1},i);
end
elseif length(FCnames)~=size(X,2)
error('FCnames doesn''t match covariate/X matrix')
else
Pnames = FCnames;
end
case {'-(1)','~(1)'} %-Simple main effect ('~' ignores zero levels)
%=======================================================================
%-Sort out arguments
%-----------------------------------------------------------------------
if size(I,2)>1, error('Simple main effect requires vector index'), end
if any(I~=floor(I)), error('Non-integer indicator vector'), end
if isempty(FCnames), FCnames = {'<Fac>'};
elseif length(FCnames)>1, error('Too many FCnames'), end
nXrows = size(I,1);
% Sort out unique factor levels - ignore zero level in '~(1)' usage
%-----------------------------------------------------------------------
if Constraint(1)~='~'
[Index,idx,jdx] = unique(I');
kdx = [1:nXrows];
else
[Index,idx,jdx] = unique(I(I~=0)');
kdx = find(I~=0)';
if isempty(Index)
X=[]; Pnames={}; Index=[];
warning(['factor has only zero level - ',...
'returning empty DesMtx partition'])
return
end
end
%-Set up unconstrained X matrix & construct parameter name index
%-----------------------------------------------------------------------
nXcols = length(Index);
%-Columns in ascending order of corresponding factor level
X = zeros(nXrows,nXcols);
Pnames = cell(nXcols,1);
for ii=1:nXcols %-ii indexes i in Index
X(:,ii) = I==Index(ii);
%-Can't use: for i=Index, X(:,i) = I==i; end
% in case Index has holes &/or doesn't start at 1!
Pnames{ii} = sprintf('%s_{%d}',FCnames{1},Index(ii));
end
%-Don't append effect level if only one level
if nXcols==1, Pnames=FCnames; end
case {'-','~'} %-Main effect / interaction ('~' ignores zero levels)
%=======================================================================
if size(I,2)==1
%-Main effect - process directly
[X,Pnames,Index,idx,jdx,kdx] = spm_DesMtx(I,[Constraint,'(1)'],FCnames);
return
end
if any((I(:))~=floor(I(:))), error('Non-integer indicator vector'), end
% Sort out unique factor level combinations & build design matrix
%-----------------------------------------------------------------------
%-Make "raw" index to unique effects
nI = I - ones(size(I,1),1)*min(I);
tmp = max(I)-min(I)+1;
tmp = [fliplr(cumprod(tmp(end:-1:2))),1];
rIndex = sum(nI.*(ones(size(I,1),1)*tmp),2)+1;
%-Ignore combinations where any factor has level zero in '~' usage
if Constraint(1)=='~'
rIndex(any(I==0,2))=0;
if all(rIndex==0)
X=[]; Pnames={}; Index=[];
warning(['no non-zero factor level combinations - ',...
'returning empty DesMtx partition'])
return
end
end
%-Build design matrix based on unique factor combinations
[X,null,sIndex,idx,jdx,kdx]=spm_DesMtx(rIndex,[Constraint,'(1)']);
%-Sort out Index matrix
Index = I(kdx(idx),:)';
%-Construct parameter name index
%-----------------------------------------------------------------------
if isempty(FCnames)
tmp = ['<Fac1>',sprintf('*<Fac%d>',2:size(I,2))];
elseif length(FCnames)==size(I,2)
tmp = [FCnames{1},sprintf('*%s',FCnames{2:end})];
else
error('#FCnames mismatches #Factors in interaction')
end
Pnames = cell(size(Index,2),1);
for c = 1:size(Index,2)
Pnames{c} = ...
[sprintf('%s_{%d',tmp,Index(1,c)),sprintf(',%d',Index(2:end,c)),'}'];
end
case {'FxC','-FxC','~FxC'} %-Factor dependent covariate effect
% ('~' ignores zero factor levels)
%=======================================================================
%-Check
%-----------------------------------------------------------------------
if size(I,2)==1, error('FxC requires multi-column I'), end
F = I(:,1:end-1);
C = I(:,end);
if ~all(all(F==floor(F),1),2)
error('non-integer indicies in F partition of FxC'), end
if isempty(FCnames)
Fnames = '';
Cnames = '<Cov>';
elseif length(FCnames)==size(I,2)
Fnames = FCnames(1:end-1);
Cnames = FCnames{end};
else
error('#FCnames mismatches #Factors+#Cov in FxC')
end
%-Set up design matrix X & names matrix - ignore zero levels if '~FxC' use
%-----------------------------------------------------------------------
if Constraint(1)~='~', [X,Pnames,Index] = spm_DesMtx(F,'-',Fnames);
else [X,Pnames,Index] = spm_DesMtx(F,'~',Fnames); end
X = X.*(C*ones(1,size(X,2)));
Pnames = cellstr([repmat([Cnames,'@'],size(Index,2),1),char(Pnames)]);
case {'.','.0','+0','+0m'} %-Constrained simple main effect
%=======================================================================
if size(I,2)~=1, error('Simple main effect requires vector index'), end
[X,Pnames,Index] = spm_DesMtx(I,'-(1)',FCnames);
%-Impose constraint if more than one effect
%-----------------------------------------------------------------------
%-Apply uniqueness constraints ('.' & '+0') to last effect, which is
% in last column, since column i corresponds to level Index(i)
%-'.0' corner point constraint is applied to zero factor level only
nXcols = size(X,2);
zCol = find(Index==0);
if nXcols==1 && ~strcmp(Constraint,'.0')
error('only one level: can''t constrain')
elseif strcmp(Constraint,'.')
X(:,nXcols)=[]; Pnames(nXcols)=[]; Index(nXcols)=[];
elseif strcmp(Constraint,'.0')
zCol = find(Index==0);
if isempty(zCol), warning('no zero level to constrain')
elseif nXcols==1, error('only one level: can''t constrain'), end
X(:,zCol)=[]; Pnames(zCol)=[]; Index(zCol)=[];
elseif strcmp(Constraint,'+0')
X(find(X(:,nXcols)),:)=-1;
X(:,nXcols)=[]; Pnames(nXcols)=[]; Index(nXcols)=[];
elseif strcmp(Constraint,'+0m')
X = X - 1/nXcols;
end
case {'.i','.i0','.j','.j0','.ij','.ij0','+i0','+j0','+ij0','+i0m','+j0m'}
%-Two way interaction effects
%=======================================================================
if size(I,2)~=2, error('Two way interaction requires Nx2 index'), end
[X,Pnames,Index] = spm_DesMtx(I,'-',FCnames);
%-Implicit sum to zero
%-----------------------------------------------------------------------
if any(strcmp(Constraint,{'+i0m','+j0m'}))
SumIToZero = strcmp(Constraint,'+i0m');
SumJToZero = strcmp(Constraint,'+j0m');
if SumIToZero %-impose implicit SumIToZero constraints
Js = sort(Index(2,:)); Js = Js([1,1+find(diff(Js))]);
for j = Js
rows = find(I(:,2)==j);
cols = find(Index(2,:)==j);
if length(cols)==1
error('Only one level: Can''t constrain')
end
X(rows,cols) = X(rows,cols) - 1/length(cols);
end
end
if SumJToZero %-impose implicit SumJToZero constraints
Is = sort(Index(1,:)); Is = Is([1,1+find(diff(Is))]);
for i = Is
rows = find(I(:,1)==i);
cols = find(Index(1,:)==i);
if length(cols)==1
error('Only one level: Can''t constrain')
end
X(rows,cols) = X(rows,cols) - 1/length(cols);
end
end
%-Explicit sum to zero
%-----------------------------------------------------------------------
elseif any(strcmp(Constraint,{'+i0','+j0','+ij0'}))
SumIToZero = any(strcmp(Constraint,{'+i0','+ij0'}));
SumJToZero = any(strcmp(Constraint,{'+j0','+ij0'}));
if SumIToZero %-impose explicit SumIToZero constraints
i = max(Index(1,:));
if i==min(Index(1,:))
error('Only one i level: Can''t constrain'), end
cols = find(Index(1,:)==i); %-columns to delete
for c=cols
j=Index(2,c);
t_cols=find(Index(2,:)==j);
t_rows=find(X(:,c));
%-This ij equals -sum(ij) over other i
% (j fixed for this col c).
%-So subtract weight of this ij factor from
% weights for all other ij factors for this j
% to impose the constraint.
X(t_rows,t_cols) = X(t_rows,t_cols)...
-X(t_rows,c)*ones(1,length(t_cols));
%-( Next line would do it, but only first time round, when all )
% ( weights are 1, and only one weight per row for this j. )
% X(t_rows,t_cols)=-1*ones(length(t_rows),length(t_cols));
end
%-delete columns
X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];
end
if SumJToZero %-impose explicit SumJToZero constraints
j = max(Index(2,:));
if j==min(Index(2,:))
error('Only one j level: Can''t constrain'), end
cols=find(Index(2,:)==j);
for c=cols
i=Index(1,c);
t_cols=find(Index(1,:)==i);
t_rows=find(X(:,c));
X(t_rows,t_cols) = X(t_rows,t_cols)...
-X(t_rows,c)*ones(1,length(t_cols));
end
%-delete columns
X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];
end
%-Corner point constraints
%-----------------------------------------------------------------------
elseif any(strcmp(Constraint,{'.i','.i0','.j','.j0','.ij','.ij0'}))
CornerPointI = any(strcmp(Constraint,{'.i','.i0','.ij','.ij0'}));
CornerPointJ = any(strcmp(Constraint,{'.j','.j0','.ij','.ij0'}));
if CornerPointI %-impose CornerPointI constraints
if Constraint(end)~='0', i = max(Index(1,:));
else i = 0; end
cols=find(Index(1,:)==i); %-columns to delete
if isempty(cols)
warning('no zero i level to constrain')
elseif all(Index(1,:)==i)
error('only one i level: can''t constrain')
end
%-delete columns
X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];
end
if CornerPointJ %-impose CornerPointJ constraints
if Constraint(end)~='0', j = max(Index(2,:));
else j = 0; end
cols=find(Index(2,:)==j);
if isempty(cols)
warning('no zero j level to constrain')
elseif all(Index(2,:)==j)
error('only one j level: can''t constrain')
end
X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[];
end
end
case {'PDS','pds'} %-Patterned data set utility
%=======================================================================
% i = spm_DesMtx('pds',v,m,n)
if nargin<4, n=1; else n=varargin{4}; end
if nargin<3, m=1; else m=varargin{3}; end
if nargin<2, varargout={[]}; return, else v=varargin{2}; end
if any([size(n),size(m)])>1, error('n & m must be scalars'), end
if any(([m,n]~=floor([m,n]))|([m,n]<1))
error('n & m must be natural numbers'), end
if sum(size(v)>1)>1, error('v must be a vector'), end
%-Computation
%-----------------------------------------------------------------------
si = ones(1,ndims(v)); si(find(size(v)>1))=n*m*length(v);
X = reshape(repmat(v(:)',m,n),si);
case {'Sca','sca'} %-Scale DesMtx for imaging
%=======================================================================
nX = []; nPnames = {}; Carg = 2;
%-Loop through the arguments accumulating scaled design matrix nX
%-----------------------------------------------------------------------
while(Carg <= nargin)
rX = varargin{Carg}; Carg=Carg+1;
if Carg<=nargin && ~isempty(varargin{Carg}) && ...
(ischar(varargin{Carg}) || iscellstr(varargin{Carg}))
rPnames = char(varargin{Carg}); Carg=Carg+1;
else %-No names to work out blocks from - normalise by column
rPnames = repmat('<UnSpec>',size(rX,2),1);
end
%-Pad out rPnames with 20 spaces to permit looking past line ends
rPnames = [rPnames,repmat(' ',size(rPnames,1),20)];
while(~isempty(rX))
if size(rX,2)>1 && max([1,find(rPnames(1,:)=='(')]) < ...
max([0,find(rPnames(1,:)==')')])
%-Non-specific block: find the rest & column normalise round zero
%===============================================================
c1 = max(find(rPnames(1,:)=='('));
d = any(diff(abs(rPnames(:,1:c1))),2)...
| ~any(rPnames(2:end,c1+1:end)==')',2);
t = min(find([d;1]));
%-Normalise columns of block around zero
%-------------------------------------------------------
tmp = size(nX,2);
nX = [nX, zeros(size(rX,1),t)];
for i=1:t
if ~any(rX(:,i))
nX(:,tmp+i) = 0;
else
nX(:,tmp+i) = rX(:,i)/max(abs(rX(:,i)));
end
end
nPnames = [nPnames; cellstr(rPnames(1:t,:))];
rX(:,1:t) = []; rPnames(1:t,:)=[];
elseif size(rX,2)>1 && max([1,find(rPnames(1,:)=='[')]) < ...
max([0,find(rPnames(1,:)==']')])
%-Block: find the rest & normalise together
%===============================================================
c1 = max(find(rPnames(1,:)=='['));
d = any(diff(abs(rPnames(:,1:c1))),2)...
| ~any(rPnames(2:end,c1+1:end)==']',2);
t = min(find([d;1]));
%-Normalise block
%-------------------------------------------------------
nX = [nX,sf_tXsca(rX(:,1:t))];
nPnames = [nPnames; cellstr(rPnames(1:t,:))];
rX(:,1:t) = []; rPnames(1:t,:)=[];
elseif size(rX,2)>1 && max([1,strfind(rPnames(1,:),'_{')]) < ...
max([0,find(rPnames(1,:)=='}')])
%-Factor, interaction of factors, or FxC: find the rest...
%===============================================================
c1 = max(strfind(rPnames(1,:),'_{'));
d = any(diff(abs(rPnames(:,1:c1+1))),2)...
| ~any(rPnames(2:end,c1+2:end)=='}',2);
t = min(find([d;1]));
%-Normalise block
%-------------------------------------------------------
tX = rX(:,1:t);
if any(rPnames(1,1:c1)=='@') %-FxC interaction
C = tX(tX~=0);
tX(tX~=0) = 2*(C-min(C))/max(C-min(C))-1;
nX = [nX,tX];
else %-Straight interaction
nX = [nX,sf_tXsca(tX)];
end
nPnames = [nPnames; cellstr(rPnames(1:t,:))];
rX(:,1:t) = []; rPnames(1:t,:)=[];
else %-Dunno! Just column normalise
%===============================================================
nX = [nX,sf_tXsca(rX(:,1))];
nPnames = [nPnames; cellstr(rPnames(1,:))];
rX(:,1) = []; rPnames(1,:)=[];
end
end
end
X = nX;
Pnames = nPnames;
case {'Fnames','fnames'} %-Turn parameter names into valid filenames
%=======================================================================
% Fnames = spm_DesMtx('FNames',Pnames)
if nargin<2, varargout={''}; return, end
Fnames = varargin{2};
for i=1:numel(Fnames)
str = Fnames{i};
str(str==',')='x'; %-',' to 'x'
str(str=='*')='-'; %-'*' to '-'
str(str=='@')='-'; %-'@' to '-'
str(str==' ')='_'; %-' ' to '_'
str(str=='/')=''; %- delete '/'
str(str=='.')=''; %- delete '.'
Fnames{i} = str;
end
Fnames = spm_str_manip(Fnames,'v'); %- retain only legal characters
X = Fnames;
case {'TeXnames','texnames'} %-Remove '@' & '*' for TeX interpretation
%=======================================================================
% TPnames = spm_DesMtx('TeXnames',Pnames)
if nargin<2, varargout={''}; return, end
TPnames = varargin{2};
for i=1:prod(size(TPnames))
str = TPnames{i};
str(str=='*')=''; %- delete '*'
str(str=='@')=''; %- delete '@'
TPnames{i} = str;
end
X = TPnames;
case {'ParMap','parmap'} %-Parameter mappings: greek to english
%=======================================================================
% Map = spm_DesMtx('ParMap',aMap)
Map = { '\mu', 'const';...
'\theta', 'repl';...
'\alpha', 'cond';...
'\gamma', 'subj';...
'\rho', 'covint';...
'\zeta', 'global';...
'\epsilon', 'error'};
if nargin<2, aMap={}; else aMap = varargin{2}; end
if isempty(aMap), X=Map; return, end
if ~(iscellstr(aMap) && ndims(aMap)==2), error('aMap must be an nx2 cellstr'), end
for i=1:size(aMap,1)
j = find(strcmp(aMap{i,1},Map(:,1)));
if isempty(j)
Map=[aMap(i,:); Map];
else
Map(j,2) = aMap(i,2);
end
end
X = Map;
case {'ETeXNames','etexnames'} %-Search & replace: for Englishifying TeX
%=======================================================================
% EPnames = spm_DesMtx('TeXnames',Pnames,aMap)
if nargin<2, varargout={''}; return, end
if nargin<3, aMap={}; else aMap = varargin{3}; end
Map = spm_DesMtx('ParMap',aMap);
EPnames = varargin{2};
for i=1:size(Map,1)
EPnames = strrep(EPnames,Map{i,1},Map{i,2});
end
X = EPnames;
otherwise %-Mis-specified arguments - ERROR
%=======================================================================
if ischar(varargin{1})
error('unrecognised action string')
else
error('unrecognised constraint type')
end
%=======================================================================
end
%=======================================================================
% - S U B F U N C T I O N S
%=======================================================================
function nX = sf_tXsca(tX)
if nargin==0, nX=[]; return, end
if abs(max(abs(tX(:)))-0.7)<(.3+1e-10)
nX = tX;
elseif all(tX(:)==tX(1))
nX = ones(size(tX));
elseif max(abs(tX(:)))<1e-10
nX = zeros(size(tX));
else
nX = 2*(tX-min(tX(:)))/max(tX(:)-min(tX(:)))-1;
end
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_review_callbacks.m
|
.m
|
antx-master/xspm8/spm_eeg_review_callbacks.m
| 76,846 |
utf_8
|
4bf26af64c0f704d189a16b6116cf1fb
|
function [varargout] = spm_eeg_review_callbacks(varargin)
% Callbacks of the M/EEG Review facility
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_review_callbacks.m 6071 2014-06-27 12:52:33Z guillaume $
spm('pointer','watch');
drawnow expose
try
D = get(spm_figure('FindWin','Graphics'),'userdata');
handles = D.PSD.handles;
end
switch varargin{1}
%% File I/O
case 'file'
switch varargin{2}
case 'save'
D0 = D;
D = meeg(rmfield(D,'PSD'));
save(D);
D = D0;
D.PSD.D0 = rmfield(D,'PSD');
set(D.PSD.handles.hfig,'userdata',D)
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[0.8314 0.8157 0.7843])
case 'saveHistory'
spm_eeg_history(D);
end
%% Get information from MEEG object
case 'get'
switch varargin{2}
case 'VIZU'
visuSensors = varargin{3};
VIZU.visuSensors = visuSensors;
VIZU.montage.clab = {D.channels(visuSensors).label};
if strcmp(D.transform.ID,'time')
M = sparse(length(visuSensors),length(D.channels));
M(sub2ind(size(M),1:length(visuSensors),visuSensors(:)')) = 1;
nts = min([2e2,D.Nsamples]);
decim = max([floor(D.Nsamples./nts),1]);
data = D.data.y(visuSensors,1:decim:D.Nsamples,:);
sd = mean(abs(data(:)-mean(data(:))));%std(data(:));
offset = (0:1:length(visuSensors)-1)'*(sd+eps)/2;
v_data = 0.25.*data +repmat(offset,[1 size(data,2) size(data,3)]);
ma = max(v_data(:))+sd;
mi = min(v_data(:))-sd;
ylim = [mi ma];
VIZU.visu_scale = 0.25;
VIZU.FontSize = 10;
VIZU.visu_offset = sd;
VIZU.offset = offset;
VIZU.ylim = ylim;
VIZU.ylim0 = ylim;
VIZU.figname = 'main visualization window';
VIZU.montage.M = M;
VIZU.y2 = permute(sum(data.^2,1),[2 3 1]);
VIZU.sci = size(VIZU.y2,1)./D.Nsamples;
else
nts = min([2e2,D.Nsamples*length(D.transform.frequencies)]);
decim = max([floor(D.Nsamples*length(D.transform.frequencies)./nts),1]);
data = D.data.y(visuSensors,:,1:decim:D.Nsamples,:);
VIZU.ylim = [min(data(:)) max(data(:))];
end
varargout{1} = VIZU;
return
case 'commentInv'
invN = varargin{3};
str = getInfo4Inv(D,invN);
varargout{1} = str;
return
case 'dataInfo'
str = getInfo4Data(D);
varargout{1} = str;
return
case 'uitable'
D = getUItable(D);
case 'prep'
Finter = spm_figure('GetWin','Interactive');
D = struct(get(Finter, 'UserData'));
D0 = D.other(1).D0;
D.other = rmfield(D.other,{'PSD','D0'});
d1 = rmfield(D,'history');
d0 = rmfield(D0,'history');
if isequal(d1,d0)
% The objects only differ by their history
% => remove last operation from modified object
D.history(end) = [];
end
spm_eeg_review(D);
hf = spm_figure('FindWin','Graphics');
D = get(hf,'userdata');
D.PSD.D0 = D0;
set(hf,'userdata',D);
spm_eeg_review_callbacks('visu','update')
spm_clf(Finter)
end
%% Visualization callbacks
case 'visu'
switch varargin{2}
%% Switch main uitabs: EEG/MEG/OTHER/INFO/SOURCE
case 'main'
try
D.PSD.VIZU.fromTab = D.PSD.VIZU.modality;
catch
D.PSD.VIZU.fromTab = [];
end
switch varargin{3}
case 'eeg'
D.PSD.VIZU.modality = 'eeg';
case 'meg'
D.PSD.VIZU.modality = 'meg';
case 'megplanar'
D.PSD.VIZU.modality = 'megplanar';
case 'other'
D.PSD.VIZU.modality = 'other';
case 'source'
D.PSD.VIZU.modality = 'source';
case 'info';
D.PSD.VIZU.modality = 'info';
try
D.PSD.VIZU.info = varargin{4};
end
case 'standard'
D.PSD.VIZU.type = 1;
case 'scalp'
D.PSD.VIZU.type = 2;
end
try,D.PSD.VIZU.xlim = get(handles.axes(1),'xlim');end
[D] = spm_eeg_review_switchDisplay(D);
try
updateDisp(D,1);
catch
set(D.PSD.handles.hfig,'userdata',D);
end
%% Switch from 'standard' to 'scalp' display type
case 'switch'
mod = get(gcbo,'userdata');
if ~isequal(mod,D.PSD.VIZU.type)
if mod == 1
spm_eeg_review_callbacks('visu','main','standard')
else
spm_eeg_review_callbacks('visu','main','scalp')
end
end
%% Update display
case 'update'
try D = varargin{3};end
updateDisp(D)
%% Scalp interpolation
case 'scalp_interp'
if ~isempty([D.channels(:).X_plot2D])
x = round(mean(get(handles.axes(1),'xlim')));
ylim = get(handles.axes(1),'ylim');
if D.PSD.VIZU.type==1
in.hl = line('parent',handles.axes,...
'xdata',[x;x],...
'ydata',[ylim(1);ylim(2)]);
end
switch D.PSD.type
case 'continuous'
trN = 1;
case 'epoched'
trN = D.PSD.trials.current(1);
in.trN = trN;
end
in.gridTime = (1:D.Nsamples).*1e3./D.Fsample + D.timeOnset.*1e3;
in.unit = 'ms';
in.x = x;
in.handles = handles;
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
in.type = 'EEG';
case 'meg'
I = D.PSD.MEG.I;
in.type = 'MEG';
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
in.type = 'MEGPLANAR';
case 'other'
I = D.PSD.other.I;
in.type = 'other';
end
I = intersect(I,find(~[D.channels.bad]));
try
pos(:,1) = [D.channels(I).X_plot2D]';
pos(:,2) = [D.channels(I).Y_plot2D]';
labels = {D.channels(I).label};
y = D.data.y(I,:,trN);
in.min = min(y(:));
in.max = max(y(:));
in.ind = I;
y = y(:,x);
spm_eeg_plotScalpData(y,pos,labels,in);
try
D.PSD.handles.hli = in.hl;
set(D.PSD.handles.hfig,'userdata',D);
end
catch
msgbox('Get 2d positions for these channels!')
end
else
msgbox('Get 2d positions for EEG/MEG channels!')
end
%% Display sensor positions (and canonical cortical mesh)
case 'sensorPos'
% get canonical mesh
mco = fullfile(spm('Dir'),'canonical','cortex_5124.surf.gii');
msc = fullfile(spm('Dir'),'canonical','scalp_2562.surf.gii');
% get and plot 3D sensor positions
try % EEG
try
for i=1:numel(D.other.inv{end}.datareg)
if isequal(D.other.inv{end}.datareg(i).modality,'EEG')
pos3d = spm_eeg_inv_transform_points(...
D.other.inv{end}.datareg(i).toMNI,...
D.other.inv{end}.datareg(i).sensors.pnt);
end
end
opt.figname = 'Coregistred EEG sensor positions';
catch
pos3d = [D.sensors.eeg.pnt];
pos3d = pos3d(D.PSD.EEG.I,:);
opt.figname = 'Uncoregistred EEG sensor positions';
end
pos3d(1,:);
% display canonical mesh
o = spm_eeg_render(mco,opt);
opt.hfig = o.handles.fi;
opt.ParentAxes = o.handles.ParentAxes;
o = spm_eeg_render(msc,opt);
set(o.handles.p,'FaceAlpha',0.75)
set(o.handles.transp,'value',0.75)
% display sensor position
figure(o.handles.fi);
set(opt.ParentAxes,'nextplot','add')
plot3(opt.ParentAxes,...
pos3d(:,1),pos3d(:,2),pos3d(:,3),'.');
try
labels = D.PSD.EEG.VIZU.montage.clab;
text(pos3d(:,1),pos3d(:,2),pos3d(:,3),...
labels,...
'parent',opt.ParentAxes);
end
axis(opt.ParentAxes,'equal')
axis(opt.ParentAxes,'tight')
axis(opt.ParentAxes,'off')
end
try % MEG
clear opt pos3d o labels
try % multimodal EEG/MEG
for i=1:numel(D.other.inv{end}.datareg)
if isequal(D.other.inv{end}.datareg(i).modality,'MEG')
pos3d = spm_eeg_inv_transform_points(...
D.other.inv{end}.datareg(i).toMNI,...
D.other.inv{end}.datareg(i).sensors.pnt);
end
end
opt.figname = 'Coregistred MEG sensor positions';
catch
pos3d = [D.sensors.meg.pnt];
opt.figname = 'Uncoregistred MEG sensor positions';
end
pos3d(1,:);
% display canonical mesh
o = spm_eeg_render(mco,opt);
opt.hfig = o.handles.fi;
opt.ParentAxes = o.handles.ParentAxes;
o = spm_eeg_render(msc,opt);
set(o.handles.p,'FaceAlpha',0.75)
set(o.handles.transp,'value',0.75)
% display sensor position
figure(o.handles.fi);
set(opt.ParentAxes,'nextplot','add')
plot3(opt.ParentAxes,...
pos3d(:,1),pos3d(:,2),pos3d(:,3),'.');
try
labels = cat(2,...
D.PSD.MEG.VIZU.montage.clab,...
D.PSD.MEGPLANAR.VIZU.montage.clab);
text(pos3d(:,1),pos3d(:,2),pos3d(:,3),...
labels,...
'parent',opt.ParentAxes);
end
axis(opt.ParentAxes,'equal')
axis(opt.ParentAxes,'tight')
axis(opt.ParentAxes,'off')
end
%% Update display for 'SOURCE' main tab
case 'inv'
cla(D.PSD.handles.axes2,'reset')
D.PSD.source.VIZU.current = varargin{3};
updateDisp(D);
%% Check xlim when resizing display window using 'standard'
%% display type
case 'checkXlim'
xlim = varargin{3};
ud = get(D.PSD.handles.gpa,'userdata');
xm = mean(xlim);
sw = abs(diff(xlim));
if sw <= ud.v.minSizeWindow
sw = ud.v.minSizeWindow;
elseif sw >= ud.v.nt
sw = ud.v.maxSizeWindow;
elseif sw >= ud.v.maxSizeWindow
sw = ud.v.maxSizeWindow;
end
if xlim(1) <= 1 && xlim(end) >= ud.v.nt
xlim = [1,ud.v.nt];
elseif xlim(1) <= 1
xlim = [1,sw];
elseif xlim(end) >= ud.v.nt
xlim = [ud.v.nt-sw+1,ud.v.nt];
end
% Restrain buttons usage:
if isequal(xlim,[1,ud.v.nt])
set(D.PSD.handles.BUTTONS.vb3,'enable','off')
set(handles.BUTTONS.slider_step,'visible','off')
set(D.PSD.handles.BUTTONS.goPlusOne,'visible','off');
set(D.PSD.handles.BUTTONS.goMinusOne,'visible','off');
else
set(handles.BUTTONS.slider_step,...
'min',sw/2,'max',ud.v.nt-sw/2+1,...
'value',mean(xlim),...
'sliderstep',.1*[sw/(ud.v.nt-1) 4*sw/(ud.v.nt-1)],...
'visible','on');
set(D.PSD.handles.BUTTONS.goPlusOne,'visible','on');
set(D.PSD.handles.BUTTONS.goMinusOne,'visible','on');
if isequal(sw,ud.v.maxSizeWindow)
set(D.PSD.handles.BUTTONS.vb3,'enable','off')
set(D.PSD.handles.BUTTONS.vb4,'enable','on')
elseif isequal(sw,ud.v.minSizeWindow)
set(D.PSD.handles.BUTTONS.vb4,'enable','off')
set(D.PSD.handles.BUTTONS.vb3,'enable','on')
else
set(D.PSD.handles.BUTTONS.vb4,'enable','on')
set(D.PSD.handles.BUTTONS.vb3,'enable','on')
end
if xlim(1) == 1
set(D.PSD.handles.BUTTONS.goMinusOne,...
'visible','on','enable','off');
set(D.PSD.handles.BUTTONS.goPlusOne,...
'visible','on','enable','on');
elseif xlim(2) == ud.v.nt
set(D.PSD.handles.BUTTONS.goPlusOne,...
'visible','on','enable','off');
set(D.PSD.handles.BUTTONS.goMinusOne,...
'visible','on','enable','on');
else
set(D.PSD.handles.BUTTONS.goPlusOne,...
'visible','on','enable','on');
set(D.PSD.handles.BUTTONS.goMinusOne,...
'visible','on','enable','on');
end
end
if nargout >= 1
varargout{1} = xlim;
else
D.PSD.VIZU.xlim = xlim;
set(D.PSD.handles.hfig,'userdata',D)
end
%% Contrast/intensity rescaling
case 'iten_sc'
switch D.PSD.VIZU.modality
case 'eeg'
D.PSD.EEG.VIZU.visu_scale = varargin{3}*D.PSD.EEG.VIZU.visu_scale;
case 'meg'
D.PSD.MEG.VIZU.visu_scale = varargin{3}*D.PSD.MEG.VIZU.visu_scale;
case 'megplanar'
D.PSD.MEGPLANAR.VIZU.visu_scale = varargin{3}*D.PSD.MEGPLANAR.VIZU.visu_scale;
case 'other'
D.PSD.other.VIZU.visu_scale = varargin{3}*D.PSD.other.VIZU.visu_scale;
end
updateDisp(D,3);
%% Resize plotted data window ('standard' display type)
case 'time_w'
% Get current plotted data window range and limits
xlim = get(handles.axes(1),'xlim');
sw = varargin{3}*diff(xlim);
xm = mean(xlim);
xlim = xm + 0.5*[-sw,sw];
xlim = spm_eeg_review_callbacks('visu','checkXlim',xlim);
D.PSD.VIZU.xlim = xlim;
updateDisp(D,4)
%% Scroll through data ('standard' display type)
case 'slider_t'
offset = get(gco,'value');
updateDisp(D)
%% Scroll through data page by page ('standard' display type)
case 'goOne'
% Get current plotted data window range and limits
xlim = get(handles.axes(1),'xlim');
sw = diff(xlim);
xlim = xlim +varargin{3}*sw;
xlim = spm_eeg_review_callbacks('visu','checkXlim',xlim);
D.PSD.VIZU.xlim = xlim;
updateDisp(D,4)
%% Zoom
case 'zoom'
switch D.PSD.VIZU.type
case 1 % 'standard' display type
if ~isempty(D.PSD.handles.zoomh)
switch get(D.PSD.handles.zoomh,'enable')
case 'on'
set(D.PSD.handles.zoomh,'enable','off')
case 'off'
set(D.PSD.handles.zoomh,'enable','on')
end
else
if get(D.PSD.handles.BUTTONS.vb5,'value')
zoom on;
else
zoom off;
end
%set(D.PSD.handles.BUTTONS.vb5,'value',~val);
end
case 2 % 'scalp' display type
set(D.PSD.handles.BUTTONS.vb5,'value',1)
switch D.PSD.VIZU.modality
case 'eeg'
VIZU = D.PSD.EEG.VIZU;
case 'meg'
VIZU = D.PSD.MEG.VIZU;
case 'megplanar'
VIZU = D.PSD.MEGPLANAR.VIZU;
case 'other'
VIZU = D.PSD.other.VIZU;
end
try axes(D.PSD.handles.scale);end
[x] = ginput(1);
indAxes = get(gco,'userdata');
if ~~indAxes
hf = figure('color',[1 1 1]);
chanLabel = D.channels(VIZU.visuSensors(indAxes)).label;
if D.channels(VIZU.visuSensors(indAxes)).bad
chanLabel = [chanLabel,' (BAD)'];
end
set(hf,'name',['channel ',chanLabel])
ha2 = axes('parent',hf,...
'nextplot','add',...
'XGrid','on','YGrid','on');
trN = D.PSD.trials.current(:);
Ntrials = length(trN);
if strcmp(D.transform.ID,'time')
leg = cell(Ntrials,1);
col = lines;
col = repmat(col(1:7,:),floor(Ntrials./7)+1,1);
hp = get(handles.axes(indAxes),'children');
pst = (0:1/D.Fsample:(D.Nsamples-1)/D.Fsample) + D.timeOnset;
pst = pst*1e3; % in msec
for i=1:Ntrials
datai = get(hp(Ntrials-i+1),'ydata')./VIZU.visu_scale;
plot(ha2,pst,datai,'color',col(i,:));
leg{i} = D.PSD.trials.TrLabels{trN(i)};
end
legend(leg)
set(ha2,'xlim',[min(pst),max(pst)],...
'ylim',get(D.PSD.handles.axes(indAxes),'ylim'))
xlabel(ha2,'time (in ms after time onset)')
unit = 'unknown';
try
unit = D.channels(VIZU.visuSensors(indAxes)).units;
end
if isequal(unit,'unknown')
ylabel(ha2,'field intensity ')
else
ylabel(ha2,['field intensity (in ',unit,')'])
end
title(ha2,['channel ',chanLabel,...
' (',D.channels(VIZU.visuSensors(indAxes)).type,')'])
else % time-frequency data
datai = squeeze(D.data.y(VIZU.visuSensors(indAxes),:,:,trN(1)));
pst = (0:1/D.Fsample:(D.Nsamples-1)/D.Fsample) + D.timeOnset;
pst = pst*1e3; % in msec
if any(size(datai)==1)
hp2 = plot(datai,...
'parent',ha2);
set(ha2,'xtick',1:10:length(pst),'xticklabel',pst(1:10:length(pst)),...
'xlim',[1 length(pst)]);
xlabel(ha2,'time (in ms after time onset)')
ylabel(ha2,'power in frequency space')
title(ha2,['channel ',chanLabel,...
' (',D.channels(VIZU.visuSensors(indAxes)).type,')',...
' -- frequency: ',num2str(D.transform.frequencies),' Hz'])
else
nx = max([1,length(pst)./10]);
xtick = floor(1:nx:length(pst));
ny = max([1,length(D.transform.frequencies)./10]);
ytick = floor(1:ny:length(D.transform.frequencies));
hp2 = image(datai,...
'CDataMapping','scaled',...
'parent',ha2);
colormap(ha2,jet)
colorbar('peer',ha2)
set(ha2,...
'xtick',xtick,...
'xticklabel',pst(xtick),...
'xlim',[0.5 length(pst)+0.5],...
'ylim',[0.5 size(datai,1)+0.5],...
'ytick',ytick,...
'yticklabel',D.transform.frequencies(ytick));
xlabel(ha2,'time (in ms after time onset)')
ylabel(ha2,'frequency (in Hz)')
title(ha2,['channel ',chanLabel,...
' (',D.channels(VIZU.visuSensors(indAxes)).type,')'])
caxis(ha2,VIZU.ylim)
end
end
axes(ha2)
end
set(D.PSD.handles.BUTTONS.vb5,'value',0)
end
otherwise;disp('unknown command !')
end
%% Events callbacks accessible from uicontextmenu
%% ('standard' display type when playing with 'continuous' data)
case 'menuEvent'
Nevents = length(D.trials.events);
x = [D.trials.events.time]';
x(:,2) = [D.trials.events.duration]';
x(:,2) = sum(x,2);
% Find the index of the selected event
currentEvent = get(gco,'userdata');
eventType = D.trials.events(currentEvent).type;
eventValue = D.trials.events(currentEvent).value;
tit = ['Current event is selection #',num2str(currentEvent),...
' /',num2str(Nevents),' (type= ',eventType,', value=',num2str(eventValue),').'];
switch varargin{2}
% Execute actions accessible from the event contextmenu : click
case 'click'
% Highlight the selected event
hh = findobj('selected','on');
set(hh,'selected','off');
set(gco,'selected','on')
% Prompt basic information on the selected event
disp(tit)
% Execute actions accessible from the event contextmenu : edit event properties
case 'EventProperties'
set(gco,'selected','on')
% Build GUI for manipulating the event properties
stc = cell(4,1);
default = cell(4,1);
stc{1} = 'Current event is a selection of type...';
stc{2} = 'Current event has value...';
stc{3} = 'Starts at (sec)...';
stc{4} = 'Duration (sec)...';
default{1} = eventType;
default{2} = num2str(eventValue);
default{3} = num2str(x(currentEvent,1));
default{4} = num2str(abs(diff(x(currentEvent,:))));
answer = inputdlg(stc,tit,1,default);
if ~isempty(answer)
try
eventType = answer{1};
eventValue = str2double(answer{2});
D.trials.events(currentEvent).time = str2double(answer{3});
D.trials.events(currentEvent).duration = str2double(answer{4});
D.trials.events(currentEvent).type = eventType;
D.trials.events(currentEvent).value = eventValue;
end
updateDisp(D,2,currentEvent)
end
% Execute actions accessible from the event contextmenu : go to next/previous event
case 'goto'
here = mean(x(currentEvent,:));
values = [D.trials.events.value];
xm = mean(x(values==eventValue,:),2);
if varargin{3} == 0
ind = find(xm < here);
else
ind = find(xm > here);
end
if ~isempty(ind)
if varargin{3} == 0
offset = round(max(xm(ind))).*D.Fsample;
else
offset = round(min(xm(ind))).*D.Fsample;
end
xlim0 = get(handles.axes,'xlim');
if ~isequal(xlim0,[1 D.Nsamples])
length_window = round(xlim0(2)-xlim0(1));
if offset < round(0.5*length_window)
offset = round(0.5*length_window);
set(handles.BUTTONS.slider_step,'value',1);
elseif offset > D.Nsamples-round(0.5*length_window)
offset = D.Nsamples-round(0.5*length_window)-1;
set(handles.BUTTONS.slider_step,'value',get(handles.BUTTONS.slider_step,'max'));
else
set(handles.BUTTONS.slider_step,'value',offset);
end
xlim = [offset-round(0.5*length_window) offset+round(0.5*length_window)];
xlim(1) = max([xlim(1) 1]);
xlim(2) = min([xlim(2) D.Nsamples]);
D.PSD.VIZU.xlim = xlim;
updateDisp(D,4)
end
end
% Execute actions accessible from the event contextmenu : delete event
case 'deleteEvent'
D.trials.events(currentEvent) = [];
updateDisp(D,2)
end
%% Events callbacks
case 'select'
switch varargin{2}
%% Switch to another trial (when playing with 'epoched' data)
case 'switch'
trN = get(gco,'value');
if ~strcmp(D.PSD.VIZU.modality,'source') && D.PSD.VIZU.type == 2
handles = rmfield(D.PSD.handles,'PLOT');
D.PSD.handles = handles;
else
try cla(D.PSD.handles.axes2,'reset');end
end
D.PSD.trials.current = trN;
status = any([D.trials(trN).bad]);
try
if status
str = 'declare as not bad';
else
str = 'declare as bad';
end
ud = get(D.PSD.handles.BUTTONS.badEvent,'userdata');
set(D.PSD.handles.BUTTONS.badEvent,...
'tooltipstring',str,...
'cdata',ud.img{2-status},'userdata',ud)
end
updateDisp(D,1)
%% Switch event to 'bad' (when playing with 'epoched' data)
case 'bad'
trN = D.PSD.trials.current;
status = any([D.trials(trN).bad]);
str1 = 'not bad';
str2 = 'bad';
if status
bad = 0;
lab = [' (',str1,')'];
str = ['declare as ',str2];
else
bad = 1;
lab = [' (',str2,')'];
str = ['declare as ',str1];
end
nt = length(trN);
for i=1:nt
D.trials(trN(i)).bad = bad;
D.PSD.trials.TrLabels{trN(i)} = ['Trial ',num2str(trN(i)),...
': ',D.trials(trN(i)).label,lab];
end
set(D.PSD.handles.BUTTONS.list1,'string',D.PSD.trials.TrLabels);
ud = get(D.PSD.handles.BUTTONS.badEvent,'userdata');
set(D.PSD.handles.BUTTONS.badEvent,...
'tooltipstring',str,...
'cdata',ud.img{2-bad},'userdata',ud)
set(D.PSD.handles.hfig,'userdata',D)
%% Add an event to current selection
%% (when playing with 'continuous' data)
case 'add'
[x,tmp] = ginput(1);
x = round(x);
x(1) = min([max([1 x(1)]) D.Nsamples]);
Nevents = length(D.trials.events);
D.trials.events(Nevents+1).time = x./D.Fsample;
D.trials.events(Nevents+1).duration = 0;
D.trials.events(Nevents+1).type = 'Manual';
D.PSD.handles.PLOT.e(Nevents+1) = 0;
if Nevents > 0
D.trials.events(Nevents+1).value = D.trials.events(Nevents).value;
else
D.trials.events(Nevents+1).value = 0;
end
% Enable tools on selections
set(handles.BUTTONS.sb2,'enable','on');
set(handles.BUTTONS.sb3,'enable','on');
% Update display
updateDisp(D,2,Nevents+1)
%% scroll through data upto next event
%% (when playing with 'continuous' data)
case 'goto'
here = get(handles.BUTTONS.slider_step,'value');
x = [D.trials.events.time]';
xm = x.*D.Fsample;
if varargin{3} == 0
ind = find(xm > here+1);
else
ind = find(xm < here-1);
end
if ~isempty(ind)
if varargin{3} == 1
offset = round(max(xm(ind)));
else
offset = round(min(xm(ind)));
end
xlim0 = get(handles.axes,'xlim');
if ~isequal(xlim0,[1 D.Nsamples])
length_window = round(xlim0(2)-xlim0(1));
if offset < round(0.5*length_window)
offset = round(0.5*length_window);
set(handles.BUTTONS.slider_step,'value',1);
elseif offset > D.Nsamples-round(0.5*length_window)
offset = D.Nsamples-round(0.5*length_window)-1;
set(handles.BUTTONS.slider_step,'value',get(handles.BUTTONS.slider_step,'max'));
else
set(handles.BUTTONS.slider_step,'value',offset);
end
xlim = [offset-round(0.5*length_window) offset+round(0.5*length_window)];
xlim(1) = max([xlim(1) 1]);
xlim(2) = min([xlim(2) D.Nsamples]);
D.PSD.VIZU.xlim = xlim;
set(handles.BUTTONS.slider_step,'value',offset);
updateDisp(D,4)
end
end
end
%% Edit callbacks (from spm_eeg_prep_ui)
case 'edit'
switch varargin{2}
case 'prep'
try rotate3d off;end
spm_eeg_prep_ui;
Finter = spm_figure('GetWin','Interactive');
D0 = D.PSD.D0;
D = rmfield(D,'PSD');
if isempty(D.other)
D.other = struct([]);
end
D.other(1).PSD = 1;
D.other(1).D0 = D0;
D = meeg(D);
set(Finter, 'UserData', D);
hc = get(Finter,'children');
delete(hc(end)); % get rid of 'file' uimenu...
%... and add an 'OK' button:
uicontrol(Finter,...
'style','pushbutton','string','OK',...
'callback','spm_eeg_review_callbacks(''get'',''prep'')',...
'tooltipstring','Update data informations in ''SPM Graphics'' window',...
'BusyAction','cancel',...
'Interruptible','off',...
'Tag','EEGprepUI');
spm_eeg_prep_ui('update_menu')
delete(setdiff(findobj(Finter), [Finter; findobj(Finter,'Tag','EEGprepUI')]));
figure(Finter);
end
end
% Check changes in the meeg object
if isstruct(D)&& isfield(D,'PSD') && ...
isfield(D.PSD,'D0')
d1 = rmfield(D,{'history','PSD'});
d0 = rmfield(D.PSD.D0,'history');
if isequal(d1,d0)
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[0.8314 0.8157 0.7843])
else
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[1 0.5 0.5])
end
end
spm('pointer','arrow');
drawnow expose
%% Main update display
function [] = updateDisp(D,flags,in)
% This function updates the display of the data and events.
if ~exist('flag','var')
flag = 0;
end
if ~exist('in','var')
in = [];
end
handles = D.PSD.handles;
% Create intermediary display variables : events
figure(handles.hfig)
% Get current event
try
trN = D.PSD.trials.current;
catch
trN = 1;
end
if ~strcmp(D.PSD.VIZU.modality,'source')
switch D.PSD.VIZU.modality
case 'eeg'
VIZU = D.PSD.EEG.VIZU;
case 'meg'
VIZU = D.PSD.MEG.VIZU;
case 'megplanar'
VIZU = D.PSD.MEGPLANAR.VIZU;
case 'other'
VIZU = D.PSD.other.VIZU;
case 'info'
return
end
switch D.PSD.VIZU.type
case 1
% Create new data to display
% - switch from scalp to standard displays
% - switch from EEG/MEG/OTHER/info/inv
if ismember(1,flags)
% delete previous axes...
try
delete(D.PSD.handles.axes)
delete(D.PSD.handles.gpa)
delete(D.PSD.handles.BUTTONS.slider_step)
end
% gather info for core display function
options.hp = handles.tabs.hp; %handles.hfig;
options.Fsample = D.Fsample;
options.timeOnset = D.timeOnset;
options.M = VIZU.visu_scale*full(VIZU.montage.M);
options.bad = [D.channels(VIZU.visuSensors(:)).bad];
if strcmp(D.PSD.type,'continuous') && ~isempty(D.trials.events)
trN = 1;
Nevents = length(D.trials.events);
x1 = {D.trials.events(:).type}';
x2 = {D.trials.events(:).value}';
if ~iscellstr(x1)
[y1,i1,j1] = unique(cell2mat(x1));
else
[y1,i1,j1] = unique(x1);
end
if ~iscellstr(x2)
[y2,i2,j2] = unique(cell2mat(x2));
else
[y2,i2,j2] = unique(x2);
end
A = [j1(:),j2(:)];
[ya,ia,ja] = unique(A,'rows');
options.events = rmfield(D.trials.events,{'duration','value'});
for i=1:length(options.events)
options.events(i).time = options.events(i).time.*D.Fsample;% +1;
options.events(i).type = ja(i);
end
end
if strcmp(D.PSD.type,'continuous')
options.minSizeWindow = 200;
try
options.itw = round(D.PSD.VIZU.xlim(1):D.PSD.VIZU.xlim(2));
end
elseif strcmp(D.PSD.type,'epoched')
options.minSizeWindow = 20;
try
options.itw = round(D.PSD.VIZU.xlim(1):D.PSD.VIZU.xlim(2));
catch
options.itw = 1:D.Nsamples;
end
else
try
options.itw = round(D.PSD.VIZU.xlim(1):D.PSD.VIZU.xlim(2));
catch
options.itw = 1:D.Nsamples;
end
options.minSizeWindow = 20;
end
options.minY = min(VIZU.ylim)-eps;
options.maxY = max(VIZU.ylim)+eps;
options.ds = 5e2;
options.pos1 = [0.08 0.11 0.86 0.79];
options.pos2 = [0.08 0.07 0.86 0.025];
options.pos3 = [0.08 0.02 0.86 0.02];
options.maxSizeWindow = 1e5;
options.tag = 'plotEEG';
options.offset = VIZU.offset;
options.ytick = VIZU.offset;
options.yticklabel = VIZU.montage.clab;
options.callback = ['spm_eeg_review_callbacks(''visu'',''checkXlim''',...
',get(ud.v.handles.axes,''xlim''))'];
% Use file_array for 'continuous' data.
if strcmp(D.PSD.type,'continuous')
options.transpose = 1;
ud = spm_DisplayTimeSeries(D.data.y,options);
else
ud = spm_DisplayTimeSeries(D.data.y(:,:,trN(1))',options);
end
% update D
D.PSD.handles.axes = ud.v.handles.axes;
D.PSD.handles.gpa = ud.v.handles.gpa;
D.PSD.handles.BUTTONS.slider_step = ud.v.handles.hslider;
D.PSD.handles.PLOT.p = ud.v.handles.hp;
% Create uicontextmenu for events (if any)
if isfield(options,'events')
D.PSD.handles.PLOT.e = [ud.v.et(:).hp];
axes(D.PSD.handles.axes)
for i=1:length(options.events)
sc.currentEvent = i;
sc.eventType = D.trials(trN(1)).events(i).type;
sc.eventValue = D.trials(trN(1)).events(i).value;
sc.N_select = Nevents;
psd_defineMenuEvent(D.PSD.handles.PLOT.e(i),sc);
end
end
for i=1:length(D.PSD.handles.PLOT.p)
cmenu = uicontextmenu;
uimenu(cmenu,'Label',['channel ',num2str(VIZU.visuSensors(i)),': ',VIZU.montage.clab{i}]);
uimenu(cmenu,'Label',['type: ',D.channels(VIZU.visuSensors(i)).type]);
uimenu(cmenu,'Label',['bad: ',num2str(D.channels(VIZU.visuSensors(i)).bad)],...
'callback',@switchBC,'userdata',i,...
'BusyAction','cancel',...
'Interruptible','off');
set(D.PSD.handles.PLOT.p(i),'uicontextmenu',cmenu);
end
set(D.PSD.handles.hfig,'userdata',D);
spm_eeg_review_callbacks('visu','checkXlim',...
get(D.PSD.handles.axes,'xlim'))
end
% modify events properties (delete,add,time,...)
if ismember(2,flags)
Nevents = length(D.trials.events);
if Nevents < length(D.PSD.handles.PLOT.e)
action = 'delete';
try,delete(D.PSD.handles.PLOT.e),end
try,D.PSD.handles.PLOT.e = [];end
else
action = 'modify';
end
col = lines;
col = col(1:7,:);
x1 = {D.trials.events(:).type}';
x2 = {D.trials.events(:).value}';
if ~iscellstr(x1)
[y1,i1,j1] = unique(cell2mat(x1));
else
[y1,i1,j1] = unique(x1);
end
if ~iscellstr(x2)
[y2,i2,j2] = unique(cell2mat(x2));
else
[y2,i2,j2] = unique(x2);
end
A = [j1(:),j2(:)];
[ya,ia,ja] = unique(A,'rows');
events = rmfield(D.trials.events,{'duration','value'});
switch action
case 'delete'
%spm_progress_bar('Init',Nevents,'Replacing events');
axes(D.PSD.handles.axes)
for i=1:Nevents
events(i).time = D.trials.events(i).time.*D.Fsample;% +1;
events(i).type = ja(i);
events(i).col = mod(events(i).type+7,7)+1;
D.PSD.handles.PLOT.e(i) = plot(D.PSD.handles.axes,...
events(i).time.*[1 1],...
VIZU.ylim,...
'color',col(events(i).col,:),...
'userdata',i,...
'ButtonDownFcn','set(gco,''selected'',''on'')',...
'Clipping','on');
% Add events uicontextmenu
sc.currentEvent = i;
sc.eventType = D.trials(trN(1)).events(i).type;
sc.eventValue = D.trials(trN(1)).events(i).value;
sc.N_select = Nevents;
psd_defineMenuEvent(D.PSD.handles.PLOT.e(i),sc);
%spm_progress_bar('Set',i)
end
%spm_progress_bar('Clear')
case 'modify'
events(in).time = D.trials.events(in).time.*D.Fsample;% +1;
events(in).type = ja(in);
events(in).col = mod(events(in).type+7,7)+1;
D.PSD.handles.PLOT.e(in) = plot(D.PSD.handles.axes,events(in).time.*[1 1],...
VIZU.ylim,'color',col(events(in).col,:));
set(D.PSD.handles.PLOT.e(in),'userdata',in,...
'ButtonDownFcn','set(gco,''selected'',''on'')',...
'Clipping','on');
% Add events uicontextmenu
sc.currentEvent = in;
sc.eventType = D.trials(trN(1)).events(in).type;
sc.eventValue = D.trials(trN(1)).events(in).value;
sc.N_select = Nevents;
psd_defineMenuEvent(D.PSD.handles.PLOT.e(in),sc);
end
set(handles.hfig,'userdata',D);
end
% modify scaling factor
if ismember(3,flags)
ud = get(D.PSD.handles.gpa,'userdata');
ud.v.M = VIZU.visu_scale*full(VIZU.montage.M);
xw = floor(get(ud.v.handles.axes,'xlim'));
xw(1) = max([1,xw(1)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xw(1):1:xw(2),:)';
else
My = ud.v.M*ud.y(:,xw(1):1:xw(2));
end
for i=1:ud.v.nc
set(ud.v.handles.hp(i),'xdata',xw(1):1:xw(2),'ydata',My(i,:)+ud.v.offset(i))
end
set(ud.v.handles.axes,'ylim',[ud.v.mi ud.v.ma],'xlim',xw);
set(D.PSD.handles.gpa,'userdata',ud);
set(handles.hfig,'userdata',D);
end
% modify plotted time window (goto, ...)
if ismember(4,flags)
ud = get(D.PSD.handles.gpa,'userdata');
xw = floor(D.PSD.VIZU.xlim);
xw(1) = max([1,xw(1)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xw(1):1:xw(2),:)';
else
My = ud.v.M*ud.y(:,xw(1):1:xw(2));
end
for i=1:ud.v.nc
set(ud.v.handles.hp(i),'xdata',xw(1):1:xw(2),'ydata',My(i,:)+ud.v.offset(i))
end
set(ud.v.handles.axes,'ylim',[ud.v.mi ud.v.ma],'xlim',xw);
set(ud.v.handles.pa,'xdata',[xw,fliplr(xw)]);
set(ud.v.handles.lb,'xdata',[xw(1) xw(1)]);
set(ud.v.handles.rb,'xdata',[xw(2) xw(2)]);
sw = diff(xw);
set(ud.v.handles.hslider,'value',mean(xw),...
'min',1+sw/2,'max',ud.v.nt-sw/2,...
'sliderstep',.1*[sw/(ud.v.nt-1) 4*sw/(ud.v.nt-1)]);
set(handles.hfig,'userdata',D);
end
case 2
if strcmp(D.transform.ID,'time')
Ntrials = length(trN);
v_data = zeros(size(VIZU.montage.M,1),...
size(D.data.y,2),Ntrials);
for i=1:Ntrials
v_datai = full(VIZU.montage.M)*D.data.y(:,:,trN(i));
v_datai = VIZU.visu_scale*(v_datai);
v_data(:,:,i) = v_datai;
end
% Create graphical objects if absent
if ~isfield(handles,'PLOT')
miY = min(v_data(:));
maY = max(v_data(:));
if miY == 0 && maY == 0
miY = -eps;
maY = eps;
else
miY = miY - miY.*1e-3;
maY = maY + maY.*1e-3;
end
for i=1:length(VIZU.visuSensors)
cmenu = uicontextmenu;
uimenu(cmenu,'Label',['channel ',num2str(VIZU.visuSensors(i)),': ',VIZU.montage.clab{i}]);
uimenu(cmenu,'Label',['type: ',D.channels(VIZU.visuSensors(i)).type]);
uimenu(cmenu,'Label',['bad: ',num2str(D.channels(VIZU.visuSensors(i)).bad)],...
'callback',@switchBC,'userdata',i,...
'BusyAction','cancel',...
'Interruptible','off');
status = D.channels(VIZU.visuSensors(i)).bad;
if ~status
color = [1 1 1];
else
color = 0.75*[1 1 1];
end
set(handles.fra(i),'uicontextmenu',cmenu);
set(handles.axes(i),'color',color,...
'ylim',[miY maY]./VIZU.visu_scale);
handles.PLOT.p(:,i) = plot(handles.axes(i),squeeze(v_data(i,:,:)),...
'uicontextmenu',cmenu,'userdata',i,'tag','plotEEG');
end
% Update axes limits and channel names
D.PSD.handles = handles;
else
% scroll through data
for i=1:length(VIZU.visuSensors)
for j=1:Ntrials
set(handles.PLOT.p(j,i),'ydata',v_data(i,:,j));
end
end
end
% Update scale axes
dz = (abs(diff(get(handles.axes(1),'ylim'))))./VIZU.visu_scale;
set(handles.scale,'yticklabel',num2str(dz));
set(handles.hfig,'userdata',D);
axes(D.PSD.handles.scale)
else %---- Time-frequency data !! ----%
for i=1:length(VIZU.visuSensors)
cmenu = uicontextmenu;
uimenu(cmenu,'Label',['channel ',num2str(VIZU.visuSensors(i)),': ',VIZU.montage.clab{i}]);
uimenu(cmenu,'Label',['type: ',D.channels(VIZU.visuSensors(i)).type]);
% uimenu(cmenu,'Label',['bad: ',num2str(D.channels(VIZU.visuSensors(i)).bad)],...
% 'callback',@switchBC,'userdata',i,...
% 'BusyAction','cancel',...
% 'Interruptible','off');
status = D.channels(VIZU.visuSensors(i)).bad;
if ~status
color = [1 1 1];
else
color = 0.75*[1 1 1];
end
datai = squeeze(D.data.y(VIZU.visuSensors(i),:,:,trN(1)));
miY = min(datai(:));
maY = max(datai(:));
if any(size(datai)==1)
D.PSD.handles.PLOT.im(i) = plot(datai,...
'parent',handles.axes(i),...
'tag','plotEEG',...
'userdata',i,...
'hittest','off');
set(handles.axes(i),...
'ylim',[miY maY]);
else
D.PSD.handles.PLOT.im(i) = image(datai,...
'parent',handles.axes(i),...
'CDataMapping','scaled',...
'tag','plotEEG',...
'userdata',i,...
'hittest','off');
end
set(handles.fra(i),'uicontextmenu',cmenu);
end
colormap(jet)
% This normalizes colorbars across channels and trials:
for i=1:length(VIZU.visuSensors)
caxis(handles.axes(i),VIZU.ylim);
end
set(handles.hfig,'userdata',D);
end
end
else % source space
% get model/trial info
VIZU = D.PSD.source.VIZU;
isInv = VIZU.isInv;
Ninv = length(isInv);
invN = VIZU.isInv(D.PSD.source.VIZU.current);
F = VIZU.F;
ID = VIZU.ID;
model = D.other.inv{invN}.inverse;
t0 = get(D.PSD.handles.BUTTONS.slider_step,'value');
tmp = (model.pst-t0).^2;
indTime = find(tmp==min(tmp));
gridTime = model.pst(indTime);
try % simple time scroll
% update time line
set(VIZU.lineTime,'xdata',[gridTime;gridTime]);
% update mesh's texture
tex = VIZU.J(:,indTime);
set(D.PSD.handles.mesh,'facevertexcdata',tex)
set(D.PSD.handles.BUTTONS.slider_step,'value',gridTime)
catch % VIZU.lineTime deleted -> switch to another source recon
% get the inverse model info
str = getInfo4Inv(D,invN);
set(D.PSD.handles.infoText,'string',str);
if Ninv>1
if isnan(ID(invN))
xF = find(isnan(ID));
else
xF = find(abs(ID-ID(invN))<eps);
end
if length(xF)>1
D.PSD.handles.hbar = bar(D.PSD.handles.BMCplot,...
xF ,F(xF)-min(F(xF)),...
'barwidth',0.5,...
'FaceColor',0.5*[1 1 1],...
'visible','off',...
'tag','plotEEG');
D.PSD.handles.BMCcurrent = plot(D.PSD.handles.BMCplot,...
find(xF==invN),0,'ro',...
'visible','off',...
'tag','plotEEG');
set(D.PSD.handles.BMCplot,...
'xtick',xF,...
'xticklabel',D.PSD.source.VIZU.labels(xF),...
'xlim',[0,length(xF)+1]);
drawnow
else
cla(D.PSD.handles.BMCplot);
set(D.PSD.handles.BMCplot,...
'xtick',[],...
'xticklabel',{});
end
end
% get model/trial time series
D.PSD.source.VIZU.J = zeros(model.Nd,size(model.T,1));
D.PSD.source.VIZU.J(model.Is,:) = model.J{trN(1)}*model.T';
D.PSD.source.VIZU.miJ = min(min(D.PSD.source.VIZU.J));
D.PSD.source.VIZU.maJ = max(max(D.PSD.source.VIZU.J));
% modify mesh/texture and add spheres...
tex = D.PSD.source.VIZU.J(:,indTime);
set(D.PSD.handles.axes,'CLim',...
[D.PSD.source.VIZU.miJ D.PSD.source.VIZU.maJ]);
set(D.PSD.handles.mesh,...
'Vertices',D.other.inv{invN}.mesh.tess_mni.vert,...
'Faces',D.other.inv{invN}.mesh.tess_mni.face,...
'facevertexcdata',tex);
try; delete(D.PSD.handles.dipSpheres);end
if isfield(D.other.inv{invN}.inverse,'dipfit') ||...
~isequal(D.other.inv{invN}.inverse.xyz,zeros(1,3))
try
xyz = D.other.inv{invN}.inverse.dipfit.Lpos;
radius = D.other.inv{invN}.inverse.dipfit.radius;
catch
xyz = D.other.inv{invN}.inverse.xyz';
radius = D.other.inv{invN}.inverse.rad(1);
end
Np = size(xyz,2);
[x,y,z] = sphere(20);
axes(D.PSD.handles.axes)
for i=1:Np
D.PSD.handles.dipSpheres(i) = patch(...
surf2patch(x.*radius+xyz(1,i),...
y.*radius+xyz(2,i),z.*radius+xyz(3,i)));
set(D.PSD.handles.dipSpheres(i),'facecolor',[1 1 1],...
'edgecolor','none','facealpha',0.5,...
'tag','dipSpheres');
end
end
% modify time series plot itself
switch D.PSD.source.VIZU.timeCourses
case 1
Jp(1,:) = min(D.PSD.source.VIZU.J,[],1);
Jp(2,:) = max(D.PSD.source.VIZU.J,[],1);
D.PSD.source.VIZU.plotTC = plot(D.PSD.handles.axes2,...
model.pst,Jp','color',0.5*[1 1 1]);
set(D.PSD.handles.axes2,'hittest','off')
% Add virtual electrode
% try
% ve = D.PSD.source.VIZU.ve;
% catch
[mj ve] = max(max(abs(D.PSD.source.VIZU.J),[],2));
D.PSD.source.VIZU.ve =ve;
% end
Jve = D.PSD.source.VIZU.J(D.PSD.source.VIZU.ve,:);
set(D.PSD.handles.axes2,'nextplot','add')
try
qC = model.qC(ve).*diag(model.qV)';
ci = 1.64*sqrt(qC);
D.PSD.source.VIZU.pve2 = plot(D.PSD.handles.axes2,...
model.pst,Jve +ci,'b:',model.pst,Jve -ci,'b:');
end
D.PSD.source.VIZU.pve = plot(D.PSD.handles.axes2,...
model.pst,Jve,'color','b');
set(D.PSD.handles.axes2,'nextplot','replace')
otherwise
% this is meant to be extended for displaying something
% else than just J (e.g. J^2, etc...)
end
grid(D.PSD.handles.axes2,'on')
box(D.PSD.handles.axes2,'on')
xlabel(D.PSD.handles.axes2,'peri-stimulus time (ms)')
ylabel(D.PSD.handles.axes2,'sources intensity')
% add time line repair
set(D.PSD.handles.axes2,...
'ylim',[D.PSD.source.VIZU.miJ,D.PSD.source.VIZU.maJ],...
'xlim',[D.PSD.source.VIZU.pst(1),D.PSD.source.VIZU.pst(end)],...
'nextplot','add');
D.PSD.source.VIZU.lineTime = line('parent',D.PSD.handles.axes2,...
'xdata',[gridTime;gridTime],...
'ydata',[D.PSD.source.VIZU.miJ,D.PSD.source.VIZU.maJ]);
set(D.PSD.handles.axes2,'nextplot','replace',...
'tag','plotEEG');
% change time slider value if out of bounds
set(D.PSD.handles.BUTTONS.slider_step,'value',gridTime)
% update data structure
set(handles.hfig,'userdata',D);
end
end
%% Switch 'bad channel' status
function [] = switchBC(varargin)
ind = get(gcbo,'userdata');
D = get(gcf,'userdata');
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
VIZU = D.PSD.EEG.VIZU;
case 'meg'
I = D.PSD.MEG.I;
VIZU = D.PSD.MEG.VIZU;
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
VIZU = D.PSD.MEGPLANAR.VIZU;
case 'other'
I = D.PSD.other.I;
VIZU = D.PSD.other.VIZU;
end
status = D.channels(I(ind)).bad;
if status
status = 0;
lineStyle = '-';
color = [1 1 1];
else
status = 1;
lineStyle = ':';
color = 0.75*[1 1 1];
end
D.channels(I(ind)).bad = status;
set(D.PSD.handles.hfig,'userdata',D);
cmenu = uicontextmenu;
uimenu(cmenu,'Label',['channel ',num2str(I(ind)),': ',VIZU.montage.clab{ind}]);
uimenu(cmenu,'Label',['type: ',D.channels(I(ind)).type]);
uimenu(cmenu,'Label',['bad: ',num2str(status)],...
'callback',@switchBC,'userdata',ind,...
'BusyAction','cancel',...
'Interruptible','off');
switch D.PSD.VIZU.type
case 1
set(D.PSD.handles.PLOT.p(ind),'uicontextmenu',cmenu,...
'lineStyle',lineStyle);
% ud = get(D.PSD.handles.axes);
% ud.v.bad(ind) = status;
% set(D.PSD.handles.axes,'userdata',ud);
case 2
set(D.PSD.handles.axes(ind),'Color',color);
set(D.PSD.handles.fra(ind),'uicontextmenu',cmenu);
set(D.PSD.handles.PLOT.p(:,ind),'uicontextmenu',cmenu);
axes(D.PSD.handles.scale)
end
d1 = rmfield(D,{'history','PSD'});
d0 = rmfield(D.PSD.D0,'history');
if isequal(d1,d0)
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[0.8314 0.8157 0.7843])
else
set(D.PSD.handles.BUTTONS.pop1,...
'BackgroundColor',[1 0.5 0.5])
end
%% Define menu event
function [] = psd_defineMenuEvent(re,sc)
% This funcion defines the uicontextmenu associated to the selected events.
% All the actions which are accessible using the right mouse click on the
% selected events are a priori defined here.
% Highlighting the selection
set(re,'buttondownfcn','spm_eeg_review_callbacks(''menuEvent'',''click'',0)');
cmenu = uicontextmenu;
set(re,'uicontextmenu',cmenu);
% Display basic info
info = ['--- EVENT #',num2str(sc.currentEvent),' /',...
num2str(sc.N_select),' (type= ',sc.eventType,', value= ',num2str(sc.eventValue),') ---'];
uimenu(cmenu,'label',info,'enable','off');
% Properties editor
uimenu(cmenu,'separator','on','label','Edit event properties',...
'callback','spm_eeg_review_callbacks(''menuEvent'',''EventProperties'',0)',...
'BusyAction','cancel',...
'Interruptible','off');
% Go to next event of the same type
hc = uimenu(cmenu,'label','Go to iso-type closest event');
uimenu(hc,'label','forward','callback','spm_eeg_review_callbacks(''menuEvent'',''goto'',1)',...
'BusyAction','cancel',...
'Interruptible','off');
uimenu(hc,'label','backward','callback','spm_eeg_review_callbacks(''menuEvent'',''goto'',0)',...
'BusyAction','cancel',...
'Interruptible','off');
% Delete action
uimenu(cmenu,'label','Delete event','callback','spm_eeg_review_callbacks(''menuEvent'',''deleteEvent'',0)',...
'BusyAction','cancel',...
'Interruptible','off');
%% Get info about source reconstruction
function str = getInfo4Inv(D,invN)
str{1} = ['Label: ',D.other.inv{invN}.comment{1}];
try
str{2} = ['Date: ',D.other.inv{invN}.date(1,:),', ',D.other.inv{invN}.date(2,:)];
catch
str{2} = ['Date: ',D.other.inv{invN}.date(1,:)];
end
if isfield(D.other.inv{invN}.inverse, 'modality')
mod0 = D.other.inv{invN}.inverse.modality;
if ischar(mod0)
mod = mod0;
else
mod = [];
for i = 1:length(mod0)
mod = [mod,' ',mod0{i}];
end
end
str{3} = ['Modality: ',mod];
else % For backward compatibility
try
mod0 = D.other.inv{invN}.modality;
if ischar(mod0)
mod = mod0;
else
mod = [];
for i = 1:length(mod0)
mod = [mod,' ',mod0{i}];
end
end
str{3} = ['Modality: ',mod];
catch
str{3} = 'Modality: ?';
end
end
if strcmp(D.other.inv{invN}.method,'Imaging')
source = 'distributed';
else
source = 'equivalent current dipoles';
end
str{4} = ['Source model: ',source,' (',D.other.inv{invN}.method,')'];
try
str{5} = ['Nb of included dipoles: ',...
num2str(length(D.other.inv{invN}.inverse.Is)),...
' / ',num2str(D.other.inv{invN}.inverse.Nd)];
catch
str{5} = 'Nb of included dipoles: undefined';
end
try
str{6} = ['Inversion method: ',D.other.inv{invN}.inverse.type];
catch
str{6} = 'Inversion method: undefined';
end
try
try
str{7} = ['Time window: ',...
num2str(floor(D.other.inv{invN}.inverse.woi(1))),...
' to ',num2str(floor(D.other.inv{invN}.inverse.woi(2))),' ms'];
catch
str{7} = ['Time window: ',...
num2str(floor(D.other.inv{invN}.inverse.pst(1))),...
' to ',num2str(floor(D.other.inv{invN}.inverse.pst(end))),' ms'];
end
catch
str{7} = 'Time window: undefined';
end
try
if D.other.inv{invN}.inverse.Han
han = 'yes';
else
han = 'no';
end
str{8} = ['Hanning: ',han];
catch
str{8} = ['Hanning: undefined'];
end
try
if isfield(D.other.inv{invN}.inverse,'lpf')
str{9} = ['Band pass filter: ',num2str(D.other.inv{invN}.inverse.lpf),...
' to ',num2str(D.other.inv{invN}.inverse.hpf), 'Hz'];
else
str{9} = ['Band pass filter: default'];
end
catch
str{9} = 'Band pass filter: undefined';
end
try
str{10} = ['Nb of temporal modes: ',...
num2str(size(D.other.inv{invN}.inverse.T,2))];
catch
str{10} = 'Nb of temporal modes: undefined';
end
try
str{11} = ['Variance accounted for: ',...
num2str(D.other.inv{invN}.inverse.R2),' %'];
catch
str{11} = 'Variance accounted for: undefined';
end
try
str{12} = ['Log model evidence (free energy): ',...
num2str(D.other.inv{invN}.inverse.F)];
catch
str{12} = 'Log model evidence (free energy): undefined';
end
%% Get data info
function str = getInfo4Data(D)
str{1} = ['File name: ',fullfile(D.path,D.fname)];
str{2} = ['Type: ',D.type];
if ~strcmp(D.transform.ID,'time')
str{2} = [str{2},' (time-frequency data, from ',...
num2str(D.transform.frequencies(1)),'Hz to ',...
num2str(D.transform.frequencies(end)),'Hz'];
if strcmp(D.transform.ID,'TF')
str{2} = [str{2},')'];
else
str{2} = [str{2},': phase)'];
end
end
delta_t = D.Nsamples./D.Fsample;
gridTime = (1:D.Nsamples)./D.Fsample + D.timeOnset;
str{3} = ['Number of time samples: ',num2str(D.Nsamples),' (',num2str(delta_t),' sec, from ',...
num2str(gridTime(1)),'s to ',num2str(gridTime(end)),'s)'];
str{4} = ['Time sampling frequency: ',num2str(D.Fsample),' Hz'];
nb = length(find([D.channels.bad]));
str{5} = ['Number of channels: ',num2str(length(D.channels)),' (',num2str(nb),' bad channels)'];
nb = length(find([D.trials.bad]));
if strcmp(D.type,'continuous')
if isfield(D.trials(1),'events')
str{6} = ['Number of events: ',num2str(length(D.trials(1).events))];
else
str{6} = ['Number of events: ',num2str(0)];
end
else
str{6} = ['Number of trials: ',num2str(length(D.trials)),' (',num2str(nb),' bad trials)'];
end
% try,str{7} = ['Time onset: ',num2str(D.timeOnset),' sec'];end
%% extracting data from spm_uitable java object
function [D] = getUItable(D)
ht = D.PSD.handles.infoUItable;
cn = get(ht,'columnNames');
table = get(ht,'data');
% !! there is some redundancy here --> to be optimized...
table2 = spm_uitable('get',ht);
emptyTable = 0;
try
emptyTable = isempty(cell2mat(table2));
end
if length(cn) == 5 % channel info
if ~emptyTable
nc = length(D.channels);
for i=1:nc
if ~isempty(table(i,1))
D.channels(i).label = table(i,1);
end
if ~isempty(table(i,2))
switch lower(table(i,2))
case 'eeg'
D.channels(i).type = 'EEG';
case 'meg'
D.channels(i).type = 'MEG';
case 'megplanar'
D.channels(i).type = 'MEGPLANAR';
case 'megmag'
D.channels(i).type = 'MEGMAG';
case 'meggrad'
D.channels(i).type = 'MEGGRAD';
case 'refmag'
D.channels(i).type = 'REFMAG';
case 'refgrad'
D.channels(i).type = 'REFGRAD';
case 'lfp'
D.channels(i).type = 'LFP';
case 'eog'
D.channels(i).type = 'EOG';
case 'veog'
D.channels(i).type = 'VEOG';
case 'heog'
D.channels(i).type = 'HEOG';
case 'other'
D.channels(i).type = 'Other';
otherwise
D.channels(i).type = 'Other';
end
end
if ~isempty(table(i,3))
switch lower(table(i,3))
case 'yes'
D.channels(i).bad = 1;
otherwise
D.channels(i).bad = 0;
end
end
if ~isempty(table(i,5))
D.channels(i).units = table(i,5);
end
end
% Find indices of channel types (these might have been changed)
D.PSD.EEG.I = find(strcmp('EEG',{D.channels.type}));
D.PSD.MEG.I = sort([find(strcmp('MEGMAG',{D.channels.type})),...
find(strcmp('MEGGRAD',{D.channels.type})) find(strcmp('MEG',{D.channels.type}))]);
D.PSD.MEGPLANAR.I = find(strcmp('MEGPLANAR',{D.channels.type}));
D.PSD.other.I = setdiff(1:nc,[D.PSD.EEG.I(:);D.PSD.MEG.I(:)]);
if ~isempty(D.PSD.EEG.I)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.EEG.I);
D.PSD.EEG.VIZU = out;
else
D.PSD.EEG.VIZU = [];
end
if ~isempty(D.PSD.MEG.I)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.MEG.I);
D.PSD.MEG.VIZU = out;
else
D.PSD.MEG.VIZU = [];
end
if ~isempty(D.PSD.MEGPLANAR.I)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.MEGPLANAR.I);
D.PSD.MEGPLANAR.VIZU = out;
else
D.PSD.MEGPLANAR.VIZU = [];
end
if ~isempty(D.PSD.other.I)
[out] = spm_eeg_review_callbacks('get','VIZU',D.PSD.other.I);
D.PSD.other.VIZU = out;
else
D.PSD.other.VIZU = [];
end
else
end
elseif length(cn) == 7
if strcmp(D.type,'continuous')
if ~emptyTable
ne = length(D.trials(1).events);
D.trials = rmfield(D.trials,'events');
j = 0;
for i=1:ne
if isempty(table(i,1))&&...
isempty(table(i,2))&&...
isempty(table(i,3))&&...
isempty(table(i,4))&&...
isempty(table(i,5))&&...
isempty(table(i,6))&&...
isempty(table(i,7))
% Row (ie event) has been cleared/deleted
else
j = j+1;
if ~isempty(table(i,2))
D.trials(1).events(j).type = table(i,2);
end
if ~isempty(table(i,3))
D.trials(1).events(j).value = str2double(table(i,3));
end
if ~isempty(table(i,4))
D.trials(1).events(j).duration = str2double(table(i,4));
end
if ~isempty(table(i,5))
D.trials(1).events(j).time = str2double(table(i,5));
end
end
end
else
D.trials(1).events = [];
delete(ht);
end
else
if ~emptyTable
nt = length(D.trials);
for i=1:nt
if ~isempty(table(i,1))
D.trials(i).label = table(i,1);
end
ne = length(D.trials(i).events);
if ne<2
if ~isempty(table(i,2))
D.trials(i).events.type = table(i,2);
end
if ~isempty(table(i,3))
D.trials(i).events.value = table(i,3);%str2double(table(i,3));
end
end
if ~isempty(table(i,6))
switch lower(table(i,6))
case 'yes'
D.trials(i).bad = 1;
otherwise
D.trials(i).bad = 0;
end
end
if D.trials(i).bad
str = ' (bad)';
else
str = ' (not bad)';
end
D.PSD.trials.TrLabels{i} = ['Trial ',num2str(i),': ',D.trials(i).label,str];
end
else
end
end
elseif length(cn) == 3
if ~emptyTable
nt = length(D.trials);
for i=1:nt
if ~isempty(table(i,1))
D.trials(i).label = table(i,1);
end
D.PSD.trials.TrLabels{i} = ['Trial ',num2str(i),' (average of ',...
num2str(D.trials(i).repl),' events): ',D.trials(i).label];
end
else
end
elseif length(cn) == 12 % source reconstructions
if ~emptyTable
if ~~D.PSD.source.VIZU.current
isInv = D.PSD.source.VIZU.isInv;
inv = D.other.inv;
Ninv = length(inv);
D.other = rmfield(D.other,'inv');
oV = D.PSD.source.VIZU;
D.PSD.source = rmfield(D.PSD.source,'VIZU');
pst = [];
j = 0; % counts the total number of final inverse solutions in D
k = 0; % counts the number of original 'imaging' inv sol
l = 0; % counts the number of final 'imaging' inv sol
for i=1:Ninv
if ~ismember(i,isInv) % not 'imaging' inverse solutions
j = j+1;
D.other.inv{j} = inv{i};
else % 'imaging' inverse solutions
k = k+1;
if isempty(table(k,1))&&...
isempty(table(k,2))&&...
isempty(table(k,3))&&...
isempty(table(k,4))&&...
isempty(table(k,5))&&...
isempty(table(k,6))&&...
isempty(table(k,7))&&...
isempty(table(k,8))&&...
isempty(table(k,9))&&...
isempty(table(k,10))&&...
isempty(table(k,11))&&...
isempty(table(k,12))
% Row (ie source reconstruction) has been cleared/deleted
% => erase inverse solution from D struct
else
j = j+1;
l = l+1;
pst = [pst;inv{isInv(k)}.inverse.pst(:)];
D.other.inv{j} = inv{isInv(k)};
D.other.inv{j}.comment{1} = table(k,1);
D.PSD.source.VIZU.isInv(l) = j;
D.PSD.source.VIZU.F(l) = oV.F(k);
D.PSD.source.VIZU.labels{l} = table(k,1);
D.PSD.source.VIZU.callbacks(l) = oV.callbacks(k);
end
end
end
end
if l >= 1
D.other.val = l;
D.PSD.source.VIZU.current = 1;
D.PSD.source.VIZU.pst = unique(pst);
D.PSD.source.VIZU.timeCourses = 1;
else
try D.other = rmfield(D.other,'val');end
D.PSD.source.VIZU.current = 0;
end
else
try D.other = rmfield(D.other,'val');end
try D.other = rmfield(D.other,'inv');end
D.PSD.source.VIZU.current = 0;
D.PSD.source.VIZU.isInv = [];
D.PSD.source.VIZU.pst = [];
D.PSD.source.VIZU.F = [];
D.PSD.source.VIZU.labels = [];
D.PSD.source.VIZU.callbacks = [];
D.PSD.source.VIZU.timeCourses = [];
delete(ht)
end
end
set(D.PSD.handles.hfig,'userdata',D)
spm_eeg_review_callbacks('visu','main','info',D.PSD.VIZU.info)
|
github
|
philippboehmsturm/antx-master
|
spm_imatrix.m
|
.m
|
antx-master/xspm8/spm_imatrix.m
| 1,545 |
utf_8
|
6bd968e6c68acf278802d6e9a58610fa
|
function P = spm_imatrix(M)
% returns the parameters for creating an affine transformation
% FORMAT P = spm_imatrix(M)
% M - Affine transformation matrix
% P - Parameters (see spm_matrix for definitions)
%___________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Stefan Kiebel
% $Id: spm_imatrix.m 1143 2008-02-07 19:33:33Z spm $
% Translations and zooms
%-----------------------------------------------------------------------
R = M(1:3,1:3);
C = chol(R'*R);
P = [M(1:3,4)' 0 0 0 diag(C)' 0 0 0];
if det(R)<0, P(7)=-P(7);end % Fix for -ve determinants
% Shears
%-----------------------------------------------------------------------
C = diag(diag(C))\C;
P(10:12) = C([4 7 8]);
R0 = spm_matrix([0 0 0 0 0 0 P(7:12)]);
R0 = R0(1:3,1:3);
R1 = R/R0;
% This just leaves rotations in matrix R1
%-----------------------------------------------------------------------
%[ c5*c6, c5*s6, s5]
%[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5]
%[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5]
P(5) = asin(rang(R1(1,3)));
if (abs(P(5))-pi/2)^2 < 1e-9,
P(4) = 0;
P(6) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3)));
else
c = cos(P(5));
P(4) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c));
P(6) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c));
end;
return;
% There may be slight rounding errors making b>1 or b<-1.
function a = rang(b)
a = min(max(b, -1), 1);
return;
|
github
|
philippboehmsturm/antx-master
|
spm_affreg.m
|
.m
|
antx-master/xspm8/spm_affreg.m
| 18,516 |
utf_8
|
0861aa4a29a7aac70856750d2c0af6ff
|
function [M,scal] = spm_affreg(VG,VF,flags,M,scal)
% Affine registration using least squares.
% FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0)
%
% VG - Vector of template volumes.
% VF - Source volume.
% flags - a structure containing various options. The fields are:
% WG - Weighting volume for template image(s).
% WF - Weighting volume for source image
% Default to [].
% sep - Approximate spacing between sampled points (mm).
% Defaults to 5.
% regtype - regularisation type. Options are:
% 'none' - no regularisation
% 'rigid' - almost rigid body
% 'subj' - inter-subject registration (default).
% 'mni' - registration to ICBM templates
% globnorm - Global normalisation flag (1)
% M0 - (optional) starting estimate. Defaults to eye(4).
% scal0 - (optional) starting estimate.
%
% M - affine transform, such that voxels in VF map to those in
% VG by VG.mat\M*VF.mat
% scal - scaling factors for VG
%
% When only one template is used, then the cost function is approximately
% symmetric, although a linear combination of templates can be used.
% Regularisation is based on assuming a multi-normal distribution for the
% elements of the Henckey Tensor. See:
% "Non-linear Elastic Deformations". R. W. Ogden (Dover), 1984.
% Weighting for the regularisation is determined approximately according
% to:
% "Incorporating Prior Knowledge into Image Registration"
% J. Ashburner, P. Neelin, D. L. Collins, A. C. Evans & K. J. Friston.
% NeuroImage 6:344-352 (1997).
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_affreg.m 4152 2011-01-11 14:13:35Z volkmar $
if nargin<5, scal = ones(length(VG),1); end;
if nargin<4, M = eye(4); end;
def_flags = struct('sep',5, 'regtype','subj','WG',[],'WF',[],'globnorm',1,'debug',0);
if nargin < 2 || ~isstruct(flags),
flags = def_flags;
else
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags.(fnms{i}) = def_flags.(fnms{i});
end;
end;
end;
% Check to ensure inputs are valid...
% ---------------------------------------------------------------
if length(VF)>1, error('Can not use more than one source image'); end;
if ~isempty(flags.WF),
if length(flags.WF)>1,
error('Can only use one source weighting image');
end;
if any(any((VF.mat-flags.WF.mat).^2>1e-8)),
error('Source and its weighting image must have same orientation');
end;
if any(any(VF.dim(1:3)-flags.WF.dim(1:3))),
error('Source and its weighting image must have same dimensions');
end;
end;
if ~isempty(flags.WG),
if length(flags.WG)>1,
error('Can only use one template weighting image');
end;
tmp = reshape(cat(3,VG(:).mat,flags.WG.mat),16,length(VG)+length(flags.WG));
else
tmp = reshape(cat(3,VG(:).mat),16,length(VG));
end;
if any(any(diff(tmp,1,2).^2>1e-8)),
error('Reference images must all have the same orientation');
end;
if ~isempty(flags.WG),
tmp = cat(1,VG(:).dim,flags.WG.dim);
else
tmp = cat(1,VG(:).dim);
end;
if any(any(diff(tmp(:,1:3),1,1))),
error('Reference images must all have the same dimensions');
end;
% ---------------------------------------------------------------
% Generate points to sample from, adding some jitter in order to
% make the cost function smoother.
% ---------------------------------------------------------------
rand('state',0); % want the results to be consistant.
dg = VG(1).dim(1:3);
df = VF(1).dim(1:3);
if length(VG)==1,
skip = sqrt(sum(VG(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
[x1,x2,x3]=ndgrid(1:skip(1):dg(1)-.5, 1:skip(2):dg(2)-.5, 1:skip(3):dg(3)-.5);
x1 = x1 + rand(size(x1))*0.5; x1 = x1(:);
x2 = x2 + rand(size(x2))*0.5; x2 = x2(:);
x3 = x3 + rand(size(x3))*0.5; x3 = x3(:);
end;
skip = sqrt(sum(VF(1).mat(1:3,1:3).^2)).^(-1)*flags.sep;
[y1,y2,y3]=ndgrid(1:skip(1):df(1)-.5, 1:skip(2):df(2)-.5, 1:skip(3):df(3)-.5);
y1 = y1 + rand(size(y1))*0.5; y1 = y1(:);
y2 = y2 + rand(size(y2))*0.5; y2 = y2(:);
y3 = y3 + rand(size(y3))*0.5; y3 = y3(:);
% ---------------------------------------------------------------
if flags.globnorm,
% Scale all images approximately equally
% ---------------------------------------------------------------
for i=1:length(VG),
VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i));
end;
VF(1).pinfo(1:2,:) = VF(1).pinfo(1:2,:)/spm_global(VF(1));
end;
% ---------------------------------------------------------------
if length(VG)==1,
[G,dG1,dG2,dG3] = spm_sample_vol(VG(1),x1,x2,x3,1);
if ~isempty(flags.WG),
WG = abs(spm_sample_vol(flags.WG,x1,x2,x3,1))+eps;
WG(~isfinite(WG)) = 1;
end;
end;
[F,dF1,dF2,dF3] = spm_sample_vol(VF(1),y1,y2,y3,1);
if ~isempty(flags.WF),
WF = abs(spm_sample_vol(flags.WF,y1,y2,y3,1))+eps;
WF(~isfinite(WF)) = 1;
end;
% ---------------------------------------------------------------
n_main_its = 0;
ss = Inf;
W = [Inf Inf Inf];
est_smo = 1;
% ---------------------------------------------------------------
for iter=1:256,
pss = ss;
p0 = [0 0 0 0 0 0 1 1 1 0 0 0];
% Initialise the cost function and its 1st and second derivatives
% ---------------------------------------------------------------
n = 0;
ss = 0;
Beta = zeros(12+length(VG),1);
Alpha = zeros(12+length(VG));
if length(VG)==1,
% Make the cost function symmetric
% ---------------------------------------------------------------
% Build a matrix to rotate the derivatives by, converting from
% derivatives w.r.t. changes in the overall affine transformation
% matrix, to derivatives w.r.t. the parameters p.
% ---------------------------------------------------------------
dt = 0.0001;
R = eye(13);
MM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat;
for i1=1:12,
p1 = p0;
p1(i1) = p1(i1)+dt;
MM1 = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat));
R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);
end;
% ---------------------------------------------------------------
[t1,t2,t3] = coords((M*VF(1).mat)\VG(1).mat,x1,x2,x3);
msk = find((t1>=1 & t1<=df(1) & t2>=1 & t2<=df(2) & t3>=1 & t3<=df(3)));
if length(msk)<32, error_message; end;
t1 = t1(msk);
t2 = t2(msk);
t3 = t3(msk);
t = spm_sample_vol(VF(1), t1,t2,t3,1);
% Get weights
% ---------------------------------------------------------------
if ~isempty(flags.WF) || ~isempty(flags.WG),
if isempty(flags.WF),
wt = WG(msk);
else
wt = spm_sample_vol(flags.WF(1), t1,t2,t3,1)+eps;
wt(~isfinite(wt)) = 1;
if ~isempty(flags.WG), wt = 1./(1./wt + 1./WG(msk)); end;
end;
wt = sparse(1:length(wt),1:length(wt),wt);
else
% wt = speye(length(msk));
wt = [];
end;
% ---------------------------------------------------------------
clear t1 t2 t3
% Update the cost function and its 1st and second derivatives.
% ---------------------------------------------------------------
[AA,Ab,ss1,n1] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,scal^(-2)*t,G(msk)-(1/scal)*t,wt);
Alpha = Alpha + R'*AA*R;
Beta = Beta + R'*Ab;
ss = ss + ss1;
n = n + n1;
% t = G(msk) - (1/scal)*t;
end;
if 1,
% Build a matrix to rotate the derivatives by, converting from
% derivatives w.r.t. changes in the overall affine transformation
% matrix, to derivatives w.r.t. the parameters p.
% ---------------------------------------------------------------
dt = 0.0001;
R = eye(12+length(VG));
MM0 = inv(M*VF.mat)*spm_matrix(p0)*M*VF.mat;
for i1=1:12,
p1 = p0;
p1(i1) = p1(i1)+dt;
MM1 = (inv(M*VF.mat)*spm_matrix(p1)*M*VF.mat);
R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1);
end;
% ---------------------------------------------------------------
[t1,t2,t3] = coords(VG(1).mat\M*VF(1).mat,y1,y2,y3);
msk = find((t1>=1 & t1<=dg(1) & t2>=1 & t2<=dg(2) & t3>=1 & t3<=dg(3)));
if length(msk)<32, error_message; end;
if length(msk)<32, error_message; end;
t1 = t1(msk);
t2 = t2(msk);
t3 = t3(msk);
t = zeros(length(t1),length(VG));
% Get weights
% ---------------------------------------------------------------
if ~isempty(flags.WF) || ~isempty(flags.WG),
if isempty(flags.WG),
wt = WF(msk);
else
wt = spm_sample_vol(flags.WG(1), t1,t2,t3,1)+eps;
wt(~isfinite(wt)) = 1;
if ~isempty(flags.WF), wt = 1./(1./wt + 1./WF(msk)); end;
end;
wt = sparse(1:length(wt),1:length(wt),wt);
else
wt = speye(length(msk));
end;
% ---------------------------------------------------------------
if est_smo,
% Compute derivatives of residuals in the space of F
% ---------------------------------------------------------------
[ds1,ds2,ds3] = transform_derivs(VG(1).mat\M*VF(1).mat,dF1(msk),dF2(msk),dF3(msk));
for i=1:length(VG),
[t(:,i),dt1,dt2,dt3] = spm_sample_vol(VG(i), t1,t2,t3,1);
ds1 = ds1 - dt1*scal(i); clear dt1
ds2 = ds2 - dt2*scal(i); clear dt2
ds3 = ds3 - dt3*scal(i); clear dt3
end;
dss = [ds1'*wt*ds1 ds2'*wt*ds2 ds3'*wt*ds3];
clear ds1 ds2 ds3
else
for i=1:length(VG),
t(:,i)= spm_sample_vol(VG(i), t1,t2,t3,1);
end;
end;
clear t1 t2 t3
% Update the cost function and its 1st and second derivatives.
% ---------------------------------------------------------------
[AA,Ab,ss2,n2] = costfun(y1,y2,y3,dF1,dF2,dF3,msk,-t,F(msk)-t*scal,wt);
Alpha = Alpha + R'*AA*R;
Beta = Beta + R'*Ab;
ss = ss + ss2;
n = n + n2;
end;
if est_smo,
% Compute a smoothness correction from the residuals and their
% derivatives. This is analagous to the one used in:
% "Analysis of fMRI Time Series Revisited"
% Friston KJ, Holmes AP, Poline JB, Grasby PJ, Williams SCR,
% Frackowiak RSJ, Turner R. Neuroimage 2:45-53 (1995).
% ---------------------------------------------------------------
vx = sqrt(sum(VG(1).mat(1:3,1:3).^2));
pW = W;
W = (2*dss/ss2).^(-.5).*vx;
W = min(pW,W);
if flags.debug, fprintf('\nSmoothness FWHM: %.3g x %.3g x %.3g mm\n', W*sqrt(8*log(2))); end;
if length(VG)==1, dens=2; else dens=1; end;
smo = prod(min(dens*flags.sep/sqrt(2*pi)./W,[1 1 1]));
est_smo=0;
n_main_its = n_main_its + 1;
end;
% Update the parameter estimates
% ---------------------------------------------------------------
nu = n*smo;
sig2 = ss/nu;
[d1,d2] = reg(M,12+length(VG),flags.regtype);
soln = (Alpha/sig2+d2)\(Beta/sig2-d1);
scal = scal - soln(13:end);
M = spm_matrix(p0 + soln(1:12)')*M;
if flags.debug,
fprintf('%d\t%g\n', iter, ss/n);
piccies(VF,VG,M,scal)
end;
% If cost function stops decreasing, then re-estimate smoothness
% and try again. Repeat a few times.
% ---------------------------------------------------------------
ss = ss/n;
if iter>1, spm_plot_convergence('Set',ss); end;
if (pss-ss)/pss < 1e-6,
est_smo = 1;
end;
if n_main_its>3, break; end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [X1,Y1,Z1] = transform_derivs(Mat,X,Y,Z)
% Given the derivatives of a scalar function, return those of the
% affine transformed function
%_______________________________________________________________________
t1 = Mat(1:3,1:3);
t2 = eye(3);
if sum((t1(:)-t2(:)).^2) < 1e-12,
X1 = X;Y1 = Y; Z1 = Z;
else
X1 = Mat(1,1)*X + Mat(1,2)*Y + Mat(1,3)*Z;
Y1 = Mat(2,1)*X + Mat(2,2)*Y + Mat(2,3)*Z;
Z1 = Mat(3,1)*X + Mat(3,2)*Y + Mat(3,3)*Z;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [d1,d2] = reg(M,n,typ)
% Analytically compute the first and second derivatives of a penalty
% function w.r.t. changes in parameters.
if nargin<3, typ = 'subj'; end;
if nargin<2, n = 13; end;
[mu,isig] = spm_affine_priors(typ);
ds = 0.000001;
d1 = zeros(n,1);
d2 = zeros(n);
p0 = [0 0 0 0 0 0 1 1 1 0 0 0];
h0 = penalty(p0,M,mu,isig);
for i=7:12, % derivatives are zero w.r.t. rotations and translations
p1 = p0;
p1(i) = p1(i)+ds;
h1 = penalty(p1,M,mu,isig);
d1(i) = (h1-h0)/ds; % First derivative
for j=7:12,
p2 = p0;
p2(j) = p2(j)+ds;
h2 = penalty(p2,M,mu,isig);
p3 = p1;
p3(j) = p3(j)+ds;
h3 = penalty(p3,M,mu,isig);
d2(i,j) = ((h3-h2)/ds-(h1-h0)/ds)/ds; % Second derivative
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function h = penalty(p,M,mu,isig)
% Return a penalty based on the elements of an affine transformation,
% which is given by:
% spm_matrix(p)*M
%
% The penalty is based on the 6 unique elements of the Hencky tensor
% elements being multinormally distributed.
%_______________________________________________________________________
% Unique elements of symmetric 3x3 matrix.
els = [1 2 3 5 6 9];
T = spm_matrix(p)*M;
T = T(1:3,1:3);
T = 0.5*logm(T'*T);
T = T(els)' - mu;
h = T'*isig*T;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [y1,y2,y3]=coords(M,x1,x2,x3)
% Affine transformation of a set of coordinates.
%_______________________________________________________________________
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 A = make_A(x1,x2,x3,dG1,dG2,dG3,t)
% Generate part of a design matrix using the chain rule...
% df/dm = df/dy * dy/dm
% where
% df/dm is the rate of change of intensity w.r.t. affine parameters
% df/dy is the gradient of the image f
% dy/dm crange of position w.r.t. change of parameters
%_______________________________________________________________________
A = [x1.*dG1 x1.*dG2 x1.*dG3 ...
x2.*dG1 x2.*dG2 x2.*dG3 ...
x3.*dG1 x3.*dG2 x3.*dG3 ...
dG1 dG2 dG3 t];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [AA,Ab,ss,n] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,lastcols,b,wt)
chunk = 10240;
lm = length(msk);
AA = zeros(12+size(lastcols,2));
Ab = zeros(12+size(lastcols,2),1);
ss = 0;
n = 0;
for i=1:ceil(lm/chunk),
ind = (((i-1)*chunk+1):min(i*chunk,lm))';
msk1 = msk(ind);
A1 = make_A(x1(msk1),x2(msk1),x3(msk1),dG1(msk1),dG2(msk1),dG3(msk1),lastcols(ind,:));
b1 = b(ind);
if ~isempty(wt),
wt1 = wt(ind,ind);
AA = AA + A1'*wt1*A1;
%Ab = Ab + A1'*wt1*b1;
Ab = Ab + (b1'*wt1*A1)';
ss = ss + b1'*wt1*b1;
n = n + trace(wt1);
clear wt1
else
AA = AA + A1'*A1;
%Ab = Ab + A1'*b1;
Ab = Ab + (b1'*A1)';
ss = ss + b1'*b1;
n = n + length(msk1);
end;
clear A1 b1 msk1 ind
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function error_message
% Display an error message for when things go wrong.
str = { 'There is not enough overlap in the images',...
'to obtain a solution.',...
' ',...
'Please check that your header information is OK.',...
'The Check Reg utility will show you the initial',...
'alignment between the images, which must be',...
'within about 4cm and about 15 degrees in order',...
'for SPM to find the optimal solution.'};
spm('alert*',str,mfilename,sqrt(-1));
error('insufficient image overlap')
%_______________________________________________________________________
%_______________________________________________________________________
function piccies(VF,VG,M,scal)
% This is for debugging purposes.
% It shows the linear combination of template images, the affine
% transformed source image, the residual image and a histogram of the
% residuals.
%_______________________________________________________________________
figure(2);
Mt = spm_matrix([0 0 (VG(1).dim(3)+1)/2]);
M = (M*VF(1).mat)\VG(1).mat;
t = zeros(VG(1).dim(1:2));
for i=1:length(VG);
t = t + spm_slice_vol(VG(i), Mt,VG(1).dim(1:2),1)*scal(i);
end;
u = spm_slice_vol(VF(1),M*Mt,VG(1).dim(1:2),1);
subplot(2,2,1);imagesc(t');axis image xy off
subplot(2,2,2);imagesc(u');axis image xy off
subplot(2,2,3);imagesc(u'-t');axis image xy off
%subplot(2,2,4);hist(b,50); % Entropy of residuals may be a nice cost function?
drawnow;
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_locate_channels.m
|
.m
|
antx-master/xspm8/spm_eeg_locate_channels.m
| 2,870 |
utf_8
|
5c2b41cee32e14bd2f6b0d7565ddd0fb
|
function [Cel, Cind, x, y] = spm_eeg_locate_channels(D, n, interpolate_bad)
% Locate channels and generate mask for converting M/EEG data into images
% FORMAT [Cel, Cind, x, y] = spm_eeg_locate_channels(D, n, interpolate_bad)
%
% D - M/EEG object
% n - number of voxels in each direction
% interpolate_bad - flag (1/0), whether bad channels should be interpolated
% or masked out
%
% Cel - coordinates of good channels in new coordinate system
% Cind - the indices of these channels in the total channel
% vector
% x, y - x and y coordinates which support data
%
%__________________________________________________________________________
%
% Locates channels and generates mask for converting M/EEG data to NIfTI
% format ('analysis at sensor level'). If flag interpolate_bad is set to 1,
% the returned x,y-coordinates will include bad sensor position. If
% interpolate_bad is 0, these locations are masked out if the sensor are
% located at the edge of the setup (where the data cannot be well
% interpolated).
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_eeg_locate_channels.m 2830 2009-03-05 17:27:34Z guillaume $
% put into n x n grid
%--------------------------------------------------------------------------
[x, y] = meshgrid(1:n, 1:n);
if interpolate_bad
% keep bad electrode positions in
%----------------------------------------------------------------------
Cel = scale_coor(D.coor2D(D.meegchannels), n);
else
% bad electrodes are masked out if located at the edge of the setup
%----------------------------------------------------------------------
Cel = scale_coor(D.coor2D(setdiff(D.meegchannels, D.badchannels)), n);
end
ch = convhull(Cel(:, 1), Cel(:, 2));
Ic = find(inpolygon(x, y, Cel(ch, 1), Cel(ch, 2)));
Cel = scale_coor(D.coor2D(setdiff(D.meegchannels, D.badchannels)), n);
Cind = setdiff(D.meegchannels, D.badchannels);
x = x(Ic); y = y(Ic);
%==========================================================================
% scale_coor
%==========================================================================
function Cel = scale_coor(Cel, n)
% check limits and stretch, if possible
dx = max(Cel(1,:)) - min(Cel(1,:));
dy = max(Cel(2,:)) - min(Cel(2,:));
if dx > 1 || dy > 1
error('Coordinates not between 0 and 1');
end
scale = (1 - 10^(-6))/max(dx, dy);
Cel(1,:) = n*scale*(Cel(1,:) - min(Cel(1,:)) + eps) + 0.5;
Cel(2,:) = n*scale*(Cel(2,:) - min(Cel(2,:)) + eps) + 0.5;
% shift to middle
dx = n+0.5 -n*eps - max(Cel(1,:));
dy = n+0.5 -n*eps - max(Cel(2,:));
Cel(1,:) = Cel(1,:) + dx/2;
Cel(2,:) = Cel(2,:) + dy/2;
% 2D coordinates in voxel-space (incl. badchannels)
Cel = round(Cel)';
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_filter.m
|
.m
|
antx-master/xspm8/spm_eeg_filter.m
| 6,617 |
utf_8
|
38ceb423092384f9bf967a6534b6484e
|
function D = spm_eeg_filter(S)
% Filter M/EEG data
% FORMAT D = spm_eeg_filter(S)
%
% S - input structure (optional)
% (optional) fields of S:
% S.D - MEEG object or filename of M/EEG mat-file
% S.filter - struct with the following fields:
% type - optional filter type, can be
% 'but' Butterworth IIR filter (default)
% 'fir' FIR filter using Matlab fir1 function
% order - filter order (default - 5 for Butterworth)
% band - filterband [low|high|bandpass|stop]
% PHz - cutoff frequency [Hz]
% dir - optional filter direction, can be
% 'onepass' forward filter only
% 'onepass-reverse' reverse filter only, i.e. backward in time
% 'twopass' zero-phase forward and reverse filter
%
% D - MEEG object (also written to disk)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_eeg_filter.m 4127 2010-11-19 18:05:18Z christophe $
SVNrev = '$Rev: 4127 $';
%-Startup
%--------------------------------------------------------------------------
spm('FnBanner', mfilename, SVNrev);
spm('FigName','M/EEG filter'); spm('Pointer', 'Watch');
if nargin == 0
S = [];
end
%-Ensure backward compatibility
%--------------------------------------------------------------------------
S = spm_eeg_compatibility(S, mfilename);
%-Get MEEG object
%--------------------------------------------------------------------------
try
D = S.D;
catch
[D, sts] = spm_select(1, 'mat', 'Select M/EEG mat file');
if ~sts, D = []; return; end
S.D = D;
end
D = spm_eeg_load(D);
%-Get parameters
%--------------------------------------------------------------------------
if ~isfield(S, 'filter')
S.filter = [];
end
if ~isfield(S.filter, 'band')
S.filter.band = cell2mat(...
spm_input('filterband', '+1', 'm',...
'lowpass|highpass|bandpass|stopband',...
{'low','high','bandpass','stop'}));
end
if ~isfield(S.filter, 'type')
S.filter.type = 'butterworth';
end
if ~isfield(S.filter, 'order')
if strcmp(S.filter.type, 'butterworth')
S.filter.order = 5;
else
S.filter.order = [];
end
end
if ~isfield(S.filter, 'dir')
S.filter.dir = 'twopass';
end
if ~isfield(S.filter, 'PHz')
switch lower(S.filter.band)
case {'low','high'}
str = 'Cutoff [Hz]';
YPos = -1;
while 1
if YPos == -1
YPos = '+1';
end
[PHz, YPos] = spm_input(str, YPos, 'r');
if PHz > 0 && PHz < D.fsample/2, break, end
str = 'Cutoff must be > 0 & < half sample rate';
end
case {'bandpass','stop'}
str = 'band [Hz]';
YPos = -1;
while 1
if YPos == -1
YPos = '+1';
end
[PHz, YPos] = spm_input(str, YPos, 'r', [], 2);
if PHz(1) > 0 && PHz(1) < D.fsample/2 && PHz(1) < PHz(2), break, end
str = 'Cutoff 1 must be > 0 & < half sample rate and Cutoff 1 must be < Cutoff 2';
end
otherwise
error('unknown filter band.')
end
S.filter.PHz = PHz;
end
%-
%--------------------------------------------------------------------------
% generate new meeg object with new filenames
Dnew = clone(D, ['f' fnamedat(D)], [D.nchannels D.nsamples D.ntrials]);
% determine channels for filtering
Fchannels = unique([D.meegchannels, D.eogchannels]);
Fs = D.fsample;
if strcmp(D.type, 'continuous')
% continuous data
spm_progress_bar('Init', nchannels(D), 'Channels filtered'); drawnow;
if nchannels(D) > 100, Ibar = floor(linspace(1, nchannels(D),100));
else Ibar = [1:nchannels(D)]; end
% work on blocks of channels
% determine blocksize
% determine block size, dependent on memory
memsz = spm('Memory');
datasz = nchannels(D)*nsamples(D)*8; % datapoints x 8 bytes per double value
blknum = ceil(datasz/memsz);
blksz = ceil(nchannels(D)/blknum);
blknum = ceil(nchannels(D)/blksz);
% now filter blocks of channels
chncnt=1;
for blk=1:blknum
% load old meeg object blockwise into workspace
blkchan=chncnt:(min(nchannels(D), chncnt+blksz-1));
if isempty(blkchan), break, end
Dtemp=D(blkchan,:,1);
chncnt=chncnt+blksz;
%loop through channels
for j = 1:numel(blkchan)
if ismember(blkchan(j), Fchannels)
Dtemp(j, :) = spm_eeg_preproc_filter(S.filter, Dtemp(j,:), Fs);
end
if ismember(j, Ibar), spm_progress_bar('Set', blkchan(j)); end
end
% write Dtemp to Dnew
Dnew(blkchan,:,1)=Dtemp;
clear Dtemp;
end;
else
% single trial or epoched
spm_progress_bar('Init', D.ntrials, 'Trials filtered'); drawnow;
if D.ntrials > 100, Ibar = floor(linspace(1, D.ntrials,100));
else Ibar = [1:D.ntrials]; end
for i = 1:D.ntrials
d = squeeze(D(:, :, i));
for j = 1:nchannels(D)
if ismember(j, Fchannels)
d(j,:) = spm_eeg_preproc_filter(S.filter, double(d(j,:)), Fs);
end
end
Dnew(:, 1:Dnew.nsamples, i) = d;
if ismember(i, Ibar), spm_progress_bar('Set', i); end
end
disp('Baseline correction is no longer done automatically by spm_eeg_filter. Use spm_eeg_bc if necessary.');
end
spm_progress_bar('Clear');
%-Save new evoked M/EEG dataset
%--------------------------------------------------------------------------
D = Dnew;
D = D.history(mfilename, S);
save(D);
%-Cleanup
%--------------------------------------------------------------------------
spm('FigName','M/EEG filter: done'); spm('Pointer', 'Arrow');
%==========================================================================
function dat = spm_eeg_preproc_filter(filter, dat, Fs)
Fp = filter.PHz;
if isequal(filter.type, 'fir')
type = 'fir';
else
type = 'but';
end
N = filter.order;
dir = filter.dir;
switch filter.band
case 'low'
dat = ft_preproc_lowpassfilter(dat,Fs,Fp,N,type,dir);
case 'high'
dat = ft_preproc_highpassfilter(dat,Fs,Fp,N,type,dir);
case 'bandpass'
dat = ft_preproc_bandpassfilter(dat, Fs, Fp, N, type, dir);
case 'stop'
dat = ft_preproc_bandstopfilter(dat,Fs,Fp,N,type,dir);
end
|
github
|
philippboehmsturm/antx-master
|
savexml.m
|
.m
|
antx-master/xspm8/savexml.m
| 5,240 |
utf_8
|
575501e05a68903f8f5a2db4cb6a18e9
|
function savexml(filename, varargin)
%SAVEXML Save workspace variables to disk in XML.
% SAVEXML FILENAME saves all workspace variables to the XML-file
% named FILENAME.xml. The data may be retrieved with LOADXML. if
% FILENAME has no extension, .xml is assumed.
%
% SAVE, by itself, creates the XML-file named 'matlab.xml'. It is
% an error if 'matlab.xml' is not writable.
%
% SAVE FILENAME X saves only X.
% SAVE FILENAME X Y Z saves X, Y, and Z. The wildcard '*' can be
% used to save only those variables that match a pattern.
%
% SAVE ... -APPEND adds the variables to an existing file.
%
% Use the functional form of SAVE, such as SAVE(filename','var1','var2'),
% when the filename or variable names are stored in strings.
%
% See also SAVE, MAT2XML, XMLTREE.
% Copyright 2003 Guillaume Flandin.
% $Revision: 4393 $ $Date: 2003/07/10 13:50 $
% $Id: savexml.m 4393 2011-07-18 14:52:32Z guillaume $
if nargin == 0
filename = 'matlab.xml';
fprintf('\nSaving to: %s\n\n',filename);
else
if ~ischar(filename)
error('[SAVEXML] Argument must contain a string.');
end
[pathstr,name,ext] = fileparts(filename);
if isempty(ext)
filename = [filename '.xml'];
end
end
if nargin <= 1, varargin = {'*'}; end
if nargout > 0
error('[SAVEXML] Too many output arguments.');
end
if strcmpi(varargin{end},'-append')
if length(varargin) > 1
varargin = varargin(1:end-1);
else
varargin = {'*'};
end
if exist(filename,'file')
% TODO % No need to parse the whole tree ? detect duplicate variables ?
t = xmltree(filename);
else
error(sprintf(...
'[SAVEXML] Unable to write file %s: file does not exist.',filename));
end
else
t = xmltree('<matfile/>');
end
for i=1:length(varargin)
v = evalin('caller',['whos(''' varargin{i} ''')']);
if isempty(v)
error(['[SAVEXML] Variable ''' varargin{i} ''' not found.']);
end
for j=1:length(v)
[t, uid] = add(t,root(t),'element',v(j).name);
t = attributes(t,'add',uid,'type',v(j).class);
t = attributes(t,'add',uid,'size',xml_num2str(v(j).size));
t = xml_var2xml(t,evalin('caller',v(j).name),uid);
end
end
save(t,filename);
%=======================================================================
function t = xml_var2xml(t,v,uid)
switch class(v)
case {'double','single','logical'}
if ~issparse(v)
t = add(t,uid,'chardata',xml_num2str(v));
else % logical
[i,j,s] = find(v);
[t, uid2] = add(t,uid,'element','row');
t = attributes(t,'add',uid2,'size',xml_num2str(size(i)));
t = add(t,uid2,'chardata',xml_num2str(i));
[t, uid2] = add(t,uid,'element','col');
t = attributes(t,'add',uid2,'size',xml_num2str(size(j)));
t = add(t,uid2,'chardata',xml_num2str(j));
[t, uid2] = add(t,uid,'element','val');
t = attributes(t,'add',uid2,'size',xml_num2str(size(s)));
t = add(t,uid2,'chardata',xml_num2str(s));
end
case 'struct'
names = fieldnames(v);
for j=1:prod(size(v))
for i=1:length(names)
[t, uid2] = add(t,uid,'element',names{i});
t = attributes(t,'add',uid2,'index',num2str(j));
t = attributes(t,'add',uid2,'type',...
class(getfield(v(j),names{i})));
t = attributes(t,'add',uid2,'size', ...
xml_num2str(size(getfield(v(j),names{i}))));
t = xml_var2xml(t,getfield(v(j),names{i}),uid2);
end
end
case 'cell'
for i=1:prod(size(v))
[t, uid2] = add(t,uid,'element','cell');
% TODO % special handling of cellstr ?
t = attributes(t,'add',uid2,'index',num2str(i));
t = attributes(t,'add',uid2,'type',class(v{i}));
t = attributes(t,'add',uid2,'size',xml_num2str(size(v{i})));
t = xml_var2xml(t,v{i},uid2);
end
case 'char'
% TODO % char values should be in CData
if size(v,1) > 1
t = add(t,uid,'chardata',v'); % row-wise order
else
t = add(t,uid,'chardata',v);
end
case {'int8','uint8','int16','uint16','int32','uint32'}
[t, uid] = add(t,uid,'element',class(v));
% TODO % Handle integer formats (cannot use sprintf or num2str)
otherwise
if ismember('serialize',methods(class(v)))
% TODO % is CData necessary for class output ?
t = add(t,uid,'cdata',serialize(v));
else
warning(sprintf(...
'[SAVEXML] Cannot convert from %s to XML.',class(v)));
end
end
%=======================================================================
function s = xml_num2str(n)
% TODO % use format ?
if isempty(n)
s = '[]';
else
s = ['[' sprintf('%g ',n(1:end-1))];
s = [s num2str(n(end)) ']'];
end
|
github
|
philippboehmsturm/antx-master
|
spm_bilinear.m
|
.m
|
antx-master/xspm8/spm_bilinear.m
| 3,787 |
utf_8
|
37e6b8a17a436698a9c87c2c7e5235be
|
function [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt)
% returns global Volterra kernels for a MIMO Bilinear system
% FORMAT [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt)
% A - (n x n) df(x(0),0)/dx - n states
% B - (n x n x m) d2f(x(0),0)/dxdu - m inputs
% C - (n x m) df(x(0),0)/du - d2f(x(0),0)/dxdu*x(0)
% D - (n x 1) f(x(0).0) - df(x(0),0)/dx*x(0)
% x0 - (n x 1) x(0)
% N - kernel depth {intervals}
% dt - interval {seconds}
%
% Volterra kernels:
%
% H0 - (n) = h0(t) = y(t)
% H1 - (N x n x m) = h1i(t,s1) = dy(t)/dui(t - s1)
% H2 - (N x N x n x m x m) = h2ij(t,s1,s2) = d2y(t)/dui(t - s1)duj(t - s2)
%
% where n = p if modes are specified
%___________________________________________________________________________
% Returns Volterra kernels for bilinear systems of the form
%
% dx/dt = f(x,u) = A*x + B1*x*u1 + ... Bm*x*um + C1u1 + ... Cmum + D
% y(t) = x(t)
%
%---------------------------------------------------------------------------
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_bilinear.m 1143 2008-02-07 19:33:33Z spm $
% Volterra kernels for bilinear systems
%===========================================================================
% parameters
%---------------------------------------------------------------------------
n = size(A,1); % state variables
m = size(C,2); % inputs
A = full(A);
B = full(B);
C = full(C);
D = full(D);
% eignvector solution {to reduce M0 to leading diagonal form}
%---------------------------------------------------------------------------
M0 = [0 zeros(1,n); D A];
[U J] = eig(M0);
V = pinv(U);
% Lie operator {M0}
%---------------------------------------------------------------------------
M0 = sparse(J);
X0 = V*[1; x0];
% 0th order kernel
%---------------------------------------------------------------------------
H0 = ex(N*dt*M0)*X0;
% 1st order kernel
%---------------------------------------------------------------------------
if nargout > 1
% Lie operator {M1}
%-------------------------------------------------------------------
for i = 1:m
M1(:,:,i) = V*[0 zeros(1,n); C(:,i) B(:,:,i)]*U;
end
% 1st order kernel
%-------------------------------------------------------------------
H1 = zeros(N,n + 1,m);
for p = 1:m
for i = 1:N
u1 = N - i + 1;
H1(u1,:,p) = ex(u1*dt*M0)*M1(:,:,p)*ex(-u1*dt*M0)*H0;
end
end
end
% 2nd order kernels
%---------------------------------------------------------------------------
if nargout > 2
H2 = zeros(N,N,n + 1,m,m);
for p = 1:m
for q = 1:m
for j = 1:N
u2 = N - j + 1;
u1 = N - [1:j] + 1;
H = ex(u2*dt*M0)*M1(:,:,q)*ex(-u2*dt*M0)*H1(u1,:,p)';
H2(u2,u1,:,q,p) = H';
H2(u1,u2,:,p,q) = H';
end
end
end
end
% project to state space and remove kernels associated with the constant
%---------------------------------------------------------------------------
if nargout > 0
H0 = real(U*H0);
H0 = H0([1:n] + 1);
end
if nargout > 1
for p = 1:m
H1(:,:,p) = real(H1(:,:,p)*U.');
end
H1 = H1(:,[1:n] + 1,:);
end
if nargout > 1
for p = 1:m
for q = 1:m
for j = 1:N
H2(j,:,:,p,q) = real(squeeze(H2(j,:,:,p,q))*U.');
end
end
end
H2 = H2(:,:,[1:n] + 1,:,:);
end
return
% matrix exponential function (for diagonal matrices)
%---------------------------------------------------------------------------
function y = ex(x)
n = length(x);
y = spdiags(exp(diag(x)),0,n,n);
return
|
github
|
philippboehmsturm/antx-master
|
spm_powell.m
|
.m
|
antx-master/xspm8/spm_powell.m
| 8,945 |
utf_8
|
5c2706664704f8db313454deb4e1b755
|
function [p,f] = spm_powell(p,xi,tolsc,func,varargin)
% Powell optimisation method
% FORMAT [p,f] = spm_powell(p,xi,tolsc,func,varargin)
% p - Starting parameter values
% xi - columns containing directions in which to begin
% searching.
% tolsc - stopping criteria
% - optimisation stops when
% sqrt(sum(((p-p_prev)./tolsc).^2))<1
% func - name of evaluated function
% varargin - remaining arguments to func (after p)
%
% p - final parameter estimates
% f - function value at minimum
%
%_______________________________________________________________________
% Method is based on Powell's optimisation method described in
% Numerical Recipes (Press, Flannery, Teukolsky & Vetterling).
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_powell.m 4156 2011-01-11 19:03:31Z guillaume $
p = p(:);
f = feval(func,p,varargin{:});
for iter=1:512,
if numel(p)>1, fprintf('iteration %d...\n', iter); end;
ibig = numel(p);
pp = p;
fp = f;
del = 0;
for i=1:length(p),
ft = f;
[p,junk,f] = min1d(p,xi(:,i),func,f,tolsc,varargin{:});
if abs(ft-f) > del,
del = abs(ft-f);
ibig = i;
end;
end;
if numel(p)==1 || sqrt(sum(((p(:)-pp(:))./tolsc(:)).^2))<1, return; end;
ft = feval(func,2.0*p-pp,varargin{:});
if ft < f,
[p,xi(:,ibig),f] = min1d(p,p-pp,func,f,tolsc,varargin{:});
end;
end;
warning('Too many optimisation iterations');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [p,pi,f] = min1d(p,pi,func,f,tolsc,varargin)
% Line search for minimum.
global lnm % used in funeval
lnm = struct('p',p,'pi',pi,'func',func,'args',[]);
lnm.args = varargin;
min1d_plot('Init', 'Line Minimisation','Function','Parameter Value');
min1d_plot('Set', 0, f);
tol = 1/sqrt(sum((pi(:)./tolsc(:)).^2));
t = bracket(f);
[f,pmin] = search(t,tol);
pi = pi*pmin;
p = p + pi;
if length(p)<12,
for i=1:length(p), fprintf('%-8.4g ', p(i)); end;
fprintf('| %.5g\n', f);
else
fprintf('%.5g\n', f);
end
min1d_plot('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function f = funeval(p)
% Reconstruct parameters and evaluate.
global lnm % defined in min1d
pt = lnm.p+p.*lnm.pi;
f = feval(lnm.func,pt,lnm.args{:});
min1d_plot('Set',p,f);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = bracket(f)
% Bracket the minimum (t(2)) between t(1) and t(3)
gold = (1+sqrt(5))/2; % Golden ratio
t(1) = struct('p',0,'f',f);
t(2).p = 1;
t(2).f = funeval(t(2).p);
% if t(2) not better than t(1) then swap
if t(2).f > t(1).f,
t(3) = t(1);
t(1) = t(2);
t(2) = t(3);
end;
t(3).p = t(2).p + gold*(t(2).p-t(1).p);
t(3).f = funeval(t(3).p);
while t(2).f > t(3).f,
% fit a polynomial to t
tmp = cat(1,t.p)-t(2).p;
pol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f);
% minimum is when gradient of polynomial is zero
% sign of pol(3) (the 2nd deriv) should be +ve
if pol(3)>0,
% minimum is when gradient of polynomial is zero
d = -pol(2)/(2*pol(3)+eps);
% A very conservative constraint on the displacement
if d > (1+gold)*(t(3).p-t(2).p),
d = (1+gold)*(t(3).p-t(2).p);
end;
u.p = t(2).p+d;
else
% sign of pol(3) (the 2nd deriv) is not +ve
% so extend out by golden ratio instead
u.p = t(3).p+gold*(t(3).p-t(2).p);
end;
% FUNCTION EVALUATION
u.f = funeval(u.p);
if (t(2).p < u.p) == (u.p < t(3).p),
% u is between t(2) and t(3)
if u.f < t(3).f,
% minimum between t(2) and t(3) - done
t(1) = t(2);
t(2) = u;
return;
elseif u.f > t(2).f,
% minimum between t(1) and u - done
t(3) = u;
return;
end;
end;
% Move all 3 points along
t(1) = t(2);
t(2) = t(3);
t(3) = u;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [f,p] = search(t, tol)
% Brent's method for line searching - given that minimum is bracketed
gold1 = 1-(sqrt(5)-1)/2;
% Current and previous displacements
d = Inf;
pd = Inf;
% sort t into best first order
[junk,ind] = sort(cat(1,t.f));
t = t(ind);
brk = [min(cat(1,t.p)) max(cat(1,t.p))];
for iter=1:128,
% check stopping criterion
if abs(t(1).p - 0.5*(brk(1)+brk(2)))+0.5*(brk(2)-brk(1)) <= 2*tol,
p = t(1).p;
f = t(1).f;
return;
end;
% keep last two displacents
ppd = pd;
pd = d;
% fit a polynomial to t
tmp = cat(1,t.p)-t(1).p;
pol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f);
% minimum is when gradient of polynomial is zero
d = -pol(2)/(2*pol(3)+eps);
u.p = t(1).p+d;
% check so that displacement is less than the last but two,
% that the displaced point is between the brackets
% and that the solution is a minimum rather than a maximum
eps2 = 2*eps*abs(t(1).p)+eps;
if abs(d) > abs(ppd)/2 || u.p < brk(1)+eps2 || u.p > brk(2)-eps2 || pol(3)<=0,
% if criteria are not met, then golden search into the larger part
if t(1).p >= 0.5*(brk(1)+brk(2)),
d = gold1*(brk(1)-t(1).p);
else
d = gold1*(brk(2)-t(1).p);
end;
u.p = t(1).p+d;
end;
% FUNCTION EVALUATION
u.f = funeval(u.p);
% Insert the new point into the appropriate position and update
% the brackets if necessary
if u.f <= t(1).f,
if u.p >= t(1).p, brk(1)=t(1).p; else brk(2)=t(1).p; end;
t(3) = t(2);
t(2) = t(1);
t(1) = u;
else
if u.p < t(1).p, brk(1)=u.p; else brk(2)=u.p; end;
if u.f <= t(2).f,
t(3) = t(2);
t(2) = u;
elseif u.f <= t(3).f,
t(3) = u;
end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function min1d_plot(action,arg1,arg2,arg3,arg4)
% Visual output for line minimisation
persistent min1dplot
%-----------------------------------------------------------------------
if (nargin == 0)
min1d_plot('Init');
else
% initialize
%---------------------------------------------------------------
if strcmpi(action,'init')
if (nargin<4)
arg3 = 'Function';
if (nargin<3)
arg2 = 'Value';
if (nargin<2)
arg1 = 'Line minimisation';
end
end
end
fg = spm_figure('FindWin','Interactive');
if ~isempty(fg)
min1dplot = struct('pointer',get(fg,'Pointer'),'name',get(fg,'Name'),'ax',[]);
min1d_plot('Clear');
set(fg,'Pointer','watch');
% set(fg,'Name',arg1);
min1dplot.ax = axes('Position', [0.15 0.1 0.8 0.75],...
'Box', 'on','Parent',fg);
lab = get(min1dplot.ax,'Xlabel');
set(lab,'string',arg3,'FontSize',10);
lab = get(min1dplot.ax,'Ylabel');
set(lab,'string',arg2,'FontSize',10);
lab = get(min1dplot.ax,'Title');
set(lab,'string',arg1);
line('Xdata',[], 'Ydata',[],...
'LineWidth',2,'Tag','LinMinPlot','Parent',min1dplot.ax,...
'LineStyle','-','Marker','o');
drawnow;
end
% reset
%---------------------------------------------------------------
elseif strcmpi(action,'set')
F = spm_figure('FindWin','Interactive');
br = findobj(F,'Tag','LinMinPlot');
if (~isempty(br))
[xd,indx] = sort([get(br,'Xdata') arg1]);
yd = [get(br,'Ydata') arg2];
yd = yd(indx);
set(br,'Ydata',yd,'Xdata',xd);
drawnow;
end
% clear
%---------------------------------------------------------------
elseif strcmpi(action,'clear')
fg = spm_figure('FindWin','Interactive');
if isstruct(min1dplot),
if ishandle(min1dplot.ax), delete(min1dplot.ax); end
set(fg,'Pointer',min1dplot.pointer);
set(fg,'Name',min1dplot.name);
end
spm_figure('Clear',fg);
drawnow;
end
end
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_vol.m
|
.m
|
antx-master/xspm8/spm_vol.m
| 4,687 |
utf_8
|
2066ba9cc72b0c288e592c2871538689
|
function V = spm_vol(P)
% Get header information for images.
% FORMAT V = spm_vol(P)
% P - a matrix of filenames.
% V - a vector of structures containing image volume information.
% The elements of the structures are:
% V.fname - the filename of the image.
% V.dim - the x, y and z dimensions of the volume
% V.dt - A 1x2 array. First element is datatype (see spm_type).
% The second is 1 or 0 depending on the endian-ness.
% V.mat - a 4x4 affine transformation matrix mapping from
% voxel coordinates to real world coordinates.
% V.pinfo - plane info for each plane of the volume.
% V.pinfo(1,:) - scale for each plane
% V.pinfo(2,:) - offset for each plane
% The true voxel intensities of the jth image are given
% by: val*V.pinfo(1,j) + V.pinfo(2,j)
% V.pinfo(3,:) - offset into image (in bytes).
% If the size of pinfo is 3x1, then the volume is assumed
% to be contiguous and each plane has the same scalefactor
% and offset.
%__________________________________________________________________________
%
% The fields listed above are essential for the mex routines, but other
% fields can also be incorporated into the structure.
%
% The images are not memory mapped at this step, but are mapped when
% the mex routines using the volume information are called.
%
% Note that spm_vol can also be applied to the filename(s) of 4-dim
% volumes. In that case, the elements of V will point to a series of 3-dim
% images.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_vol.m 4045 2010-08-26 15:10:46Z guillaume $
if ~nargin
V = struct('fname', {},...
'dim', {},...
'dt', {},...
'pinfo', {},...
'mat', {},...
'n', {},...
'descrip', {},...
'private', {});
return;
end
% If is already a vol structure then just return
if isstruct(P), V = P; return; end
V = subfunc2(P);
%==========================================================================
function V = subfunc2(P)
if iscell(P)
V = cell(size(P));
for j=1:numel(P)
if iscell(P{j})
V{j} = subfunc2(P{j});
else
V{j} = subfunc1(P{j});
end
end
else
V = subfunc1(P);
end
%==========================================================================
function V = subfunc1(P)
if isempty(P), V = []; return; end
counter = 0;
for i=1:size(P,1)
v = subfunc(P(i,:));
[V(counter+1:counter+size(v, 2),1).fname] = deal('');
[V(counter+1:counter+size(v, 2),1).dim] = deal([0 0 0 0]);
[V(counter+1:counter+size(v, 2),1).mat] = deal(eye(4));
[V(counter+1:counter+size(v, 2),1).pinfo] = deal([1 0 0]');
[V(counter+1:counter+size(v, 2),1).dt] = deal([0 0]);
if isempty(v)
hread_error_message(P(i,:));
error(['Can''t get volume information for ''' P(i,:) '''']);
end
f = fieldnames(v);
for j=1:size(f,1)
eval(['[V(counter+1:counter+size(v,2),1).' f{j} '] = deal(v.' f{j} ');']);
end
counter = counter + size(v,2);
end
%==========================================================================
function V = subfunc(p)
[pth,nam,ext,n1] = spm_fileparts(deblank(p));
p = fullfile(pth,[nam ext]);
n = str2num(n1);
if ~spm_existfile(p)
error('File "%s" does not exist.', p);
end
switch ext
case {'.nii','.NII'}
% Do nothing
case {'.img','.IMG'}
if ~spm_existfile(fullfile(pth,[nam '.hdr'])) && ...
~spm_existfile(fullfile(pth,[nam '.HDR']))
error('File "%s" does not exist.', fullfile(pth,[nam '.hdr']));
end
case {'.hdr','.HDR'}
ext = '.img';
p = fullfile(pth,[nam ext]);
if ~spm_existfile(p)
error('File "%s" does not exist.', p);
end
otherwise
error('File "%s" is not of a recognised type.', p);
end
V = spm_vol_nifti(p,n);
if isempty(n) && length(V.private.dat.dim) > 3
V0(1) = V;
for i = 2:V.private.dat.dim(4)
V0(i) = spm_vol_nifti(p, i);
end
V = V0;
end
if ~isempty(V), return; end
return;
%==========================================================================
function hread_error_message(q)
str = {...
'Error reading information on:',...
[' ',spm_str_manip(q,'k40d')],...
' ',...
'Please check that it is in the correct format.'};
spm('alert*',str,mfilename,sqrt(-1));
return;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_epochs.m
|
.m
|
antx-master/xspm8/spm_eeg_epochs.m
| 7,801 |
utf_8
|
4fabb15c82422268deb9dca5b1a0ea6b
|
function D = spm_eeg_epochs(S)
% Epoching continuous M/EEG data
% FORMAT D = spm_eeg_epochs(S)
%
% S - input structure (optional)
% (optional) fields of S:
% S.D - MEEG object or filename of M/EEG mat-file with
% continuous data
% S.bc - baseline-correct the data (1 - yes, 0 - no).
%
% Either (to use a ready-made trial definition):
% S.epochinfo.trl - Nx2 or Nx3 matrix (N - number of trials)
% [start end offset]
% S.epochinfo.conditionlabels - one label or cell array of N labels
% S.epochinfo.padding - the additional time period around each
% trial for which the events are saved with
% the trial (to let the user keep and use
% for analysis events which are outside) [in ms]
%
% Or (to define trials using (spm_eeg_definetrial)):
% S.pretrig - pre-trigger time [in ms]
% S.posttrig - post-trigger time [in ms]
% S.trialdef - structure array for trial definition with fields
% S.trialdef.conditionlabel - string label for the condition
% S.trialdef.eventtype - string
% S.trialdef.eventvalue - string, numeric or empty
%
% S.reviewtrials - review individual trials after selection
% S.save - save trial definition
%
% Output:
% D - MEEG object (also written on disk)
%__________________________________________________________________________
%
% spm_eeg_epochs extracts single trials from continuous EEG/MEG data. The
% length of an epoch is determined by the samples before and after stimulus
% presentation. One can limit the extracted trials to specific trial types.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Stefan Kiebel
% $Id: spm_eeg_epochs.m 4430 2011-08-12 18:47:17Z vladimir $
SVNrev = '$Rev: 4430 $';
%-Startup
%--------------------------------------------------------------------------
spm('FnBanner', mfilename, SVNrev);
spm('FigName','M/EEG epoching'); spm('Pointer','Watch');
%-Get MEEG object
%--------------------------------------------------------------------------
try
D = S.D;
catch
[D, sts] = spm_select(1, 'mat', 'Select M/EEG mat file');
if ~sts, D = []; return; end
S.D = D;
end
D = spm_eeg_load(D);
S.D = fullfile(D.path, D.fname);
%-Check that the input file contains continuous data
%--------------------------------------------------------------------------
if ~strncmpi(D.type, 'cont', 4)
error('The file must contain continuous data.');
end
if ~isfield(S, 'bc')
S.bc = 1;
% S.bc = spm_input('Subtract baseline?','+1','yes|no',[1 0], 1);
end
%-First case: deftrials (default for GUI call)
%--------------------------------------------------------------------------
if isfield(S, 'trialdef') || nargin == 0
if isfield(S, 'pretrig')
S_definetrial.pretrig = S.pretrig;
end
if isfield(S, 'posttrig')
S_definetrial.posttrig = S.posttrig;
end
if isfield(S, 'trialdef')
S_definetrial.trialdef = S.trialdef;
end
if isfield(S, 'reviewtrials')
S_definetrial.reviewtrials = S.reviewtrials;
end
if isfield(S, 'save')
S_definetrial.save = S.save;
end
S_definetrial.D = S.D;
S_definetrial.event = D.events;
S_definetrial.fsample = D.fsample;
S_definetrial.timeonset = D.timeonset;
S_definetrial.bc = S.bc;
[epochinfo.trl, epochinfo.conditionlabels, S] = spm_eeg_definetrial(S_definetrial);
%-Second case: epochinfo (trlfile and trl)
%--------------------------------------------------------------------------
else
try
epochinfo.trl = S.epochinfo.trl;
epochinfo.conditionlabels = S.epochinfo.conditionlabels;
catch
try
epochinfo.trlfile = S.epochinfo.trlfile;
catch
epochinfo.trlfile = spm_select(1, 'mat', 'Select a trial definition file');
end
try
epochinfo.trl = getfield(load(S.epochinfo.trlfile, 'trl'), 'trl');
epochinfo.conditionlabels = getfield(load(epochinfo.trlfile, 'conditionlabels'), 'conditionlabels');
catch
error('Trouble reading trl file.');
end
end
end
trl = epochinfo.trl;
conditionlabels = epochinfo.conditionlabels;
if numel(conditionlabels) == 1
conditionlabels = repmat(conditionlabels, 1, size(trl, 1));
end
try
epochinfo.padding = S.epochinfo.padding;
catch
epochinfo.padding = 0;
% for history
S.epochinfo.padding = epochinfo.padding;
end
% checks on input
if size(trl, 2) >= 3
timeOnset = unique(trl(:, 3))./D.fsample;
trl = trl(:, 1:2);
else
timeOnset = 0;
end
if length(timeOnset) > 1
error('All trials should have identical baseline');
end
nsampl = unique(round(diff(trl, [], 2)))+1;
if length(nsampl) > 1 || nsampl<1
error('All trials should have identical and positive lengths');
end
inbounds = (trl(:,1)>=1 & trl(:, 2)<=D.nsamples);
rejected = find(~inbounds);
rejected = rejected(:)';
if ~isempty(rejected)
trl = trl(inbounds, :);
conditionlabels = conditionlabels(inbounds);
warning([D.fname ': Events ' num2str(rejected) ' not extracted - out of bounds']);
end
ntrial = size(trl, 1);
%-Generate new MEEG object with new filenames
%--------------------------------------------------------------------------
Dnew = clone(D, ['e' fnamedat(D)], [D.nchannels nsampl, ntrial]);
%-Epoch data
%--------------------------------------------------------------------------
spm_progress_bar('Init', ntrial, 'Events read');
if ntrial > 100, Ibar = floor(linspace(1, ntrial, 100));
else Ibar = [1:ntrial]; end
for i = 1:ntrial
d = D(:, trl(i, 1):trl(i, 2), 1);
Dnew(:, :, i) = d;
Dnew = events(Dnew, i, select_events(D.events, ...
[trl(i, 1)/D.fsample-epochinfo.padding trl(i, 2)/D.fsample+epochinfo.padding]));
if ismember(i, Ibar), spm_progress_bar('Set', i); end
end
Dnew = conditions(Dnew, [], conditionlabels);
% The conditions will later be sorted in the original order they were defined.
if isfield(S, 'trialdef')
Dnew = condlist(Dnew, {S.trialdef(:).conditionlabel});
end
Dnew = trialonset(Dnew, [], trl(:, 1)./D.fsample+D.trialonset);
Dnew = timeonset(Dnew, timeOnset);
Dnew = type(Dnew, 'single');
%-Perform baseline correction if there are negative time points
%--------------------------------------------------------------------------
if S.bc
if time(Dnew, 1) < 0
S1 = [];
S1.D = Dnew;
S1.time = [time(Dnew, 1, 'ms') 0];
S1.save = false;
S1.updatehistory = false;
Dnew = spm_eeg_bc(S1);
else
warning('There was no baseline specified. The data is not baseline-corrected');
end
end
%-Save new evoked M/EEG dataset
%--------------------------------------------------------------------------
D = Dnew;
% Remove some redundant stuff potentially put in by spm_eeg_definetrial
if isfield(S, 'event'), S = rmfield(S, 'event'); end
D = D.history(mfilename, S);
save(D);
%-Cleanup
%--------------------------------------------------------------------------
spm_progress_bar('Clear');
spm('FigName','M/EEG epoching: done'); spm('Pointer','Arrow');
%==========================================================================
function event = select_events(event, timeseg)
% Utility function to select events according to time segment
if ~isempty(event)
[time ind] = sort([event(:).time]);
selectind = ind(time >= timeseg(1) & time <= timeseg(2));
event = event(selectind);
end
|
github
|
philippboehmsturm/antx-master
|
spm_jobman.m
|
.m
|
antx-master/xspm8/spm_jobman.m
| 21,770 |
utf_8
|
10c04d4d60570a5fff732bdebb4a6482
|
function varargout = spm_jobman(varargin)
% Main interface for SPM Batch System
% This function provides a compatibility layer between SPM and matlabbatch.
% It translates spm_jobman callbacks into matlabbatch callbacks and allows
% to edit and run SPM5 style batch jobs.
%
% FORMAT spm_jobman('initcfg')
% Initialise jobs configuration and set MATLAB path accordingly.
%
% FORMAT spm_jobman('run',job)
% FORMAT output_list = spm_jobman('run',job)
% Run specified job
% job - filename of a job (.m, .mat or .xml), or
% cell array of filenames, or
% 'jobs'/'matlabbatch' variable, or
% cell array of 'jobs'/'matlabbatch' variables.
% output_list - cell array containing the output arguments from each
% module in the job. The format and contents of these
% outputs is defined in the configuration of each module
% (.prog and .vout callbacks).
%
% FORMAT job_id = spm_jobman
% job_id = spm_jobman('interactive')
% job_id = spm_jobman('interactive',job)
% job_id = spm_jobman('interactive',job,node)
% job_id = spm_jobman('interactive','',node)
% Run the user interface in interactive mode.
% node - indicate which part of the configuration is to be used.
% For example, it could be 'spm.spatial.coreg.estimate'.
% job_id - can be used to manipulate this job in cfg_util. Note that
% changes to the job in cfg_util will not show up in cfg_ui
% unless 'Update View' is called.
%__________________________________________________________________________
%
% Programmers help:
%
% FORMAT output_list = spm_jobman('serial')
% output_list = spm_jobman('serial',job[,'', input1,...inputN])
% output_list = spm_jobman('serial',job ,node[,input1,...inputN])
% output_list = spm_jobman('serial','' ,node[,input1,...inputN])
% Run the user interface in serial mode. If job is not empty, then node
% is silently ignored. Inputs can be a list of arguments. These are passed
% on to the open inputs of the specified job/node. Each input should be
% suitable to be assigned to item.val{1}. For cfg_repeat/cfg_choice items,
% input should be a cell list of indices input{1}...input{k} into
% item.value. See cfg_util('filljob',...) for details.
%
% FORMAT jobs = spm_jobman('spm5tospm8',jobs)
% Take a cell list of SPM5 job structures and returns SPM8 compatible versions.
%
% FORMAT job = spm_jobman('spm5tospm8bulk',jobfiles)
% Take a cell string with SPM5 job filenames and saves them in SPM8
% compatible format. The new job files will be MATLAB .m files. Their
% filenames will be derived from the input filenames. To make sure they are
% valid MATLAB script names they will be processed with
% genvarname(filename) and have a '_spm8' string appended to their
% filename.
%
% FORMAT spm_jobman('help',node)
% spm_jobman('help',node,width)
% Create a cell array containing help information. This is justified
% to be 'width' characters wide. e.g.
% h = spm_jobman('help','spm.spatial.coreg.estimate');
% for i=1:numel(h), fprintf('%s\n',h{i}); end
%
% FORMAT [tag, job] = spm_jobman('harvest', job_id|cfg_item|cfg_struct)
% Take the job with id job_id in cfg_util and extract what is
% needed to save it as a batch job (for experts only). If the argument is a
% cfg_item or cfg_struct tree, it will be harvested outside cfg_util.
% tag - tag of the root node of the current job/cfg_item tree
% job - harvested data from the current job/cfg_item tree
%
% FORMAT spm_jobman('pulldown')
% Create a pulldown 'TASKS' menu in the Graphics window.
%__________________________________________________________________________
%
% not implemented: FORMAT spm_jobman('jobhelp')
% Create a cell array containing help information specific for a certain
% job. Help is only printed for items where job specific help is
% present. This can be used together with spm_jobman('help') to create a
% job specific manual.
%
% not implemented: FORMAT spm_jobman('chmod')
% Change the modality for the TASKS pulldown.
%
% not implemented: FORMAT spm_jobman('defaults')
% Run the interactive defaults editor.
%
% not implemented: FORMAT output_list = spm_jobman('run_nogui',job)
% Run a job without X11 (as long as there is no graphics output from the
% job itself). The matlabbatch system does not need graphics output to run
% a job.
%__________________________________________________________________________
%
% This code is based on earlier versions by John Ashburner, Philippe
% Ciuciu and Guillaume Flandin.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Copyright (C) 2008 Freiburg Brain Imaging
% Volkmar Glauche
% $Id: spm_jobman.m 4242 2011-03-11 15:12:04Z guillaume $
persistent isInitCfg;
if isempty(isInitCfg) && ~(nargin == 1 && strcmpi(varargin{1},'initcfg'))
warning('spm:spm_jobman:NotInitialised',...
'Run spm_jobman(''initcfg''); beforehand');
spm_jobman('initcfg');
end
isInitCfg = true;
if ~nargin
h = cfg_ui;
if nargout > 0, varargout = {h}; end
return;
end
cmd = lower(varargin{1});
if strcmp(cmd,'run_nogui')
warning('spm:spm_jobman:NotImplemented', ...
'Callback ''%s'' not implemented.', cmd);
cmd = 'run';
end
if any(strcmp(cmd, {'serial','interactive','run'}))
if nargin > 1
% sort out job/node arguments for interactive, serial, run cmds
if nargin>=2 && ~isempty(varargin{2})
% do not consider node if job is given
if ischar(varargin{2}) || iscellstr(varargin{2})
jobs = load_jobs(varargin{2});
elseif iscell(varargin{2})
if iscell(varargin{2}{1})
% assume varargin{2} is a cell of jobs
jobs = varargin{2};
else
% assume varargin{2} is a single job
jobs{1} = varargin{2};
end
end
mljob = canonicalise_job(jobs);
elseif any(strcmp(cmd, {'interactive','serial'})) && nargin>=3 && isempty(varargin{2})
% Node spec only allowed for 'interactive', 'serial'
arg3 = regexprep(varargin{3},'^spmjobs\.','spm.');
mod_cfg_id = cfg_util('tag2mod_cfg_id',arg3);
else
error('spm:spm_jobman:WrongUI', ...
'Don''t know how to handle this ''%s'' call.', lower(varargin{1}));
end
end
end
switch cmd
case {'initcfg'}
if ~isdeployed
addpath(fullfile(spm('Dir'),'matlabbatch'));
addpath(fullfile(spm('Dir'),'config'));
end
cfg_get_defaults('cfg_util.genscript_run', @genscript_run);
cfg_util('initcfg'); % This must be the first call to cfg_util
if ~spm('cmdline')
f = cfg_ui('Visible','off'); % Create invisible batch ui
f0 = findobj(f, 'Tag','MenuFile'); % Add entries to file menu
f2 = uimenu(f0,'Label','Load SPM5 job', 'Callback',@load_job, ...
'HandleVisibility','off', 'tag','jobs', ...
'Separator','on');
f3 = uimenu(f0,'Label','Bulk Convert SPM5 job(s)', ...
'Callback',@conv_jobs, ...
'HandleVisibility','off', 'tag','jobs');
end
case {'interactive'}
if exist('mljob', 'var')
cjob = cfg_util('initjob', mljob);
elseif exist('mod_cfg_id', 'var')
if isempty(mod_cfg_id)
arg3 = regexprep(varargin{3},'^spmjobs\.','spm.');
warning('spm:spm_jobman:NodeNotFound', ...
['Can not find executable node ''%s'' - running '...
'matlabbatch without default node.'], arg3);
cjob = cfg_util('initjob');
else
cjob = cfg_util('initjob');
mod_job_id = cfg_util('addtojob', cjob, mod_cfg_id);
cfg_util('harvest', cjob, mod_job_id);
end
else
cjob = cfg_util('initjob');
end
cfg_ui('local_showjob', findobj(0,'tag','cfg_ui'), cjob);
if nargout > 0
varargout{1} = cjob;
end
case {'serial'}
if exist('mljob', 'var')
cjob = cfg_util('initjob', mljob);
else
cjob = cfg_util('initjob');
if nargin > 2
arg3 = regexprep(varargin{3},'^spmjobs\.','spm.');
[mod_cfg_id, item_mod_id] = cfg_util('tag2cfg_id', lower(arg3));
cfg_util('addtojob', cjob, mod_cfg_id);
end
end
sts = cfg_util('filljobui', cjob, @serial_ui, varargin{4:end});
if sts
cfg_util('run', cjob);
if nargout > 0
varargout{1} = cfg_util('getalloutputs', cjob);
end
end
cfg_util('deljob', cjob);
case {'run'}
cjob = cfg_util('initjob', mljob);
cfg_util('run', cjob);
if nargout > 0
varargout{1} = cfg_util('getalloutputs', cjob);
end
cfg_util('deljob', cjob);
case {'spm5tospm8'}
varargout{1} = canonicalise_job(varargin{2});
case {'spm5tospm8bulk'}
conv_jobs(varargin{2});
case {'harvest'}
if nargin == 1
error('spm:spm_jobman:CantHarvest', ...
['Can not harvest job without job_id. Please use ' ...
'spm_jobman(''harvest'', job_id).']);
elseif cfg_util('isjob_id', varargin{2})
[tag job] = cfg_util('harvest', varargin{2});
elseif isa(varargin{2}, 'cfg_item')
[tag job] = harvest(varargin{2}, varargin{2}, false, false);
elseif isstruct(varargin{2})
% try to convert into class before harvesting
c = cfg_struct2cfg(varargin{2});
[tag job] = harvest(c,c,false,false);
else
error('spm:spm_jobman:CantHarvestThis', ...
'Can not harvest this argument.');
end
varargout{1} = tag;
varargout{2} = job;
case {'help'}
if (nargin < 2) || isempty(varargin{2})
node = 'spm';
else
node = regexprep(varargin{2},'^spmjobs\.','spm.');
end
if nargin < 3
width = 60;
else
width = varargin{3};
end
varargout{1} = cfg_util('showdocwidth', width, node);
case {'pulldown'}
pulldown;
case {'defaults'}
warning('spm:spm_jobman:NotImplemented', ...
'Callback ''%s'' not implemented.', varargin{1});
case {'chmod'}
warning('spm:spm_jobman:NotImplemented', ...
'Callback ''%s'' not implemented.', varargin{1});
case {'jobhelp'}
warning('spm:spm_jobman:NotImplemented', ...
'Callback ''%s'' not implemented.', varargin{1});
otherwise
error(['"' varargin{1} '" - unknown option']);
end
%==========================================================================
% function [mljob, comp] = canonicalise_job(job)
%==========================================================================
function [mljob, comp] = canonicalise_job(job)
% job: a cell list of job data structures.
% Check whether job is a SPM5 or matlabbatch job. In the first case, all
% items in job{:} should have a fieldname of either 'temporal', 'spatial',
% 'stats', 'tools' or 'util'. If this is the case, then job will be
% assigned to mljob{1}.spm, which is the tag of the SPM root
% configuration item.
comp = true(size(job));
mljob = cell(size(job));
for cj = 1:numel(job)
for k = 1:numel(job{cj})
comp(cj) = comp(cj) && any(strcmp(fieldnames(job{cj}{k}), ...
{'temporal', 'spatial', 'stats', 'tools', 'util'}));
if ~comp(cj)
break;
end
end
if comp(cj)
tmp = convert_jobs(job{cj});
for i=1:numel(tmp),
mljob{cj}{i}.spm = tmp{i};
end
else
mljob{cj} = job{cj};
end
end
%==========================================================================
% function conv_jobs(varargin)
%==========================================================================
function conv_jobs(varargin)
% Select a list of jobs, canonicalise each of it and save as a .m file
% using gencode.
spm('Pointer','Watch');
if nargin == 0 || ~iscellstr(varargin{1})
[fname sts] = spm_select([1 Inf], 'batch', 'Select job file(s)');
fname = cellstr(fname);
if ~sts, return; end
else
fname = varargin{1};
end
joblist = load_jobs(fname);
for k = 1:numel(fname)
if ~isempty(joblist{k})
[p n] = spm_fileparts(fname{k});
% Save new job as genvarname(*_spm8).m
newfname = fullfile(p, sprintf('%s.m', ...
genvarname(sprintf('%s_spm8', n))));
fprintf('SPM5 job: %s\nSPM8 job: %s\n', fname{k}, newfname);
cjob = cfg_util('initjob', canonicalise_job(joblist(k)));
cfg_util('savejob', cjob, newfname);
cfg_util('deljob', cjob);
end
end
spm('Pointer','Arrow');
%==========================================================================
% function load_job(varargin)
%==========================================================================
function load_job(varargin)
% Select a single job file, canonicalise it and display it in GUI
[fname sts] = spm_select([1 Inf], 'batch', 'Select job file');
if ~sts, return; end
spm('Pointer','Watch');
joblist = load_jobs(fname);
if ~isempty(joblist{1})
spm_jobman('interactive',joblist{1});
end
spm('Pointer','Arrow');
%==========================================================================
% function newjobs = load_jobs(job)
%==========================================================================
function newjobs = load_jobs(job)
% Load a list of possible job files, return a cell list of jobs. Jobs can
% be either SPM5 (i.e. containing a 'jobs' variable) or SPM8/matlabbatch
% jobs. If a job file failed to load, an empty cell is returned in the
% list.
if ischar(job)
filenames = cellstr(job);
else
filenames = job;
end
newjobs = {};
for cf = 1:numel(filenames)
[p,nam,ext] = fileparts(filenames{cf});
switch ext
case '.xml'
spm('Pointer','Watch');
try
loadxml(filenames{cf},'jobs');
catch
try
loadxml(filenames{cf},'matlabbatch');
catch
warning('spm:spm_jobman:LoadFailed','LoadXML failed: ''%s''',filenames{cf});
end
end
spm('Pointer','Arrow');
case '.mat'
try
S=load(filenames{cf});
if isfield(S,'matlabbatch')
matlabbatch = S.matlabbatch;
elseif isfield(S,'jobs')
jobs = S.jobs;
else
warning('spm:spm_jobman:JobNotFound','No SPM5/SPM8 job found in ''%s''', filenames{cf});
end
catch
warning('spm:spm_jobman:LoadFailed','Load failed: ''%s''',filenames{cf});
end
case '.m'
try
fid = fopen(filenames{cf},'rt');
str = fread(fid,'*char');
fclose(fid);
eval(str);
catch
warning('spm:spm_jobman:LoadFailed','Load failed: ''%s''',filenames{cf});
end
if ~(exist('jobs','var') || exist('matlabbatch','var'))
warning('spm:spm_jobman:JobNotFound','No SPM5/SPM8 job found in ''%s''', filenames{cf});
end
otherwise
warning('Unknown extension: ''%s''', filenames{cf});
end
if exist('jobs','var')
newjobs = [newjobs(:); {jobs}];
clear jobs;
elseif exist('matlabbatch','var')
newjobs = [newjobs(:); {matlabbatch}];
clear matlabbatch;
end
end
%==========================================================================
% function njobs = convert_jobs(jobs)
%==========================================================================
function njobs = convert_jobs(jobs)
decel = struct('spatial',struct('realign',[],'coreg',[],'normalise',[]),...
'temporal',[],...
'stats',[],...
'meeg',[],...
'util',[],...
'tools',struct('dartel',[]));
njobs = {};
for i0 = 1:numel(jobs)
tmp0 = fieldnames(jobs{i0});
tmp0 = tmp0{1};
if any(strcmp(tmp0,fieldnames(decel)))
for i1=1:numel(jobs{i0}.(tmp0))
tmp1 = fieldnames(jobs{i0}.(tmp0){i1});
tmp1 = tmp1{1};
if ~isempty(decel.(tmp0))
if any(strcmp(tmp1,fieldnames(decel.(tmp0)))),
for i2=1:numel(jobs{i0}.(tmp0){i1}.(tmp1)),
njobs{end+1} = struct(tmp0,struct(tmp1,jobs{i0}.(tmp0){i1}.(tmp1){i2}));
end
else
njobs{end+1} = struct(tmp0,jobs{i0}.(tmp0){i1});
end
else
njobs{end+1} = struct(tmp0,jobs{i0}.(tmp0){i1});
end
end
else
njobs{end+1} = jobs{i0};
end
end
%==========================================================================
% function pulldown
%==========================================================================
function pulldown
fg = spm_figure('findwin','Graphics');
if isempty(fg), return; end;
delete(findall(fg,'tag','jobs'));
f0 = uimenu(fg,'Label','TASKS', ...
'HandleVisibility','off', 'tag','jobs');
f1 = uimenu(f0,'Label','BATCH', 'Callback',@cfg_ui, ...
'HandleVisibility','off', 'tag','jobs');
f4 = uimenu(f0,'Label','SPM (interactive)', ...
'HandleVisibility','off', 'tag','jobs', 'Separator','on');
cfg_ui('local_setmenu', f4, cfg_util('tag2cfg_id', 'spm'), ...
@local_init_interactive, false);
f5 = uimenu(f0,'Label','SPM (serial)', ...
'HandleVisibility','off', 'tag','jobs');
cfg_ui('local_setmenu', f5, cfg_util('tag2cfg_id', 'spm'), ...
@local_init_serial, false);
%==========================================================================
% function local_init_interactive(varargin)
%==========================================================================
function local_init_interactive(varargin)
cjob = cfg_util('initjob');
mod_cfg_id = get(gcbo,'userdata');
cfg_util('addtojob', cjob, mod_cfg_id);
cfg_ui('local_showjob', findobj(0,'tag','cfg_ui'), cjob);
%==========================================================================
% function local_init_serial(varargin)
%==========================================================================
function local_init_serial(varargin)
mod_cfg_id = get(gcbo,'userdata');
cjob = cfg_util('initjob');
cfg_util('addtojob', cjob, mod_cfg_id);
sts = cfg_util('filljobui', cjob, @serial_ui);
if sts
cfg_util('run', cjob);
end
cfg_util('deljob', cjob);
%==========================================================================
% function [val sts] = serial_ui(item)
%==========================================================================
function [val sts] = serial_ui(item)
% wrapper function to translate cfg_util('filljobui'... input requests into
% spm_input/cfg_select calls.
sts = true;
switch class(item)
case 'cfg_choice'
labels = cell(size(item.values));
values = cell(size(item.values));
for k = 1:numel(item.values)
labels{k} = item.values{k}.name;
values{k} = k;
end
val = spm_input(item.name, 1, 'm', labels, values);
case 'cfg_menu'
val = spm_input(item.name, 1, 'm', item.labels, item.values);
val = val{1};
case 'cfg_repeat'
labels = cell(size(item.values));
values = cell(size(item.values));
for k = 1:numel(item.values)
labels{k} = item.values{k}.name;
values{k} = k;
end
% enter at least item.num(1) values
for k = 1:item.num(1)
val(k) = spm_input(sprintf('%s(%d)', item.name, k), 1, 'm', ...
labels, values);
end
% enter more (up to varargin{3}(2) values
labels = {labels{:} 'Done'};
% values is a cell list of natural numbers, use -1 for Done
values = {values{:} -1};
while numel(val) < item.num(2)
val1 = spm_input(sprintf('%s(%d)', item.name, numel(val)+1), 1, ...
'm', labels, values);
if val1{1} == -1
break;
else
val(end+1) = val1;
end
end
case 'cfg_entry'
val = spm_input(item.name, 1, item.strtype, '', item.num, ...
item.extras);
case 'cfg_files'
[t,sts] = cfg_getfile(item.num, item.filter, item.name, '', ...
item.dir, item.ufilter);
if sts
val = cellstr(t);
else
val = {};
error('File selector was closed.');
end
end
%==========================================================================
% function [code cont] = genscript_run
%==========================================================================
function [code cont] = genscript_run
% Return code snippet to initialise SPM defaults and run a job generated by
% cfg_util('genscript',...) through spm_jobman.
modality = spm('CheckModality');
code{1} = sprintf('spm(''defaults'', ''%s'');', modality);
code{2} = 'spm_jobman(''serial'', jobs, '''', inputs{:});';
cont = false;
|
github
|
philippboehmsturm/antx-master
|
spm_bms_partition.m
|
.m
|
antx-master/xspm8/spm_bms_partition.m
| 4,648 |
utf_8
|
0b0d4cfa175b9620fe86629a8490391c
|
function spm_bms_partition(BMS)
% Compute model partitioning for BMS
% FORMAT spm_bms_partition(BMS)
%
% Input:
% BMS structure (BMS.mat)
%
% Output:
% PPM (images) for each of the subsets defined
% xppm_subsetn.img (RFX) and ppm_subsetn.img (FFX)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Maria Joao Rosa
% $Id: spm_bms_partition.m 4310 2011-04-18 16:07:35Z guillaume $
% Contrast vector
% -------------------------------------------------------------------------
spm_input('Specify contrast vector. Example: [1 1 2 2 3 3]',1,'d');
contrast = spm_input('Contrast vector',2,'e',[]);
% Inference method to plot
% -------------------------------------------------------------------------
method = spm_input('Inference method',3,'b','FFX|RFX',['FFX';'RFX']);
nb_subsets = length(unique(contrast));
max_cont = max(contrast);
nb_models = length(contrast);
switch method
case 'FFX'
str_method = 'ffx';
str_output = 'ppm';
case 'RFX'
str_method = 'rfx';
str_output = 'xppm';
otherwise
error('Unknown inference method.');
end
% Check if ffx exists
% -------------------------------------------------------------------------
if ~isfield(BMS.map,str_method)
msgbox(sprintf('No %s analysis in current BMS.mat.',method));
return
end
% Check number of subsets and nb of models
% -------------------------------------------------------------------------
bms_fields = eval(sprintf('BMS.map.%s.ppm',str_method));
nmodels = size(bms_fields,2);
if nb_models ~= nmodels || nb_subsets == 1 || max_cont ~= nb_subsets
msgbox('Invalid contrast vector!')
return
end
% Get data for each subset
% -------------------------------------------------------------------------
data = cell(1,nb_subsets);
for i = 1:nmodels,
num = contrast(i);
data{num} = [data{num};bms_fields{i}];
end
% Create new images by summing old the ppms
% -------------------------------------------------------------------------
pth = fileparts(BMS.fname);
data_vol = cell(nb_subsets,1);
ftmp = cell(nb_subsets,1);
for j = 1:nb_subsets,
data_vol{j} = spm_vol(char(data{j}));
n_models_sub = size(data{j},1);
ftmp{j} = 'i1';
for jj = 1:n_models_sub-1
ftmp{j} = [ftmp{j},sprintf(' + i%d',jj+1)];
end
fname = fullfile(pth,sprintf('subset%d_%s.img',j,str_output));
save_fn{j} = fname;
Vo = calc_im(j,data_vol,fname,ftmp);
end
% Save new BMS structure
% -------------------------------------------------------------------------
bms_struct = eval(sprintf('BMS.map.%s',str_method));
bms_struct.subsets = save_fn;
switch method
case 'FFX'
BMS.map.ffx = bms_struct;
case 'RFX'
BMS.map.rfx = bms_struct;
end
file_name = BMS.fname;
BMS.xSPM = [];
save(file_name,'BMS')
% Return to results
%==========================================================================
spm_input('Done',1,'d');
return;
%==========================================================================
% out = calc_im(j,data_vol,fname,ftmp)
%==========================================================================
% Function to sum the data (taken from spm_imcalc)
%--------------------------------------------------------------------------
function out = calc_im(j,data_vol,fname,ftmp)
Vi_tmp = data_vol{j};
Vi = Vi_tmp(1);
Vo(j) = struct(...
'fname', fname,...
'dim', Vi.dim,...
'dt', [spm_type('float32') spm_platform('bigend')],...
'mat', Vi.mat,...
'descrip', 'spm - algebra');
hold = 1; mask = 0; dmtx = 0;
Vi = data_vol{j};
n = numel(Vi);
Y = zeros(Vo(j).dim(1:3));
f = ftmp{j};
for p = 1:Vo(j).dim(3),
B = spm_matrix([0 0 -p 0 0 0 1 1 1]);
if dmtx, X=zeros(n,prod(Vo(j).dim(1:2))); end
for i = 1:n
M = inv(B*inv(Vo(j).mat)*Vi(i).mat);
d = spm_slice_vol(Vi(i),M,Vo(j).dim(1:2),[hold,NaN]);
if (mask<0), d(isnan(d))=0; end;
if (mask>0) && ~spm_type(Vi(i).dt(1),'nanrep'), d(d==0)=NaN; end
if dmtx, X(i,:) = d(:)'; else eval(['i',num2str(i),'=d;']); end
end
try
eval(['Yp = ' f ';']);
catch
error(['Can''t evaluate "',f,'".']);
end
if prod(Vo(j).dim(1:2)) ~= numel(Yp),
error(['"',f,'" produced incompatible image.']); end
if (mask<0), Yp(isnan(Yp))=0; end
Y(:,:,p) = reshape(Yp,Vo(j).dim(1:2));
end
temp = Vo(j);
temp = spm_write_vol(temp,Y);
out(j) = temp;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_vbecd_disp.m
|
.m
|
antx-master/xspm8/spm_eeg_inv_vbecd_disp.m
| 23,018 |
UNKNOWN
|
5277a06e987a0014165d867f7c51bb1b
|
function spm_eeg_inv_vbecd_disp(action,varargin)
% Display the dipoles as obtained from VB-ECD
%
% FORMAT spm_eeg_inv_vbecd_disp('Init',D)
% Display the latest VB-ECD solution saved in the .inv{} field of the
% data structure D.
%
% FORMAT spm_eeg_inv_vbecd_disp('Init',D, ind)
% Display the ind^th .inv{} cell element, if it is actually a VB-ECD
% solution.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Christophe Phillips
% $Id: spm_eeg_inv_vbecd_disp.m 3951 2010-06-28 15:09:36Z gareth $
% Note:
% unfortunately I cannot see how to ensure that when zooming in the image
% the dipole location stays in place...
global st
Fig = spm_figure('GetWin','Graphics');
colors = {'y','b','g','r','c','m'}; % 6 possible colors
marker = {'o','x','+','*','s','d','v','p','h'}; % 9 possible markers
Ncolors = length(colors);
Nmarker = length(marker);
if nargin == 0, action = 'Init'; end;
switch lower(action),
%==========================================================================
case 'init'
%==========================================================================
% FORMAT spm_eeg_inv_vbecd_disp('init',D,ind)
% Initialise the variables with GUI
%--------------------------------------------------------------------------
if nargin<2
D = spm_eeg_load;
else
D = varargin{1};
end
if nargin<3
% find the latest inverse produced with vbecd
Ninv = length(D.inv);
lind = [];
for ii=1:Ninv
if isfield(D.inv{ii},'method') && ...
strcmp(D.inv{ii}.method,'vbecd')
lind = [lind ii];
end
end
ind = max(lind);
if ~ind,
spm('alert*','No VB-ECD solution found with this data file!',...
'VB-ECD display')
return
end
else
ind = varargin{3};
end
% Stash dipole(s) information in sdip structure
sdip = D.inv{ind}.inverse;
% if the exit flag is not in the structure, assume everything went ok.
if ~isfield(sdip,'exitflag')
sdip.exitflag = ones(1,sdip.n_seeds);
end
try
error('crap');
Pimg = spm_vol(D.inv{ind}.mesh.sMRI);
catch
Pimg = spm_vol(fullfile(spm('dir'), 'canonical', 'single_subj_T1.nii'));
end
spm_orthviews('Reset');
spm_orthviews('Image', Pimg, [0.0 0.45 1 0.55]);
spm_orthviews('MaxBB');
spm_orthviews('AddContext')
st.callback = 'spm_image(''shopos'');';
% remove clicking in image
for ii=1:3,
set(st.vols{1}.ax{ii}.ax,'ButtonDownFcn',';');
end
WS = spm('WinScale');
% Build GUI
%==========================================================================
% Location:
%--------------------------------------------------------------------------
uicontrol(Fig,'Style','Frame','Position',[60 25 200 325].*WS, ...
'DeleteFcn','spm_image(''reset'');');
uicontrol(Fig,'Style','Frame','Position',[70 250 180 90].*WS);
uicontrol(Fig,'Style','Text', 'Position',[75 320 170 016].*WS, ...
'String','Current Position');
uicontrol(Fig,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:');
uicontrol(Fig,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:');
uicontrol(Fig,'Style','Text', 'Position',[75 255 75 020].*WS,'String','Img Intens.:');
st.mp = uicontrol(Fig,'Style','Text', 'Position',[110 295 135 020].*WS,'String','');
st.vp = uicontrol(Fig,'Style','Text', 'Position',[110 275 135 020].*WS,'String','');
st.in = uicontrol(Fig,'Style','Text', 'Position',[150 255 85 020].*WS,'String','');
c = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;';
uicontrol(Fig,'Style','togglebutton','Position',[95 220 125 20].*WS,...
'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs');
% Dipoles/seeds selection:
%--------------------------------------------------------------------------
uicontrol(Fig,'Style','Frame','Position',[300 25 180 325].*WS);
sdip.hdl.hcl = uicontrol(Fig,'Style','pushbutton','Position',[310 320 100 20].*WS, ...
'String','Clear all','CallBack','spm_eeg_inv_vbecd_disp(''ClearAll'')');
sdip.hdl.hseed=zeros(sdip.n_seeds,1);
for ii=1:sdip.n_seeds
if sdip.exitflag(ii)==1
sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','togglebutton','String',num2str(ii),...
'Position',[310+rem(ii-1,8)*20 295-fix((ii-1)/8)*20 20 20].*WS,...
'CallBack','spm_eeg_inv_vbecd_disp(''ChgSeed'')');
else
sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','Text','String',num2str(ii), ...
'Position',[310+rem(ii-1,8)*20 293-fix((ii-1)/8)*20 20 20].*WS) ;
end
end
uicontrol(Fig,'Style','text','String','Select dipole # :', ...
'Position',[310 255-fix((sdip.n_seeds-1)/8)*20 110 20].*WS);
txt_box = cell(sdip.n_dip,1);
for ii=1:sdip.n_dip, txt_box{ii} = num2str(ii); end
txt_box{sdip.n_dip+1} = 'all';
sdip.hdl.hdip = uicontrol(Fig,'Style','popup','String',txt_box, ...
'Position',[420 258-fix((sdip.n_seeds-1)/8)*20 40 20].*WS, ...
'Callback','spm_eeg_inv_vbecd_disp(''ChgDip'')');
% Dipoles orientation and strength:
%--------------------------------------------------------------------------
uicontrol(Fig,'Style','Frame','Position',[70 120 180 90].*WS);
uicontrol(Fig,'Style','Text', 'Position',[75 190 170 016].*WS, ...
'String','Dipole orientation & strength');
uicontrol(Fig,'Style','Text', 'Position',[75 165 65 020].*WS, ...
'String','x-y-z or.:');
uicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS, ...
'String','theta-phi or.:');
uicontrol(Fig,'Style','Text', 'Position',[75 125 75 020].*WS, ...
'String','Dip. intens.:');
sdip.hdl.hor1 = uicontrol(Fig,'Style','Text', 'Position', ...
[140 165 105 020].*WS,'String','a');
sdip.hdl.hor2 = uicontrol(Fig,'Style','Text', 'Position', ...
[150 145 85 020].*WS,'String','b');
sdip.hdl.int = uicontrol(Fig,'Style','Text', 'Position', ...
[150 125 85 020].*WS,'String','c');
st.vols{1}.sdip = sdip;
% First plot = all the seeds that converged !
l_conv = find(sdip.exitflag==1);
if isempty(l_conv)
error('No seed converged towards a stable solution, nothing to be displayed !')
else
spm_eeg_inv_vbecd_disp('DrawDip',l_conv,1)
set(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons
end
%==========================================================================
case 'drawdip'
%==========================================================================
% FORMAT spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip,sdip)
% e.g. spm_eeg_inv_vbecd_disp('DrawDip',1,1,sdip)
% e.g. spm_eeg_inv_vbecd_disp('DrawDip',[1:5],1,sdip)
%--------------------------------------------------------------------------
if nargin < 2
i_seed = 1;
else
i_seed = varargin{1};
end
if nargin<3
i_dip = 1;
else
i_dip = varargin{2};
end
if nargin<4
if isfield(st.vols{1},'sdip')
sdip = st.vols{1}.sdip;
else
error('I can''t find sdip structure');
end
else
sdip = varargin{3};
st.vols{1}.sdip = sdip;
end
if any(i_seed>sdip.n_seeds) || i_dip>(sdip.n_dip+1)
error('Wrong i_seed or i_dip index in spm_eeg_inv_vbecd_disp');
end
% Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously,
% The 3D cut will then be at the mean location of all sources !!!
if i_dip == (sdip.n_dip+1)
i_dip = 1:sdip.n_dip;
end
% if seed indexes passed is wrong (no convergence) remove the wrong ones
i_seed(sdip.exitflag(i_seed)~=1) = [];
if isempty(i_seed)
error('You passed the wrong seed indexes...')
end
if size(i_seed,2)==1, i_seed=i_seed'; end
% Display business
%--------------------------------------------------------------------------
loc_mm = sdip.mniloc{i_seed(1)}(:,i_dip);
if length(i_seed)>1
% unit = ones(1,sdip.n_dip);
for ii = i_seed(2:end)
loc_mm = loc_mm + sdip.mniloc{ii}(:,i_dip);
end
loc_mm = loc_mm/length(i_seed);
end
if length(i_dip)>1
loc_mm = mean(loc_mm,2);
end
% Place the underlying image at right cuts
spm_orthviews('Reposition',loc_mm);
if length(i_dip)>1
tabl_seed_dip = [kron(ones(length(i_dip),1),i_seed') ...
kron(i_dip',ones(length(i_seed),1))];
else
tabl_seed_dip = [i_seed' ones(length(i_seed),1)*i_dip];
end
% Scaling, according to all dipoles in the selected seed sets.
% The time displayed is the one corresponding to the maximum EEG power !
Mn_j = -1;
l3 = -2:0;
for ii = 1:length(i_seed)
for jj = 1:sdip.n_dip
Mn_j = max([Mn_j sqrt(sum(sdip.jmni{ii}(jj*3+l3,sdip.Mtb).^2))]);
end
end
st.vols{1}.sdip.tabl_seed_dip = tabl_seed_dip;
% Display all dipoles, the 1st one + the ones close enough.
% Run through the 6 colors and 9 markers to differentiate the dipoles.
% NOTA: 2 dipoles coming from the same set will have same colour/marker
ind = 1 ;
dip_h = zeros(9,size(tabl_seed_dip,1),1);
% each dipole displayed has 9 handles:
% 3 per view (2*3): for the line, for the circle & for the error
js_m = zeros(3,1);
% Deal with case of multiple i_seed and i_dip displayed.
% make sure dipole from same i_seed have same colour but different marker.
pi_dip = find(diff(tabl_seed_dip(:,2)));
if isempty(pi_dip)
% i.e. only one dip displayed per seed, use old fashion
for ii=1:size(tabl_seed_dip,1)
if ii>1
if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1)
ind = ind+1;
end
end
ic = mod(ind-1,Ncolors)+1;
im = fix(ind/Ncolors)+1;
loc_pl = sdip.mniloc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2));
js = sdip.jmni{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb);
vloc = sdip.cov_loc{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,tabl_seed_dip(ii,2)*3+l3);
dip_h(:,ii) = add1dip(loc_pl,js/Mn_j*20,vloc, ...
marker{im},colors{ic},st.vols{1}.ax,Fig,st.bb);
js_m = js_m+js;
end
else
for ii=1:pi_dip(1)
if ii>1
if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1)
ind = ind+1;
end
end
ic = mod(ind-1,Ncolors)+1;
for jj=1:sdip.n_dip
im = mod(jj-1,Nmarker)+1;
loc_pl = sdip.mniloc{tabl_seed_dip(ii,1)}(:,jj);
js = sdip.jmni{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb);
vloc = sdip.cov_loc{tabl_seed_dip(ii,1)}(jj*3+l3,jj*3+l3);
js_m = js_m+js;
dip_h(:,ii+(jj-1)*pi_dip(1)) = ...
add1dip(loc_pl,js/Mn_j*20,vloc, ...
marker{im},colors{ic},st.vols{1}.ax,Fig,st.bb);
end
end
end
st.vols{1}.sdip.ax = dip_h;
% Display dipoles orientation and strength
js_m = js_m/size(tabl_seed_dip,1);
[th,phi,Ijs_m] = cart2sph(js_m(1),js_m(2),js_m(3));
Njs_m = round(js_m'/Ijs_m*100)/100;
Angle = round([th phi]*1800/pi)/10;
set(sdip.hdl.hor1,'String',[num2str(Njs_m(1)),' ',num2str(Njs_m(2)), ...
' ',num2str(Njs_m(3))]);
set(sdip.hdl.hor2,'String',[num2str(Angle(1)),'� ',num2str(Angle(2)),'�']);
set(sdip.hdl.int,'String',Ijs_m);
% Change the colour of toggle button of dipoles actually displayed
for ii=tabl_seed_dip(:,1)
set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 1 .7]);
end
%==========================================================================
case 'clearall'
%==========================================================================
% Clears all dipoles, and reset the toggle buttons
%--------------------------------------------------------------------------
if isfield(st.vols{1},'sdip')
sdip = st.vols{1}.sdip;
else
error('I can''t find sdip structure');
end
disp('Clears all dipoles')
spm_eeg_inv_vbecd_disp('ClearDip');
for ii=1:st.vols{1}.sdip.n_seeds
if sdip.exitflag(ii)==1
set(st.vols{1}.sdip.hdl.hseed(ii),'Value',0);
end
end
set(st.vols{1}.sdip.hdl.hdip,'Value',1);
%==========================================================================
case 'chgseed'
%==========================================================================
% Changes the seeds displayed
%--------------------------------------------------------------------------
% disp('Change seed')
sdip = st.vols{1}.sdip;
if isfield(sdip,'tabl_seed_dip')
prev_seeds = p_seed(sdip.tabl_seed_dip);
else
prev_seeds = [];
end
l_seed = zeros(sdip.n_seeds,1);
for ii=1:sdip.n_seeds
if sdip.exitflag(ii)==1
l_seed(ii) = get(sdip.hdl.hseed(ii),'Value');
end
end
l_seed = find(l_seed);
% Modify the list of seeds displayed
if isempty(l_seed)
% Nothing left displayed
i_seed=[];
elseif isempty(prev_seeds)
% Just one dipole added, nothing before
i_seed=l_seed;
elseif length(prev_seeds)>length(l_seed)
% One seed removed
i_seed = prev_seeds;
for ii=1:length(l_seed)
p = find(prev_seeds==l_seed(ii));
if ~isempty(p)
prev_seeds(p) = [];
end % prev_seeds is left with the index of the one removed
end
i_seed(i_seed==prev_seeds) = [];
% Remove the dipole & change the button colour
spm_eeg_inv_vbecd_disp('ClearDip',prev_seeds);
set(sdip.hdl.hseed(prev_seeds),'BackgroundColor',[.7 .7 .7]);
else
% One dipole added
i_seed = prev_seeds;
for ii=1:length(prev_seeds)
p = find(prev_seeds(ii)==l_seed);
if ~isempty(p)
l_seed(p) = [];
end % l_seed is left with the index of the one added
end
i_seed = [i_seed ; l_seed];
end
i_dip = get(sdip.hdl.hdip,'Value');
spm_eeg_inv_vbecd_disp('ClearDip');
if ~isempty(i_seed)
spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip);
end
%==========================================================================
case 'chgdip'
%==========================================================================
% Changes the dipole index for the first seed displayed
%--------------------------------------------------------------------------
disp('Change dipole')
sdip = st.vols{1}.sdip;
i_dip = get(sdip.hdl.hdip,'Value');
if isfield(sdip,'tabl_seed_dip')
i_seed = p_seed(sdip.tabl_seed_dip);
else
i_seed = [];
end
if ~isempty(i_seed)
spm_eeg_inv_vbecd_disp('ClearDip')
spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip);
end
%==========================================================================
case 'cleardip'
%==========================================================================
% FORMAT spm_eeg_inv_vbecd_disp('ClearDip',seed_i)
% e.g. spm_eeg_inv_vbecd_disp('ClearDip')
% clears all displayed dipoles
% e.g. spm_eeg_inv_vbecd_disp('ClearDip',1)
% clears the first dipole displayed
%--------------------------------------------------------------------------
if nargin>2
seed_i = varargin{1};
else
seed_i = 0;
end
if isfield(st.vols{1},'sdip')
sdip = st.vols{1}.sdip;
else
return; % I don't do anything, as I can't find sdip strucure
end
if isfield(sdip,'ax')
Nax = size(sdip.ax,2);
else
return; % I don't do anything, as I can't find axes info
end
if seed_i==0 % removes everything
for ii=1:Nax
for jj=1:9
delete(sdip.ax(jj,ii));
end
end
for ii=sdip.tabl_seed_dip(:,1)
set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 .7 .7]);
end
sdip = rmfield(sdip,'tabl_seed_dip');
sdip = rmfield(sdip,'ax');
elseif seed_i<=Nax % remove one seed only
l_seed = find(sdip.tabl_seed_dip(:,1)==seed_i);
for ii=l_seed
for jj=1:9
delete(sdip.ax(jj,ii));
end
end
sdip.ax(:,l_seed) = [];
sdip.tabl_seed_dip(l_seed,:) = [];
else
error('Trying to clear unspecified dipole');
end
st.vols{1}.sdip = sdip;
%==========================================================================
case 'redrawdip'
%==========================================================================
% spm_eeg_inv_vbecd_disp('RedrawDip')
% redraw everything, useful when zooming into image
%--------------------------------------------------------------------------
% spm_eeg_inv_vbecd_disp('ClearDip')
% spm_eeg_inv_vbecd_disp('ChgDip')
% disp('Change dipole')
sdip = st.vols{1}.sdip;
i_dip = get(sdip.hdl.hdip,'Value');
if isfield(sdip,'tabl_seed_dip')
i_seed = p_seed(sdip.tabl_seed_dip);
else
i_seed = [];
end
if ~isempty(i_seed)
spm_eeg_inv_vbecd_disp('ClearDip')
spm_eeg_inv_vbecd_disp('DrawDip',i_seed,i_dip);
end
%==========================================================================
otherwise
%==========================================================================
warning('Unknown action string');
end
% warning(sw);
return
%==========================================================================
% dh = add1dip(loc,js,vloc,mark,col,ax,Fig,bb)
%==========================================================================
function dh = add1dip(loc,js,vloc,mark,col,ax,Fig,bb)
% Plots the dipoles on the 3 views, with an error ellipse for location
% Then returns the handle to the plots
global st
is = inv(st.Space);
loc = is(1:3,1:3)*loc(:) + is(1:3,4);
% taking into account the zooming/scaling only for the location
% NOT for the dipole's amplitude.
% Amplitude plotting is quite arbitrary anyway and up to some scaling
% defined for better viewing...
loc(1,:) = loc(1,:) - bb(1,1)+1;
loc(2,:) = loc(2,:) - bb(1,2)+1;
loc(3,:) = loc(3,:) - bb(1,3)+1;
% +1 added to be like John's orthview code
% prepare error ellipse
vloc = is(1:3,1:3)*vloc*is(1:3,1:3);
[V,E] = eig(vloc);
VE = V*diag(sqrt(diag(E))); % use std
% VE = V*E; % or use variance ???
dh = zeros(9,1);
figure(Fig)
% Transverse slice, # 1
%----------------------
set(Fig,'CurrentAxes',ax{1}.ax)
set(ax{1}.ax,'NextPlot','add')
dh(1) = plot(loc(1),loc(2),[mark,col],'LineWidth',1);
dh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2);
% add error ellipse
[uu,ss,vv] = svd(VE([1 2],:));
[phi] = cart2pol(uu(1,1),uu(2,1));
e = diag(ss);
t = (-1:.02:1)*pi;
x = e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi)+loc(1);
y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(2);
dh(3) = plot(x,y,[':',col],'LineWidth',.5);
set(ax{1}.ax,'NextPlot','replace')
% Coronal slice, # 2
%----------------------
set(Fig,'CurrentAxes',ax{2}.ax)
set(ax{2}.ax,'NextPlot','add')
dh(4) = plot(loc(1),loc(3),[mark,col],'LineWidth',1);
dh(5) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2);
% add error ellipse
[uu,ss,vv] = svd(VE([1 3],:));
[phi] = cart2pol(uu(1,1),uu(2,1));
e = diag(ss);
t = (-1:.02:1)*pi;
x = e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi)+loc(1);
y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(3);
dh(6) = plot(x,y,[':',col],'LineWidth',.5);
set(ax{2}.ax,'NextPlot','replace')
% Sagital slice, # 3
%----------------------
set(Fig,'CurrentAxes',ax{3}.ax)
set(ax{3}.ax,'NextPlot','add')
% dh(5) = plot(dim(2)-loc(2),loc(3),[mark,col],'LineWidth',2);
% dh(6) = plot(dim(2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);
dh(7) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',1);
dh(8) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2);
% add error ellipse
[uu,ss,vv] = svd(VE([2 3],:));
[phi] = cart2pol(uu(1,1),uu(2,1));
e = diag(ss);
t = (-1:.02:1)*pi;
x = -(e(1)*cos(t)*cos(phi)-e(2)*sin(t)*sin(phi))+bb(2,2)-bb(1,2)-loc(2);
y = e(2)*sin(t)*cos(phi)+e(1)*cos(t)*sin(phi)+loc(3);
dh(9) = plot(x,y,[':',col],'LineWidth',.5);
set(ax{3}.ax,'NextPlot','replace')
return
%==========================================================================
% pr_seed = p_seed(tabl_seed_dip)
%==========================================================================
function pr_seed = p_seed(tabl_seed_dip)
% Gets the list of seeds used in the previous display
ls = sort(tabl_seed_dip(:,1));
if length(ls)==1
pr_seed = ls;
else
pr_seed = ls([find(diff(ls)) ; length(ls)]);
end
%
% OLD STUFF
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Use it with arguments or not:
% - spm_eeg_inv_vbecd_disp('Init')
% The routine asks for the dipoles file and image to display
% - spm_eeg_inv_vbecd_disp('Init',sdip)
% The routine will use the avg152T1 canonical image
% - spm_eeg_inv_vbecd_disp('Init',sdip,P)
% The routines dispays the dipoles on image P.
%
% If multiple seeds have been used, you can select the seeds to display
% by pressing their index.
% Given that the sources could have different locations, the slices
% displayed will be the 3D view at the *average* or *mean* locations of
% selected sources.
% If more than 1 dipole was fitted at a time, then selection of source 1
% to N is possible through the pull-down selector.
%
% The location of the source/cut is displayed in mm and voxel, as well as
% the underlying image intensity at that location.
% The cross hair position can be hidden by clicking on its button.
%
% Nota_1: If the cross hair is manually moved by clicking in the image or
% changing its coordinates, the dipole displayed will NOT be at
% the right displayed location. That's something that needs to be improved...
%
% Nota_2: Some seeds may have not converged within the limits fixed,
% these dipoles are not displayed...
%
% Fields needed in sdip structure to plot on an image:
% + n_seeds: nr of seeds set used, i.e. nr of solutions calculated
% + n_dip: nr of fitted dipoles on the EEG time series
% + loc: location of fitted dipoles, cell{1,n_seeds}(3 x n_dip)
% remember that loc is fixed over the time window.
% + j: sources amplitude over the time window,
% cell{1,n_seeds}(3*n_dip x Ntimebins)
% + Mtb: index of maximum power in EEG time series used
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % First point to consider
% loc_mm = sdip.loc{i_seed(1)}(:,i_dip);
%
% % PLace the underlying image at right cuts
% spm_orthviews('Reposition',loc_mm);
% % spm_orthviews('Reposition',loc_vx);
% % spm_orthviews('Xhairs','off')
%
% % if i_seed = set, Are there other dipoles close enough ?
% tabl_seed_dip=[i_seed(1) i_dip]; % table summarising which set & dip to use.
% if length(i_seed)>1
% unit = ones(1,sdip.n_dip);
% for ii = i_seed(2:end)'
% d2 = sqrt(sum((sdip.loc{ii}-loc_mm*unit).^2));
% l_cl = find(d2<=lim_cl);
% if ~isempty(l_cl)
% for jj=l_cl
% tabl_seed_dip = [tabl_seed_dip ; [ii jj]];
% end
% end
% end
% end
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get(sdip.hdl.hseed(1),'Value')
% for ii=1:sdip.n_seeds, delete(hseed(ii)); end
% h1 = uicontrol(Fig,'Style','togglebutton','Position',[600 25 10 10].*WS)
% h2 = uicontrol(Fig,'Style','togglebutton','Position',[620 100 20 20].*WS,'String','1')
% h2 = uicontrol(Fig,'Style','checkbox','Position',[600 100 10 10].*WS)
% h3 = uicontrol(Fig,'Style','radiobutton','Position',[600 150 20 20].*WS)
% h4 = uicontrol(Fig,'Style','radiobutton','Position',[700 150 20 20].*WS)
% delete(h2),delete(h3),delete(h4),
% delete(hdip)
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_definetrial.m
|
.m
|
antx-master/xspm8/spm_eeg_definetrial.m
| 11,429 |
utf_8
|
56a6ae7de86bca4e155843aa0d2f736f
|
function [trl, conditionlabels, S] = spm_eeg_definetrial(S)
% Definition of trials based on events
% FORMAT[trl, conditionlabels, S] = spm_eeg_definetrial(S)
% S - input structure (optional)
% (optional) fields of S:
% S.event - event struct (optional)
% S.fsample - sampling rate
% S.dataset - raw dataset (events and fsample can be read from there if absent)
% S.inputformat - data type (optional) to force the use of specific data reader
% S.timeonset - time of the first sample in the data [default: 0]
% S.pretrig - pre-trigger time in ms
% S.posttrig - post-trigger time in ms
% S.trialdef - structure array for trial definition with fields (optional)
% S.trialdef.conditionlabel - string label for the condition
% S.trialdef.eventtype - string
% S.trialdef.eventvalue - string, numeric or empty
% S.reviewtrials - review individual trials after selection (yes/no: 1/0)
% S.save - save trial definition (yes/no: 1/0)
% OUTPUT:
% trl - Nx3 matrix [start end offset]
% conditionlabels - Nx1 cell array of strings, label for each trial
% S - modified configuration structure (for history)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak, Robert Oostenveld
% $Id: spm_eeg_definetrial.m 4756 2012-05-28 15:59:42Z vladimir $
SVNrev = '$Rev: 4756 $';
%-Startup
%--------------------------------------------------------------------------
spm('sFnBanner', mfilename, SVNrev);
spm('FigName','M/EEG trial definition');
%-Get input parameters
%--------------------------------------------------------------------------
try
S.inputformat;
catch
S.inputformat = [];
end
if ~isfield(S, 'event') || ~isfield(S, 'fsample')
if ~isfield(S, 'dataset')
S.dataset = spm_select(1, '\.*', 'Select M/EEG data file');
end
hdr = ft_read_header(S.dataset, 'fallback', 'biosig', 'headerformat', S.inputformat);
S.fsample = hdr.Fs;
event = ft_read_event(S.dataset, 'detectflank', 'both', 'eventformat', S.inputformat);
if ~isempty(strmatch('UPPT001', hdr.label))
% This is s somewhat ugly fix to the specific problem with event
% coding in FIL CTF. It can also be useful for other CTF systems where the
% pulses in the event channel go downwards.
fil_ctf_events = ft_read_event(S.dataset, 'detectflank', 'down', 'type', 'UPPT001', 'trigshift', -1, 'eventformat', S.inputformat);
if ~isempty(fil_ctf_events)
[fil_ctf_events(:).type] = deal('FIL_UPPT001_down');
event = cat(1, event(:), fil_ctf_events(:));
end
end
if ~isempty(strmatch('UPPT002', hdr.label))
% This is s somewhat ugly fix to the specific problem with event
% coding in FIL CTF. It can also be useful for other CTF systems where the
% pulses in the event channel go downwards.
fil_ctf_events = ft_read_event(S.dataset, 'detectflank', 'down', 'type', 'UPPT002', 'trigshift', -1, 'eventformat', S.inputformat);
if ~isempty(fil_ctf_events)
[fil_ctf_events(:).type] = deal('FIL_UPPT002_down');
event = cat(1, event(:), fil_ctf_events(:));
end
end
% This is another FIL-specific fix that will hopefully not affect other sites
if isfield(hdr, 'orig') && isfield(hdr.orig, 'VERSION') && isequal(uint8(hdr.orig.VERSION),uint8([255 'BIOSEMI']))
ind = strcmp('STATUS', {event(:).type});
val = [event(ind).value];
if any(val>255)
bytes = dec2bin(val);
bytes = bytes(:, end-7:end);
bytes = flipdim(bytes, 2);
val = num2cell(bin2dec(bytes));
[event(ind).value] = deal(val{:});
end
end
else
event = S.event;
end
if ~isfield(S, 'timeonset')
S.timeonset = 0;
end
if ~isfield(event, 'time')
for i = 1:numel(event)
if S.timeonset == 0
event(i).time = event(i).sample./S.fsample;
else
event(i).time = (event(i).sample - 1)./S.fsample + S.timeonset;
end
end
end
if ~isfield(event, 'sample')
for i = 1:numel(event)
if S.timeonset == 0
event(i).sample = event(i).time*S.fsample;
else
event(i).sample = (event(i).time-S.timeonset)*S.fsample+1;
end
event(i).sample = round(event(i).sample);
end
end
if isempty(event)
error('No event information was found in the input');
end
if ~isfield(S, 'pretrig')
S.pretrig = spm_input('Start of trial in PST [ms]', '+1', 'r', '', 1);
end
if ~isfield(S, 'posttrig')
S.posttrig = spm_input('End of trial in PST [ms]', '+1', 'r', '', 1);
end
if ~isfield(S, 'trialdef')
S.trialdef = [];
ncond = spm_input('How many conditions?', '+1', 'n', '1');
for i = 1:ncond
OK = 0;
pos = '+1';
while ~OK
conditionlabel = spm_input(['Label of condition ' num2str(i)], pos, 's');
selected = select_event_ui(event);
if isempty(conditionlabel) || isempty(selected)
pos = '-1';
else
for j = 1:size(selected, 1)
S.trialdef = [S.trialdef ...
struct('conditionlabel', conditionlabel, ...
'eventtype', selected{j, 1}, ...
'eventvalue', selected{j, 2})];
OK=1;
end
end
end
end
end
for i = 1:length(S.trialdef)
if ~isfield(S.trialdef(i),'trlshift')
trlshift(i) = 0;
else
trlshift(i) = round(S.trialdef(i).trlshift * S.fsample/1000); % assume passed as ms
end
end
%-Build trl based on selected events
%--------------------------------------------------------------------------
trl = [];
conditionlabels = {};
for i=1:numel(S.trialdef)
if ischar(S.trialdef(i).eventvalue)
% convert single string into cell-array, otherwise the intersection does not work as intended
S.trialdef(i).eventvalue = {S.trialdef(i).eventvalue};
end
sel = [];
% select all events of the specified type and with the specified value
for j=find(strcmp(S.trialdef(i).eventtype, {event.type}))
if isempty(S.trialdef(i).eventvalue)
sel = [sel j];
elseif ~isempty(intersect(event(j).value, S.trialdef(i).eventvalue))
sel = [sel j];
end
end
for j=1:length(sel)
% override the offset of the event
trloff = round(0.001*S.pretrig*S.fsample);
% also shift the begin sample with the specified amount
if ismember(event(sel(j)).type, {'trial', 'average'})
% In case of trial events treat the 0 time point as time of the
% event rather than the beginning of the trial
trlbeg = event(sel(j)).sample - event(sel(j)).offset + trloff;
else
trlbeg = event(sel(j)).sample + trloff;
end
trldur = round(0.001*(-S.pretrig+S.posttrig)*S.fsample);
trlend = trlbeg + trldur;
% Added by Rik in case wish to shift triggers (e.g, due to a delay
% between trigger and visual/auditory stimulus reaching subject).
trlbeg = trlbeg + trlshift(i);
trlend = trlend + trlshift(i);
% add the beginsample, endsample and offset of this trial to the list
trl = [trl; trlbeg trlend trloff];
conditionlabels{end+1} = S.trialdef(i).conditionlabel;
end
end
%-Sort the trl in right temporal order
%--------------------------------------------------------------------------
[junk, sortind] = sort(trl(:,1));
trl = trl(sortind, :);
conditionlabels = conditionlabels(sortind);
%-Review selected trials
%--------------------------------------------------------------------------
if ~isfield(S, 'reviewtrials')
S.reviewtrials = spm_input('Review individual trials?','+1','yes|no',[1 0], 0);
end
if S.reviewtrials
eventstrings=cell(size(trl,1),1);
for i=1:size(trl,1)
eventstrings{i}=[num2str(i) ' Label: ' conditionlabels{i} ' Time (sec): ' num2str((trl(i, 1)- trl(i, 3))./S.fsample)];
end
selected = find(trl(:,1)>0);
[indx OK] = listdlg('ListString', eventstrings, 'SelectionMode', 'multiple', 'InitialValue', ...
selected, 'Name', 'Select events', 'ListSize', [300 300]);
if OK
trl=trl(indx, :);
conditionlabels = conditionlabels(indx);
end
end
%-Create trial definition file
%--------------------------------------------------------------------------
if ~isfield(S, 'save')
S.save = spm_input('Save trial definition?','+1','yes|no',[1 0], 0);
end
if S.save
[trlfilename, trlpathname] = uiputfile( ...
{'*.mat', 'MATLAB File (*.mat)'}, 'Save trial definition as');
save(fullfile(trlpathname, trlfilename), 'trl', 'conditionlabels');
end
%-Cleanup
%--------------------------------------------------------------------------
spm('FigName','M/EEG trial definition: done');
%==========================================================================
% select_event_ui
%==========================================================================
function selected = select_event_ui(event)
% Allow the user to select an event using GUI
selected={};
if isempty(event)
fprintf('no events were found\n');
return
end
eventtype = unique({event.type});
Neventtype = length(eventtype);
% Two lists are built in parallel
settings={}; % The list of actual values to be used later
strsettings={}; % The list of strings to show in the GUI
for i=1:Neventtype
sel = find(strcmp(eventtype{i}, {event.type}));
numind = find(...
cellfun('isclass', {event(sel).value}, 'double') & ...
~cellfun('isempty', {event(sel).value}));
charind = find(cellfun('isclass', {event(sel).value}, 'char'));
emptyind = find(cellfun('isempty', {event(sel).value}));
if ~isempty(numind)
numvalue = unique([event(sel(numind)).value]);
for j=1:length(numvalue)
ninstances = sum([event(sel(numind)).value] == numvalue(j));
strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ' num2str(numvalue(j)) ...
' ; ' num2str(ninstances) ' instances']}];
settings=[settings; [eventtype(i), {numvalue(j)}]];
end
end
if ~isempty(charind)
charvalue = unique({event(sel(charind)).value});
if ~iscell(charvalue)
charvalue = {charvalue};
end
for j=1:length(charvalue)
ninstances = length(strmatch(charvalue{j}, {event(sel(charind)).value}, 'exact'));
strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ' charvalue{j}...
' ; ' num2str(ninstances) ' instances']}];
settings=[settings; [eventtype(i), charvalue(j)]];
end
end
if ~isempty(emptyind)
strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ; ' ...
num2str(length(emptyind)) ' instances']}];
settings=[settings; [eventtype(i), {[]}]];
end
end
[selection ok]= listdlg('ListString',strsettings, 'SelectionMode', 'multiple', 'Name', 'Select event', 'ListSize', [400 300]);
if ok
selected=settings(selection, :);
else
selected={};
end
|
github
|
philippboehmsturm/antx-master
|
spm_mvb_cvk2.m
|
.m
|
antx-master/xspm8/spm_mvb_cvk2.m
| 5,093 |
utf_8
|
751f7db1cea711d16bdb424252c3e636
|
function [p,pc,R2] = spm_mvb_cvk2(MVB,k)
% k-fold cross validation of a multivariate Bayesian model
% FORMAT [p_value,percent,R2] = spm_mvb_cvk(MVB,k)
%
% MVB - Multivariate Bayes structure
% k - k-fold cross-validation ('0' implies a leave-one-out scheme)
%
% p - p-value: under a null GLM
% percent: proportion correct (median threshold)
% R2 - coefficient of determination
%
% spm_mvb_cvk performs a k-fold cross-validation by trying to predict
% the target variable using training and test partitions on orthogonal
% mixtures of data (from null space of confounds).
% This version uses the optimised covariance model from spm_mvb.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_mvb_cvk2.m 3806 2010-04-06 14:42:32Z ged $
%-partition order
%--------------------------------------------------------------------------
try
k;
catch
str = 'k-fold cross-validation';
k = spm_input(str,'!+1','b',{'2','4','8','loo'},[2 4 8 0]);
end
%-Get figure handles and set title
%--------------------------------------------------------------------------
Fmvb = spm_figure('GetWin','MVB');
spm_clf(Fmvb);
% get MVB results
%==========================================================================
try
MVB;
catch
mvb = spm_select(1,'mat','please select models',[],pwd,'MVB_*');
MVB = load(mvb(1,:));
MVB = MVB.MVB;
end
% whiten target and predictor (X) variables (Y) (i.e., remove correlations)
%--------------------------------------------------------------------------
X = MVB.X;
X0 = MVB.X0;
V = MVB.V;
% residual forming matrix
%--------------------------------------------------------------------------
Ns = length(X);
R = speye(Ns) - X0*pinv(X0);
% leave-one-out
%--------------------------------------------------------------------------
if ~k
k = Ns;
end
pX = zeros(Ns,1);
qX = zeros(Ns,1);
qE = zeros(size(MVB.Y,2),k);
% k-fold cross-validation
%==========================================================================
for i = 1:k
[px qx qe] = mvb_cv(MVB,i,k);
pX = pX + px;
qX = qX + qx;
qE(:,i) = qe;
end
% parametric inference
%==========================================================================
% test correlation
%--------------------------------------------------------------------------
[T df] = spm_ancova(X,V,qX,1);
p = 1 - spm_Tcdf(T,df(2));
% percent correct (after projection)
%--------------------------------------------------------------------------
pX = R*X;
qX = R*qX;
T = sign(pX - median(pX)) == sign(qX - median(qX));
pc = 100*sum(T)/length(T);
R2 = corrcoef(pX,qX);
R2 = 100*(R2(1,2)^2);
% assign in base memory
%--------------------------------------------------------------------------
MVB.p_value = p;
MVB.percent = pc;
MVB.R2 = R2;
MVB.cvk = struct('qX',qX,'qE',qE);
% save results
%--------------------------------------------------------------------------
save(MVB.name,'MVB')
assignin('base','MVB',MVB)
% display and plot validation
%--------------------------------------------------------------------------
spm_mvb_cvk_display(MVB)
return
%==========================================================================
function [X,qX,qE] = mvb_cv(MVB,n,k)
%==========================================================================
% MVB - multivariate structure
% n - subset
% k - partition
% Unpack MVB and create test subspace
%--------------------------------------------------------------------------
V = MVB.V;
U = MVB.M.U;
X = MVB.X;
Y = MVB.Y;
X0 = MVB.X0;
h = MVB.M.h;
Cp = MVB.M.Cp;
% Specify indices of training and test data
%--------------------------------------------------------------------------
Ns = length(X);
ns = floor(Ns/k);
test = [1:ns] + (n - 1)*ns;
tran = [1:Ns];
tran(test) = [];
test = full(sparse(test,test,1,Ns,Ns));
tran = full(sparse(tran,tran,1,Ns,Ns));
% Training - add test space to confounds
%==========================================================================
R = speye(Ns) - [X0 test]*pinv([X0 test]);
R = spm_svd(R);
L = R'*Y*U;
% get error covariance
%--------------------------------------------------------------------------
Ce = sparse(Ns,Ns);
if isstruct(V)
for i = 1:length(V)
Ce = Ce + h(i)*V{i};
end
else
Ce = V*h(1);
end
Ce = R'*Ce*R;
% MAP estimates of pattern weights from training data
%----------------------------------------------------------------------
MAP = Cp*L'*inv(Ce + L*Cp*L');
qE = MAP*R'*X;
% Test - add training space to confounds and get predicted X
%==========================================================================
R = speye(Ns) - [X0 tran]*pinv([X0 tran]);
X = R*X; % test data
qE = U*qE; % weights
qX = R*Y*qE; % prediction
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_displayECD.m
|
.m
|
antx-master/xspm8/spm_eeg_displayECD.m
| 8,250 |
utf_8
|
471c105bf4bbbec394478ff1a280b571
|
function [out] = spm_eeg_displayECD(Pos,Orient,Var,Names,options)
% Plot dipole positions onto the SPM canonical mesh
% FORMAT [out] = spm_eeg_displayDipoles(Pos,Orient,Var,Names,options)
%
% IN (admissible choices):
% - Pos: a 3xndip matrix containing the positions of the dipoles in
% the canonical frame of reference
% - Orient: the same with dipole orientations
% - Var: the same with position variance
% - Names: the same with dipole names
% - options: an optional structure containing
% .hfig: the handle of the display figure
% .tag: the tag to be associated with the created UI objects
% .add: binary variable ({0}, 1: just add dipole in the figure .hfig)
%
% OUT:
% - out: a structure containing the handles of the object in the figure
% (including the mesh, the dipoles, the transparency slider, etc...)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_displayECD.m 4054 2010-08-27 19:27:09Z karl $
% checks and defaults
%--------------------------------------------------------------------------
hfig = [];
ParentAxes = [];
query = [];
handles = [];
tag = '';
try, options; catch, options = []; end
try, hfig = options.hfig; end
try, tag = options.tag; end
try, ParentAxes = options.ParentAxes; end
try, query = options.query; end
try, handles = options.handles; end
try
figure(hfig);
catch
hfig = spm_figure('GetWin','Graphics');
spm_figure('Clear',hfig);
ParentAxes = axes('parent',hfig);
end
try
markersize = options.markersize;
catch
markersize = 20;
end
try
meshsurf = options.meshsurf;
catch
meshsurf = fullfile(spm('Dir'),'canonical','cortex_5124.surf.gii');
end
if isscalar(Var), Var = Pos*0 + Var^2; end
try, Pos{1}; catch, Pos = {Pos}; end
try, Orient{1}; catch, Orient = {Orient};end
try, Var{1}; catch, Var = {Var}; end
ndip = size(Pos{1},2);
if ~exist('Names','var') || isempty(Names)
for i=1:ndip
Names{i} = num2str(i);
end
end
col = ['b','g','r','c','m','y','k','w'];
tmp = ceil(ndip./numel(col));
col = repmat(col,1,tmp);
pa = get(ParentAxes,'position');
if ndip > 0
if isempty(query)
opt.hfig = hfig;
opt.ParentAxes = ParentAxes;
opt.visible = 'off';
pos2 = [pa(1),pa(2)+0.25*pa(4),0.03,0.5*pa(4)];
out = spm_eeg_render(meshsurf,opt);
handles.mesh = out.handles.p;
handles.BUTTONS.transp = out.handles.transp;
handles.hfig = out.handles.fi;
handles.ParentAxes = out.handles.ParentAxes;
set(handles.mesh,...
'facealpha',0.1,...
'visible','on')
set(handles.BUTTONS.transp,...
'value',0.1,...
'position',pos2,...
'visible','on')
end
set(ParentAxes,'nextplot','add')
for j=1:length(Pos)
for i =1:ndip
try
set(handles.hp(j,i),...
'xdata',Pos{j}(1,i),...
'ydata',Pos{j}(2,i),...
'zdata',Pos{j}(3,i));
catch
handles.hp(j,i) = plot3(handles.ParentAxes,...
Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...
[col(i),'.'],...
'markerSize',markersize,...
'visible','off');
end
try
no = sqrt(sum(Orient{j}(:,i).^2));
if no > 0
Oi = 1e1.*Orient{j}(:,i)./no;
else
Oi = 1e-5*ones(3,1);
end
try
set(handles.hq(j,i),...
'xdata',Pos{j}(1,i),...
'ydata',Pos{j}(2,i),...
'zdata',Pos{j}(3,i),...
'udata',Oi(1),...
'vdata',Oi(2),...
'wdata',Oi(3))
catch
handles.hq(j,i) = quiver3(handles.ParentAxes,...
Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...
Oi(1),Oi(2),Oi(3),col(i),...
'lineWidth',2,'visible','off');
end
if isequal(query,'add')
set(handles.hq(j,i),...
'LineStyle','--',...
'lineWidth',1)
end
end
[x,y,z]= ellipsoid(Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...
1.*sqrt(Var{j}(1,i)),1.*sqrt(Var{j}(2,i)),1.*sqrt(Var{j}(1,i)),20);
try
set(handles.hs(j,i),...
'xdata',x,...
'ydata',y,...
'zdata',z);
catch
handles.hs(j,i) = surf(handles.ParentAxes,...
x,y,z,...
'edgecolor','none',...
'facecolor',col(i),...
'facealpha',0.2,...
'visible','off');
end
try
set(handles.ht(j,i),...
'position',Pos{j}(:,i));
catch
handles.ht(j,i) = text(...
Pos{j}(1,i),Pos{j}(2,i),Pos{j}(3,i),...
Names{i},...
'Parent',handles.ParentAxes,...
'visible','off');
end
end
end
if length(Pos) > 1
try, set(handles.hp(end,:),'visible','on'); end
try, set(handles.hq(end,:),'visible','on'); end
try, set(handles.hs(end,:),'visible','on'); end
try, set(handles.ht(end,:),'visible','on'); end
handles.uic(1) = uicontrol(handles.fi,...
'units','normalized',...
'position',[0.45,0.5,0.2,0.03],...
'style','radio','string','Show priors',...
'callback',@doChange1,...
'BackgroundColor',[1 1 1],...
'tooltipstring','Display prior locations',...
'userdata',handles,'value',0,...
'BusyAction','cancel',...
'Interruptible','off',...
'tag','plotEEG');
handles.uic(2) = uicontrol(handles.fi,...
'units','normalized',...
'position',[0.45,0.53,0.2,0.03],...
'style','radio','string','Show posteriors',...
'callback',@doChange2,...
'BackgroundColor',[1 1 1],...
'tooltipstring','Display posterior locations',...
'userdata',handles,'value',1,...
'BusyAction','cancel',...
'Interruptible','off',...
'tag','plotEEG');
else
try, set(handles.hp(1,:),'visible','on'); end
try, set(handles.hq(1,:),'visible','on'); end
try, set(handles.hs(1,:),'visible','on'); end
try, set(handles.ht(1,:),'visible','on'); end
end
end
try
clear out
out.handles = handles;
catch
out = [];
end
%==========================================================================
function doChange1(i1,i2)
val = get(i1,'value');
handles = get(i1,'userdata');
if ~val
try, set(handles.hp(1,:),'visible','off'); end
try, set(handles.hq(1,:),'visible','off'); end
try, set(handles.hs(1,:),'visible','off'); end
try, set(handles.ht(1,:),'visible','off'); end
else
try, set(handles.hp(1,:),'visible','on'); end
try, set(handles.hq(1,:),'visible','on'); end
try, set(handles.hs(1,:),'visible','on'); end
try, set(handles.ht(1,:),'visible','on'); end
end
%==========================================================================
function doChange2(i1,i2)
val = get(i1,'value');
handles = get(i1,'userdata');
if ~val
try, set(handles.hp(2,:),'visible','off'); end
try, set(handles.hq(2,:),'visible','off'); end
try, set(handles.hs(2,:),'visible','off'); end
try, set(handles.ht(2,:),'visible','off'); end
else
try, set(handles.hp(2,:),'visible','on'); end
try, set(handles.hq(2,:),'visible','on'); end
try, set(handles.hs(2,:),'visible','on'); end
try, set(handles.ht(2,:),'visible','on'); end
end
|
github
|
philippboehmsturm/antx-master
|
spm_uw_apply.m
|
.m
|
antx-master/xspm8/spm_uw_apply.m
| 14,676 |
utf_8
|
79e215c42faaa2e17fc6bae5cea47179
|
function varargout = spm_uw_apply(ds,flags)
% Reslices images volume by volume
% FORMAT spm_uw_apply(ds,[flags])
% or
% FORMAT P = spm_uw_apply(ds,[flags])
%
%
% ds - a structure created by spm_uw_estimate.m containing the fields:
% ds can also be an array of structures, each struct corresponding
% to one sesssion (it hardly makes sense to try and pool fields across
% sessions since there will have been a reshimming). In that case each
% session is unwarped separately, unwarped into the distortion space of
% the average (default) position of that series, and with the first
% scan on the series defining the pahse encode direction. After that each
% scan is transformed into the space of the first scan of the first series.
% Naturally, there is still only one actual resampling (interpolation).
% It will be assumed that the same unwarping parameters have been used
% for all sessions (anything else would be truly daft).
%
% .P - Images used when estimating deformation field and/or
% its derivative w.r.t. modelled factors. Note that this
% struct-array may contain .mat fields that differ from
% those you would observe with spm_vol(P(1).fname). This
% is because spm_uw_estimate has an option to re-estimate
% the movement parameters. The re-estimated parameters are
% not written to disc (in the form of .mat files), but rather
% stored in the P array in the ds struct.
%
% .order - Number of basis functions to use for each dimension.
% If the third dimension is left out, the order for
% that dimension is calculated to yield a roughly
% equal spatial cut-off in all directions.
% Default: [8 8 *]
% .sfP - Static field supplied by the user. It should be a
% filename or handle to a voxel-displacement map in
% the same space as the first EPI image of the time-
% series. If using the FieldMap toolbox, realignment
% should (if necessary) have been performed as part of
% the process of creating the VDM. Note also that the
% VDM mut be in undistorted space, i.e. if it is
% calculated from an EPI based field-map sequence
% it should have been inverted before passing it to
% spm_uw_estimate. Again, the FieldMap toolbox will
% do this for you.
% .regorder - Regularisation of derivative fields is based on the
% regorder'th (spatial) derivative of the field.
% Default: 1
% .lambda - Fudge factor used to decide relative weights of
% data and regularisation.
% Default: 1e5
% .jm - Jacobian Modulation. If set, intensity (Jacobian)
% deformations are included in the model. If zero,
% intensity deformations are not considered.
% .fot - List of indexes for first order terms to model
% derivatives for. Order of parameters as defined
% by spm_imatrix.
% Default: [4 5]
% .sot - List of second order terms to model second
% derivatives of. Should be an nx2 matrix where
% e.g. [4 4; 4 5; 5 5] means that second partial
% derivatives of rotation around x- and y-axis
% should be modelled.
% Default: []
% .fwhm - FWHM (mm) of smoothing filter applied to images prior
% to estimation of deformation fields.
% Default: 6
% .rem - Re-Estimation of Movement parameters. Set to unity means
% that movement-parameters should be re-estimated at each
% iteration.
% Default: 0
% .noi - Maximum number of Iterations.
% Default: 5
% .exp_round - Point in position space to do Taylor expansion around.
% 'First', 'Last' or 'Average'.
% .p0 - Average position vector (three translations in mm
% and three rotations in degrees) of scans in P.
% .q - Deviations from mean position vector of modelled
% effects. Corresponds to deviations (and deviations
% squared) of a Taylor expansion of deformation fields.
% .beta - Coeffeicents of DCT basis functions for partial
% derivatives of deformation fields w.r.t. modelled
% effects. Scaled such that resulting deformation
% fields have units mm^-1 or deg^-1 (and squares
% thereof).
% .SS - Sum of squared errors for each iteration.
%
% flags - a structure containing various options. The fields are:
%
% mask - mask output images (1 for yes, 0 for no)
% To avoid artifactual movement-related variance the realigned
% set of images can be internally masked, within the set (i.e.
% if any image has a zero value at a voxel than all images have
% zero values at that voxel). Zero values occur when regions
% 'outside' the image are moved 'inside' the image during
% realignment.
%
% mean - write mean image
% The average of all the realigned scans is written to
% mean*.img.
%
% interp - the interpolation method (see e.g. spm_bsplins.m).
%
% which - Values of 0 or 1 are allowed.
% 0 - don't create any resliced images.
% Useful if you only want a mean resliced image.
% 1 - reslice all the images.
%
% udc - Values 1 or 2 are allowed
% 1 - Do only unwarping (not correcting
% for changing sampling density).
% 2 - Do both unwarping and Jacobian correction.
%
%
% prefix - Filename prefix for resliced image files. Defaults to 'u'.
%
% The spatially realigned images are written to the orginal
% subdirectory with the same filename but prefixed with an 'u'.
% They are all aligned with the first.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jesper Andersson
% $Id: spm_uw_apply.m 4152 2011-01-11 14:13:35Z volkmar $
tiny = 5e-2;
def_flags = spm_get_defaults('realign.write');
def_flags.udc = 1;
def_flags.prefix = 'u';
defnames = fieldnames(def_flags);
if nargin < 1 || isempty(ds)
ds = load(spm_select(1,'.*uw\.mat$','Select Unwarp result file'),'ds');
ds = ds.ds;
end
%
% Default to using Jacobian modulation for the reslicing if it was
% used during the estimation phase.
%
if ds(1).jm ~= 0
def_flags.udc = 2;
end
%
% Replace defaults with user supplied values for all fields
% defined by user.
%
if nargin < 2 || isempty(flags)
flags = def_flags;
end
for i=1:length(defnames)
if ~isfield(flags,defnames{i})
flags.(defnames{i}) = def_flags.(defnames{i});
end
end
if numel(flags.which) == 2
flags.mean = flags.which(2);
flags.which = flags.which(1);
end
ntot = 0;
for i=1:length(ds)
ntot = ntot + length(ds(i).P);
end
hold = [repmat(flags.interp,1,3) flags.wrap];
linfun = inline('fprintf(''%-60s%s'', x,repmat(sprintf(''\b''),1,60))');
%
% Create empty sfield for all structs.
%
[ds.sfield] = deal([]);
%
% Make space for output P-structs if required
%
if nargout > 0
oP = cell(length(ds),1);
end
%
% First, create mask if so required.
%
if flags.mask || flags.mean,
linfun('Computing mask..');
spm_progress_bar('Init',ntot,'Computing available voxels',...
'volumes completed');
[x,y,z] = ndgrid(1:ds(1).P(1).dim(1),1:ds(1).P(1).dim(2),1:ds(1).P(1).dim(3));
xyz = [x(:) y(:) z(:) ones(prod(ds(1).P(1).dim(1:3)),1)]; clear x y z;
if flags.mean
Count = zeros(prod(ds(1).P(1).dim(1:3)),1);
Integral = zeros(prod(ds(1).P(1).dim(1:3)),1);
end
% if flags.mask
msk = zeros(prod(ds(1).P(1).dim(1:3)),1);
% end
tv = 1;
for s=1:length(ds)
def_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));
Bx = spm_dctmtx(ds(s).P(1).dim(1),ds(s).order(1));
By = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2));
Bz = spm_dctmtx(ds(s).P(1).dim(3),ds(s).order(3));
if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)
T = ds(s).sfP.mat\ds(1).P(1).mat;
txyz = xyz * T';
c = spm_bsplinc(ds(s).sfP,ds(s).hold);
ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);
ds(s).sfield = ds(s).sfield(:);
clear c txyz;
end
for i=1:size(ds(s).beta,2)
def_array(:,i) = spm_get_def(Bx,By,Bz,ds(s).beta(:,i));
end
sess_msk = zeros(prod(ds(1).P(1).dim(1:3)),1);
for i = 1:numel(ds(s).P)
T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;
txyz = xyz * T';
txyz(:,2) = txyz(:,2) + spm_get_image_def(ds(s).P(i),ds(s),def_array);
tmp = false(size(txyz,1),1);
if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).P(i).dim(1)+tiny); end
if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).P(i).dim(2)+tiny); end
if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).P(i).dim(3)+tiny); end
sess_msk = sess_msk + real(tmp);
spm_progress_bar('Set',tv);
tv = tv+1;
end
msk = msk + sess_msk;
if flags.mean, Count = Count + repmat(length(ds(s).P),prod(ds(s).P(1).dim(1:3)),1) - sess_msk; end % Changed 23/3-05
%
% Include static field in estmation of mask.
%
if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)
T = inv(ds(s).sfP.mat) * ds(1).P(1).mat;
txyz = xyz * T';
tmp = false(size(txyz,1),1);
if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).sfP.dim(1)+tiny); end
if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).sfP.dim(2)+tiny); end
if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).sfP.dim(3)+tiny); end
msk = msk + real(tmp);
end
if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield)
ds(s).sfield = [];
end
end
if flags.mask, msk = find(msk ~= 0); end
end
linfun('Reslicing images..');
spm_progress_bar('Init',ntot,'Reslicing','volumes completed');
jP = ds(1).P(1);
jP = rmfield(jP,{'fname','descrip','n','private'});
jP.dim = jP.dim(1:3);
jP.dt = [spm_type('float64'), spm_platform('bigend')];
jP.pinfo = [1 0]';
tv = 1;
for s=1:length(ds)
def_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));
Bx = spm_dctmtx(ds(s).P(1).dim(1),ds(s).order(1));
By = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2));
Bz = spm_dctmtx(ds(s).P(1).dim(3),ds(s).order(3));
if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP)
T = ds(s).sfP.mat\ds(1).P(1).mat;
txyz = xyz * T';
c = spm_bsplinc(ds(s).sfP,ds(s).hold);
ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold);
ds(s).sfield = ds(s).sfield(:);
clear c txyz;
end
for i=1:size(ds(s).beta,2)
def_array(:,i) = spm_get_def(Bx,By,Bz,ds(s).beta(:,i));
end
if flags.udc > 1
ddef_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2));
dBy = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2),'diff');
for i=1:size(ds(s).beta,2)
ddef_array(:,i) = spm_get_def(Bx,dBy,Bz,ds(s).beta(:,i));
end
end
for i = 1:length(ds(s).P)
linfun(['Reslicing volume ' num2str(tv) '..']);
%
% Read undeformed image.
%
T = inv(ds(s).P(i).mat) * ds(1).P(1).mat;
txyz = xyz * T';
if flags.udc > 1
[def,jac] = spm_get_image_def(ds(s).P(i),ds(s),def_array,ddef_array);
else
def = spm_get_image_def(ds(s).P(i),ds(s),def_array);
end
txyz(:,2) = txyz(:,2) + def;
if flags.udc > 1
jP.dat = reshape(jac,ds(s).P(i).dim(1:3));
jtxyz = xyz * T';
c = spm_bsplinc(jP.dat,hold);
jac = spm_bsplins(c,jtxyz(:,1),jtxyz(:,2),jtxyz(:,3),hold);
end
c = spm_bsplinc(ds(s).P(i),hold);
ima = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),hold);
if flags.udc > 1
ima = ima .* jac;
end
%
% Write it if so required.
%
if flags.which
PO = ds(s).P(i);
PO.fname = prepend(PO.fname,flags.prefix);
PO.mat = ds(1).P(1).mat;
PO.descrip = 'spm - undeformed';
ivol = ima;
if flags.mask
ivol(msk) = NaN;
end
ivol = reshape(ivol,PO.dim(1:3));
PO = spm_create_vol(PO);
for ii=1:PO.dim(3),
PO = spm_write_plane(PO,ivol(:,:,ii),ii);
end;
if nargout > 0
oP{s}(i) = PO;
end
end
%
% Build up mean image if so required.
%
if flags.mean
Integral = Integral + nan2zero(ima);
end
spm_progress_bar('Set',tv);
tv = tv+1;
end
if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield)
ds(s).sfield = [];
end
end
if flags.mean
% Write integral image (16 bit signed)
%-----------------------------------------------------------
sw = warning('off','MATLAB:divideByZero');
Integral = Integral./Count;
warning(sw);
PO = ds(1).P(1);
[pth,nm,xt,vr] = spm_fileparts(deblank(ds(1).P(1).fname));
PO.fname = fullfile(pth,['mean' flags.prefix nm xt vr]);
PO.pinfo = [max(max(max(Integral)))/32767 0 0]';
PO.descrip = 'spm - mean undeformed image';
PO.dt = [4 spm_platform('bigend')];
ivol = reshape(Integral,PO.dim);
spm_write_vol(PO,ivol);
end
linfun(' ');
spm_figure('Clear','Interactive');
if nargout > 0
varargout{1} = oP;
end
return;
%_______________________________________________________________________
function PO = prepend(PI,pre)
[pth,nm,xt,vr] = spm_fileparts(deblank(PI));
PO = fullfile(pth,[pre nm xt vr]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vo = nan2zero(vi)
vo = vi;
vo(~isfinite(vo)) = 0;
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_prep_ui.m
|
.m
|
antx-master/xspm8/spm_eeg_prep_ui.m
| 29,442 |
utf_8
|
80bb3efbe6195079a20c2e95d5a38104
|
function spm_eeg_prep_ui(callback)
% User interface for spm_eeg_prep function performing several tasks
% for preparation of converted MEEG data for further analysis
% FORMAT spm_eeg_prep_ui(callback)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_eeg_prep_ui.m 3833 2010-04-22 14:49:48Z vladimir $
spm('Pointer','Watch');
if ~nargin, callback = 'CreateMenu'; end
eval(callback);
spm('Pointer','Arrow');
%==========================================================================
% function CreateMenu
%==========================================================================
function CreateMenu
SVNrev = '$Rev: 3833 $';
spm('FnBanner', 'spm_eeg_prep_ui', SVNrev);
Finter = spm('FnUIsetup', 'M/EEG prepare', 0);
%-Draw top level menu
% ====== File ===================================
FileMenu = uimenu(Finter,'Label','File',...
'Tag','EEGprepUI',...
'HandleVisibility','on');
FileOpenMenu = uimenu(FileMenu, ...
'Label','Open',...
'Separator','off',...
'Tag','EEGprepUI',...
'HandleVisibility', 'on',...
'Accelerator','O',...
'Callback', 'spm_eeg_prep_ui(''FileOpenCB'')');
FileSaveMenu = uimenu(FileMenu, ...
'Label','Save',...
'Separator','off',...
'Tag','EEGprepUI',...
'Enable','off',...
'HandleVisibility', 'on',...
'Accelerator','S',...
'Callback', 'spm_eeg_prep_ui(''FileSaveCB'')');
FileExitMenu = uimenu(FileMenu, ...
'Label','Quit',...
'Separator','on',...
'Tag','EEGprepUI',...
'HandleVisibility', 'on',...
'Accelerator','Q',...
'Callback', 'spm_eeg_prep_ui(''FileExitCB'')');
% ====== Channel types ===============================
ChanTypeMenu = uimenu(Finter,'Label','Channel types',...
'Tag','EEGprepUI',...
'Enable', 'off', ...
'HandleVisibility','on');
chanTypes = {'EEG', 'EOG', 'ECG', 'EMG', 'LFP', 'Other'};
for i = 1:length(chanTypes)
CTypesMenu(i) = uimenu(ChanTypeMenu, 'Label', chanTypes{i},...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''ChanTypeCB'')');
end
CTypesRef2MEGMenu = uimenu(ChanTypeMenu, 'Label', 'MEGREF=>MEG',...
'Tag','EEGprepUI',...
'Enable', 'off', ...
'HandleVisibility','on',...
'Separator', 'on',...
'Callback', 'spm_eeg_prep_ui(''MEGChanTypeCB'')');
CTypesDefaultMenu = uimenu(ChanTypeMenu, 'Label', 'Default',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on',...
'Callback', 'spm_eeg_prep_ui(''ChanTypeDefaultCB'')');
CTypesReviewMenu = uimenu(ChanTypeMenu, 'Label', 'Review',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''ChanTypeCB'')');
% ====== Sensors ===================================
Coor3DMenu = uimenu(Finter,'Label','Sensors',...
'Tag','EEGprepUI',...
'Enable', 'off', ...
'HandleVisibility','on');
LoadEEGSensMenu = uimenu(Coor3DMenu, 'Label', 'Load EEG sensors',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on');
LoadEEGSensTemplateMenu = uimenu(LoadEEGSensMenu, 'Label', 'Assign default',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''LoadEEGSensTemplateCB'')');
LoadEEGSensMatMenu = uimenu(LoadEEGSensMenu, 'Label', 'From *.mat file',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''LoadEEGSensCB'')');
LoadEEGSensOtherMenu = uimenu(LoadEEGSensMenu, 'Label', 'Convert locations file',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''LoadEEGSensCB'')');
HeadshapeMenu = uimenu(Coor3DMenu, 'Label', 'Load MEG Fiducials/Headshape',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''HeadshapeCB'')');
CoregisterMenu = uimenu(Coor3DMenu, 'Label', 'Coregister',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''CoregisterCB'')');
% ====== 2D projection ===================================
Coor2DMenu = uimenu(Finter, 'Label','2D projection',...
'Tag','EEGprepUI',...
'Enable', 'off', ...
'HandleVisibility','on');
EditMEGMenu = uimenu(Coor2DMenu, 'Label', 'Edit existing MEG',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''EditExistingCoor2DCB'')');
EditEEGMenu = uimenu(Coor2DMenu, 'Label', 'Edit existing EEG',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''EditExistingCoor2DCB'')');
LoadTemplateMenu = uimenu(Coor2DMenu, 'Label', 'Load template',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''LoadTemplateCB'')');
SaveTemplateMenu = uimenu(Coor2DMenu, 'Label', 'Save template',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''SaveTemplateCB'')');
Project3DEEGMenu = uimenu(Coor2DMenu, 'Label', 'Project 3D (EEG)',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''Project3DCB'')');
Project3DMEGMenu = uimenu(Coor2DMenu, 'Label', 'Project 3D (MEG)',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''Project3DCB'')');
AddCoor2DMenu = uimenu(Coor2DMenu, 'Label', 'Add sensor',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''AddCoor2DCB'')');
DeleteCoor2DMenu = uimenu(Coor2DMenu, 'Label', 'Delete sensor',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''DeleteCoor2DCB'')');
UndoMoveCoor2DMenu = uimenu(Coor2DMenu, 'Label', 'Undo move',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''UndoMoveCoor2DCB'')');
ApplyCoor2DMenu = uimenu(Coor2DMenu, 'Label', 'Apply',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Separator', 'on', ...
'Callback', 'spm_eeg_prep_ui(''ApplyCoor2DCB'')');
Clear2DMenu = uimenu(Coor2DMenu, 'Label', 'Clear',...
'Tag','EEGprepUI',...
'Enable', 'on', ...
'HandleVisibility','on',...
'Callback', 'spm_eeg_prep_ui(''Clear2DCB'')');
%==========================================================================
% function FileOpenCB
%==========================================================================
function FileOpenCB
D = spm_eeg_load;
setD(D);
update_menu;
%==========================================================================
% function FileSaveCB
%==========================================================================
function FileSaveCB
D = getD;
if ~isempty(D)
D.save;
end
update_menu;
%==========================================================================
% function FileExitCB
%==========================================================================
function FileExitCB
spm_figure('Clear','Interactive');
spm('FigName','M/EEG prepare: done');
%==========================================================================
% function ChanTypeCB
%==========================================================================
function ChanTypeCB
type = get(gcbo, 'Label');
D = getD;
if ~isempty(D)
chanlist ={};
for i = 1:D.nchannels
if strncmp(D.chantype(i), 'MEG', 3) || strncmp(D.chantype(i), 'REF', 3)
chanlist{i} = [num2str(i) ' Label: ' D.chanlabels(i) ' Type: ' D.chantype(i) , ' (nonmodifiable)'];
else
chanlist{i} = [num2str(i) ' Label: ' D.chanlabels(i) ' Type: ' D.chantype(i)];
end
chanlist{i} = [chanlist{i}{:}];
end
if strcmpi(type, 'review')
listdlg('ListString', chanlist, 'SelectionMode', 'single', 'Name', 'Review channels', 'ListSize', [400 300]);
return
else
[selection ok]= listdlg('ListString', chanlist, 'SelectionMode', 'multiple',...
'InitialValue', strmatch(type, D.chantype) ,'Name', ['Set type to ' type], 'ListSize', [400 300]);
selection(strmatch('MEG', chantype(D, selection))) = [];
if ok && ~isempty(selection)
S.task = 'settype';
S.D = D;
S.ind = selection;
S.type = type;
D = spm_eeg_prep(S);
setD(D);
end
end
end
update_menu;
%==========================================================================
% function MEGChanTypeCB
%==========================================================================
function MEGChanTypeCB
S = [];
S.D = getD;
S.task = 'settype';
switch get(gcbo, 'Label')
case 'MEGREF=>MEG'
dictionary = {
'REFMAG', 'MEGMAG';
'REFGRAD', 'MEGGRAD';
};
ind = spm_match_str(S.D.chantype, dictionary(:,1));
grad = S.D.sensors('meg');
if ~isempty(grad)
% Under some montages only subset of the reference sensors are
% in the grad
[junk, sel] = intersect(S.D.chanlabels(ind), grad.label);
ind = ind(sel);
end
S.ind = ind;
[sel1, sel2] = spm_match_str(S.D.chantype(S.ind), dictionary(:, 1));
S.type = dictionary(sel2, 2);
D = spm_eeg_prep(S);
end
setD(D);
update_menu;
%==========================================================================
% function ChanTypeDefaultCB
%==========================================================================
function ChanTypeDefaultCB
S.D = getD;
S.task = 'defaulttype';
D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function LoadEEGSensTemplateCB
%==========================================================================
function LoadEEGSensTemplateCB
S.D = getD;
S.task = 'defaulteegsens';
if strcmp(S.D.modality(1, 0), 'Multimodal')
fid = fiducials(S.D);
if ~isempty(fid)
lblfid = fid.fid.label;
S.regfid = match_fiducials({'nas'; 'lpa'; 'rpa'}, lblfid);
S.regfid(:, 2) = {'spmnas'; 'spmlpa'; 'spmrpa'};
else
warndlg(strvcat('Could not match EEG fiducials for multimodal dataset.', ...
' EEG coregistration might fail.'));
end
end
D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function LoadEEGSensCB
%==========================================================================
function LoadEEGSensCB
D = getD;
switch get(gcbo, 'Label')
case 'From *.mat file'
[S.sensfile, sts] = spm_select(1,'mat','Select EEG sensors file');
if ~sts, return, end
S.source = 'mat';
[S.headshapefile, sts] = spm_select(1,'mat','Select EEG fiducials file');
if ~sts, return, end
S.fidlabel = spm_input('Fiducial labels:', '+1', 's', 'nas lpa rpa');
case 'Convert locations file'
[S.sensfile, sts] = spm_select(1, '.*', 'Select locations file');
if ~sts, return, end
S.source = 'locfile';
end
if strcmp(D.modality(1, 0), 'Multimodal')
if ~isempty(D.fiducials)
S.regfid = {};
if strcmp(S.source, 'mat')
fidlabel = S.fidlabel;
lblshape = {};
fidnum = 0;
while ~all(isspace(fidlabel))
fidnum = fidnum+1;
[lblshape{fidnum} fidlabel] = strtok(fidlabel);
end
if (fidnum < 3)
error('At least 3 labeled fiducials are necessary');
end
else
shape = ft_read_headshape(S.sensfile);
lblshape = shape.fid.label;
end
fid = fiducials(D);
lblfid = fid.fid.label;
S.regfid = match_fiducials(lblshape, lblfid);
else
warndlg(strvcat('Could not match EEG fiducials for multimodal dataset.', ...
' EEG coregistration might fail.'));
end
end
S.D = D;
S.task = 'loadeegsens';
D = spm_eeg_prep(S);
% ====== This is for the future ==================================
% sens = D.sensors('EEG');
% label = D.chanlabels(strmatch('EEG',D.chantype));
%
% [sel1, sel2] = spm_match_str(label, sens.label);
%
% montage = [];
% montage.labelorg = sens.label;
% montage.labelnew = label;
% montage.tra = sparse(zeros(numel(label), numel(sens.label)));
% montage.tra(sub2ind(size(montage.tra), sel1, sel2)) = 1;
%
% montage = spm_eeg_montage_ui(montage);
%
% S = [];
% S.D = D;
% S.task = 'sens2chan';
% S.montage = montage;
%
% D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function HeadshapeCB
%==========================================================================
function HeadshapeCB
S = [];
S.D = getD;
S.task = 'headshape';
[S.headshapefile, sts] = spm_select(1, '.*', 'Select fiducials/headshape file');
if ~sts, return, end
S.source = 'convert';
shape = ft_read_headshape(S.headshapefile);
lblshape = shape.fid.label;
fid = fiducials(S.D);
if ~isempty(fid)
lblfid = fid.fid.label;
S.regfid = match_fiducials(lblshape, lblfid);
end
D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function CoregisterCB
%==========================================================================
function CoregisterCB
S = [];
S.D = getD;
S.task = 'coregister';
D = spm_eeg_prep(S);
% Bring the menu back
spm_eeg_prep_ui;
setD(D);
update_menu;
%==========================================================================
% function EditExistingCoor2DCB
%==========================================================================
function EditExistingCoor2DCB
D = getD;
switch get(gcbo, 'Label')
case 'Edit existing MEG'
xy = D.coor2D('MEG');
label = D.chanlabels(strmatch('MEG', D.chantype));
case 'Edit existing EEG'
xy = D.coor2D('EEG');
label = D.chanlabels(strmatch('EEG', D.chantype, 'exact'));
end
plot_sensors2D(xy, label);
update_menu;
%==========================================================================
% function LoadTemplateCB
%==========================================================================
function LoadTemplateCB
[sensorfile, sts] = spm_select(1, 'mat', 'Select sensor template file', ...
[], fullfile(spm('dir'), 'EEGtemplates'));
if ~sts, return, end
template = load(sensorfile);
if isfield(template, 'Cnames') && isfield(template, 'Cpos')
plot_sensors2D(template.Cpos, template.Cnames);
end
update_menu;
%==========================================================================
% function SaveTemplateCB
%==========================================================================
function SaveTemplateCB
handles=getHandles;
Cnames = handles.label;
Cpos = handles.xy;
Rxy = 1.5;
Nchannels = length(Cnames);
[filename, pathname] = uiputfile('*.mat', 'Save channel template as');
save(fullfile(pathname, filename), 'Cnames', 'Cpos', 'Rxy', 'Nchannels');
%==========================================================================
% function Project3DCB
%==========================================================================
function Project3DCB
D = getD;
switch get(gcbo, 'Label')
case 'Project 3D (EEG)'
modality = 'EEG';
case 'Project 3D (MEG)'
modality = 'MEG';
end
if ~isfield(D, 'val')
D.val = 1;
end
if isfield(D, 'inv') && isfield(D.inv{D.val}, 'datareg')
datareg = D.inv{D.val}.datareg;
ind = strmatch(modality, {datareg(:).modality}, 'exact');
sens = datareg(ind).sensors;
else
sens = D.sensors(modality);
end
[xy, label] = spm_eeg_project3D(sens, modality);
plot_sensors2D(xy, label);
update_menu;
%==========================================================================
% function AddCoor2DCB
%==========================================================================
function AddCoor2DCB
newlabel = spm_input('Label?', '+1', 's');
if isempty(newlabel)
return;
end
coord = spm_input('Coordinates [x y]', '+1', 'r', '0.5 0.5', 2);
handles = getHandles;
if ~isfield(handles, 'xy')
handles.xy = [];
end
if ~isfield(handles, 'xy')
handles.xy = [];
end
if ~isfield(handles, 'label')
handles.label = {};
end
plot_sensors2D([handles.xy coord(:)], ...
[handles.label newlabel]);
update_menu;
%==========================================================================
% function ApplyCoor2DCB
%==========================================================================
function ApplyCoor2DCB
handles = getHandles;
D = getD;
S = [];
S.task = 'setcoor2d';
S.D = D;
S.xy = handles.xy;
S.label = handles.label;
D = spm_eeg_prep(S);
setD(D);
update_menu;
%==========================================================================
% function update_menu
%==========================================================================
function update_menu
Finter = spm_figure('GetWin','Interactive');
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'File'), 'Enable', 'on');
IsEEG = 'off';
IsMEG = 'off';
IsNeuromag = 'off';
HasSensors = 'off';
HasSensorsEEG = 'off';
HasSensorsMEG = 'off';
HasChannelsMEGREF = 'off';
HasFiducials = 'off';
HasDefaultLocs = 'off';
HasHistory = 'off';
if isa(get(Finter, 'UserData'), 'meeg')
Dloaded = 'on';
D = getD;
if ~isempty(strmatch('EEG', D.chantype, 'exact'))
IsEEG = 'on';
end
if ~isempty(strmatch('MEG', D.chantype));
IsMEG = 'on';
end
if ft_senstype(D.chanlabels, 'neuromag') &&...
isfield(D, 'origchantypes')
IsNeuromag = 'on';
end
if ~isempty(strmatch('REF', D.chantype));
HasChannelsMEGREF = 'on';
end
if ~isempty(D.sensors('EEG')) || ~isempty(D.sensors('MEG'))
HasSensors = 'on';
end
if ~isempty(D.sensors('EEG'))
HasSensorsEEG = 'on';
end
if ~isempty(D.sensors('MEG'))
HasSensorsMEG = 'on';
end
if ~isempty(D.fiducials)
HasFiducials = 'on';
end
template_sfp = dir(fullfile(spm('dir'), 'EEGtemplates', '*.sfp'));
template_sfp = {template_sfp.name};
ind = strmatch([ft_senstype(D.chanlabels) '.sfp'], template_sfp, 'exact');
if ~isempty(ind)
HasDefaultLocs = 'on';
end
if ~isempty(D.history)
HasHistory = 'on';
end
else
Dloaded = 'off';
end
handles = getHandles;
IsTemplate = 'off';
IsSelected = 'off';
IsMoved = 'off';
if ~isempty(handles)
if isfield(handles, 'xy') && size(handles.xy, 1)>0
IsTemplate = 'on';
end
if isfield(handles, 'labelSelected') && ~isempty(handles.labelSelected)
IsSelected = 'on';
end
if isfield(handles, 'lastMoved')
isMoved = 'on';
end
end
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Save'), 'Enable', 'on');
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Channel types'), 'Enable', Dloaded);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Sensors'), 'Enable', Dloaded);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', '2D projection'), 'Enable', Dloaded);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'MEGREF=>MEG'), 'Enable', HasChannelsMEGREF);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Assign default'), 'Enable', HasDefaultLocs);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Load EEG sensors'), 'Enable', IsEEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Load MEG Fiducials/Headshape'), 'Enable', HasSensorsMEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Headshape'), 'Enable', HasSensorsMEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Coregister'), 'Enable', HasSensors);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Edit existing EEG'), 'Enable', IsEEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Edit existing MEG'), 'Enable', IsMEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Project 3D (EEG)'), 'Enable', HasSensorsEEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Project 3D (MEG)'), 'Enable', HasSensorsMEG);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Delete sensor'), 'Enable', IsSelected);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Undo move'), 'Enable', IsMoved);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Apply'), 'Enable', IsTemplate);
set(findobj(Finter,'Tag','EEGprepUI', 'Label', 'Clear'), 'Enable', IsTemplate);
delete(setdiff(findobj(Finter), [Finter; findobj(Finter,'Tag','EEGprepUI')]));
if strcmp(Dloaded, 'on') && isfield(D,'PSD') && D.PSD == 1
try
hc = get(Finter,'children');
hc = findobj(hc,'flat','type','uimenu');
hc = findobj(hc,'flat','label','File');
delete(hc)
end
uicontrol(Finter,...
'style','pushbutton','string','OK',...
'callback','spm_eeg_review_callbacks(''get'',''prep'')',...
'tooltipstring','Send changes to ''SPM Graphics'' window',...
'BusyAction','cancel',...
'Interruptible','off',...
'Tag','EEGprepUI');
end
figure(Finter);
%==========================================================================
% function getD
%==========================================================================
function D = getD
Finter = spm_figure('GetWin','Interactive');
D = get(Finter, 'UserData');
if ~isa(D, 'meeg')
D = [];
end
%==========================================================================
% function setD
%==========================================================================
function setD(D)
Finter = spm_figure('GetWin','Interactive');
set(Finter, 'UserData', D);
%==========================================================================
% function getHandles
%==========================================================================
function handles = getHandles
Fgraph = spm_figure('GetWin','Graphics');
handles = get(Fgraph, 'UserData');
%==========================================================================
% function setHandles
%==========================================================================
function setHandles(handles)
Fgraph = spm_figure('GetWin','Graphics');
set(Fgraph, 'UserData', handles);
%==========================================================================
% function plot_sensors2D
%==========================================================================
function plot_sensors2D(xy, label)
Fgraph = spm_figure('GetWin','Graphics');
spm_clf(Fgraph);
handles = [];
if ~isempty(xy)
if size(xy, 1) ~= 2
xy = xy';
end
xy(xy < 0.05) = 0.05;
xy(xy > 0.95) = 0.95;
handles.h_lbl=text(xy(1,:), xy(2, :),strvcat(label),...
'FontSize', 9,...
'Color','r',...
'FontWeight','bold');
set(handles.h_lbl, 'ButtonDownFcn', 'spm_eeg_prep_ui(''LabelClickCB'')');
hold on
handles.h_el =[];
for i=1:size(xy, 2)
handles.h_el(i) = plot(xy(1,i), xy(2,i), 'or');
end
set(handles.h_el,'MarkerFaceColor','r','MarkerSize', 2,'MarkerEdgeColor','k');
handles.TemplateFrame = ...
plot([0.05 0.05 0.95 0.95 0.05], [0.05 0.95 0.95 0.05 0.05], 'k-');
axis off;
end
handles.xy = xy;
handles.label = label(:)';
setHandles(handles);
update_menu;
%==========================================================================
% function DeleteCoor2DCB
%==========================================================================
function DeleteCoor2DCB
handles = getHandles;
graph = spm_figure('GetWin','Graphics');
if isfield(handles, 'labelSelected') && ~isempty(handles.labelSelected)
set(graph, 'WindowButtonDownFcn', '');
label=get(handles.labelSelected, 'String');
ind=strmatch(label, handles.label, 'exact');
delete([handles.labelSelected handles.pointSelected]);
handles.xy(:, ind)=[];
handles.label(ind) = [];
plot_sensors2D(handles.xy, handles.label)
end
%==========================================================================
% function UndoMoveCoor2DCB
%==========================================================================
function UndoMoveCoor2DCB
handles = getHandles;
if isfield(handles, 'lastMoved')
label = get(handles.lastMoved(end).label, 'String');
ind = strmatch(label, handles.label, 'exact');
handles.xy(:, ind) = handles.lastMoved(end).coords(:);
set(handles.lastMoved(end).point, 'XData', handles.lastMoved(end).coords(1));
set(handles.lastMoved(end).point, 'YData', handles.lastMoved(end).coords(2));
set(handles.lastMoved(end).label, 'Position', handles.lastMoved(end).coords);
if length(handles.lastMoved)>1
handles.lastMoved = handles.lastMoved(1:(end-1));
else
handles = rmfield(handles, 'lastMoved');
end
setHandles(handles);
update_menu;
end
%==========================================================================
% function LabelClickCB
%==========================================================================
function LabelClickCB
handles=getHandles;
Fgraph = spm_figure('GetWin','Graphics');
if isfield(handles, 'labelSelected') && ~isempty(handles.labelSelected)
if handles.labelSelected == gcbo
set(handles.labelSelected, 'Color', 'r');
set(handles.pointSelected,'MarkerFaceColor', 'r');
set(Fgraph, 'WindowButtonDownFcn', '');
else
handles.pointSelected=[];
handles.labelSelected=[];
end
else
set(Fgraph, 'WindowButtonDownFcn', 'spm_eeg_prep_ui(''LabelMoveCB'')');
coords = get(gcbo, 'Position');
handles.labelSelected=gcbo;
handles.pointSelected=findobj(gca, 'Type', 'line',...
'XData', coords(1), 'YData', coords(2));
set(handles.labelSelected, 'Color', 'g');
set(handles.pointSelected,'MarkerFaceColor', 'g');
end
setHandles(handles);
update_menu;
%==========================================================================
% function LabelMoveCB
%==========================================================================
function LabelMoveCB
handles = getHandles;
Fgraph = spm_figure('GetWin','Graphics');
coords=mean(get(gca, 'CurrentPoint'));
coords(coords < 0.05) = 0.05;
coords(coords > 0.95) = 0.95;
set(handles.pointSelected, 'XData', coords(1));
set(handles.pointSelected, 'YData', coords(2));
set(handles.labelSelected, 'Position', coords);
set(handles.labelSelected, 'Color', 'r');
set(handles.pointSelected,'MarkerFaceColor','r','MarkerSize',2,'MarkerEdgeColor','k');
set(Fgraph, 'WindowButtonDownFcn', '');
set(Fgraph, 'WindowButtonMotionFcn', 'spm_eeg_prep_ui(''CancelMoveCB'')');
labelind=strmatch(get(handles.labelSelected, 'String'), handles.label);
if isfield(handles, 'lastMoved')
handles.lastMoved(end+1).point = handles.pointSelected;
handles.lastMoved(end).label = handles.labelSelected;
handles.lastMoved(end).coords = handles.xy(:, labelind);
else
handles.lastMoved.point = handles.pointSelected;
handles.lastMoved.label = handles.labelSelected;
handles.lastMoved.coords = handles.xy(:, labelind);
end
handles.xy(:, labelind) = coords(1:2)';
setHandles(handles);
update_menu;
%==========================================================================
% function CancelMoveCB
%==========================================================================
function CancelMoveCB
Fgraph = spm_figure('GetWin','Graphics');
handles = getHandles;
handles.pointSelected=[];
handles.labelSelected=[];
set(Fgraph, 'WindowButtonMotionFcn', '');
setHandles(handles);
update_menu;
%==========================================================================
% function Clear2DCB
%==========================================================================
function Clear2DCB
plot_sensors2D([], {});
update_menu;
%==========================================================================
% function match_fiducials
%==========================================================================
function regfid = match_fiducials(lblshape, lblfid)
if numel(intersect(upper(lblshape), upper(lblfid))) < 3
if numel(lblshape)<3 || numel(lblfid)<3
warndlg('3 fiducials are required');
return;
else
regfid = {};
for i = 1:length(lblfid)
[selection ok]= listdlg('ListString',lblshape, 'SelectionMode', 'single',...
'InitialValue', strmatch(upper(lblfid{i}), upper(lblshape)), ...
'Name', ['Select matching fiducial for ' lblfid{i}], 'ListSize', [400 300]);
if ~ok
continue
end
regfid = [regfid; [lblfid(i) lblshape(selection)]];
end
if size(regfid, 1) < 3
warndlg('3 fiducials are required to load headshape');
return;
end
end
else
[sel1, sel2] = spm_match_str(upper(lblfid), upper(lblshape));
lblfid = lblfid(sel1);
lblshape = lblshape(sel2);
regfid = [lblfid(:) lblshape(:)];
end
|
github
|
philippboehmsturm/antx-master
|
spm_read_netcdf.m
|
.m
|
antx-master/xspm8/spm_read_netcdf.m
| 4,350 |
utf_8
|
1cd1b0f7f4b4349d963028c168cd4f2d
|
function cdf = spm_read_netcdf(fname)
% Read the header information from a NetCDF file into a data structure.
% FORMAT cdf = spm_read_netcdf(fname)
% fname - name of NetCDF file
% cdf - data structure
%
% See: http://www.unidata.ucar.edu/packages/netcdf/
% _________________________________________________________________________
% Copyright (C) 1999-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_read_netcdf.m 4182 2011-02-01 12:29:09Z guillaume $
dsiz = [1 1 2 4 4 8];
fp=fopen(fname,'r','ieee-be');
if fp==-1
cdf = [];
return;
end
% Return null if not a CDF file.
%--------------------------------------------------------------------------
mgc = fread(fp,4,'uchar')';
if ~all(['CDF' 1] == mgc)
cdf = [];
fclose(fp);
if all(mgc==[137,72,68,70])
fprintf(['"%s" appears to be based around HDF.\n',...
'This is a newer version of MINC that SPM can not yet read.\n'],...
fname);
end
return;
end
% I've no idea what this is for
numrecs = fread(fp,1,'uint32');
cdf = struct('numrecs', numrecs,...
'dim_array', [], ...
'gatt_array', [], ...
'var_array', []);
dt = fread(fp,1,'uint32');
if dt == 10
% Dimensions
nelem = fread(fp,1,'uint32');
for j=1:nelem
str = readname(fp);
dim_length = fread(fp,1,'uint32');
cdf.dim_array(j).name = str;
cdf.dim_array(j).dim_length = dim_length;
end
dt = fread(fp,1,'uint32');
end
while ~dt, dt = fread(fp,1,'uint32'); end
if dt == 12
% Attributes
nelem = fread(fp,1,'uint32');
for j=1:nelem
str = readname(fp);
nc_type = fread(fp,1,'uint32');
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,dtypestr(nc_type));
if nc_type == 2, val = deblank([val' ' ']); end
padding= fread(fp,...
ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar');
cdf.gatt_array(j).name = str;
cdf.gatt_array(j).nc_type = nc_type;
cdf.gatt_array(j).val = val;
end
dt = fread(fp,1,'uint32');
end
while ~dt, dt = fread(fp,1,'uint32'); end
if dt == 11
% Variables
nelem = fread(fp,1,'uint32');
for j=1:nelem
str = readname(fp);
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,'uint32');
cdf.var_array(j).name = str;
cdf.var_array(j).dimid = val+1;
cdf.var_array(j).nc_type = 0;
cdf.var_array(j).vsize = 0;
cdf.var_array(j).begin = 0;
dt0 = fread(fp,1,'uint32');
if dt0 == 12
nelem0 = fread(fp,1,'uint32');
for jj=1:nelem0
str = readname(fp);
nc_type= fread(fp,1,'uint32');
nnelem = fread(fp,1,'uint32');
val = fread(fp,nnelem,dtypestr(nc_type));
if nc_type == 2, val = deblank([val' ' ']); end
padding= fread(fp,...
ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar');
cdf.var_array(j).vatt_array(jj).name = str;
cdf.var_array(j).vatt_array(jj).nc_type = nc_type;
cdf.var_array(j).vatt_array(jj).val = val;
end
dt0 = fread(fp,1,'uint32');
end
cdf.var_array(j).nc_type = dt0;
cdf.var_array(j).vsize = fread(fp,1,'uint32');
cdf.var_array(j).begin = fread(fp,1,'uint32');
end
dt = fread(fp,1,'uint32');
end
fclose(fp);
%==========================================================================
% function str = dtypestr(i)
%==========================================================================
function str = dtypestr(i)
% Returns a string appropriate for reading or writing the CDF data-type.
types = char('uint8','uint8','int16','int32','float32','float64');
str = deblank(types(i,:));
%==========================================================================
% function name = readname(fp)
%==========================================================================
function name = readname(fp)
% Extracts a name from a CDF file pointed to at the right location by fp.
stlen = fread(fp,1,'uint32');
name = deblank([fread(fp,stlen,'uchar')' ' ']);
padding = fread(fp,ceil(stlen/4)*4-stlen,'uchar');
|
github
|
philippboehmsturm/antx-master
|
spm_figure.m
|
.m
|
antx-master/xspm8/spm_figure.m
| 38,709 |
utf_8
|
4197abc8004aba283a121158d6f42aa7
|
function varargout=spm_figure(varargin)
% Setup and callback functions for Graphics window
% FORMAT varargout=spm_figure(varargin)
%
% spm_figure provides utility routines for using the SPM Graphics
% interface. Most used syntaxes are listed here, see the embedded callback
% reference in the main body of this function, below the help text.
%
% FORMAT F = spm_figure('Create',Tag,Name,Visible)
% FORMAT F = spm_figure('FindWin',Tag)
% FORMAT F = spm_figure('GetWin',Tag)
% FORMAT spm_figure('Clear',F,Tags)
% FORMAT spm_figure('Close',F)
% FORMAT spm_figure('Print',F)
% FORMAT spm_figure('WaterMark',F,str,Tag,Angle,Perm)
%
% FORMAT spm_figure('NewPage',hPage)
% FORMAT spm_figure('TurnPage',move,F)
% FORMAT spm_figure('DeletePageControls',F)
% FORMAT n = spm_figure('#page')
% FORMAT n = spm_figure('CurrentPage')
%__________________________________________________________________________
%
% spm_figure creates and manages the 'Graphics' window. This window and
% these facilities may be used independently of SPM, and any number of
% Graphics windows my be used within the same MATLAB session. (Though
% only one SPM 'Graphics' 'Tag'ed window is permitted).
%
% The Graphics window is provided with a menu bar at the top that
% facilitates editing and printing of the current graphic display.
% (This menu is also provided as a figure background "ContextMenu" -
% right-clicking on the figure background should bring up the menu).
%
% "Print": Graphics windows with multi-page axes are printed page by page.
%
% "Clear": Clears the Graphics window. If in SPM usage (figure 'Tag'ed as
% 'Graphics') then all SPM windows are cleared and reset.
%
% "Colours":
% * gray, hot, pink, jet: Sets the colormap to selected item.
% * gray-hot, etc: Creates a 'split' colormap {128 x 3 matrix}.
% The lower half is a gray scale and the upper half is selected
% colormap This colormap is used for viewing 'rendered' SPMs on a
% PET, MRI or other background images.
% Colormap effects:
% * Invert: Inverts (flips) the current color map.
% * Brighten and Darken: Brighten and Darken the current colourmap
% using the MATLAB BRIGHTEN command, with beta's of +0.2 and -0.2
% respectively.
%
% For SPM usage, the figure should be 'Tag'ed as 'Graphics'.
%
% See also: spm_print, spm_clf
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm_figure.m 6071 2014-06-27 12:52:33Z guillaume $
%==========================================================================
% - FORMAT specifications for embedded CallBack functions
%==========================================================================
%
% FORMAT F = spm_figure
% [ShortCut] Defaults to Action 'Create'
%
% FORMAT F = spm_figure(F) - numeric F
% [ShortCut] Defaults to spm_figure('CreateBar',F)
%
% FORMAT F = spm_figure('Create',Tag,Name,Visible)
% Create a full length WhiteBg figure 'Tag'ed Tag (if specified),
% with a ToolBar and background context menu.
% Equivalent to spm_figure('CreateWin','Tag') and spm_figure('CreateBar')
% Tag - 'Tag' string for figure.
% Name - Name for window
% Visible - 'on' or 'off'
% F - Figure used
%
% FORMAT F = spm_figure('FindWin',F)
% Finds window with 'Tag' or figure numnber F - returns empty F if not found
% F - (Input) Figure to use [Optional] - 'Tag' string or figure number.
% - Defaults to 'Graphics'
% F - (Output) Figure number (if found) or empty (if not).
%
% FORMAT F = spm_figure('GetWin',Tag)
% Like spm_figure('FindWin',Tag), except that if no such 'Tag'ged figure
% is found and 'Tag' is recognized, one is created. Further, the "got"
% window is made current.
% Tag - Figure 'Tag' to get, defaults to 'Graphics'
% F - Figure number (if found/created) or empty (if not).
%
% FORMAT spm_figure('Clear',F,Tags)
% Clears figure, leaving ToolBar (& other objects with invisible handles)
% Optional third argument specifies 'Tag's of objects to delete.
% If figure F is 'Tag'ged 'Interactive' (SPM usage), then the window
% name and pointer are reset.
% F - 'Tag' string or figure number of figure to clear, defaults to gcf
% Tags - 'Tag's (string matrix or cell array of strings) of objects to delete
% *regardless* of 'HandleVisibility'. Only these objects are deleted.
% '!all' denotes all objects
%
% FORMAT spm_figure('Close',F)
% Closes figures (deletion without confirmation)
% Also closes the docking container if empty.
% F - 'Tag' string or figure number of figure to clear, defaults to gcf
%
% FORMAT spm_figure('Print',F)
% F - [Optional] Figure to print. ('Tag' or figure number)
% Defaults to figure 'Tag'ed as 'Graphics'.
% If none found, uses CurrentFigure if avaliable.
% If objects 'Tag'ed 'NextPage' and 'PrevPage' are found, then the
% pages are shown and printed in order. In breif, pages are held as
% seperate axes, with ony one 'Visible' at any one time. The handles of
% the "page" axes are stored in the 'UserData' of the 'NextPage'
% object, while the 'PrevPage' object holds the current page number.
% See spm_help('!Disp') for details on setting up paging axes.
%
% FORMAT [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',hPage)
% SPM pagination function: Makes objects with handles hPage paginated
% Creates pagination buttons if necessary.
% hPage - Handles of objects to stick to this page
% hNextPage, hPrevPage, hPageNo - Handles of pagination controls
%
% FORMAT spm_figure('TurnPage',move,F)
% SPM pagination function: Turn to specified page
%
% FORMAT spm_figure('DeletePageControls',F)
% SPM pagination function: Deletes page controls
% F - [Optional] Figure in which to attempt to turn the page
% Defaults to 'Graphics' 'Tag'ged window
%
% FORMAT n = spm_figure('#page')
% Returns the current number of pages.
%
% FORMAT n = spm_figure('CurrentPage');
% Return the current page number.
%
% FORMAT spm_figure('WaterMark',F,str,Tag,Angle,Perm)
% Adds watermark to figure windows.
% F - Figure for watermark. Defaults to gcf
% str - Watermark string. Defaults (missing or empty) to SPM
% Tag - Tag for watermark axes. Defaults to ''
% Angle - Angle for watermark. Defaults to -45
% Perm - If specified, then watermark is permanent (HandleVisibility 'off')
%
% FORMAT F = spm_figure('CreateWin',Tag,Name,Visible)
% Creates a full length WhiteBg figure 'Tag'ged Tag (if specified).
% F - Figure created
% Tag - Tag for window
% Name - Name for window
% Visible - 'on' or 'off'
%
% FORMAT spm_figure('CreateBar',F)
% Creates toolbar in figure F (defaults to gcf). F can be a 'Tag'
%
% FORMAT spm_figure('ColorMap')
% Callback for "ColorMap" menu
%
% FORMAT spm_figure('FontSize')
% Callback for "FontSize" menu
%__________________________________________________________________________
%-Condition arguments
%--------------------------------------------------------------------------
if ~nargin, Action = 'Create'; else Action = varargin{1}; end
%==========================================================================
switch lower(Action), case 'create'
%==========================================================================
% F = spm_figure('Create',Tag,Name,Visible)
if nargin<4, Visible='on'; else Visible=varargin{4}; end
if nargin<3, Name=''; else Name=varargin{3}; end
if nargin<2, Tag=''; else Tag=varargin{2}; end
F = spm_figure('CreateWin',Tag,Name,Visible);
spm_figure('CreateBar',F);
spm_figure('FigContextMenu',F);
varargout = {F};
%==========================================================================
case 'findwin'
%==========================================================================
% F=spm_figure('FindWin',F)
% F=spm_figure('FindWin',Tag)
%-Find window: Find window with FigureNumber# / 'Tag' attribute
%-Returns empty if window cannot be found - deletes multiple tagged figs.
if nargin<2, F='Graphics'; else F=varargin{2}; end
if isempty(F)
% Leave F empty
elseif ischar(F)
% Finds Graphics window with 'Tag' string - delete multiples
Tag = F;
F = findall(allchild(0),'Flat','Tag',Tag);
if length(F) > 1
% Multiple Graphics windows - close all but most recent
close(F(2:end))
F = F(1);
end
else
% F is supposed to be a figure number - check it
if ~any(F==allchild(0)), F=[]; end
end
varargout = {F};
%==========================================================================
case 'getwin'
%==========================================================================
% F=spm_figure('GetWin',Tag)
%-Like spm_figure('FindWin',Tag), except that if no such 'Tag'ged figure
% is found and 'Tag' is recognized, one is created.
if nargin<2, Tag='Graphics'; else Tag=varargin{2}; end
F = spm_figure('FindWin',Tag);
if isempty(F)
if ischar(Tag)
switch Tag
case 'Graphics'
F = spm_figure('Create','Graphics','Graphics');
case 'DEM'
F = spm_figure('Create','DEM','Dynamic Expectation Maximisation');
case 'DFP'
F = spm_figure('Create','DFP','Variational filtering');
case 'FMIN'
F = spm_figure('Create','FMIN','Function minimisation');
case 'MFM'
F = spm_figure('Create','MFM','Mean-field and neural mass models');
case 'MVB'
F = spm_figure('Create','MVB','Multivariate Bayes');
case 'SI'
F = spm_figure('Create','SI','System Identification');
case 'PPI'
F = spm_figure('Create','PPI','Physio/Psycho-Physiologic Interaction');
case 'Interactive'
F = spm('CreateIntWin');
otherwise
F = spm_figure('Create',Tag,Tag);
end
end
else
set(0,'CurrentFigure',F);
figure(F);
end
varargout = {F};
%==========================================================================
case 'parentfig'
%==========================================================================
% F=spm_figure('ParentFig',h)
warning('spm_figure(''ParentFig'',h) is deprecated. Use ANCESTOR instead.');
if nargin<2, error('No object specified'), else h=varargin{2}; end
F = ancestor(h,'figure');
varargout = {F};
%==========================================================================
case 'clear'
%==========================================================================
% spm_figure('Clear',F,Tags)
%-Sort out arguments
if nargin<3, Tags=[]; else Tags=varargin{3}; end
if nargin<2, F=get(0,'CurrentFigure'); else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Clear figure
isdocked = strcmp(get(F,'WindowStyle'),'docked');
if isempty(Tags)
%-Clear figure of objects with 'HandleVisibility' 'on'
pos = get(F,'Position');
delete(findall(allchild(F),'flat','HandleVisibility','on'));
drawnow
if ~isdocked, set(F,'Position',pos); end
%-Reset figures callback functions
zoom(F,'off');
rotate3d(F,'off');
set(F,'KeyPressFcn','',...
'WindowButtonDownFcn','',...
'WindowButtonMotionFcn','',...
'WindowButtonUpFcn','')
%-If this is the 'Interactive' window, reset name & UserData
if strcmp(get(F,'Tag'),'Interactive')
set(F,'Name','','UserData',[]), end
else
%-Clear specified objects from figure
if ischar(Tags); Tags=cellstr(Tags); end
if any(strcmp(Tags(:),'!all'))
delete(allchild(F))
else
for tag = Tags(:)'
delete(findall(allchild(F),'flat','Tag',tag{:}));
end
end
end
set(F,'Pointer','Arrow')
%if ~isdocked && ~spm('CmdLine'), movegui(F); end
%==========================================================================
case 'close'
%==========================================================================
% spm_figure('Close',F)
%-Sort out arguments
if nargin < 2, F = gcf; else F = varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Detect if SPM windows are in docked mode
hMenu = spm_figure('FindWin','Menu');
isdocked = strcmp(get(hMenu,'WindowStyle'),'docked');
%-Close figures (and deleted without confirmation)
delete(F);
%-If in docked mode and closing SPM, close the container as well
if isdocked && ismember(hMenu,F)
try
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
group = ['Statistical Parametric Mapping (' spm('Ver') ')'];
hContainer = desktop.getGroupContainer(group);
hContainer.getTopLevelAncestor.hide;
end
end
%==========================================================================
case 'print'
%==========================================================================
% spm_figure('Print',F,fname)
%-Arguments & defaults
if nargin<3, fname=''; else fname=varargin{3};end
if nargin<2, F='Graphics'; else F=varargin{2}; end
%-Find window to print, default to gcf if specified figure not found
% Return if no figures
if ~isempty(F), F = spm_figure('FindWin',F); end
if isempty(F), F = get(0,'CurrentFigure'); end
if isempty(F), return, end
%-Note current figure, & switch to figure to print
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)
%-See if window has paging controls
hNextPage = findall(F,'Tag','NextPage');
hPrevPage = findall(F,'Tag','PrevPage');
hPageNo = findall(F,'Tag','PageNo');
iPaged = ~isempty(hNextPage);
%-Temporarily change all units to normalized prior to printing
H = findall(allchild(F),'flat','Type','axes');
if ~isempty(H)
un = cellstr(get(H,'Units'));
set(H,'Units','normalized');
end
%-Print
if ~iPaged
spm_print(fname,F);
else
hPg = get(hNextPage,'UserData');
Cpage = get(hPageNo, 'UserData');
nPages = size(hPg,1);
set([hNextPage,hPrevPage,hPageNo],'Visible','off');
if Cpage~=1
set(hPg{Cpage,1},'Visible','off');
end
for p = 1:nPages
set(hPg{p,1},'Visible','on');
spm_print(fname,F);
set(hPg{p,1},'Visible','off');
end
set(hPg{Cpage,1},'Visible','on');
set([hNextPage,hPrevPage,hPageNo],'Visible','on');
end
if ~isempty(H), set(H,{'Units'},un); end
set(0,'CurrentFigure',cF);
%==========================================================================
case 'printto'
%==========================================================================
%spm_figure('PrintTo',F)
%-Arguments & defaults
if nargin<2, F='Graphics'; else F=varargin{2}; end
%-Find window to print, default to gcf if specified figure not found
% Return if no figures
F=spm_figure('FindWin',F);
if isempty(F), F = get(0,'CurrentFigure'); end
if isempty(F), return, end
[fn, pn, fi] = uiputfile({'*.ps','PostScript file (*.ps)'},'Print to File');
if isequal(fn,0) || isequal(pn,0), return, end
psname = fullfile(pn, fn);
spm_figure('Print',F,psname);
%==========================================================================
case 'newpage'
%==========================================================================
% [hNextPage, hPrevPage, hPageNo] = spm_figure('NewPage',h)
if nargin<2 || isempty(varargin{2}), error('No handles to paginate')
else h=varargin{2}(:)'; end
%-Work out which figure we're in
F = ancestor(h(1),'figure');
hNextPage = findall(F,'Tag','NextPage');
hPrevPage = findall(F,'Tag','PrevPage');
hPageNo = findall(F,'Tag','PageNo');
%-Create pagination widgets if required
%--------------------------------------------------------------------------
if isempty(hNextPage)
WS = spm('WinScale');
FS = spm('FontSizes');
SatFig = findall(0,'Tag','Satellite');
if ~isempty(SatFig)
SatFigPos = get(SatFig,'Position');
hNextPagePos = [SatFigPos(3)-25 15 15 15];
hPrevPagePos = [SatFigPos(3)-40 15 15 15];
hPageNo = [SatFigPos(3)-40 5 30 10];
else
hNextPagePos = [580 022 015 015].*WS;
hPrevPagePos = [565 022 015 015].*WS;
hPageNo = [550 005 060 015].*WS;
end
hNextPage = uicontrol(F,'Style','Pushbutton',...
'HandleVisibility','on',...
'String','>','FontSize',FS(10),...
'ToolTipString','next page',...
'Callback','spm_figure(''TurnPage'',''+1'',gcbf)',...
'Position',hNextPagePos,...
'ForegroundColor',[0 0 0],...
'Tag','NextPage','UserData',[]);
hPrevPage = uicontrol(F,'Style','Pushbutton',...
'HandleVisibility','on',...
'String','<','FontSize',FS(10),...
'ToolTipString','previous page',...
'Callback','spm_figure(''TurnPage'',''-1'',gcbf)',...
'Position',hPrevPagePos,...
'Visible','on',...
'Enable','off',...
'Tag','PrevPage');
hPageNo = uicontrol(F,'Style','Text',...
'HandleVisibility','on',...
'String','1',...
'FontSize',FS(6),...
'HorizontalAlignment','center',...
'BackgroundColor','w',...
'Position',hPageNo,...
'Visible','on',...
'UserData',1,...
'Tag','PageNo','UserData',1);
end
%-Add handles for this page to UserData of hNextPage
%-Make handles for this page invisible if PageNo>1
%--------------------------------------------------------------------------
mVis = strcmp('on',get(h,'Visible'));
mHit = strcmp('on',get(h,'HitTest'));
hPg = get(hNextPage,'UserData');
if isempty(hPg)
hPg = {h(mVis), h(~mVis), h(mHit), h(~mHit)};
else
hPg = [hPg; {h(mVis), h(~mVis), h(mHit), h(~mHit)}];
set(h(mVis),'Visible','off');
set(h(mHit),'HitTest','off');
end
set(hNextPage,'UserData',hPg)
%-Return handles to pagination controls if requested
if nargout>0, varargout = {[hNextPage, hPrevPage, hPageNo]}; end
%==========================================================================
case 'turnpage'
%==========================================================================
% spm_figure('TurnPage',move,F)
if nargin<3, F='Graphics'; else F=varargin{3}; end
if nargin<2, move=1; else move=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findall(F,'Tag','NextPage');
hPrevPage = findall(F,'Tag','PrevPage');
hPageNo = findall(F,'Tag','PageNo');
if isempty(hNextPage), return, end
hPg = get(hNextPage,'UserData');
Cpage = get(hPageNo, 'UserData');
nPages = size(hPg,1);
%-Sort out new page number
if ischar(move), Npage = Cpage+eval(move); else Npage = move; end
Npage = max(min(Npage,nPages),1);
%-Make current page invisible, new page visible, set page number string
set(hPg{Cpage,1},'Visible','off');
set(hPg{Cpage,3},'HitTest','off');
set(hPg{Npage,1},'Visible','on');
set(hPg{Npage,3},'HitTest','on');
set(hPageNo,'UserData',Npage,'String',sprintf('%d / %d',Npage,nPages))
for k = 1:length(hPg{Npage,1})
if strcmp(get(hPg{Npage,1}(k),'Type'),'axes')
axes(hPg{Npage,1}(k));
end
end
%-Disable appropriate page turning control if on first/last page
if Npage==1, set(hPrevPage,'Enable','off')
else set(hPrevPage,'Enable','on'), end
if Npage==nPages, set(hNextPage,'Enable','off')
else set(hNextPage,'Enable','on'), end
%==========================================================================
case 'deletepagecontrols'
%==========================================================================
% spm_figure('DeletePageControls',F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findall(F,'Tag','NextPage');
hPrevPage = findall(F,'Tag','PrevPage');
hPageNo = findall(F,'Tag','PageNo');
delete([hNextPage hPrevPage hPageNo])
%==========================================================================
case '#page'
%==========================================================================
% n = spm_figure('#Page',F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hNextPage = findall(F,'Tag','NextPage');
if isempty(hNextPage)
n = 1;
else
n = size(get(hNextPage,'UserData'),1)+1;
end
varargout = {n};
%==========================================================================
case 'currentpage'
%==========================================================================
% n = spm_figure('CurrentPage', F)
if nargin<2, F='Graphics'; else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), error('No Graphics window'), end
hPageNo = findall(F,'Tag','PageNo');
Cpage = get(hPageNo, 'UserData');
varargout = {Cpage};
%==========================================================================
case 'watermark'
%==========================================================================
% spm_figure('WaterMark',F,str,Tag,Angle,Perm)
if nargin<6, HVis='on'; else HVis='off'; end
if nargin<5, Angle=-45; else Angle=varargin{5}; end
if nargin<4 || isempty(varargin{4}), Tag = 'WaterMark'; else Tag=varargin{4}; end
if nargin<3 || isempty(varargin{3}), str = 'SPM'; else str=varargin{3}; end
if nargin<2, if any(allchild(0)), F=gcf; else F=''; end
else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Specify watermark color from background colour
Colour = get(F,'Color');
%-Only mess with grayscale backgrounds
if ~all(Colour==Colour(1)), return, end
%-Work out colour - lighter unless grey value > 0.9
Colour = Colour+(2*(Colour(1)<0.9)-1)*0.02;
cF = get(0,'CurrentFigure');
set(0,'CurrentFigure',F)
Units=get(F,'Units');
set(F,'Units','normalized');
h = axes('Position',[0.45,0.5,0.1,0.1],...
'Units','normalized',...
'Visible','off',...
'Tag',Tag);
set(F,'Units',Units)
text(0.5,0.5,str,...
'FontSize',spm('FontSize',80),...
'FontWeight','Bold',...
'FontName',spm_platform('Font','times'),...
'Rotation',Angle,...
'HorizontalAlignment','Center',...
'VerticalAlignment','middle',...
'Color',Colour,...
'ButtonDownFcn',[...
'if strcmp(get(gcbf,''SelectionType''),''open''),',...
'delete(get(gcbo,''Parent'')),',...
'end'])
set(h,'HandleVisibility',HVis)
set(0,'CurrentFigure',cF)
%==========================================================================
case 'createwin'
%==========================================================================
% F=spm_figure('CreateWin',Tag,Name,Visible)
if nargin<4 || isempty(varargin{4}), Visible='on'; else Visible=varargin{4}; end
if nargin<3, Name=''; else Name = varargin{3}; end
if nargin<2, Tag=''; else Tag = varargin{2}; end
FS = spm('FontSizes'); %-Scaled font sizes
PF = spm_platform('fonts'); %-Font names (for this platform)
Rect = spm('WinSize','Graphics'); %-Graphics window rectangle
S0 = spm('WinSize','0',1); %-Screen size (of the current monitor)
F = figure(...
'Tag',Tag,...
'Position',[S0(1) S0(2) 0 0] + Rect,...
'Resize','off',...
'Color','w',...
'ColorMap',gray(64),...
'DefaultTextColor','k',...
'DefaultTextInterpreter','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultAxesColor','w',...
'DefaultAxesXColor','k',...
'DefaultAxesYColor','k',...
'DefaultAxesZColor','k',...
'DefaultAxesFontName',PF.helvetica,...
'DefaultPatchFaceColor','k',...
'DefaultPatchEdgeColor','k',...
'DefaultSurfaceEdgeColor','k',...
'DefaultLineColor','k',...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'DefaultUicontrolInterruptible','on',...
'PaperType','A4',...
'PaperUnits','normalized',...
'PaperPosition',[.0726 .0644 .854 .870],...
'InvertHardcopy','off',...
'Renderer',spm_get_defaults('renderer'),...
'Visible','off',...
'Toolbar','none');
if ~isempty(Name)
set(F,'Name',sprintf('%s%s: %s',spm('ver'),...
spm('getUser',' (%s)'),Name),'NumberTitle','off')
end
set(F,'Visible',Visible)
varargout = {F};
isdocked = strcmp(get(spm_figure('FindWin','Menu'),'WindowStyle'),'docked');
if isdocked
try
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
group = ['Statistical Parametric Mapping (' spm('Ver') ')'];
set(getJFrame(F),'GroupName',group);
set(F,'WindowStyle','docked');
end
end
%==========================================================================
case 'createbar'
%==========================================================================
% spm_figure('CreateBar',F)
if nargin<2, if any(allchild(0)), F=gcf; else F=''; end
else F=varargin{2}; end
F = spm_figure('FindWin',F);
if isempty(F), return, end
%-Help Menu
t0 = findall(allchild(F),'Flat','Label','&Help');
delete(allchild(t0)); set(t0,'Callback','');
if isempty(t0), t0 = uimenu( F,'Label','&Help'); end;
pos = get(t0,'Position');
uimenu(t0,'Label','SPM Help','CallBack','spm_help');
uimenu(t0,'Label','SPM Manual (PDF)',...
'CallBack','try,open(fullfile(spm(''dir''),''man'',''manual.pdf''));end');
t1=uimenu(t0,'Label','SPM &Web Resources');
uimenu(t1,'Label','SPM Web &Site',...
'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/'');');
uimenu(t1,'Label','SPM &WikiBook',...
'CallBack','web(''http://en.wikibooks.org/wiki/SPM'');');
uimenu(t1,'Separator','on','Label','SPM &Extensions',...
'CallBack','web(''http://www.fil.ion.ucl.ac.uk/spm/ext/'');');
%-Check Menu
if ~isdeployed
uimenu(t0,'Separator','on','Label','SPM Check Installation',...
'CallBack','spm_check_installation(''full'')');
uimenu(t0,'Label','SPM Check for Updates',...
'CallBack','spm(''alert"'',evalc(''spm_update''),''SPM Update'');');
end
%- About Menu
uimenu(t0,'Separator','on','Label',['&About ' spm('Ver')],...
'CallBack',@spm_about);
uimenu(t0,'Label','&About MATLAB',...
'CallBack','helpmenufcn(gcbf,''HelpAbout'')');
%-Figure Menu
t0=uimenu(F, 'Position',pos, 'Label','&SPM Figure', 'HandleVisibility','off', 'Callback',@myisresults);
%-Show All Figures
uimenu(t0, 'Label','Show All &Windows', 'HandleVisibility','off',...
'CallBack','spm(''Show'');');
%-Dock SPM Figures
uimenu(t0, 'Label','&Dock SPM Windows', 'HandleVisibility','off',...
'CallBack',@mydockspm);
%-Print Menu
t1=uimenu(t0, 'Label','&Save Figure', 'HandleVisibility','off','Separator','on');
uimenu(t1, 'Label','&Default File', 'HandleVisibility','off', ...
'CallBack','spm_figure(''Print'',gcf)');
uimenu(t1, 'Label','&Specify File...', 'HandleVisibility','off', ...
'CallBack','spm_figure(''PrintTo'',spm_figure(''FindWin'',''Graphics''))');
%-Copy Figure
if ispc
uimenu(t0, 'Label','Co&py Figure', 'HandleVisibility','off',...
'CallBack','editmenufcn(gcbf,''EditCopyFigure'')');
end
%-Clear Menu
uimenu(t0, 'Label','&Clear Figure', 'HandleVisibility','off', ...
'CallBack','spm_figure(''Clear'',gcbf)');
%-Close non-SPM figures
uimenu(t0, 'Label','C&lose non-SPM Figures', 'HandleVisibility','off', ...
'CallBack',@myclosefig);
%-Colour Menu
t1=uimenu(t0, 'Label','C&olours', 'HandleVisibility','off','Separator','on');
t2=uimenu(t1, 'Label','Colormap');
uimenu(t2, 'Label','Gray', 'CallBack','spm_figure(''ColorMap'',''gray'')');
uimenu(t2, 'Label','Hot', 'CallBack','spm_figure(''ColorMap'',''hot'')');
uimenu(t2, 'Label','Pink', 'CallBack','spm_figure(''ColorMap'',''pink'')');
uimenu(t2, 'Label','Jet', 'CallBack','spm_figure(''ColorMap'',''jet'')');
uimenu(t2, 'Label','Gray-Hot', 'CallBack','spm_figure(''ColorMap'',''gray-hot'')');
uimenu(t2, 'Label','Gray-Cool', 'CallBack','spm_figure(''ColorMap'',''gray-cool'')');
uimenu(t2, 'Label','Gray-Pink', 'CallBack','spm_figure(''ColorMap'',''gray-pink'')');
uimenu(t2, 'Label','Gray-Jet', 'CallBack','spm_figure(''ColorMap'',''gray-jet'')');
t2=uimenu(t1, 'Label','Effects');
uimenu(t2, 'Label','Invert', 'CallBack','spm_figure(''ColorMap'',''invert'')');
uimenu(t2, 'Label','Brighten', 'CallBack','spm_figure(''ColorMap'',''brighten'')');
uimenu(t2, 'Label','Darken', 'CallBack','spm_figure(''ColorMap'',''darken'')');
%-Font Size Menu
t1=uimenu(t0, 'Label','&Font Size', 'HandleVisibility','off');
uimenu(t1, 'Label','&Increase', 'CallBack','spm_figure(''FontSize'',1)', 'Accelerator', '=');
uimenu(t1, 'Label','&Decrease', 'CallBack','spm_figure(''FontSize'',-1)', 'Accelerator', '-');
%-Satellite Table
uimenu(t0, 'Label','&Results Table', 'HandleVisibility','off', ...
'Separator','on', 'Callback',@mysatfig);
% Tasks Menu
%try, spm_jobman('pulldown'); end
%==========================================================================
case 'figcontextmenu'
%==========================================================================
% h = spm_figure('FigContextMenu',F)
if nargin<2
F = get(0,'CurrentFigure');
if isempty(F), error('no figure'), end
else
F = spm_figure('FindWin',varargin{2});
if isempty(F), error('no such figure'), end
end
h = uicontextmenu('Parent',F,'HandleVisibility','CallBack');
copy_menu(F,h);
set(F,'UIContextMenu',h)
varargout = {h};
%==========================================================================
case 'colormap'
%==========================================================================
% spm_figure('ColorMap',ColAction)
if nargin<2, ColAction='gray'; else ColAction=varargin{2}; end
switch lower(ColAction), case 'gray'
colormap(gray(64))
case 'hot'
colormap(hot(64))
case 'pink'
colormap(pink(64))
case 'jet'
colormap(jet(64))
case 'gray-hot'
tmp = hot(64 + 16); tmp = tmp((1:64) + 16,:);
colormap([gray(64); tmp]);
case 'gray-cool'
cool = [zeros(10,1) zeros(10,1) linspace(0.5,1,10)';
zeros(31,1) linspace(0,1,31)' ones(31,1);
linspace(0,1,23)' ones(23,1) ones(23,1) ];
colormap([gray(64); cool]);
case 'gray-pink'
tmp = pink(64 + 16); tmp = tmp((1:64) + 16,:);
colormap([gray(64); tmp]);
case 'gray-jet'
colormap([gray(64); jet(64)]);
case 'invert'
colormap(flipud(colormap));
case 'brighten'
colormap(brighten(colormap, 0.2));
case 'darken'
colormap(brighten(colormap, -0.2));
otherwise
error('Illegal ColAction specification');
end
%==========================================================================
case 'fontsize'
%==========================================================================
% spm_figure('FontSize',sz)
if nargin<2, sz=0; else sz=varargin{2}; end
h = [get(0,'CurrentFigure') spm_figure('FindWin','Satellite')];
h = [findall(h,'type','text'); findall(h,'type','uicontrol')];
fs = get(h,'fontsize');
if ~isempty(fs)
set(h,{'fontsize'},cellfun(@(x) max(x+sz,eps),fs,'UniformOutput',false));
end
%==========================================================================
otherwise
%==========================================================================
warning(['Illegal Action string: ',Action])
end
return;
%==========================================================================
function myisresults(obj,evt)
%==========================================================================
hr = findall(obj,'Label','&Results Table');
try
evalin('base','xSPM;');
set(hr,'Enable','on');
catch
set(hr,'Enable','off');
end
SatWindow = spm_figure('FindWin','Satellite');
if ~isempty(SatWindow)
set(hr,'Checked','on');
else
set(hr,'Checked','off');
end
%==========================================================================
function mysatfig(obj,evt)
%==========================================================================
SatWindow = spm_figure('FindWin','Satellite');
if ~isempty(SatWindow)
figure(SatWindow)
else
FS = spm('FontSizes'); %-Scaled font sizes
PF = spm_platform('fonts'); %-Font names
WS = spm('WinSize','0','raw'); %-Screen size (of current monitor)
Rect = [WS(1)+5 WS(4)*.40 WS(3)*.49 WS(4)*.57];
figure(...
'Tag','Satellite',...
'Position',Rect,...
'Resize','off',...
'MenuBar','none',...
'Name','SPM: Satellite Results Table',...
'Numbertitle','off',...
'Color','w',...
'ColorMap',gray(64),...
'DefaultTextColor','k',...
'DefaultTextInterpreter','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultAxesColor','w',...
'DefaultAxesXColor','k',...
'DefaultAxesYColor','k',...
'DefaultAxesZColor','k',...
'DefaultAxesFontName',PF.helvetica,...
'DefaultPatchFaceColor','k',...
'DefaultPatchEdgeColor','k',...
'DefaultSurfaceEdgeColor','k',...
'DefaultLineColor','k',...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'DefaultUicontrolInterruptible','on',...
'PaperType','A4',...
'PaperUnits','normalized',...
'PaperPosition',[.0726 .0644 .854 .870],...
'InvertHardcopy','off',...
'Renderer',spm_get_defaults('renderer'),...
'Visible','on');
end
%==========================================================================
function mydockspm(obj,evt)
%==========================================================================
% Largely inspired by setFigDockGroup from Yair Altman
% http://www.mathworks.com/matlabcentral/fileexchange/16650
hMenu = spm_figure('FindWin','Menu');
hInt = spm_figure('FindWin','Interactive');
hGra = spm_figure('FindWin','Graphics');
h = [hMenu hInt hGra];
group = ['Statistical Parametric Mapping (' spm('Ver') ')'];
try
desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
if ~ismember(group,cell(desktop.getGroupTitles))
desktop.addGroup(group);
end
for i=1:length(h)
set(getJFrame(h(i)),'GroupName',group);
end
hContainer = desktop.getGroupContainer(group);
set(hContainer,'userdata',group);
end
set(h,'WindowStyle','docked');
try, pause(0.5), desktop.setGroupDocked(group,false); end
%==========================================================================
function myclosefig(obj,evt)
%==========================================================================
hMenu = spm_figure('FindWin','Menu');
hInt = spm_figure('FindWin','Interactive');
hGra = spm_figure('FindWin','Graphics');
h = setdiff(findobj(get(0,'children'),'flat','visible','on'), ...
[hMenu hInt hGra gcf]);
close(h,'force');
%==========================================================================
function copy_menu(F,G)
%==========================================================================
handles = findall(allchild(F),'Flat','Type','uimenu','Visible','on');
if isempty(handles), return; end;
for F1=handles(:)'
if ~ismember(get(F1,'Label'),{'&Window' '&Desktop'})
G1 = uimenu(G,'Label',get(F1,'Label'),...
'CallBack',get(F1,'CallBack'),...
'Position',get(F1,'Position'),...
'Separator',get(F1,'Separator'));
copy_menu(F1,G1);
end
end
%==========================================================================
function jframe = getJFrame(h)
%==========================================================================
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
hhFig = handle(h);
jframe = [];
maxTries = 16;
while maxTries > 0
try
jframe = get(hhFig,'javaframe');
if ~isempty(jframe)
break;
else
maxTries = maxTries - 1;
drawnow; pause(0.1);
end
catch
maxTries = maxTries - 1;
drawnow; pause(0.1);
end
end
if isempty(jframe)
error('Cannot retrieve the java frame from handle.');
end
%==========================================================================
function spm_about(obj,evt)
%==========================================================================
[v,r] = spm('Ver');
h = figure('MenuBar','none',...
'NumberTitle','off',...
'Name',['About ' v],...
'Resize','off',...
'Toolbar','none',...
'Tag','AboutSPM',...
'WindowStyle','Modal',...
'Color',[0 0 0],...
'Visible','off',...
'DoubleBuffer','on');
pos = get(h,'Position');
pos([3 4]) = [300 400];
set(h,'Position',pos);
set(h,'Visible','on');
a = axes('Parent',h, 'Units','pixels', 'Position',[50 201 200 200],...
'Visible','off');
IMG = imread(fullfile(spm('Dir'),'man','images','spm8.png'));
image(IMG,'Parent',a); set(a,'Visible','off');
a = axes('Parent',h,'Units','pixels','Position',[0 0 300 400],...
'Visible','off','Tag','textcont');
text(0.5,0.45,'Statistical Parametric Mapping','Parent',a,...
'HorizontalAlignment','center','Color',[1 1 1],'FontWeight','Bold');
text(0.5,0.40,[v ' (v' r ')'],'Parent',a,'HorizontalAlignment','center',...
'Color',[1 1 1]);
text(0.5,0.30,'Wellcome Trust Centre for Neuroimaging','Parent',a,...
'HorizontalAlignment','center','Color',[1 1 1],'FontWeight','Bold');
text(0.5,0.25,['Copyright (C) 1991,1994-' datestr(now,'yyyy')],...
'Parent',a,'HorizontalAlignment','center','Color',[1 1 1]);
text(0.5,0.20,'http://www.fil.ion.ucl.ac.uk/spm/','Parent',a,...
'HorizontalAlignment','center','Color',[1 1 1],...
'ButtonDownFcn','web(''http://www.fil.ion.ucl.ac.uk/spm/'');');
uicontrol('Style','pushbutton','String','Credits','Position',[40 25 60 25],...
'Callback',@myscroll,'BusyAction','Cancel');
uicontrol('Style','pushbutton','String','OK','Position',[200 25 60 25],...
'Callback','close(gcf)','BusyAction','Cancel');
%==========================================================================
function myscroll(obj,evt)
%==========================================================================
ax = findobj(gcf,'Tag','textcont');
cla(ax);
[current, previous] = spm_authors;
authors = {['*' spm('Ver') '*'] current{:} '' ...
'*Previous versions*' previous{:} '' ...
'*Thanks to the SPM community*'};
x = 0.2;
h = [];
for i=1:numel(authors)
h(i) = text(0.5,x,authors{i},'Parent',ax,...
'HorizontalAlignment','center','Color',col(x));
if any(authors{i} == '*')
set(h(i),'String',strrep(authors{i},'*',''),'FontWeight','Bold');
end
x = x - 0.05;
end
pause(0.5);
try
for j=1:fix((0.5-(0.2-numel(authors)*0.05))/0.01)
for i=1:numel(h)
p = get(h(i),'Position');
p2 = p(2)+0.01;
set(h(i),'Position',[p(1) p2 p(3)],'Color',col(p2));
if p2 > 0.5, set(h(i),'Visible','off'); end
end
pause(0.1)
end
end
%==========================================================================
function c = col(x)
%==========================================================================
if x < 0.4 && x > 0.3
c = [1 1 1];
elseif x <= 0.3
c = [1 1 1] - 6*abs(0.3-x);
else
c = [1 1 1] - 6*abs(0.4-x);
end
c(c<0) = 0; c(c>1) = 1;
|
github
|
philippboehmsturm/antx-master
|
spm_P_RF.m
|
.m
|
antx-master/xspm8/spm_P_RF.m
| 6,258 |
utf_8
|
12cabbf3a8ca0c5e43a3fd4025db3e69
|
function [P,p,Ec,Ek] = spm_P_RF(c,k,Z,df,STAT,R,n)
% Returns the [un]corrected P value using unifed EC theory
% FORMAT [P p Ec Ek] = spm_P_RF(c,k,z,df,STAT,R,n)
%
% c - cluster number
% k - extent {RESELS}
% z - height {minimum over n values}
% df - [df{interest} df{error}]
% STAT - Statistical field
% 'Z' - Gaussian field
% 'T' - T - field
% 'X' - Chi squared field
% 'F' - F - field
% R - RESEL Count {defining search volume}
% n - number of component SPMs in conjunction
%
% P - corrected P value - P(C >= c | K >= k}
% p - uncorrected P value
% Ec - expected number of clusters (maxima)
% Ek - expected number of resels per cluster
%
%__________________________________________________________________________
%
% spm_P_RF returns the probability of c or more clusters with more than
% k resels in volume process of R RESELS thresholded at u. All p values
% can be considered special cases:
%
% spm_P_RF(1,0,z,df,STAT,1,n) = uncorrected p value
% spm_P_RF(1,0,z,df,STAT,R,n) = corrected p value {based on height z)
% spm_P_RF(1,k,u,df,STAT,R,n) = corrected p value {based on extent k at u)
% spm_P_RF(c,k,u,df,STAT,R,n) = corrected p value {based on number c at k and u)
% spm_P_RF(c,0,u,df,STAT,R,n) = omnibus p value {based on number c at u)
%
% If n > 1 a conjunction probility over the n values of the statistic
% is returned
%__________________________________________________________________________
%
% References:
%
% [1] Hasofer AM (1978) Upcrossings of random fields
% Suppl Adv Appl Prob 10:14-21
% [2] Friston KJ et al (1994) Assessing the Significance of Focal Activations
% Using Their Spatial Extent
% Human Brain Mapping 1:210-220
% [3] Worsley KJ et al (1996) A Unified Statistical Approach for Determining
% Significant Signals in Images of Cerebral Activation
% Human Brain Mapping 4:58-73
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_P_RF.m 4225 2011-03-02 15:53:05Z guillaume $
% get expectations
%==========================================================================
% get EC densities
%--------------------------------------------------------------------------
D = find(R,1,'last');
R = R(1:D);
G = sqrt(pi)./gamma(([1:D])/2);
EC = spm_ECdensity(STAT,Z,df);
EC = max(EC(1:D),eps);
% corrected p value
%--------------------------------------------------------------------------
P = triu(toeplitz(EC'.*G))^n;
P = P(1,:);
EM = (R./G).*P; % <maxima> over D dimensions
Ec = sum(EM); % <maxima>
EN = P(1)*R(D); % <resels>
Ek = EN/EM(D); % Ek = EN/EM(D);
% get P{n > k}
%==========================================================================
% assume a Gaussian form for P{n > k} ~ exp(-beta*k^(2/D))
% Appropriate for SPM{Z} and high d.f. SPM{T}
%--------------------------------------------------------------------------
D = D - 1;
if ~k || ~D
p = 1;
elseif STAT == 'Z'
beta = (gamma(D/2 + 1)/Ek)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'T'
beta = (gamma(D/2 + 1)/Ek)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'X'
beta = (gamma(D/2 + 1)/Ek)^(2/D);
p = exp(-beta*(k^(2/D)));
elseif STAT == 'F'
beta = (gamma(D/2 + 1)/Ek)^(2/D);
p = exp(-beta*(k^(2/D)));
end
% Poisson clumping heuristic {for multiple clusters}
%==========================================================================
P = 1 - spm_Pcdf(c - 1,(Ec + eps)*p);
% set P and p = [] for non-implemented cases
%++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if k > 0 && (STAT == 'X' || STAT == 'F')
P = []; p = [];
end
%++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
%==========================================================================
% spm_ECdensity
%==========================================================================
function [EC] = spm_ECdensity(STAT,t,df)
% Returns the EC density
%__________________________________________________________________________
%
% Reference : Worsley KJ et al 1996, Hum Brain Mapp. 4:58-73
%
%--------------------------------------------------------------------------
% EC densities (EC}
%--------------------------------------------------------------------------
t = t(:)';
if STAT == 'Z'
% Gaussian Field
%----------------------------------------------------------------------
a = 4*log(2);
b = exp(-t.^2/2);
EC(1,:) = 1 - spm_Ncdf(t);
EC(2,:) = a^(1/2)/(2*pi)*b;
EC(3,:) = a/((2*pi)^(3/2))*b.*t;
EC(4,:) = a^(3/2)/((2*pi)^2)*b.*(t.^2 - 1);
elseif STAT == 'T'
% T - Field
%----------------------------------------------------------------------
v = df(2);
a = 4*log(2);
b = exp(gammaln((v+1)/2) - gammaln(v/2));
c = (1+t.^2/v).^((1-v)/2);
EC(1,:) = 1 - spm_Tcdf(t,v);
EC(2,:) = a^(1/2)/(2*pi)*c;
EC(3,:) = a/((2*pi)^(3/2))*c.*t/((v/2)^(1/2))*b;
EC(4,:) = a^(3/2)/((2*pi)^2)*c.*((v-1)*(t.^2)/v - 1);
elseif STAT == 'X'
% X - Field
%----------------------------------------------------------------------
v = df(2);
a = (4*log(2))/(2*pi);
b = t.^(1/2*(v - 1)).*exp(-t/2-gammaln(v/2))/2^((v-2)/2);
EC(1,:) = 1 - spm_Xcdf(t,v);
EC(2,:) = a^(1/2)*b;
EC(3,:) = a*b.*(t-(v-1));
EC(4,:) = a^(3/2)*b.*(t.^2-(2*v-1)*t+(v-1)*(v-2));
elseif STAT == 'F'
% F Field
%----------------------------------------------------------------------
k = df(1);
v = df(2);
a = (4*log(2))/(2*pi);
b = gammaln(v/2) + gammaln(k/2);
EC(1,:) = 1 - spm_Fcdf(t,df);
EC(2,:) = a^(1/2)*exp(gammaln((v+k-1)/2)-b)*2^(1/2)...
*(k*t/v).^(1/2*(k-1)).*(1+k*t/v).^(-1/2*(v+k-2));
EC(3,:) = a*exp(gammaln((v+k-2)/2)-b)*(k*t/v).^(1/2*(k-2))...
.*(1+k*t/v).^(-1/2*(v+k-2)).*((v-1)*k*t/v-(k-1));
EC(4,:) = a^(3/2)*exp(gammaln((v+k-3)/2)-b)...
*2^(-1/2)*(k*t/v).^(1/2*(k-3)).*(1+k*t/v).^(-1/2*(v+k-2))...
.*((v-1)*(v-2)*(k*t/v).^2-(2*v*k-v-k-1)*(k*t/v)+(k-1)*(k-2));
end
|
github
|
philippboehmsturm/antx-master
|
spm_dicom_headers.m
|
.m
|
antx-master/xspm8/spm_dicom_headers.m
| 20,594 |
utf_8
|
1383d5701aed00742ecf464bb28923b6
|
function hdr = spm_dicom_headers(P, essentials)
% Read header information from DICOM files
% FORMAT hdr = spm_dicom_headers(P [,essentials])
% P - array of filenames
% essentials - if true, then only save the essential parts of the header
% hdr - cell array of headers, one element for each file.
%
% Contents of headers are approximately explained in:
% http://medical.nema.org/dicom/2001.html
%
% This code will not work for all cases of DICOM data, as DICOM is an
% extremely complicated "standard".
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_dicom_headers.m 4334 2011-05-31 16:39:53Z john $
if nargin<2, essentials = false; end
dict = readdict;
j = 0;
hdr = {};
if size(P,1)>1, spm_progress_bar('Init',size(P,1),'Reading DICOM headers','Files complete'); end;
for i=1:size(P,1),
tmp = readdicomfile(P(i,:),dict);
if ~isempty(tmp),
if essentials, tmp = spm_dicom_essentials(tmp); end
j = j + 1;
hdr{j} = tmp;
end;
if size(P,1)>1, spm_progress_bar('Set',i); end;
end;
if size(P,1)>1, spm_progress_bar('Clear'); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ret = readdicomfile(P,dict)
ret = [];
P = deblank(P);
fp = fopen(P,'r','ieee-le');
if fp==-1, warning(['Cant open "' P '".']); return; end;
fseek(fp,128,'bof');
dcm = char(fread(fp,4,'uint8')');
if ~strcmp(dcm,'DICM'),
% Try truncated DICOM file fomat
fseek(fp,0,'bof');
tag.group = fread(fp,1,'ushort');
tag.element = fread(fp,1,'ushort');
if isempty(tag.group) || isempty(tag.element),
fclose(fp);
warning('Truncated file "%s"',P);
return;
end;
%t = dict.tags(tag.group+1,tag.element+1);
if isempty(find(dict.group==tag.group & dict.element==tag.element,1)) && ~(tag.group==8 && tag.element==0),
% entry not found in DICOM dict and not from a GE Twin+excite
% that starts with with an 8/0 tag that I can't find any
% documentation for.
fclose(fp);
warning(['"' P '" is not a DICOM file.']);
return;
else
fseek(fp,0,'bof');
end;
end;
try
ret = read_dicom(fp, 'il',dict);
ret.Filename = fopen(fp);
catch
fprintf('Trouble reading DICOM file %s, skipping.\n', fopen(fp));
l = lasterror;
disp(l.message);
end
fclose(fp);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [ret,len] = read_dicom(fp, flg, dict,lim)
if nargin<4, lim=Inf; end;
%if lim==2^32-1, lim=Inf; end;
len = 0;
ret = [];
tag = read_tag(fp,flg,dict);
while ~isempty(tag) && ~(tag.group==65534 && tag.element==57357), % && tag.length==0),
%fprintf('%.4x/%.4x %d\n', tag.group, tag.element, tag.length);
if tag.length>0,
switch tag.name,
case {'GroupLength'},
% Ignore it
fseek(fp,tag.length,'cof');
case {'PixelData'},
ret.StartOfPixelData = ftell(fp);
ret.SizeOfPixelData = tag.length;
ret.VROfPixelData = tag.vr;
fseek(fp,tag.length,'cof');
case {'CSAData'}, % raw data
ret.StartOfCSAData = ftell(fp);
ret.SizeOfCSAData = tag.length;
fseek(fp,tag.length,'cof');
case {'CSAImageHeaderInfo', 'CSASeriesHeaderInfo','Private_0029_1110','Private_0029_1120','Private_0029_1210','Private_0029_1220'},
dat = decode_csa(fp,tag.length);
ret.(tag.name) = dat;
case {'TransferSyntaxUID'},
dat = char(fread(fp,tag.length,'uint8')');
dat = deblank(dat);
ret.(tag.name) = dat;
switch dat,
case {'1.2.840.10008.1.2'}, % Implicit VR Little Endian
flg = 'il';
case {'1.2.840.10008.1.2.1'}, % Explicit VR Little Endian
flg = 'el';
case {'1.2.840.10008.1.2.1.99'}, % Deflated Explicit VR Little Endian
warning(['Cant read Deflated Explicit VR Little Endian file "' fopen(fp) '".']);
flg = 'dl';
return;
case {'1.2.840.10008.1.2.2'}, % Explicit VR Big Endian
%warning(['Cant read Explicit VR Big Endian file "' fopen(fp) '".']);
flg = 'eb'; % Unused
case {'1.2.840.10008.1.2.4.50','1.2.840.10008.1.2.4.51','1.2.840.10008.1.2.4.70',...
'1.2.840.10008.1.2.4.80','1.2.840.10008.1.2.4.90','1.2.840.10008.1.2.4.91'}, % JPEG Explicit VR
flg = 'el';
%warning(['Cant read JPEG Encoded file "' fopen(fp) '".']);
otherwise,
flg = 'el';
warning(['Unknown Transfer Syntax UID for "' fopen(fp) '".']);
return;
end;
otherwise,
switch tag.vr,
case {'UN'},
% Unknown - read as char
dat = fread(fp,tag.length,'uint8')';
case {'AE', 'AS', 'CS', 'DA', 'DS', 'DT', 'IS', 'LO', 'LT',...
'PN', 'SH', 'ST', 'TM', 'UI', 'UT'},
% Character strings
dat = char(fread(fp,tag.length,'uint8')');
switch tag.vr,
case {'UI','ST'},
dat = deblank(dat);
case {'DS'},
try
dat = textscan(dat,'%f','delimiter','\\')';
dat = dat{1};
catch
dat = textscan(dat,'%f','delimiter','/')';
dat = dat{1};
end
case {'IS'},
dat = textscan(dat,'%d','delimiter','\\')';
dat = double(dat{1});
case {'DA'},
dat = strrep(dat,'.',' ');
dat = textscan(dat,'%4d%2d%2d');
[y,m,d] = deal(dat{:});
dat = datenum(double(y),double(m),double(d));
case {'TM'},
if any(dat==':'),
dat = textscan(dat,'%d:%d:%f');
[h,m,s] = deal(dat{:});
h = double(h);
m = double(m);
else
dat = textscan(dat,'%2d%2d%f');
[h,m,s] = deal(dat{:});
h = double(h);
m = double(m);
end
if isempty(h), h = 0; end;
if isempty(m), m = 0; end;
if isempty(s), s = 0; end;
dat = s+60*(m+60*h);
case {'LO'},
dat = uscore_subst(dat);
otherwise,
end;
case {'OB'},
% dont know if this should be signed or unsigned
dat = fread(fp,tag.length,'uint8')';
case {'US', 'AT', 'OW'},
dat = fread(fp,tag.length/2,'uint16')';
case {'SS'},
dat = fread(fp,tag.length/2,'int16')';
case {'UL'},
dat = fread(fp,tag.length/4,'uint32')';
case {'SL'},
dat = fread(fp,tag.length/4,'int32')';
case {'FL'},
dat = fread(fp,tag.length/4,'float')';
case {'FD'},
dat = fread(fp,tag.length/8,'double')';
case {'SQ'},
[dat,len1] = read_sq(fp, flg,dict,tag.length);
tag.length = len1;
otherwise,
dat = '';
if tag.length
fseek(fp,tag.length,'cof');
warning(['Unknown VR [' num2str(tag.vr+0) '] in "'...
fopen(fp) '" (offset=' num2str(ftell(fp)) ').']);
end
end;
if ~isempty(tag.name),
ret.(tag.name) = dat;
end;
end;
end;
len = len + tag.le + tag.length;
if len>=lim, return; end;
tag = read_tag(fp,flg,dict);
end;
if ~isempty(tag),
len = len + tag.le;
% I can't find this bit in the DICOM standard, but it seems to
% be needed for Philips Integra
if tag.group==65534 && tag.element==57357 && tag.length~=0,
fseek(fp,-4,'cof');
len = len-4;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [ret,len] = read_sq(fp, flg, dict,lim)
ret = {};
n = 0;
len = 0;
while len<lim,
tag.group = fread(fp,1,'ushort');
tag.element = fread(fp,1,'ushort');
tag.length = fread(fp,1,'uint');
if isempty(tag.length), return; end;
%if tag.length == 2^32-1, % FFFFFFFF
%tag.length = Inf;
%end;
if tag.length==13, tag.length=10; end;
len = len + 8;
if (tag.group == 65534) && (tag.element == 57344), % FFFE/E000
[Item,len1] = read_dicom(fp, flg, dict, tag.length);
len = len + len1;
if ~isempty(Item)
n = n + 1;
ret{n} = Item;
else
end
elseif (tag.group == 65279) && (tag.element == 224), % FEFF/00E0
% Byte-swapped
[fname,perm,fmt] = fopen(fp);
flg1 = flg;
if flg(2)=='b',
flg1(2) = 'l';
else
flg1(2) = 'b';
end;
[Item,len1] = read_dicom(fp, flg1, dict, tag.length);
len = len + len1;
n = n + 1;
ret{n} = Item;
pos = ftell(fp);
fclose(fp);
fp = fopen(fname,perm,fmt);
fseek(fp,pos,'bof');
elseif (tag.group == 65534) && (tag.element == 57565), % FFFE/E0DD
break;
elseif (tag.group == 65279) && (tag.element == 56800), % FEFF/DDE0
% Byte-swapped
break;
else
warning([num2str(tag.group) '/' num2str(tag.element) ' unexpected.']);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function tag = read_tag(fp,flg,dict)
tag.group = fread(fp,1,'ushort');
tag.element = fread(fp,1,'ushort');
if isempty(tag.element), tag=[]; return; end;
if tag.group == 2, flg = 'el'; end;
%t = dict.tags(tag.group+1,tag.element+1);
t = find(dict.group==tag.group & dict.element==tag.element);
if t>0,
tag.name = dict.values(t).name;
tag.vr = dict.values(t).vr{1};
else
% Set tag.name = '' in order to restrict the fields to those
% in the dictionary. With a reduced dictionary, this could
% speed things up considerably.
% tag.name = '';
tag.name = sprintf('Private_%.4x_%.4x',tag.group,tag.element);
tag.vr = 'UN';
end;
if flg(2) == 'b',
[fname,perm,fmt] = fopen(fp);
if strcmp(fmt,'ieee-le') || strcmp(fmt,'ieee-le.l64'),
pos = ftell(fp);
fclose(fp);
fp = fopen(fname,perm,'ieee-be');
fseek(fp,pos,'bof');
end;
end;
if flg(1) =='e',
tag.vr = char(fread(fp,2,'uint8')');
tag.le = 6;
switch tag.vr,
case {'OB','OW','SQ','UN','UT'}
if ~strcmp(tag.vr,'UN') || tag.group~=65534,
fseek(fp,2,0);
end;
tag.length = double(fread(fp,1,'uint'));
tag.le = tag.le + 6;
case {'AE','AS','AT','CS','DA','DS','DT','FD','FL','IS','LO','LT','PN','SH','SL','SS','ST','TM','UI','UL','US'},
tag.length = double(fread(fp,1,'ushort'));
tag.le = tag.le + 2;
case char([0 0])
if (tag.group == 65534) && (tag.element == 57357)
% at least on GE, ItemDeliminationItem does not have a
% VR, but 4 bytes zeroes as length
tag.vr = 'UN';
tag.le = 8;
tag.length = 0;
tmp = fread(fp,1,'ushort');
elseif (tag.group == 65534) && (tag.element == 57565)
% SequenceDelimitationItem - NOT ENTIRELY HAPPY WITH THIS
double(fread(fp,1,'uint'));
tag.vr = 'UN';
tag.length = 0;
tag.le = tag.le + 6;
else
warning('Don''t know how to handle VR of ''\0\0''');
end;
otherwise,
fseek(fp,2,0);
tag.length = double(fread(fp,1,'uint'));
tag.le = tag.le + 6;
end;
else
tag.le = 8;
tag.length = double(fread(fp,1,'uint'));
end;
if isempty(tag.vr) || isempty(tag.length),
tag = [];
return;
end;
if rem(tag.length,2),
if tag.length==4294967295,
tag.length = Inf;
return;
elseif tag.length==13,
% disp(['Whichever manufacturer created "' fopen(fp) '" is taking the p***!']);
% For some bizarre reason, known only to themselves, they confuse lengths of
% 13 with lengths of 10.
tag.length = 10;
else
warning(['Unknown odd numbered Value Length (' sprintf('%x',tag.length) ') in "' fopen(fp) '".']);
tag = [];
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dict = readdict(P)
if nargin<1, P = 'spm_dicom_dict.mat'; end;
try
dict = load(P);
catch
fprintf('\nUnable to load the file "%s".\n', P);
rethrow(lasterror);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dict = readdict_txt
fid = fopen('spm_dicom_dict.txt','rt');
file = textscan(fid,'%s','delimiter','\n','whitespace',''); file = file{1};
fclose(fid);
clear values
i = 0;
for i0=1:length(file),
words = textscan(file{i0},'%s','delimiter','\t'); words = words{1};
if length(words)>=5 && ~strcmp(words{1}(3:4),'xx'),
grp = sscanf(words{1},'%x');
ele = sscanf(words{2},'%x');
if ~isempty(grp) && ~isempty(ele),
i = i + 1;
group(i) = grp;
element(i) = ele;
vr = {};
for j=1:length(words{4})/2,
vr{j} = words{4}(2*(j-1)+1:2*(j-1)+2);
end;
name = words{3};
msk = ~(name>='a' & name<='z') & ~(name>='A' & name<='Z') &...
~(name>='0' & name<='9') & ~(name=='_');
name(msk) = '';
values(i) = struct('name',name,'vr',{vr},'vm',words{5});
end;
end;
end;
tags = sparse(group+1,element+1,1:length(group));
dict = struct('values',values,'tags',tags);
dict = desparsify(dict);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dict = desparsify(dict)
[group,element] = find(dict.tags);
offs = zeros(size(group));
for k=1:length(group),
offs(k) = dict.tags(group(k),element(k));
end;
dict.group(offs) = group-1;
dict.element(offs) = element-1;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = decode_csa(fp,lim)
% Decode shadow information (0029,1010) and (0029,1020)
[fname,perm,fmt] = fopen(fp);
pos = ftell(fp);
if strcmp(fmt,'ieee-be') || strcmp(fmt,'ieee-be.l64'),
fclose(fp);
fp = fopen(fname,perm,'ieee-le');
fseek(fp,pos,'bof');
end;
c = fread(fp,4,'uint8');
fseek(fp,pos,'bof');
if all(c'==[83 86 49 48]), % "SV10"
t = decode_csa2(fp,lim);
else
t = decode_csa1(fp,lim);
end;
if strcmp(fmt,'ieee-be') || strcmp(fmt,'ieee-be.l64'),
fclose(fp);
fp = fopen(fname,perm,fmt);
end;
fseek(fp,pos+lim,'bof');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = decode_csa1(fp,lim)
n = fread(fp,1,'uint32');
if isempty(n) || n>1024 || n <= 0,
fseek(fp,lim-4,'cof');
t = struct('name','JUNK: Don''t know how to read this damned file format');
return;
end;
unused = fread(fp,1,'uint32')'; % Unused "M" or 77 for some reason
tot = 2*4;
for i=1:n,
t(i).name = fread(fp,64,'uint8')';
msk = find(~t(i).name)-1;
if ~isempty(msk),
t(i).name = char(t(i).name(1:msk(1)));
else
t(i).name = char(t(i).name);
end;
t(i).vm = fread(fp,1,'int32')';
t(i).vr = fread(fp,4,'uint8')';
t(i).vr = char(t(i).vr(1:3));
t(i).syngodt = fread(fp,1,'int32')';
t(i).nitems = fread(fp,1,'int32')';
t(i).xx = fread(fp,1,'int32')'; % 77 or 205
tot = tot + 64+4+4+4+4+4;
for j=1:t(i).nitems
% This bit is just wierd
t(i).item(j).xx = fread(fp,4,'int32')'; % [x x 77 x]
len = t(i).item(j).xx(1)-t(1).nitems;
if len<0 || len+tot+4*4>lim,
t(i).item(j).val = '';
tot = tot + 4*4;
break;
end;
t(i).item(j).val = char(fread(fp,len,'uint8')');
fread(fp,4-rem(len,4),'uint8');
tot = tot + 4*4+len+(4-rem(len,4));
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function t = decode_csa2(fp,lim)
unused1 = fread(fp,4,'uint8'); % Unused
unused2 = fread(fp,4,'uint8'); % Unused
n = fread(fp,1,'uint32');
opos = ftell(fp);
if isempty(n) || n>1024 || n < 0,
fseek(fp,lim-4,'cof');
t = struct('name','Don''t know how to read this damned file format');
return;
end;
unused = fread(fp,1,'uint32')'; % Unused "M" or 77 for some reason
pos = 16;
for i=1:n,
t(i).name = fread(fp,64,'uint8')';
pos = pos + 64;
msk = find(~t(i).name)-1;
if ~isempty(msk),
t(i).name = char(t(i).name(1:msk(1)));
else
t(i).name = char(t(i).name);
end;
t(i).vm = fread(fp,1,'int32')';
t(i).vr = fread(fp,4,'uint8')';
t(i).vr = char(t(i).vr(1:3));
t(i).syngodt = fread(fp,1,'int32')';
t(i).nitems = fread(fp,1,'int32')';
t(i).xx = fread(fp,1,'int32')'; % 77 or 205
pos = pos + 20;
for j=1:t(i).nitems
t(i).item(j).xx = fread(fp,4,'int32')'; % [x x 77 x]
pos = pos + 16;
len = t(i).item(j).xx(2);
if len>lim-pos,
len = lim-pos;
t(i).item(j).val = char(fread(fp,len,'uint8')');
fread(fp,rem(4-rem(len,4),4),'uint8');
warning('Problem reading Siemens CSA field');
return;
end
t(i).item(j).val = char(fread(fp,len,'uint8')');
fread(fp,rem(4-rem(len,4),4),'uint8');
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function str_out = uscore_subst(str_in)
str_out = str_in;
pos = strfind(str_in,'+AF8-');
if ~isempty(pos),
str_out(pos) = '_';
str_out(repmat(pos,4,1)+repmat((1:4)',1,numel(pos))) = [];
end
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_mesh_spherify.m
|
.m
|
antx-master/xspm8/spm_eeg_inv_mesh_spherify.m
| 5,338 |
utf_8
|
95d0130b96a9bec003e301440cfd4caa
|
function [pnt, tri] = spm_eeg_inv_mesh_spherify(pnt, tri, varargin)
% Takes a cortical mesh and scales it so that it fits into a
% unit sphere.
%
% This function determines the points of the original mesh that support a
% convex hull and determines the radius of those points. Subsequently the
% radius of the support points is interpolated onto all vertices of the
% original mesh, and the vertices of the original mesh are scaled by
% dividing them by this interpolated radius.
%
% Use as
% [pnt, tri] = mesh_spherify(pnt, tri, ...)
%
% Optional arguments should come as key-value pairs and may include
% shift = 'no', mean', 'range'
% smooth = number (default = 20)
% Copyright (C) 2008, Robert Oostenveld
%
% $Log: mesh_spherify.m,v $
% Revision 1.1 2008/12/18 16:14:08 roboos
% new implementation
%
% $Id: spm_eeg_inv_mesh_spherify.m 2696 2009-02-05 20:29:48Z guillaume $
global fb
if isempty(fb)
fb = false;
end
shift = keyval('shift', varargin);
smooth = keyval('smooth', varargin);
% set the concentration factor
if ~isempty(smooth)
k = smooth;
else
k = 100;
end
% the following code is for debugging
if fb
figure
[sphere_pnt, sphere_tri] = icosahedron162;
y = vonmisesfischer(5, [0 0 1], sphere_pnt);
triplot(sphere_pnt, sphere_tri, y);
end
npnt = size(pnt, 1);
ntri = size(tri, 1);
switch shift
case 'mean'
pnt(:,1) = pnt(:,1) - mean(pnt(:,1));
pnt(:,2) = pnt(:,2) - mean(pnt(:,2));
pnt(:,3) = pnt(:,3) - mean(pnt(:,3));
case 'range'
minx = min(pnt(:,1));
miny = min(pnt(:,2));
minz = min(pnt(:,3));
maxx = max(pnt(:,1));
maxy = max(pnt(:,2));
maxz = max(pnt(:,3));
pnt(:,1) = pnt(:,1) - mean([minx maxx]);
pnt(:,2) = pnt(:,2) - mean([miny maxy]);
pnt(:,3) = pnt(:,3) - mean([minz maxz]);
otherwise
% do nothing
end
% determine the convex hull, especially to determine the support points
tric = convhulln(pnt);
sel = unique(tric(:));
% create a triangulation for only the support points
support_pnt = pnt(sel,:);
support_tri = convhulln(support_pnt);
if fb
figure
triplot(support_pnt, support_tri, [], 'faces_skin');
triplot(pnt, tri, [], 'faces_skin');
alpha 0.5
end
% determine the radius and thereby scaling factor for the support points
support_scale = zeros(length(sel),1);
for i=1:length(sel)
support_scale(i) = norm(support_pnt(i,:));
end
% interpolate the scaling factor for the support points to all points
scale = zeros(npnt,1);
for i=1:npnt
u = pnt(i,:);
y = vonmisesfischer(k, u, support_pnt);
y = y ./ sum(y);
scale(i) = y' * support_scale;
end
% apply the interpolated scaling to all points
pnt(:,1) = pnt(:,1) ./ scale;
pnt(:,2) = pnt(:,2) ./ scale;
pnt(:,3) = pnt(:,3) ./ scale;
% downscale the points further to make sure that nothing sticks out
n = zeros(npnt,1);
for i = 1:npnt
n(i) = norm(pnt(i, :));
end
mscale = (1-eps) / max(n);
pnt = mscale * pnt;
if fb
figure
[sphere_pnt, sphere_tri] = icosahedron162;
triplot(sphere_pnt, sphere_tri, [], 'faces_skin');
triplot(pnt, tri, [], 'faces_skin');
alpha 0.5
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% VONMISESFISCHER probability distribution
%
% Use as
% y = vonmisesfischer(k, u, x)
% where
% k = concentration parameter
% u = mean direction
% x = direction of the points on the sphere
%
% The von Mises?Fisher distribution is a probability distribution on the
% (p?1) dimensional sphere in Rp. If p=2 the distribution reduces to the
% von Mises distribution on the circle. The distribution belongs to the
% field of directional statistics.
%
% This implementation is based on
% http://en.wikipedia.org/wiki/Von_Mises-Fisher_distribution
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = vonmisesfischer(k, u, x)
% the data describes N points in P-dimensional space
[n, p] = size(x);
% ensure that the direction vectors are unit length
u = u ./ norm(u);
for i=1:n
x(i,:) = x(i,:) ./ norm(x(i,:));
end
% FIXME this normalisation is wrong
% but it is not yet needed, so the problem is acceptable for now
% Cpk = (k^((p/2)-1)) ./ ( (2*pi)^(p/2) * besseli(p/2-1, k));
Cpk = 1;
y = exp(k * u * x') ./ Cpk;
y = y(:);
function [val] = keyval(key, varargin);
% KEYVAL returns the value that corresponds to the requested key in a
% key-value pair list of variable input arguments
%
% Use as
% [val] = keyval(key, varargin)
%
% See also VARARGIN
% Copyright (C) 2005-2007, Robert Oostenveld
%
% $Log: keyval.m,v $
% Revision 1.1 2008/11/13 09:55:36 roboos
% moved from fieldtrip/private, fileio or from roboos/misc to new location at fieldtrip/public
%
% Revision 1.2 2007/07/18 12:43:53 roboos
% test for an even number of optional input arguments
%
% Revision 1.1 2005/11/04 10:24:46 roboos
% new implementation
%
if length(varargin)==1 && iscell(varargin{1})
varargin = varargin{1};
end
if mod(length(varargin),2)
error('optional input arguments should come in key-value pairs, i.e. there should be an even number');
end
keys = varargin(1:2:end);
vals = varargin(2:2:end);
hit = find(strcmp(key, keys));
if length(hit)==0
% the requested key was not found
val = [];
elseif length(hit)==1
% the requested key was found
val = vals{hit};
else
error('multiple input arguments with the same name');
end
|
github
|
philippboehmsturm/antx-master
|
spm_image.m
|
.m
|
antx-master/xspm8/spm_image.m
| 20,761 |
utf_8
|
a7e827e9560894219b55572753d8dde4
|
function spm_image(action,varargin)
% Image and header display
% FORMAT spm_image
%__________________________________________________________________________
%
% spm_image is an interactive facility that allows orthogonal sections
% from an image volume to be displayed. Clicking the cursor on either
% of the three images moves the point around which the orthogonal
% sections are viewed. The co-ordinates of the cursor are shown both
% in voxel co-ordinates and millimeters within some fixed framework.
% The intensity at that point in the image (sampled using the current
% interpolation scheme) is also given. The position of the crosshairs
% can also be moved by specifying the co-ordinates in millimeters to
% which they should be moved. Clicking on the horizontal bar above
% these boxes will move the cursor back to the origin (analogous to
% setting the crosshair position (in mm) to [0 0 0]).
%
% The images can be re-oriented by entering appropriate translations,
% rotations and zooms into the panel on the left. The transformations
% can then be saved by hitting the "Reorient images..." button. The
% transformations that were applied to the image are saved to the header
% information of the selected images. The transformations are considered
% to be relative to any existing transformations that may be stored.
% Note that the order that the transformations are applied in is the
% same as in spm_matrix.m.
%
% The ``Reset...'' button next to it is for setting the orientation of
% images back to transverse. It retains the current voxel sizes,
% but sets the origin of the images to be the centre of the volumes
% and all rotations back to zero.
%
% The right panel shows miscellaneous information about the image.
% This includes:
% Dimensions - the x, y and z dimensions of the image.
% Datatype - the computer representation of each voxel.
% Intensity - scalefactors and possibly a DC offset.
% Miscellaneous other information about the image.
% Vox size - the distance (in mm) between the centres of
% neighbouring voxels.
% Origin - the voxel at the origin of the co-ordinate system
% Dir Cos - Direction cosines. This is a widely used
% representation of the orientation of an image.
%
% There are also a few options for different resampling modes, zooms
% etc. You can also flip between voxel space or world space. If you
% are re-orienting the images, make sure that world space is specified.
% Blobs (from activation studies) can be superimposed on the images and
% the intensity windowing can also be changed.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_image.m 4205 2011-02-21 15:39:08Z guillaume $
global st
if ~nargin, action = 'Init'; end
if ~any(strcmpi(action,{'init','reset'})) && ...
(isempty(st) || ~isfield(st,'vols') || isempty(st.vols{1}))
spm_image('Reset');
warning('Lost all the image information');
return;
end
switch lower(action)
case {'init','display'}
% Display image
%----------------------------------------------------------------------
if isempty(varargin)
[P, sts] = spm_select(1,'image','Select image');
if ~sts, return; end
else
P = varargin{1};
end
if ischar(P), P = spm_vol(P); end
P = P(1);
init_display(P);
case 'repos'
% The widgets for translation rotation or zooms have been modified
%----------------------------------------------------------------------
trz = varargin{1};
try, st.B(trz) = eval(get(gco,'String')); end
set(gco,'String',st.B(trz));
st.vols{1}.premul = spm_matrix(st.B);
% spm_orthviews('MaxBB');
spm_image('Zoom');
spm_image('Update');
case 'shopos'
% The position of the crosshairs has been moved
%----------------------------------------------------------------------
if isfield(st,'mp')
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.mp)
set(st.mp,'String',sprintf('%.1f %.1f %.1f',spm_orthviews('Pos')));
pos = spm_orthviews('Pos',1);
set(st.vp,'String',sprintf('%.1f %.1f %.1f',pos));
set(st.in,'String',sprintf('%g',spm_sample_vol(st.vols{1},pos(1),pos(2),pos(3),st.hld)));
else
st.Callback = ';';
st = rmfield(st,{'mp','vp','in'});
end
else
st.Callback = ';';
end
case 'setposmm'
% Move the crosshairs to the specified position {mm}
%----------------------------------------------------------------------
if isfield(st,'mp')
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.mp)
pos = sscanf(get(st.mp,'String'), '%g %g %g');
if length(pos)~=3
pos = spm_orthviews('Pos');
end
spm_orthviews('Reposition',pos);
end
end
case 'setposvx'
% Move the crosshairs to the specified position {vx}
%----------------------------------------------------------------------
if isfield(st,'mp')
fg = spm_figure('Findwin','Graphics');
if any(findobj(fg) == st.vp)
pos = sscanf(get(st.vp,'String'), '%g %g %g');
if length(pos)~=3
pos = spm_orthviews('pos',1);
end
tmp = st.vols{1}.premul*st.vols{1}.mat;
pos = tmp(1:3,:)*[pos ; 1];
spm_orthviews('Reposition',pos);
end
end
case 'addblobs'
% Add blobs to the image - in full colour
%----------------------------------------------------------------------
spm_figure('Clear','Interactive');
nblobs = spm_input('Number of sets of blobs',1,'1|2|3|4|5|6',[1 2 3 4 5 6],1);
for i=1:nblobs
[SPM,xSPM] = spm_getSPM;
c = spm_input('Colour','+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
spm_orthviews('AddColouredBlobs',1,xSPM.XYZ,xSPM.Z,xSPM.M,colours(c,:));
set(st.blobber,'String','Remove Blobs','Callback','spm_image(''RemoveBlobs'');');
end
spm_orthviews('AddContext',1);
spm_orthviews('Redraw');
case {'removeblobs','rmblobs'}
% Remove all blobs from the images
%----------------------------------------------------------------------
spm_orthviews('RemoveBlobs',1);
set(st.blobber,'String','Add Blobs','Callback','spm_image(''AddBlobs'');');
spm_orthviews('RemoveContext',1);
spm_orthviews('Redraw');
case 'window'
% Window
%----------------------------------------------------------------------
op = get(st.win,'Value');
if op == 1
spm_orthviews('Window',1); % automatic
else
spm_orthviews('Window',1,spm_input('Range','+1','e','',2));
end
case 'reorient'
% Reorient images
%----------------------------------------------------------------------
mat = spm_matrix(st.B);
if det(mat)<=0
spm('alert!','This will flip the images',mfilename,0,1);
end
[P, sts] = spm_select([1 Inf], 'image','Images to reorient');
if ~sts, return; else P = cellstr(P); end
Mats = zeros(4,4,numel(P));
spm_progress_bar('Init',numel(P),'Reading current orientations',...
'Images Complete');
for i=1:numel(P)
Mats(:,:,i) = spm_get_space(P{i});
spm_progress_bar('Set',i);
end
spm_progress_bar('Init',numel(P),'Reorienting images',...
'Images Complete');
for i=1:numel(P)
spm_get_space(P{i},mat*Mats(:,:,i));
spm_progress_bar('Set',i);
end
spm_progress_bar('Clear');
tmp = spm_get_space([st.vols{1}.fname ',' num2str(st.vols{1}.n)]);
if sum((tmp(:)-st.vols{1}.mat(:)).^2) > 1e-8
spm_image('Init',st.vols{1}.fname);
end
case 'resetorient'
% Reset orientation of images
%----------------------------------------------------------------------
[P,sts] = spm_select([1 Inf], 'image','Images to reset orientation of');
if ~sts, return; else P = cellstr(P); end
spm_progress_bar('Init',numel(P),'Resetting orientations',...
'Images Complete');
for i=1:numel(P)
V = spm_vol(P{i});
M = V.mat;
vox = sqrt(sum(M(1:3,1:3).^2));
if det(M(1:3,1:3))<0, vox(1) = -vox(1); end
orig = (V.dim(1:3)+1)/2;
off = -vox.*orig;
M = [vox(1) 0 0 off(1)
0 vox(2) 0 off(2)
0 0 vox(3) off(3)
0 0 0 1];
spm_get_space(P{i},M);
spm_progress_bar('Set',i);
end
spm_progress_bar('Clear');
tmp = spm_get_space([st.vols{1}.fname ',' num2str(st.vols{1}.n)]);
if sum((tmp(:)-st.vols{1}.mat(:)).^2) > 1e-8
spm_image('Init',st.vols{1}.fname);
end
case 'update'
% Modify the positional information in the right hand panel
%----------------------------------------------------------------------
mat = st.vols{1}.premul*st.vols{1}.mat;
Z = spm_imatrix(mat);
Z = Z(7:9);
set(st.posinf.z,'String', sprintf('%.3g x %.3g x %.3g', Z));
O = mat\[0 0 0 1]'; O=O(1:3)';
set(st.posinf.o, 'String', sprintf('%.3g %.3g %.3g', O));
R = spm_imatrix(mat);
R = spm_matrix([0 0 0 R(4:6)]);
R = R(1:3,1:3);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(1,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m1, 'String', tmp2);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(2,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m2, 'String', tmp2);
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(3,1:3)); tmp2(tmp2=='+') = ' ';
set(st.posinf.m3, 'String', tmp2);
tmp = [[R zeros(3,1)] ; 0 0 0 1]*diag([Z 1])*spm_matrix(-O) - mat;
if sum(tmp(:).^2)>1e-5
set(st.posinf.w, 'String', 'Warning: shears involved');
else
set(st.posinf.w, 'String', '');
end
case 'zoom'
% Zoom in
%----------------------------------------------------------------------
[zl rl] = spm_orthviews('ZoomMenu');
% Values are listed in reverse order
cz = numel(zl)-get(st.zoomer,'Value')+1;
spm_orthviews('Zoom',zl(cz),rl(cz));
case 'reset'
% Reset
%----------------------------------------------------------------------
spm_orthviews('Reset');
spm_figure('Clear','Graphics');
end
%==========================================================================
function init_display(P)
global st
fg = spm_figure('GetWin','Graphics');
spm_image('Reset');
spm_orthviews('Image', P, [0.0 0.45 1 0.55]);
if isempty(st.vols{1}), return; end
spm_orthviews('MaxBB');
st.callback = 'spm_image(''shopos'');';
st.B = [0 0 0 0 0 0 1 1 1 0 0 0];
% Widgets for re-orienting images.
%--------------------------------------------------------------------------
WS = spm('WinScale');
uicontrol(fg,'Style','Frame','Position',[60 25 200 325].*WS,'DeleteFcn','spm_image(''reset'');');
uicontrol(fg,'Style','Text', 'Position',[75 220 100 016].*WS,'String','right {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 200 100 016].*WS,'String','forward {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 180 100 016].*WS,'String','up {mm}');
uicontrol(fg,'Style','Text', 'Position',[75 160 100 016].*WS,'String','pitch {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 140 100 016].*WS,'String','roll {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 120 100 016].*WS,'String','yaw {rad}');
uicontrol(fg,'Style','Text', 'Position',[75 100 100 016].*WS,'String','resize {x}');
uicontrol(fg,'Style','Text', 'Position',[75 80 100 016].*WS,'String','resize {y}');
uicontrol(fg,'Style','Text', 'Position',[75 60 100 016].*WS,'String','resize {z}');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',1)','Position',[175 220 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',2)','Position',[175 200 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',3)','Position',[175 180 065 020].*WS,'String','0','ToolTipString','translate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',4)','Position',[175 160 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',5)','Position',[175 140 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',6)','Position',[175 120 065 020].*WS,'String','0','ToolTipString','rotate');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',7)','Position',[175 100 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',8)','Position',[175 80 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','edit','Callback','spm_image(''repos'',9)','Position',[175 60 065 020].*WS,'String','1','ToolTipString','zoom');
uicontrol(fg,'Style','Pushbutton','String','Reorient images...','Callback','spm_image(''reorient'')',...
'Position',[70 35 125 020].*WS,'ToolTipString','modify position information of selected images');
uicontrol(fg,'Style','Pushbutton','String','Reset...','Callback','spm_image(''resetorient'')',...
'Position',[195 35 55 020].*WS,'ToolTipString','reset orientations of selected images');
% Crosshair position
%--------------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[70 250 180 90].*WS);
uicontrol(fg,'Style','Text', 'Position',[75 320 170 016].*WS,'String','Crosshair Position');
uicontrol(fg,'Style','PushButton', 'Position',[75 316 170 006].*WS,...
'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');
% uicontrol(fg,'Style','PushButton', 'Position',[75 315 170 020].*WS,'String','Crosshair Position',...
% 'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin');
uicontrol(fg,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:');
uicontrol(fg,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:');
uicontrol(fg,'Style','Text', 'Position',[75 255 65 020].*WS,'String','Intensity:');
st.mp = uicontrol(fg,'Style','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates');
st.vp = uicontrol(fg,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates');
st.in = uicontrol(fg,'Style','Text', 'Position',[140 255 85 020].*WS,'String','');
% General information
%--------------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[305 25 280 325].*WS);
uicontrol(fg,'Style','Text','Position' ,[310 330 50 016].*WS,...
'HorizontalAlignment','right', 'String', 'File:');
uicontrol(fg,'Style','Text','Position' ,[360 330 210 016].*WS,...
'HorizontalAlignment','left', 'String', spm_str_manip(st.vols{1}.fname,'k25'),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 310 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Dimensions:');
uicontrol(fg,'Style','Text','Position' ,[410 310 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%d x %d x %d', st.vols{1}.dim(1:3)),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 290 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Datatype:');
uicontrol(fg,'Style','Text','Position' ,[410 290 160 016].*WS,...
'HorizontalAlignment','left', 'String', spm_type(st.vols{1}.dt(1)),'FontWeight','bold');
uicontrol(fg,'Style','Text','Position' ,[310 270 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Intensity:');
str = 'varied';
if size(st.vols{1}.pinfo,2) == 1
if st.vols{1}.pinfo(2)
str = sprintf('Y = %g X + %g', st.vols{1}.pinfo(1:2)');
else
str = sprintf('Y = %g X', st.vols{1}.pinfo(1)');
end
end
uicontrol(fg,'Style','Text','Position' ,[410 270 160 016].*WS,...
'HorizontalAlignment','left', 'String', str,'FontWeight','bold');
if isfield(st.vols{1}, 'descrip')
uicontrol(fg,'Style','Text','Position' ,[310 250 260 016].*WS,...
'HorizontalAlignment','center', 'String', st.vols{1}.descrip,'FontWeight','bold');
end
% Positional information
%--------------------------------------------------------------------------
mat = st.vols{1}.premul*st.vols{1}.mat;
Z = spm_imatrix(mat);
Z = Z(7:9);
uicontrol(fg,'Style','Text','Position' ,[310 210 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Vox size:');
st.posinf = struct('z',uicontrol(fg,'Style','Text','Position' ,[410 210 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%.3g x %.3g x %.3g', Z),'FontWeight','bold'));
O = mat\[0 0 0 1]'; O=O(1:3)';
uicontrol(fg,'Style','Text','Position' ,[310 190 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Origin:');
st.posinf.o = uicontrol(fg,'Style','Text','Position' ,[410 190 160 016].*WS,...
'HorizontalAlignment','left', 'String', sprintf('%.3g %.3g %.3g', O),'FontWeight','bold');
R = spm_imatrix(mat);
R = spm_matrix([0 0 0 R(4:6)]);
R = R(1:3,1:3);
uicontrol(fg,'Style','Text','Position' ,[310 170 100 016].*WS,...
'HorizontalAlignment','right', 'String', 'Dir Cos:');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(1,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m1 = uicontrol(fg,'Style','Text','Position' ,[410 170 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(2,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m2 = uicontrol(fg,'Style','Text','Position' ,[410 150 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp2 = sprintf('%+5.3f %+5.3f %+5.3f', R(3,1:3)); tmp2(tmp2=='+') = ' ';
st.posinf.m3 = uicontrol(fg,'Style','Text','Position' ,[410 130 160 016].*WS,...
'HorizontalAlignment','left', 'String', tmp2,'FontWeight','bold');
tmp = [[R zeros(3,1)] ; 0 0 0 1]*diag([Z 1])*spm_matrix(-O) - mat;
st.posinf.w = uicontrol(fg,'Style','Text','Position' ,[310 110 260 016].*WS,...
'HorizontalAlignment','center', 'String', '','FontWeight','bold');
if sum(tmp(:).^2)>1e-8
set(st.posinf.w, 'String', 'Warning: shears involved');
end
% Assorted other buttons
%--------------------------------------------------------------------------
uicontrol(fg,'Style','Frame','Position',[310 30 270 70].*WS);
zl = spm_orthviews('ZoomMenu');
czlabel = cell(size(zl));
% List zoom steps in reverse order
zl = zl(end:-1:1);
for cz = 1:numel(zl)
if isinf(zl(cz))
czlabel{cz} = 'Full Volume';
elseif isnan(zl(cz))
czlabel{cz} = 'BBox (Y > ...)';
elseif zl(cz) == 0
czlabel{cz} = 'BBox (nonzero)';
else
czlabel{cz} = sprintf('%dx%dx%dmm', 2*zl(cz), 2*zl(cz), 2*zl(cz));
end
end
st.zoomer = uicontrol(fg,'Style','popupmenu' ,'Position',[315 75 125 20].*WS,...
'String',czlabel,...
'Callback','spm_image(''zoom'')','ToolTipString','zoom in by different amounts');
c = 'if get(gco,''Value'')==1, spm_orthviews(''Space''), else, spm_orthviews(''Space'', 1);end;spm_image(''zoom'')';
uicontrol(fg,'Style','popupmenu' ,'Position',[315 55 125 20].*WS,...
'String',char('World Space','Voxel Space'),...
'Callback',c,'ToolTipString','display in aquired/world orientation');
c = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;';
uicontrol(fg,'Style','togglebutton','Position',[450 75 125 20].*WS,...
'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs');
uicontrol(fg,'Style','popupmenu' ,'Position',[450 55 125 20].*WS,...
'String',char('NN interp','bilin interp','sinc interp'),...
'Callback','tmp_ = [0 1 -4];spm_orthviews(''Interp'',tmp_(get(gco,''Value'')))',...
'Value',2,'ToolTipString','interpolation method for displaying images');
st.win = uicontrol(fg,'Style','popupmenu','Position',[315 35 125 20].*WS,...
'String',char('Auto Window','Manual Window'),'Callback','spm_image(''window'');','ToolTipString','range of voxel intensities displayed');
% uicontrol(fg,'Style','pushbutton','Position',[315 35 125 20].*WS,...
% 'String','Window','Callback','spm_image(''window'');','ToolTipString','range of voxel intensities % displayed');
st.blobber = uicontrol(fg,'Style','pushbutton','Position',[450 35 125 20].*WS,...
'String','Add Blobs','Callback','spm_image(''addblobs'');','ToolTipString','superimpose activations');
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_montage_ui.m
|
.m
|
antx-master/xspm8/spm_eeg_montage_ui.m
| 7,209 |
utf_8
|
81b00840683562c05ad7e333633cbfb5
|
function montage = spm_eeg_montage_ui(montage)
% GUI for EEG montage (rereference EEG data to new reference channel(s))
% FORMAT montage = spm_eeg_montage_ui(montage)
%
% montage - structure with fields:
% tra - MxN matrix
% labelnew - Mx1 cell-array - new labels
% labelorg - Nx1 cell-array - original labels
%
% Output is empty if the GUI is closed.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_montage_ui.m 3674 2010-01-12 18:25:05Z jean $
error(nargchk(1,1,nargin));
% Create the figure
%--------------------------------------------------------------------------
fig = figure;
S0 = spm('WinSize','0',1);
pos = get(fig,'position');
pos2 = [40 70 pos(3)-60 pos(4)-100];
pos = [S0(1) S0(2) 0 0] + [pos(1) pos(2) 1.8*pos(3) pos(4)];
set(gcf,...
'menubar', 'none',...
'position', pos,...
'numbertitle', 'off',...
'name', 'Montage edition');
addButtons(fig);
% Display the uitable component
%--------------------------------------------------------------------------
table = cat(2,montage.labelnew(:),num2cell(montage.tra));
colnames = cat(2,'channel labels',montage.labelorg(:)');
pause(1e-1) % This is weird, but fixes java troubles.
[ht,hc] = spm_uitable(table,colnames);
set(ht,'position',pos2, 'units','normalized');
% Display the matrix representation of the montage
%--------------------------------------------------------------------------
ax = axes('position',[0.6 0.18 0.4 0.77]);
hi = imagesc(montage.tra,'parent',ax);
axis('image');
colormap('bone');
zoom(fig,'on');
% Store info in figure's userdata and wait for user interaction
%--------------------------------------------------------------------------
ud.hi = hi;
ud.ht = ht;
ud.montage = montage;
set(fig,'userdata',ud);
uiwait(fig);
% Get the montage from the GUI
%--------------------------------------------------------------------------
try
ud = get(fig,'userdata');
montage = ud.montage;
close(fig);
catch % GUI was closed without 'OK' button
montage = [];
end
%==========================================================================
function doAddRow(obj,evd,h)
%==========================================================================
% 'add row' button subfunction
ud = get(h,'userdata');
[M,newLabels] = getM(ud.ht);
M = [M;zeros(1,size(M,2))];
newLabels = cat(1,newLabels(:),num2str(size(M,1)));
set(ud.ht,'units','pixels');
pos = get(ud.ht,'Position');
delete(ud.ht);
table = cat(2,newLabels,num2cell(M));
colnames = cat(2,'channel labels',ud.montage.labelorg(:)');
pause(1) % This is weird, but fixes java troubles.
ht = spm_uitable(table,colnames);
set(ht,'position',pos,...
'units','normalized');
ud.ht = ht;
set(h,'userdata',ud);
doCheck(obj,evd,h);
%==========================================================================
function doLoad(obj,evd,h)
%==========================================================================
% 'load' button subfunction
[t,sts] = spm_select(1,'mat','Load montage file');
if sts
montage = load(t);
if ismember('montage', fieldnames(montage))
montage = montage.montage;
ud = get(h,'userdata');
set(ud.ht,'units','pixels');
pos = get(ud.ht,'Position');
delete(ud.ht);
table = cat(2,montage.labelnew(:),num2cell(montage.tra));
colnames = cat(2,'channel labels',montage.labelorg(:)');
pause(1) % This is weird, but fixes java troubles.
ht = spm_uitable(table,colnames);
set(ht,'position',pos,...
'units','normalized');
ud.ht = ht;
ud.montage = montage;
set(h,'userdata',ud);
pause(1)
doCheck(obj,evd,h);
else
spm('alert!','File did not contain any montage!','Montage edition');
end
end
%==========================================================================
function doSave(obj,evd,h)
%==========================================================================
% 'save as' button subfunction
doCheck(obj,evd,h);
ud = get(h,'userdata');
[M,newLabels] = getM(ud.ht);
% delete row if empty:
ind = ~any(M,2);
M(ind,:) = [];
newLabels(ind) = [];
montage.tra = M;
montage.labelorg = ud.montage.labelorg;
montage.labelnew = newLabels;
uisave('montage','SPMeeg_montage.mat');
%==========================================================================
function doOK(obj,evd,h)
%==========================================================================
% 'OK' button subfunction
doCheck(obj,evd,h);
ud = get(h,'userdata');
[M, newLabels] = getM(ud.ht);
% delete row if empty:
ind = ~any(M,2);
M(ind,:) = [];
newLabels(ind) = [];
montage.tra = M;
montage.labelorg = ud.montage.labelorg(:);
montage.labelnew = newLabels(:);
ud.montage = montage;
set(h,'userdata',ud);
uiresume(h);
%==========================================================================
function doCheck(obj,evd,h)
%==========================================================================
% Update the montage display
ud = get(h,'userdata');
M = getM(ud.ht);
set(ud.hi,'cdata',M);
set(gca,'xlim',[0.5 size(M,1)]);
set(gca,'ylim',[0.5 size(M,2)]);
axis('image');
drawnow;
%==========================================================================
function [M,newLabels] = getM(ht)
%==========================================================================
% extracting montage from java object
nnew = get(ht,'NumRows');
nold = get(ht,'NumColumns')-1;
M = zeros(nnew,nold);
data = get(ht,'data');
for i =1:nnew
if ~isempty(data(i,1))
newLabels{i} = data(i,1);
else
newLabels{i} = [];
end
for j =1:nold
if ~isempty(data(i,j+1))
if ~ischar(data(i,j+1))
M(i,j) = data(i,j+1);
else
M0 = str2double(data(i,j+1));
if ~isempty(M0)
M(i,j) = M0;
else
M(i,j) = 0;
end
end
else
M(i,j) = 0;
end
end
end
%==========================================================================
function addButtons(h)
%==========================================================================
% adding buttons to the montage GUI
hAdd = uicontrol('style','pushbutton',...
'string','Add row','callback',{@doAddRow,h},...
'position',[60 20 80 20]);
set(hAdd,'units','normalized');
hLoad = uicontrol('style','pushbutton',...
'string','Load file','callback',{@doLoad,h},...
'position',[180 20 80 20]);
set(hLoad,'units','normalized');
hSave = uicontrol('style','pushbutton',...
'string','Save as','callback',{@doSave,h},...
'position',[280 20 80 20]);
set(hSave,'units','normalized');
hOK = uicontrol('style','pushbutton',...
'string',' OK ','callback',{@doOK,h},...
'position',[400 20 80 20]);
set(hOK,'units','normalized');
hCheck = uicontrol('style','pushbutton',...
'string',' Refresh display ','callback',{@doCheck,h},...
'position',[760 20 120 20]);
set(hCheck,'units','normalized');
|
github
|
philippboehmsturm/antx-master
|
spm_interp.m
|
.m
|
antx-master/xspm8/spm_interp.m
| 1,111 |
utf_8
|
5f0170891b0600c4824810d278725d9f
|
function [x] = spm_interp(x,r)
% 1 or 2-D array interpolation
% FORMAT [x] = spm_interp(x,r)
% x - array
% r - interpolation rate
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_interp.m 3733 2010-02-18 17:43:18Z karl $
% interpolate
%---------------------------------------------------------------------------
[n m] = size(x);
if n > 1 && m > 1 % matrix
X = zeros(r*n,m);
for i = 1:m
X(:,i) = interpolate(x(:,i),r);
end
x = zeros(r*n,r*m);
for i = 1:r*n
x(i,:) = interpolate(X(i,:),r)';
end
elseif n == 1 % row vector
x = interpolate(x',r)';
elseif m == 1 % column vector
x = interpolate(x,r);
end
% Interpolate using DCT
% -------------------------------------------------------------------------
function [u] = interpolate(y,r)
if r == 1;
u = y;
else
y = y(:);
n = size(y,1);
Dy = spm_dctmtx(r*n,n);
Du = spm_dctmtx(n,n);
Dy = Dy*sqrt(r);
u = Dy*(Du'*y);
end
|
github
|
philippboehmsturm/antx-master
|
spm_transverse.m
|
.m
|
antx-master/xspm8/spm_transverse.m
| 15,678 |
utf_8
|
22c28b8cda464e1764eee552402294ab
|
function spm_transverse(varargin)
% Rendering of regional effects [SPM{T/F}] on transverse sections
% FORMAT spm_transverse('set',SPM,hReg)
% FORMAT spm_transverse('setcoords',xyzmm)
% FORMAT spm_transverse('clear')
%
% SPM - structure containing SPM, distribution & filtering details
% about the excursion set (xSPM)
% - required fields are:
% .Z - minimum of n Statistics {filtered on u and k}
% .STAT - distribution {Z, T, X or F}
% .u - height threshold
% .XYZ - location of voxels {voxel coords}
% .iM - mm -> voxels matrix
% .VOX - voxel dimensions {mm}
% .DIM - image dimensions {voxels}
%
% hReg - handle of MIP XYZ registry object (see spm_XYZreg for details)
%
% spm_transverse automatically updates its co-ordinates from the
% registry, but clicking on the slices has no effect on the registry.
% i.e., the updating is one way only.
%
% See also: spm_getSPM
%__________________________________________________________________________
%
% spm_transverse is called by the SPM results section and uses
% variables in SPM and SPM to create three transverse sections though a
% background image. Regional foci from the selected SPM{T/F} are
% rendered on this image.
%
% Although the SPM{.} adopts the neurological convention (left = left)
% the rendered images follow the same convention as the original data.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston & John Ashburner
% $Id: spm_transverse.m 3348 2009-09-03 10:32:01Z guillaume $
switch lower(varargin{1})
case 'set'
% draw slices
%----------------------------------------------------------------------
init(varargin{2},varargin{3});
case 'setcoords'
% reposition
%----------------------------------------------------------------------
disp('Reposition');
case 'clear'
% clear
%----------------------------------------------------------------------
clear_global;
end
return;
%==========================================================================
% function init(SPM,hReg)
%==========================================================================
function init(SPM,hReg)
%-Get figure handles
%--------------------------------------------------------------------------
Fgraph = spm_figure('GetWin','Graphics');
%-Get the image on which to render
%--------------------------------------------------------------------------
spms = spm_select(1,'image','Select image for rendering on');
spm('Pointer','Watch');
%-Delete previous axis and their pagination controls (if any)
%--------------------------------------------------------------------------
spm_results_ui('Clear',Fgraph);
global transv
transv = struct('blob',[],'V',spm_vol(spms),'h',[],'hReg',hReg,'fig',Fgraph);
transv.blob = struct('xyz', round(SPM.XYZ), 't',SPM.Z, 'dim',SPM.DIM(1:3),...
'iM',SPM.iM,...
'vox', sqrt(sum(SPM.M(1:3,1:3).^2)), 'u', SPM.u);
%-Get current location and convert to pixel co-ordinates
%--------------------------------------------------------------------------
xyzmm = spm_XYZreg('GetCoords',transv.hReg);
xyz = round(transv.blob.iM(1:3,:)*[xyzmm; 1]);
try
units = SPM.units;
catch
units = {'mm' 'mm' 'mm'};
end
%-Extract data from SPM [at one plane separation] and get background slices
%--------------------------------------------------------------------------
dim = ceil(transv.blob.dim(1:3)'.*transv.blob.vox);
A = transv.blob.iM*transv.V.mat;
hld = 0;
zoomM = inv(spm_matrix([0 0 -1 0 0 0 transv.blob.vox([1 2]) 1]));
zoomM1 = spm_matrix([0 0 0 0 0 0 transv.blob.vox([1 2]) 1]);
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)) < 0.5);
T2 = full(sparse(transv.blob.xyz(1,Q),transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T2 = spm_slice_vol(T2,zoomM,dim([1 2]),[hld NaN]);
Q = find(T2==0) ; T2(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3);0 0 0 1]*A;
D2 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([max(D2(:)) eps]);
minD = min([min(D2(:)) eps]);
if transv.blob.dim(3) > 1
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)+1) < 0.5);
T1 = full(sparse(transv.blob.xyz(1,Q),...
transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T1 = spm_slice_vol(T1,zoomM,dim([1 2]),[hld NaN]);
Q = find(T1==0) ; T1(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)+1;0 0 0 1]*A;
D1 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([maxD ; D1(:)]);
minD = min([minD ; D1(:)]);
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)-1) < 0.5);
T3 = full(sparse(transv.blob.xyz(1,Q),...
transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T3 = spm_slice_vol(T3,zoomM,dim([1 2]),[hld NaN]);
Q = find(T3==0) ; T3(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)-1;0 0 0 1]*A;
D3 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([maxD ; D3(:)]);
minD = min([minD ; D3(:)]);
end
mx = max([max(T2(:)) eps]);
mn = min([min(T2(:)) 0]);
D2 = (D2-minD)/(maxD-minD);
if transv.blob.dim(3) > 1,
D1 = (D1-minD)/(maxD-minD);
D3 = (D3-minD)/(maxD-minD);
mx = max([mx ; T1(:) ; T3(:) ; eps]);
mn = min([mn ; T1(:) ; T3(:) ; 0]);
end;
%-Configure {128 level} colormap
%--------------------------------------------------------------------------
cmap = get(Fgraph,'Colormap');
if size(cmap,1) ~= 128
figure(Fgraph)
spm_figure('Colormap','gray-hot')
cmap = get(Fgraph,'Colormap');
end
D = length(cmap)/2;
Q = find(T2(:) > transv.blob.u); T2 = (T2(Q)-mn)/(mx-mn); D2(Q) = 1+1.51/D + T2; T2 = D*D2;
if transv.blob.dim(3) > 1
Q = find(T1(:) > transv.blob.u); T1 = (T1(Q)-mn)/(mx-mn); D1(Q) = 1+1.51/D + T1; T1 = D*D1;
Q = find(T3(:) > transv.blob.u); T3 = (T3(Q)-mn)/(mx-mn); D3(Q) = 1+1.51/D + T3; T3 = D*D3;
end
set(Fgraph,'Units','pixels')
siz = get(Fgraph,'Position');
siz = siz(3:4);
P = xyz.*transv.blob.vox';
%-Render activation foci on background images
%--------------------------------------------------------------------------
if transv.blob.dim(3) > 1
zm = min([(siz(1) - 120)/(dim(1)*3),(siz(2)/2 - 60)/dim(2)]);
xo = (siz(1)-(dim(1)*zm*3)-120)/2;
yo = (siz(2)/2 - dim(2)*zm - 60)/2;
transv.h(1) = axes('Units','pixels','Parent',Fgraph,'Position',[20+xo 20+yo dim(1)*zm dim(2)*zm]);
transv.h(2) = image(rot90(spm_grid(T1)),'Parent',transv.h(1));
axis image; axis off;
tmp = SPM.iM\[xyz(1:2)' (xyz(3)-1) 1]';
ax=transv.h(1);tpoint=get(ax,'title');
str=sprintf('z = %0.0f%s',tmp(3),units{3});
set(tpoint,'string',str);
transv.h(3) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(1));
transv.h(4) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(1));
transv.h(5) = axes('Units','pixels','Parent',Fgraph,'Position',[40+dim(1)*zm+xo 20+yo dim(1)*zm dim(2)*zm]);
transv.h(6) = image(rot90(spm_grid(T2)),'Parent',transv.h(5));
axis image; axis off;
tmp = SPM.iM\[xyz(1:2)' xyz(3) 1]';
ax=transv.h(5);tpoint=get(ax,'title');
str=sprintf('z = %0.0f%s',tmp(3),units{3});
set(tpoint,'string',str);
transv.h(7) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(5));
transv.h(8) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(5));
transv.h(9) = axes('Units','pixels','Parent',Fgraph,'Position',[60+dim(1)*zm*2+xo 20+yo dim(1)*zm dim(2)*zm]);
transv.h(10) = image(rot90(spm_grid(T3)),'Parent',transv.h(9));
axis image; axis off;
tmp = SPM.iM\[xyz(1:2)' (xyz(3)+1) 1]';
ax=transv.h(9);tpoint=get(ax,'title');
str=sprintf('z = %0.0f%s',tmp(3),units{3});
set(tpoint,'string',str);
transv.h(11) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(9));
transv.h(12) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(9));
% colorbar
%----------------------------------------------------------------------
q = [80+dim(1)*zm*3+xo 20+yo 20 dim(2)*zm];
if SPM.STAT=='P'
str='Effect size';
else
str=[SPM.STAT ' value'];
end
transv.h(13) = axes('Units','pixels','Parent',Fgraph,'Position',q,'Visible','off');
transv.h(14) = image([0 mx/32],[mn mx],(1:D)' + D,'Parent',transv.h(13));
ax=transv.h(13);
tpoint=get(ax,'title');
set(tpoint,'string',str);
set(tpoint,'FontSize',9);
%title(ax,str,'FontSize',9);
set(ax,'XTickLabel',[]);
axis(ax,'xy');
else
zm = min([(siz(1) - 80)/dim(1),(siz(2)/2 - 60)/dim(2)]);
xo = (siz(1)-(dim(1)*zm)-80)/2;
yo = (siz(2)/2 - dim(2)*zm - 60)/2;
transv.h(1) = axes('Units','pixels','Parent',Fgraph,'Position',[20+xo 20+yo dim(1)*zm dim(2)*zm]);
transv.h(2) = image(rot90(spm_grid(T2)),'Parent',transv.h(1));
axis image; axis off;
title(sprintf('z = %0.0f%s',xyzmm(3),units{3}));
transv.h(3) = line([1 1]*P(1),[0 dim(2)],'Color','w','Parent',transv.h(1));
transv.h(4) = line([0 dim(1)],[1 1]*(dim(2)-P(2)+1),'Color','w','Parent',transv.h(1));
% colorbar
%----------------------------------------------------------------------
q = [40+dim(1)*zm+xo 20+yo 20 dim(2)*zm];
transv.h(5) = axes('Units','pixels','Parent',Fgraph,'Position',q,'Visible','off');
transv.h(6) = image([0 mx/32],[mn mx],(1:D)' + D,'Parent',transv.h(5));
if SPM.STAT=='P'
str='Effect size';
else
str=[SPM.STAT ' value'];
end
title(str,'FontSize',9);
set(gca,'XTickLabel',[]);
axis xy;
end
spm_XYZreg('Add2Reg',transv.hReg,transv.h(1), 'spm_transverse');
for h=transv.h,
set(h,'DeleteFcn',@clear_global);
end
%-Reset pointer
%--------------------------------------------------------------------------
spm('Pointer','Arrow')
return;
%==========================================================================
% function reposition(xyzmm)
%==========================================================================
function reposition(xyzmm)
global transv
if ~isstruct(transv), return; end;
spm('Pointer','Watch');
%-Get current location and convert to pixel co-ordinates
%--------------------------------------------------------------------------
% xyzmm = spm_XYZreg('GetCoords',transv.hReg)
xyz = round(transv.blob.iM(1:3,:)*[xyzmm; 1]);
% extract data from SPM [at one plane separation]
% and get background slices
%--------------------------------------------------------------------------
dim = ceil(transv.blob.dim(1:3)'.*transv.blob.vox);
A = transv.blob.iM*transv.V.mat;
hld = 0;
zoomM = inv(spm_matrix([0 0 -1 0 0 0 transv.blob.vox([1 2]) 1]));
zoomM1 = spm_matrix([0 0 0 0 0 0 transv.blob.vox([1 2]) 1]);
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)) < 0.5);
T2 = full(sparse(transv.blob.xyz(1,Q),transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T2 = spm_slice_vol(T2,zoomM,dim([1 2]),[hld NaN]);
Q = find(T2==0) ; T2(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3);0 0 0 1]*A;
D2 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([max(D2(:)) eps]);
minD = min([min(D2(:)) 0]);
if transv.blob.dim(3) > 1
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)+1) < 0.5);
T1 = full(sparse(transv.blob.xyz(1,Q),...
transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T1 = spm_slice_vol(T1,zoomM,dim([1 2]),[hld NaN]);
Q = find(T1==0) ; T1(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)+1;0 0 0 1]*A;
D1 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([maxD ; D1(:)]);
minD = min([minD ; D1(:)]);
Q = find(abs(transv.blob.xyz(3,:) - xyz(3)-1) < 0.5);
T3 = full(sparse(transv.blob.xyz(1,Q),...
transv.blob.xyz(2,Q),transv.blob.t(Q),transv.blob.dim(1),transv.blob.dim(2)));
T3 = spm_slice_vol(T3,zoomM,dim([1 2]),[hld NaN]);
Q = find(T3==0) ; T3(Q) = NaN;
D = zoomM1*[1 0 0 0;0 1 0 0;0 0 1 -xyz(3)-1;0 0 0 1]*A;
D3 = spm_slice_vol(transv.V,inv(D),dim([1 2]),1);
maxD = max([maxD ; D3(:)]);
minD = min([minD ; D3(:)]);
end
mx = max([max(T2(:)) eps]);
mn = min([min(T2(:)) 0]);
D2 = (D2-minD)/(maxD-minD);
if transv.blob.dim(3) > 1,
D1 = (D1-minD)/(maxD-minD);
D3 = (D3-minD)/(maxD-minD);
mx = max([mx ; T1(:) ; T3(:) ; eps]);
mn = min([mn ; T1(:) ; T3(:) ; 0]);
end;
%-Configure {128 level} colormap
%--------------------------------------------------------------------------
cmap = get(transv.fig,'Colormap');
if size(cmap,1) ~= 128
figure(transv.fig)
spm_figure('Colormap','gray-hot')
cmap = get(transv.fig,'Colormap');
end
D = length(cmap)/2;
Q = find(T2(:) > transv.blob.u); T2 = (T2(Q)-mn)/(mx-mn); D2(Q) = 1+1.51/D + T2; T2 = D*D2;
if transv.blob.dim(3) > 1
Q = find(T1(:) > transv.blob.u); T1 = (T1(Q)-mn)/(mx-mn); D1(Q) = 1+1.51/D + T1; T1 = D*D1;
Q = find(T3(:) > transv.blob.u); T3 = (T3(Q)-mn)/(mx-mn); D3(Q) = 1+1.51/D + T3; T3 = D*D3;
end
P = xyz.*transv.blob.vox';
%-Render activation foci on background images
%--------------------------------------------------------------------------
if transv.blob.dim(3) > 1
set(transv.h(2),'Cdata',rot90(spm_grid(T1)));
tmp = transv.blob.iM\[xyz(1:2)' (xyz(3)-1) 1]';
set(get(transv.h(1),'Title'),'String',sprintf('z = %0.0fmm',tmp(3)));
set(transv.h(3),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);
set(transv.h(4),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));
set(transv.h(6),'Cdata',rot90(spm_grid(T2)));
set(get(transv.h(5),'Title'),'String',sprintf('z = %0.0fmm',xyzmm(3)));
set(transv.h(7),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);
set(transv.h(8),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));
set(transv.h(10),'Cdata',rot90(spm_grid(T3)));
tmp = transv.blob.iM\[xyz(1:2)' (xyz(3)+1) 1]';
set(get(transv.h(9),'Title'),'String',sprintf('z = %0.0fmm',tmp(3)));
set(transv.h(11),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);
set(transv.h(12),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));
% colorbar
%----------------------------------------------------------------------
set(transv.h(14), 'Ydata',[mn mx], 'Cdata',(1:D)' + D);
set(transv.h(13),'XTickLabel',[],'Ylim',[mn mx]);
else
set(transv.h(2),'Cdata',rot90(spm_grid(T2)));
set(get(transv.h(1),'Title'),'String',sprintf('z = %0.0fmm',xyzmm(3)));
set(transv.h(3),'Xdata',[1 1]*P(1),'Ydata',[0 dim(2)]);
set(transv.h(4),'Xdata',[0 dim(1)],'Ydata',[1 1]*(dim(2)-P(2)+1));
% colorbar
%----------------------------------------------------------------------
set(transv.h(6), 'Ydata',[0 d], 'Cdata',(1:D)' + D);
set(transv.h(5),'XTickLabel',[],'Ylim',[0 d]);
end
%-Reset pointer
%--------------------------------------------------------------------------
spm('Pointer','Arrow')
return;
%==========================================================================
% function clear_global(varargin)
%==========================================================================
function clear_global(varargin)
global transv
if isstruct(transv),
for h = transv.h,
if ishandle(h), set(h,'DeleteFcn',''); end;
end
for h = transv.h,
if ishandle(h), delete(h); end;
end
transv = [];
clear global transv;
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_prep.m
|
.m
|
antx-master/xspm8/spm_eeg_prep.m
| 17,655 |
utf_8
|
d0182fc86adc8bc7eba089ae3f0dab97
|
function D = spm_eeg_prep(S)
% Prepare converted M/EEG data for further analysis
% FORMAT D = spm_eeg_prep(S)
% S - configuration structure (optional)
% (optional) fields of S:
% S.D - MEEG object or filename of M/EEG mat-file
% S.task - action string. One of 'settype', 'defaulttype',
% 'loadtemplate','setcoor2d', 'project3d', 'loadeegsens',
% 'defaulteegsens', 'sens2chan', 'headshape', 'coregister'.
% S.updatehistory - update history information [default: true]
% S.save - save MEEG object [default: false]
%
% D - MEEG object
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_eeg_prep.m 4808 2012-07-27 15:13:39Z vladimir $
if ~nargin
spm_eeg_prep_ui;
return;
end
D = spm_eeg_load(S.D);
switch lower(S.task)
%----------------------------------------------------------------------
case 'settype'
%----------------------------------------------------------------------
D = chantype(D, S.ind, S.type);
%----------------------------------------------------------------------
case 'defaulttype'
%----------------------------------------------------------------------
if isfield(S, 'ind')
ind = S.ind;
else
ind = 1:D.nchannels;
end
dictionary = {
'eog', 'EOG';
'eeg', 'EEG';
'ecg', 'ECG';
'lfp', 'LFP';
'emg', 'EMG';
'meg', 'MEG';
'ref', 'REF';
'megmag', 'MEGMAG';
'megplanar', 'MEGPLANAR';
'meggrad', 'MEGGRAD';
'refmag', 'REFMAG';
'refgrad', 'REFGRAD'
};
D = chantype(D, ind, 'Other');
type = ft_chantype(D.chanlabels);
% If there is useful information in the original types it
% overwrites the default assignment
if isfield(D, 'origchantypes')
[sel1, sel2] = spm_match_str(chanlabels(D, ind), D.origchantypes.label);
type(ind(sel1)) = D.origchantypes.type(sel2);
end
spmtype = repmat({'Other'}, 1, length(ind));
[sel1, sel2] = spm_match_str(type(ind), dictionary(:, 1));
spmtype(sel1) = dictionary(sel2, 2);
D = chantype(D, ind, spmtype);
%----------------------------------------------------------------------
case {'loadtemplate', 'setcoor2d', 'project3d'}
%----------------------------------------------------------------------
switch lower(S.task)
case 'loadtemplate'
template = load(S.P); % must contain Cpos, Cnames
xy = template.Cpos;
label = template.Cnames;
case 'setcoor2d'
xy = S.xy;
label = S.label;
case 'project3d'
if ~isfield(D, 'val')
D.val = 1;
end
if isfield(D, 'inv') && isfield(D.inv{D.val}, 'datareg')
datareg = D.inv{D.val}.datareg;
ind = strmatch(S.modality, {datareg(:).modality}, 'exact');
sens = datareg(ind).sensors;
else
sens = D.sensors(S.modality);
end
[xy, label] = spm_eeg_project3D(sens, S.modality);
end
[sel1, sel2] = spm_match_str(lower(D.chanlabels), lower(label));
if ~isempty(sel1)
megind = D.meegchannels('MEG');
eegind = D.meegchannels('EEG');
if ~isempty(intersect(megind, sel1)) && ~isempty(setdiff(megind, sel1))
error('2D locations not found for all MEG channels');
end
if ~isempty(intersect(eegind, sel1)) && ~isempty(setdiff(eegind, sel1))
warning(['2D locations not found for all EEG channels, changing type of channels', ...
num2str(setdiff(eegind, sel1)) ' to ''Other''']);
D = chantype(D, setdiff(eegind, sel1), 'Other');
end
D = coor2D(D, sel1, num2cell(xy(:, sel2)));
end
%----------------------------------------------------------------------
case 'loadeegsens'
%----------------------------------------------------------------------
switch S.source
case 'mat'
senspos = load(S.sensfile);
name = fieldnames(senspos);
senspos = getfield(senspos,name{1});
label = chanlabels(D, sort(strmatch('EEG', D.chantype, 'exact')));
if size(senspos, 1) ~= length(label)
error('To read sensor positions without labels the numbers of sensors and EEG channels should match.');
end
elec = [];
elec.chanpos = senspos;
elec.elecpos = senspos;
elec.label = label;
headshape = load(S.headshapefile);
name = fieldnames(headshape);
headshape = getfield(headshape,name{1});
shape = [];
fidnum = 0;
while ~all(isspace(S.fidlabel))
fidnum = fidnum+1;
[shape.fid.label{fidnum} S.fidlabel] = strtok(S.fidlabel);
end
if (fidnum < 3) || (size(headshape, 1) < fidnum)
error('At least 3 labeled fiducials are necessary');
end
shape.fid.pnt = headshape(1:fidnum, :);
if size(headshape, 1) > fidnum
shape.pnt = headshape((fidnum+1):end, :);
else
shape.pnt = [];
end
case 'locfile'
label = chanlabels(D, D.meegchannels('EEG'));
elec = ft_read_sens(S.sensfile);
% Remove headshape points
hspind = strmatch('headshape', elec.label);
elec.chanpos(hspind, :) = [];
elec.elecpos(hspind, :) = [];
elec.label(hspind) = [];
% This handles FIL Polhemus case and other possible cases
% when no proper labels are available.
if isempty(intersect(label, elec.label))
ind = str2num(strvcat(elec.label));
if length(ind) == length(label)
elec.label = label(ind);
else
error('To read sensor positions without labels the numbers of sensors and EEG channels should match.');
end
end
shape = ft_read_headshape(S.sensfile);
% In case electrode file is used for fiducials, the
% electrodes can be used as headshape
if ~isfield(shape, 'pnt') || isempty(shape.pnt) && ...
size(shape.fid.pnt, 1) > 3
shape.pnt = shape.fid.pnt;
end
end
elec = ft_convert_units(elec, 'mm');
shape= ft_convert_units(shape, 'mm');
if isequal(D.modality(1, 0), 'Multimodal')
if ~isempty(D.fiducials) && isfield(S, 'regfid') && ~isempty(S.regfid)
M1 = coreg(D.fiducials, shape, S.regfid);
elec = ft_transform_sens(M1, elec);
else
error(['MEG fiducials matched to EEG fiducials are required '...
'to add EEG sensors to a multimodal dataset.']);
end
else
D = fiducials(D, shape);
end
D = sensors(D, 'EEG', elec);
%----------------------------------------------------------------------
case 'defaulteegsens'
%----------------------------------------------------------------------
template_sfp = dir(fullfile(spm('dir'), 'EEGtemplates', '*.sfp'));
template_sfp = {template_sfp.name};
ind = strmatch([ft_senstype(D.chanlabels(D.meegchannels('EEG'))) '.sfp'], template_sfp, 'exact');
if ~isempty(ind)
fid = D.fiducials;
if isequal(D.modality(1, 0), 'Multimodal') && ~isempty(fid)
nzlbl = {'fidnz', 'nz', 'nas', 'nasion', 'spmnas'};
lelbl = {'fidle', 'fidt9', 'lpa', 'lear', 'earl', 'le', 'l', 't9', 'spmlpa'};
relbl = {'fidre', 'fidt10', 'rpa', 'rear', 'earr', 're', 'r', 't10', 'spmrpa'};
[sel1, nzind] = spm_match_str(nzlbl, lower(fid.fid.label));
if ~isempty(nzind)
nzind = nzind(1);
end
[sel1, leind] = spm_match_str(lelbl, lower(fid.fid.label));
if ~isempty(leind)
leind = leind(1);
end
[sel1, reind] = spm_match_str(relbl, lower(fid.fid.label));
if ~isempty(reind)
reind = reind(1);
end
regfid = fid.fid.label([nzind, leind, reind]);
if numel(regfid) < 3
error('Could not automatically understand the MEG fiducial labels. Please use the GUI.');
else
regfid = [regfid(:) {'spmnas'; 'spmlpa'; 'spmrpa'}];
end
S1 = [];
S1.D = D;
S1.task = 'loadeegsens';
S1.source = 'locfile';
S1.regfid = regfid;
S1.sensfile = fullfile(spm('dir'), 'EEGtemplates', template_sfp{ind});
S1.updatehistory = 0;
D = spm_eeg_prep(S1);
else
elec = ft_read_sens(fullfile(spm('dir'), 'EEGtemplates', template_sfp{ind}));
[sel1, sel2] = spm_match_str(lower(D.chanlabels), lower(elec.label));
sens = elec;
sens.chanpos = sens.chanpos(sel2, :);
sens.elecpos = sens.elecpos(sel2, :);
% This takes care of possible case mismatch
sens.label = D.chanlabels(sel1);
sens.label = sens.label(:);
D = sensors(D, 'EEG', sens);
% Assumes that the first 3 points in standard location files
% are the 3 fiducials (nas, lpa, rpa)
fid = [];
fid.pnt = elec.elecpos;
fid.fid.pnt = elec.elecpos(1:3, :);
fid.fid.label = elec.label(1:3);
[xy, label] = spm_eeg_project3D(D.sensors('EEG'), 'EEG');
[sel1, sel2] = spm_match_str(lower(D.chanlabels), lower(label));
if ~isempty(sel1)
eegind = strmatch('EEG', chantype(D), 'exact');
if ~isempty(intersect(eegind, sel1)) && ~isempty(setdiff(eegind, sel1))
warning(['2D locations not found for all EEG channels, changing type of channels ', ...
num2str(setdiff(eegind(:)', sel1(:)')) ' to ''Other''']);
D = chantype(D, setdiff(eegind, sel1), 'Other');
end
if any(any(coor2D(D, sel1) - xy(:, sel2)))
D = coor2D(D, sel1, num2cell(xy(:, sel2)));
end
end
if ~isempty(D.fiducials) && isfield(S, 'regfid') && ~isempty(S.regfid)
M1 = coreg(D.fiducials, fid, S.regfid);
D = sensors(D, 'EEG', ft_transform_sens(M1, D.sensors('EEG')));
else
D = fiducials(D, fid);
end
end
end
%----------------------------------------------------------------------
case 'sens2chan'
%----------------------------------------------------------------------
montage = S.montage;
eeglabel = D.chanlabels(strmatch('EEG',D.chantype));
meglabel = D.chanlabels(strmatch('MEG',D.chantype));
if ~isempty(intersect(eeglabel, montage.labelnew))
sens = sensors(D, 'EEG');
if isempty(sens)
error('The montage cannod be applied - no EEG sensors specified');
end
sens = ft_apply_montage(sens, montage, 'keepunused', 'no');
D = sensors(D, 'EEG', sens);
elseif ~isempty(intersect(meglabel, montage.labelnew))
sens = sensors(D, 'MEG');
if isempty(sens)
error('The montage cannod be applied - no MEG sensors specified');
end
sens = ft_apply_montage(sens, montage, 'keepunused', 'no');
D = sensors(D, 'MEG', sens);
else
error('The montage cannot be applied to the sensors');
end
%----------------------------------------------------------------------
case 'headshape'
%----------------------------------------------------------------------
switch S.source
case 'mat'
headshape = load(S.headshapefile);
name = fieldnames(headshape);
headshape = getfield(headshape,name{1});
shape = [];
fidnum = 0;
while ~all(isspace(S.fidlabel))
fidnum = fidnum+1;
[shape.fid.label{fidnum} S.fidlabel] = strtok(S.fidlabel);
end
if (fidnum < 3) || (size(headshape, 1) < fidnum)
error('At least 3 labeled fiducials are necessary');
end
shape.fid.pnt = headshape(1:fidnum, :);
if size(headshape, 1) > fidnum
shape.pnt = headshape((fidnum+1):end, :);
else
shape.pnt = [];
end
otherwise
shape = ft_read_headshape(S.headshapefile);
% In case electrode file is used for fiducials, the
% electrodes can be used as headshape
if ~isfield(shape, 'pnt') || isempty(shape.pnt) && ...
size(shape.fid.pnt, 1) > 3
shape.pnt = shape.fid.pnt;
end
end
shape = ft_convert_units(shape, 'mm');
fid = D.fiducials;
if ~isempty(fid) && isfield(S, 'regfid') && ~isempty(S.regfid)
M1 = coreg(fid, shape, S.regfid);
shape = ft_transform_headshape(M1, shape);
end
D = fiducials(D, shape);
%----------------------------------------------------------------------
case 'coregister'
%----------------------------------------------------------------------
[ok, D] = check(D, 'sensfid');
if ~ok
error('Coregistration cannot be performed due to missing data');
end
try
val = D.val;
Msize = D.inv{val}.mesh.Msize;
catch
val = 1;
Msize = 1;
end
D = spm_eeg_inv_mesh_ui(D, val, 1, Msize);
D = spm_eeg_inv_datareg_ui(D, val);
%----------------------------------------------------------------------
otherwise
%----------------------------------------------------------------------
fprintf('Unknown task ''%s'' to perform: Nothing done.\n',S.task);
end
% When prep is called from other functions with history, history should be
% disabled
if ~isfield(S, 'updatehistory') || S.updatehistory
Stemp = S;
Stemp.D = fullfile(D.path,D.fname);
Stemp.save = 1;
D = D.history('spm_eeg_prep', Stemp);
end
if isfield(S, 'save') && S.save
save(D);
end
%==========================================================================
% function coreg
%==========================================================================
function M1 = coreg(fid, shape, regfid)
[junk, sel1] = spm_match_str(regfid(:, 1), fid.fid.label);
[junk, sel2] = spm_match_str(regfid(:, 2), shape.fid.label);
S = [];
S.targetfid = fid;
S.targetfid.fid.pnt = S.targetfid.fid.pnt(sel1, :);
S.sourcefid = shape;
S.sourcefid.fid.pnt = S.sourcefid.fid.pnt(sel2, :);
S.sourcefid.fid.label = S.sourcefid.fid.label(sel2);
S.targetfid.fid.label = S.sourcefid.fid.label;
S.template = 1;
S.useheadshape = 0;
M1 = spm_eeg_inv_datareg(S);
|
github
|
philippboehmsturm/antx-master
|
spm_bias_ui.m
|
.m
|
antx-master/xspm8/spm_bias_ui.m
| 5,624 |
utf_8
|
bf36e864bf3d49ba97e9bc133ecb84c2
|
function spm_bias_ui(P)
% Non-uniformity correct images.
%
% The objective function is related to minimising the entropy of
% the image histogram, but is modified slightly.
% This fixes the problem with the SPM99 non-uniformity correction
% algorithm, which tends to try to reduce the image intensities. As
% the field was constrainded to have an average value of one, then
% this caused the field to bend upwards in regions not included in
% computations of image non-uniformity.
%
%_______________________________________________________________________
% Ref:
% J Ashburner. 2002. "Another MRI Bias Correction Approach" [abstract].
% Presented at the 8th International Conference on Functional Mapping of
% the Human Brain, June 2-6, 2002, Sendai, Japan. Available on CD-Rom
% in NeuroImage, Vol. 16, No. 2.
%
%_______________________________________________________________________
%
% The Prompts Explained
%_______________________________________________________________________
%
% 'Scans to correct' - self explanatory
%
%_______________________________________________________________________
%
% Defaults Options
%_______________________________________________________________________
%[ things in square brackets indicate corresponding defaults field ]
%
% 'Number of histogram bins?'
% The probability density of the image intensity is represented by a
% histogram. The optimum number of bins depends on the number of voxels
% in the image. More voxels allows a more detailed representation.
% Another factor is any potential aliasing effect due to there being a
% discrete number of different intensities in the image. Fewer bins
% should be used in this case.
% [defaults.bias.nbins]
%
% 'Regularisation?'
% The importance of smoothness for the estimated bias field. Without
% any regularisation, the algorithm will attempt to correct for
% different grey levels arising from different tissue types, rather than
% just correcting bias artifact.
% Bias correction uses a Bayesian framework (again) to model intensity
% inhomogeneities in the image(s). The variance associated with each
% tissue class is assumed to be multiplicative (with the
% inhomogeneities). The low frequency intensity variability is
% modelled by a linear combination of three dimensional DCT basis
% functions (again), using a fast algorithm (again) to generate the
% curvature matrix. The regularization is based upon minimizing the
% integral of square of the fourth derivatives of the modulation field
% (the integral of the squares of the first and second derivs give the
% membrane and bending energies respectively).
% [defaults.bias.reg]
%
% 'Cutoff?'
% Cutoff of DCT bases. Only DCT bases of periods longer than the
% cutoff are used to describe the warps. The number used will
% depend on the cutoff and the field of view of the image.
% [defaults.bias.cutoff]
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_bias_ui.m 3756 2010-03-05 18:43:37Z guillaume $
global defaults
if nargin==1 && strcmpi(P,'defaults');
defaults.bias = edit_defaults(defaults.bias);
return;
end;
bias_ui(defaults.bias);
return;
%=======================================================================
%=======================================================================
function bias_ui(flags)
% User interface for nonuniformity correction
spm('FnBanner',mfilename,'$Rev: 3756 $');
[Finter,unused,CmdLine] = spm('FnUIsetup','Flatten');
spm_help('!ContextHelp',mfilename);
PP = spm_select(Inf, 'image', 'Scans to correct');
spm('Pointer','Watch');
for i=1:size(PP,1),
spm('FigName',['Flatten: working on scan ' num2str(i)],Finter,CmdLine);
drawnow;
P = deblank(PP(i,:));
T = spm_bias_estimate(P,flags);
[pth,nm,xt,vr] = spm_fileparts(P);
S = fullfile(pth,['bias_' nm '.mat']);
%S = ['bias_' nm '.mat'];
spm_bias_apply(P,S);
end;
if 0,
fg = spm_figure('FindWin','Interactive');
if ~isempty(fg), spm_figure('Clear',fg); end;
end
spm('FigName','Flatten: done',Finter,CmdLine);
spm('Pointer');
return;
%=======================================================================
%=======================================================================
function flags = edit_defaults(flags)
nb = [32 64 128 256 512 1024 2048];
tmp = find(nb == flags.nbins);
if isempty(tmp), tmp = 6; end;
flags.nbins = spm_input('Number of histogram bins?','+1','m',...
[' 32 bins | 64 bins| 128 bins| 256 bins| 512 bins|1024 bins|2048 bins'],...
nb, tmp);
rg = [0 0.00001 0.0001 0.001 0.01 0.1 1.0 10];
tmp = find(rg == flags.reg);
if isempty(tmp), tmp = 4; end;
flags.reg = spm_input('Regularisation?','+1','m',...
['no regularisation (0)|extremely light regularisation (0.00001)|'...
'very light regularisation (0.0001)|light regularisation (0.001)|',...
'medium regularisation (0.01)|heavy regularisation (0.1)|'...
'very heavy regularisation (1)|extremely heavy regularisation (10)'],...
rg, tmp);
co = [20 25 30 35 40 45 50 60 70 80 90 100];
tmp = find(co == flags.cutoff);
if isempty(tmp), tmp = 4; end;
flags.cutoff = spm_input('Cutoff?','+1','m',...
[' 20mm cutoff| 25mm cutoff| 30mm cutoff| 35mm cutoff| 40mm cutoff|'...
' 45mm cutoff| 50mm cutoff| 60mm cutoff| 70mm cutoff| 80mm cutoff|'...
' 90mm cutoff|100mm cutoff'],...
co, tmp);
return;
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
spm_mesh_render.m
|
.m
|
antx-master/xspm8/spm_mesh_render.m
| 26,531 |
utf_8
|
8b3c350d44240000e9ceec7b0d41cdc9
|
function varargout = spm_mesh_render(action,varargin)
% Display a surface mesh & various utilities
% FORMAT H = spm_mesh_render('Disp',M,'PropertyName',propertyvalue)
% M - a GIfTI filename/object or patch structure
% H - structure containing handles of various objects
% Opens a new figure unless a 'parent' Property is provided with an axis
% handle.
%
% FORMAT H = spm_mesh_render(M)
% Shortcut to previous call format.
%
% FORMAT H = spm_mesh_render('ContextMenu',AX)
% AX - axis handle or structure returned by spm_mesh_render('Disp',...)
%
% FORMAT H = spm_mesh_render('Overlay',AX,P)
% AX - axis handle or structure given by spm_mesh_render('Disp',...)
% P - data to be overlayed on mesh (see spm_mesh_project)
%
% FORMAT H = spm_mesh_render('ColourBar',AX,MODE)
% AX - axis handle or structure returned by spm_mesh_render('Disp',...)
% MODE - {['on'],'off'}
%
% FORMAT H = spm_mesh_render('ColourMap',AX,MAP)
% AX - axis handle or structure returned by spm_mesh_render('Disp',...)
% MAP - a colour map matrix
%
% FORMAT MAP = spm_mesh_render('ColourMap',AX)
% Retrieves the current colourmap.
%
% FORMAT spm_mesh_render('Register',AX,hReg)
% AX - axis handle or structure returned by spm_mesh_render('Disp',...)
% hReg - Handle of HandleGraphics object to build registry in.
% See spm_XYZreg for more information.
%__________________________________________________________________________
% Copyright (C) 2010-2011 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_mesh_render.m 5109 2012-12-11 20:53:42Z guillaume $
%-Input parameters
%--------------------------------------------------------------------------
if ~nargin, action = 'Disp'; end
if ~ischar(action)
varargin = {action varargin{:}};
action = 'Disp';
end
varargout = {[]};
%-Action
%--------------------------------------------------------------------------
switch lower(action)
%-Display
%======================================================================
case 'disp'
if isempty(varargin)
[M, sts] = spm_select(1,'mesh','Select surface mesh file');
if ~sts, return; end
else
M = varargin{1};
end
if ischar(M), M = export(gifti(M),'patch'); end
O = getOptions(varargin{2:end});
%-Figure & Axis
%------------------------------------------------------------------
if isfield(O,'parent')
H.axis = O.parent;
H.figure = ancestor(H.axis,'figure');
figure(H.figure); axes(H.axis);
else
H.figure = figure('Color',[1 1 1]);
H.axis = axes('Parent',H.figure);
set(H.axis,'Visible','off');
end
renderer = get(H.figure,'Renderer');
set(H.figure,'Renderer','OpenGL');
%-Patch
%------------------------------------------------------------------
P = struct('vertices',M.vertices, 'faces',M.faces);
H.patch = patch(P,...
'FaceColor', [0.6 0.6 0.6],...
'EdgeColor', 'none',...
'FaceLighting', 'phong',...
'SpecularStrength', 0.7,...
'AmbientStrength', 0.1,...
'DiffuseStrength', 0.7,...
'SpecularExponent', 10,...
'Clipping', 'off',...
'DeleteFcn', {@myDeleteFcn, renderer},...
'Visible', 'off',...
'Tag', 'SPMMeshRender',...
'Parent', H.axis);
setappdata(H.patch,'patch',P);
%-Label connected components of the mesh
%------------------------------------------------------------------
C = spm_mesh_label(P);
setappdata(H.patch,'cclabel',C);
%-Compute mesh curvature
%------------------------------------------------------------------
curv = spm_mesh_curvature(P) > 0;
setappdata(H.patch,'curvature',curv);
%-Apply texture to mesh
%------------------------------------------------------------------
updateTexture(H,[]);
%-Set viewpoint, light and manipulation options
%------------------------------------------------------------------
axis(H.axis,'image');
axis(H.axis,'off');
view(H.axis,[-90 0]);
material(H.figure,'dull');
H.light = camlight; set(H.light,'Parent',H.axis);
H.rotate3d = rotate3d(H.axis);
set(H.rotate3d,'Enable','on');
set(H.rotate3d,'ActionPostCallback',{@myPostCallback, H});
%try
% setAllowAxesRotate(H.rotate3d, ...
% setxor(findobj(H.figure,'Type','axes'),H.axis), false);
%end
%-Store handles
%------------------------------------------------------------------
setappdata(H.axis,'handles',H);
set(H.patch,'Visible','on');
%-Add context menu
%------------------------------------------------------------------
spm_mesh_render('ContextMenu',H);
%-Context Menu
%======================================================================
case 'contextmenu'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if ~isempty(get(H.patch,'UIContextMenu')), return; end
cmenu = uicontextmenu('Callback',{@myMenuCallback, H});
uimenu(cmenu, 'Label','Inflate', 'Interruptible','off', ...
'Callback',{@myInflate, H});
uimenu(cmenu, 'Label','Overlay...', 'Interruptible','off', ...
'Callback',{@myOverlay, H});
uimenu(cmenu, 'Label','Image Sections...', 'Interruptible','off', ...
'Callback',{@myImageSections, H});
c = uimenu(cmenu, 'Label', 'Connected Components', 'Interruptible','off');
C = getappdata(H.patch,'cclabel');
for i=1:length(unique(C))
uimenu(c, 'Label',sprintf('Component %d',i), 'Checked','on', ...
'Callback',{@myCCLabel, H});
end
uimenu(cmenu, 'Label','Rotate', 'Checked','on', 'Separator','on', ...
'Callback',{@mySwitchRotate, H});
uimenu(cmenu, 'Label','Synchronise Views', 'Visible','off', ...
'Checked','off', 'Tag','SynchroMenu', 'Callback',{@mySynchroniseViews, H});
c = uimenu(cmenu, 'Label','View');
uimenu(c, 'Label','Go to Y-Z view (right)', 'Callback', {@myView, H, [90 0]});
uimenu(c, 'Label','Go to Y-Z view (left)', 'Callback', {@myView, H, [-90 0]});
uimenu(c, 'Label','Go to X-Y view (top)', 'Callback', {@myView, H, [0 90]});
uimenu(c, 'Label','Go to X-Y view (bottom)', 'Callback', {@myView, H, [-180 -90]});
uimenu(c, 'Label','Go to X-Z view (front)', 'Callback', {@myView, H, [-180 0]});
uimenu(c, 'Label','Go to X-Z view (back)', 'Callback', {@myView, H, [0 0]});
uimenu(cmenu, 'Label','Colorbar', 'Callback', {@myColourbar, H});
c = uimenu(cmenu, 'Label','Colormap');
clrmp = {'hot' 'jet' 'gray' 'hsv' 'bone' 'copper' 'pink' 'white' ...
'flag' 'lines' 'colorcube' 'prism' 'cool' 'autumn' ...
'spring' 'winter' 'summer'};
for i=1:numel(clrmp)
uimenu(c, 'Label', clrmp{i}, 'Callback', {@myColourmap, H});
end
c = uimenu(cmenu, 'Label','Transparency');
uimenu(c, 'Label','0%', 'Checked','on', 'Callback', {@myTransparency, H});
uimenu(c, 'Label','20%', 'Checked','off', 'Callback', {@myTransparency, H});
uimenu(c, 'Label','40%', 'Checked','off', 'Callback', {@myTransparency, H});
uimenu(c, 'Label','60%', 'Checked','off', 'Callback', {@myTransparency, H});
uimenu(c, 'Label','80%', 'Checked','off', 'Callback', {@myTransparency, H});
uimenu(cmenu, 'Label','Data Cursor', 'Callback', {@myDataCursor, H});
c = uimenu(cmenu, 'Label','Background Color');
uimenu(c, 'Label','White', 'Callback', {@myBackgroundColor, H, [1 1 1]});
uimenu(c, 'Label','Black', 'Callback', {@myBackgroundColor, H, [0 0 0]});
uimenu(c, 'Label','Custom...', 'Callback', {@myBackgroundColor, H, []});
uimenu(cmenu, 'Label','Save As...', 'Separator', 'on', ...
'Callback', {@mySave, H});
set(H.rotate3d,'enable','off');
try, set(H.rotate3d,'uicontextmenu',cmenu); end
try, set(H.patch, 'uicontextmenu',cmenu); end
set(H.rotate3d,'enable','on');
dcm_obj = datacursormode(H.figure);
set(dcm_obj, 'Enable','off', 'SnapToDataVertex','on', ...
'DisplayStyle','Window', 'Updatefcn',{@myDataCursorUpdate, H});
%-Overlay
%======================================================================
case 'overlay'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if nargin < 3, varargin{2} = []; end
updateTexture(H,varargin{2:end});
%-Slices
%======================================================================
case 'slices'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if nargin < 3, varargin{2} = []; end
renderSlices(H,varargin{2:end});
%-ColourBar
%======================================================================
case {'colourbar', 'colorbar'}
if isempty(varargin), varargin{1} = gca; end
if length(varargin) == 1, varargin{2} = 'on'; end
H = getHandles(varargin{1});
d = getappdata(H.patch,'data');
col = getappdata(H.patch,'colourmap');
if strcmpi(varargin{2},'off')
if isfield(H,'colourbar') && ishandle(H.colourbar)
delete(H.colourbar);
H = rmfield(H,'colourbar');
setappdata(H.axis,'handles',H);
end
return;
end
if isempty(d) || ~any(d(:)), varargout = {H}; return; end
if isempty(col), col = hot(256); end
if ~isfield(H,'colourbar') || ~ishandle(H.colourbar)
H.colourbar = colorbar('peer',H.axis);
set(H.colourbar,'Tag','');
set(get(H.colourbar,'Children'),'Tag','');
end
c(1:size(col,1),1,1:size(col,2)) = col;
ic = findobj(H.colourbar,'Type','image');
if size(d,1) > 1
set(ic,'CData',c(1:size(d,1),:,:));
set(ic,'YData',[1 size(d,1)]);
set(H.colourbar,'YLim',[1 size(d,1)]);
set(H.colourbar,'YTickLabel',[]);
else
set(ic,'CData',c);
clim = getappdata(H.patch,'clim');
if isempty(clim), clim = [false min(d) max(d)]; end
set(ic,'YData',clim(2:3));
set(H.colourbar,'YLim',clim(2:3));
end
setappdata(H.axis,'handles',H);
%-ColourMap
%======================================================================
case {'colourmap', 'colormap'}
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if length(varargin) == 1
varargout = { getappdata(H.patch,'colourmap') };
return;
else
setappdata(H.patch,'colourmap',varargin{2});
d = getappdata(H.patch,'data');
updateTexture(H,d);
end
%-CLim
%======================================================================
case 'clim'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
if length(varargin) == 1
c = getappdata(H.patch,'clim');
if ~isempty(c), c = c(2:3); end
varargout = { c };
return;
else
if isempty(varargin{2}) || any(~isfinite(varargin{2}))
setappdata(H.patch,'clim',[false NaN NaN]);
else
setappdata(H.patch,'clim',[true varargin{2}]);
end
d = getappdata(H.patch,'data');
updateTexture(H,d);
end
%-Register
%======================================================================
case 'register'
if isempty(varargin), varargin{1} = gca; end
H = getHandles(varargin{1});
hReg = varargin{2};
xyz = spm_XYZreg('GetCoords',hReg);
hs = myCrossBar('Create',H,xyz);
set(hs,'UserData',hReg);
spm_XYZreg('Add2Reg',hReg,hs,@myCrossBar);
%-Otherwise...
%======================================================================
otherwise
try
H = spm_mesh_render('Disp',action,varargin{:});
catch
error('Unknown action.');
end
end
varargout = {H};
%==========================================================================
function O = getOptions(varargin)
O = [];
if ~nargin
return;
elseif nargin == 1 && isstruct(varargin{1})
for i=fieldnames(varargin{1})
O.(lower(i{1})) = varargin{1}.(i{1});
end
elseif mod(nargin,2) == 0
for i=1:2:numel(varargin)
O.(lower(varargin{i})) = varargin{i+1};
end
else
error('Invalid list of property/value pairs.');
end
%==========================================================================
function H = getHandles(H)
if ~nargin || isempty(H), H = gca; end
if ishandle(H) && ~isappdata(H,'handles')
a = H; clear H;
H.axis = a;
H.figure = ancestor(H.axis,'figure');
H.patch = findobj(H.axis,'type','patch');
H.light = findobj(H.axis,'type','light');
H.rotate3d = rotate3d(H.figure);
setappdata(H.axis,'handles',H);
elseif ishandle(H)
H = getappdata(H,'handles');
else
H = getappdata(H.axis,'handles');
end
%==========================================================================
function myMenuCallback(obj,evt,H)
H = getHandles(H);
h = findobj(obj,'Label','Rotate');
if strcmpi(get(H.rotate3d,'Enable'),'on')
set(h,'Checked','on');
else
set(h,'Checked','off');
end
if numel(findobj('Tag','SPMMeshRender','Type','Patch')) > 1
h = findobj(obj,'Tag','SynchroMenu');
set(h,'Visible','on');
end
h = findobj(obj,'Label','Colorbar');
d = getappdata(H.patch,'data');
if isempty(d) || ~any(d(:)), set(h,'Enable','off'); else set(h,'Enable','on'); end
if isfield(H,'colourbar')
if ishandle(H.colourbar)
set(h,'Checked','on');
else
H = rmfield(H,'colourbar');
set(h,'Checked','off');
end
else
set(h,'Checked','off');
end
setappdata(H.axis,'handles',H);
%==========================================================================
function myPostCallback(obj,evt,H)
P = findobj('Tag','SPMMeshRender','Type','Patch');
if numel(P) == 1
camlight(H.light);
else
for i=1:numel(P)
H = getappdata(ancestor(P(i),'axes'),'handles');
camlight(H.light);
end
end
%==========================================================================
function varargout = myCrossBar(varargin)
switch lower(varargin{1})
case 'create'
%----------------------------------------------------------------------
% hMe = myCrossBar('Create',H,xyz)
H = varargin{2};
xyz = varargin{3};
hold(H.axis,'on');
hs = plot3(xyz(1),xyz(2),xyz(3),'Marker','+','MarkerSize',60,...
'parent',H.axis,'Color',[1 1 1],'Tag','CrossBar','ButtonDownFcn',{});
varargout = {hs};
case 'setcoords'
%----------------------------------------------------------------------
% [xyz,d] = myCrossBar('SetCoords',xyz,hMe)
hMe = varargin{3};
xyz = varargin{2};
set(hMe,'XData',xyz(1));
set(hMe,'YData',xyz(2));
set(hMe,'ZData',xyz(3));
varargout = {xyz,[]};
otherwise
%----------------------------------------------------------------------
error('Unknown action string')
end
%==========================================================================
function myInflate(obj,evt,H)
spm_mesh_inflate(H.patch,Inf,1);
axis(H.axis,'image');
%==========================================================================
function myCCLabel(obj,evt,H)
C = getappdata(H.patch,'cclabel');
F = get(H.patch,'Faces');
ind = sscanf(get(obj,'Label'),'Component %d');
V = get(H.patch,'FaceVertexAlphaData');
Fa = get(H.patch,'FaceAlpha');
if ~isnumeric(Fa)
if ~isempty(V), Fa = max(V); else Fa = 1; end
if Fa == 0, Fa = 1; end
end
if isempty(V) || numel(V) == 1
Ve = get(H.patch,'Vertices');
if isempty(V) || V == 1
V = Fa * ones(size(Ve,1),1);
else
V = zeros(size(Ve,1),1);
end
end
if strcmpi(get(obj,'Checked'),'on')
V(reshape(F(C==ind,:),[],1)) = 0;
set(obj,'Checked','off');
else
V(reshape(F(C==ind,:),[],1)) = Fa;
set(obj,'Checked','on');
end
set(H.patch, 'FaceVertexAlphaData', V);
if all(V)
set(H.patch, 'FaceAlpha', Fa);
else
set(H.patch, 'FaceAlpha', 'interp');
end
%==========================================================================
function myTransparency(obj,evt,H)
t = 1 - sscanf(get(obj,'Label'),'%d%%') / 100;
set(H.patch,'FaceAlpha',t);
set(get(get(obj,'parent'),'children'),'Checked','off');
set(obj,'Checked','on');
%==========================================================================
function mySwitchRotate(obj,evt,H)
if strcmpi(get(H.rotate3d,'enable'),'on')
set(H.rotate3d,'enable','off');
set(obj,'Checked','off');
else
set(H.rotate3d,'enable','on');
set(obj,'Checked','on');
end
%==========================================================================
function myView(obj,evt,H,varargin)
view(H.axis,varargin{1});
axis(H.axis,'image');
camlight(H.light);
%==========================================================================
function myColourbar(obj,evt,H)
y = {'on','off'}; toggle = @(x) y{1+strcmpi(x,'on')};
spm_mesh_render('Colourbar',H,toggle(get(obj,'Checked')));
%==========================================================================
function myColourmap(obj,evt,H)
spm_mesh_render('Colourmap',H,feval(get(obj,'Label'),256));
%==========================================================================
function mySynchroniseViews(obj,evt,H)
P = findobj('Tag','SPMMeshRender','Type','Patch');
v = get(H.axis,'cameraposition');
for i=1:numel(P)
H = getappdata(ancestor(P(i),'axes'),'handles');
set(H.axis,'cameraposition',v);
axis(H.axis,'image');
camlight(H.light);
end
%==========================================================================
function myDataCursor(obj,evt,H)
dcm_obj = datacursormode(H.figure);
set(dcm_obj, 'Enable','on', 'SnapToDataVertex','on', ...
'DisplayStyle','Window', 'Updatefcn',{@myDataCursorUpdate, H});
%==========================================================================
function txt = myDataCursorUpdate(obj,evt,H)
pos = get(evt,'Position');
txt = {['X: ',num2str(pos(1))],...
['Y: ',num2str(pos(2))],...
['Z: ',num2str(pos(3))]};
i = ismember(get(H.patch,'vertices'),pos,'rows');
txt = {['Node: ' num2str(find(i))] txt{:}};
d = getappdata(H.patch,'data');
if ~isempty(d) && any(d(:))
if any(i), txt = {txt{:} ['T: ',num2str(d(i))]}; end
end
hMe = findobj(H.axis,'Tag','CrossBar');
if ~isempty(hMe)
ws = warning('off');
spm_XYZreg('SetCoords',pos,get(hMe,'UserData'));
warning(ws);
end
%==========================================================================
function myBackgroundColor(obj,evt,H,varargin)
if isempty(varargin{1})
c = uisetcolor(H.figure, ...
'Pick a background color...');
if numel(c) == 1, return; end
else
c = varargin{1};
end
h = findobj(H.figure,'Tag','SPMMeshRenderBackground');
if isempty(h)
set(H.figure,'Color',c);
else
set(h,'Color',c);
end
%==========================================================================
function mySave(obj,evt,H)
[filename, pathname, filterindex] = uiputfile({...
'*.gii' 'GIfTI files (*.gii)'; ...
'*.png' 'PNG files (*.png)';...
'*.dae' 'Collada files (*.dae)';...
'*.idtf' 'IDTF files (*.idtf)'}, 'Save as');
if ~isequal(filename,0) && ~isequal(pathname,0)
[pth,nam,ext] = fileparts(filename);
switch ext
case '.gii'
filterindex = 1;
case '.png'
filterindex = 2;
case '.dae'
filterindex = 3;
case '.idtf'
filterindex = 4;
otherwise
switch filterindex
case 1
filename = [filename '.gii'];
case 2
filename = [filename '.png'];
case 3
filename = [filename '.dae'];
end
end
switch filterindex
case 1
G = gifti(H.patch);
[p,n,e] = fileparts(filename);
[p,n,e] = fileparts(n);
switch lower(e)
case '.func'
save(gifti(getappdata(H.patch,'data')),...
fullfile(pathname, filename));
case '.surf'
save(gifti(struct('vertices',G.vertices,'faces',G.faces)),...
fullfile(pathname, filename));
case '.rgba'
save(gifti(G.cdata),fullfile(pathname, filename));
otherwise
save(G,fullfile(pathname, filename));
end
case 2
u = get(H.axis,'units');
set(H.axis,'units','pixels');
p = get(H.axis,'Position');
r = get(H.figure,'Renderer');
hc = findobj(H.figure,'Tag','SPMMeshRenderBackground');
if isempty(hc)
c = get(H.figure,'Color');
else
c = get(hc,'Color');
end
h = figure('Position',p+[0 0 10 10], ...
'InvertHardcopy','off', ...
'Color',c, ...
'Renderer',r);
copyobj(H.axis,h);
set(H.axis,'units',u);
set(get(h,'children'),'visible','off');
%a = get(h,'children');
%set(a,'Position',get(a,'Position').*[0 0 1 1]+[10 10 0 0]);
if isdeployed
deployprint(h, '-dpng', '-opengl', fullfile(pathname, filename));
else
print(h, '-dpng', '-opengl', fullfile(pathname, filename));
end
close(h);
set(getappdata(obj,'fig'),'renderer',r);
case 3
save(gifti(H.patch),fullfile(pathname, filename),'collada');
case 4
save(gifti(H.patch),fullfile(pathname, filename),'idtf');
end
end
%==========================================================================
function myDeleteFcn(obj,evt,renderer)
try, rotate3d(get(obj,'parent'),'off'); end
set(ancestor(obj,'figure'),'Renderer',renderer);
%==========================================================================
function myOverlay(obj,evt,H)
[P, sts] = spm_select(1,'\.img|\.nii|\.gii|\.mat','Select file to overlay');
if ~sts, return; end
spm_mesh_render('Overlay',H,P);
%==========================================================================
function myImageSections(obj,evt,H)
[P, sts] = spm_select(1,'image','Select image to render');
if ~sts, return; end
renderSlices(H,P);
%==========================================================================
function renderSlices(H,P,pls)
if nargin <3
pls = 0.05:0.2:0.9;
end
N = nifti(P);
d = size(N.dat);
pls = round(pls.*d(3));
hold(H.axis,'on');
for i=1:numel(pls)
[x,y,z] = ndgrid(1:d(1),1:d(2),pls(i));
f = N.dat(:,:,pls(i));
x1 = N.mat(1,1)*x + N.mat(1,2)*y + N.mat(1,3)*z + N.mat(1,4);
y1 = N.mat(2,1)*x + N.mat(2,2)*y + N.mat(2,3)*z + N.mat(2,4);
z1 = N.mat(3,1)*x + N.mat(3,2)*y + N.mat(3,3)*z + N.mat(3,4);
surf(x1,y1,z1, repmat(f,[1 1 3]), 'EdgeColor','none', ...
'Clipping','off', 'Parent',H.axis);
end
hold(H.axis,'off');
axis(H.axis,'image');
%==========================================================================
function C = updateTexture(H,v,col)
%-Get colourmap
%--------------------------------------------------------------------------
if nargin<3, col = getappdata(H.patch,'colourmap'); end
if isempty(col), col = hot(256); end
setappdata(H.patch,'colourmap',col);
%-Get curvature
%--------------------------------------------------------------------------
curv = getappdata(H.patch,'curvature');
if size(curv,2) == 1
curv = 0.5 * repmat(curv,1,3) + 0.3 * repmat(~curv,1,3);
end
%-Project data onto surface mesh
%--------------------------------------------------------------------------
if nargin < 2, v = []; end
if ischar(v)
[p,n,e] = fileparts(v);
if strcmp([n e],'SPM.mat')
swd = pwd;
spm_figure('GetWin','Interactive');
[SPM,v] = spm_getSPM(struct('swd',p));
cd(swd);
else
try, spm_vol(v); catch, v = gifti(v); end;
end
end
if isa(v,'gifti'), v = v.cdata; end
if isa(v,'file_array'), v = v(); end
if isempty(v)
v = zeros(size(curv))';
elseif ischar(v) || iscellstr(v) || isstruct(v)
v = spm_mesh_project(H.patch,v);
elseif isnumeric(v) || islogical(v)
if size(v,2) == 1
v = v';
end
else
error('Unknown data type.');
end
v(isinf(v)) = NaN;
setappdata(H.patch,'data',v);
%-Create RGB representation of data according to colourmap
%--------------------------------------------------------------------------
C = zeros(size(v,2),3);
clim = getappdata(H.patch, 'clim');
if isempty(clim), clim = [false NaN NaN]; end
mi = clim(2); ma = clim(3);
if any(v(:))
if size(col,1)>3
if size(v,1) == 1
if ~clim(1), mi = min(v(:)); ma = max(v(:)); end
C = squeeze(ind2rgb(floor(((v(:)-mi)/(ma-mi))*size(col,1)),col));
else
C = v; v = v';
end
else
if ~clim(1), ma = max(v(:)); end
for i=1:size(v,1)
C = C + v(i,:)'/ma * col(i,:);
end
end
else
end
setappdata(H.patch, 'clim', [false mi ma]);
%-Build texture by merging curvature and data
%--------------------------------------------------------------------------
C = repmat(~any(v,1),3,1)' .* curv + repmat(any(v,1),3,1)' .* C;
set(H.patch, 'FaceVertexCData',C, 'FaceColor','interp');
%-Update the colourbar
%--------------------------------------------------------------------------
if isfield(H,'colourbar')
spm_mesh_render('Colourbar',H);
end
|
github
|
philippboehmsturm/antx-master
|
spm_smooth.m
|
.m
|
antx-master/xspm8/spm_smooth.m
| 3,746 |
utf_8
|
641f9055c7e9c0b87c38737330881a53
|
function spm_smooth(P,Q,s,dtype)
% 3 dimensional convolution of an image
% FORMAT spm_smooth(P,Q,S,dtype)
% P - image to be smoothed (or 3D array)
% Q - filename for smoothed image (or 3D array)
% S - [sx sy sz] Gaussian filter width {FWHM} in mm (or edges)
% dtype - datatype [default: 0 == same datatype as P]
%____________________________________________________________________________
%
% spm_smooth is used to smooth or convolve images in a file (maybe).
%
% The sum of kernel coeficients are set to unity. Boundary
% conditions assume data does not exist outside the image in z (i.e.
% the kernel is truncated in z at the boundaries of the image space). S
% can be a vector of 3 FWHM values that specifiy an anisotropic
% smoothing. If S is a scalar isotropic smoothing is implemented.
%
% If Q is not a string, it is used as the destination of the smoothed
% image. It must already be defined with the same number of elements
% as the image.
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Tom Nichols
% $Id: spm_smooth.m 4172 2011-01-26 12:13:29Z guillaume $
%-----------------------------------------------------------------------
if numel(s) == 1, s = [s s s]; end
if nargin < 4, dtype = 0; end;
if ischar(P), P = spm_vol(P); end;
if isstruct(P),
for i= 1:numel(P),
smooth1(P(i),Q,s,dtype);
end
else
smooth1(P,Q,s,dtype);
end
%_______________________________________________________________________
%_______________________________________________________________________
function smooth1(P,Q,s,dtype)
if isstruct(P),
VOX = sqrt(sum(P.mat(1:3,1:3).^2));
else
VOX = [1 1 1];
end;
if ischar(Q) && isstruct(P),
[pth,nam,ext,num] = spm_fileparts(Q);
q = fullfile(pth,[nam,ext]);
Q = P;
Q.fname = q;
if ~isempty(num),
Q.n = str2num(num);
end;
if ~isfield(Q,'descrip'), Q.descrip = sprintf('SPM compatible'); end;
Q.descrip = sprintf('%s - conv(%g,%g,%g)',Q.descrip, s);
if dtype~=0, % Need to figure out some rescaling.
Q.dt(1) = dtype;
if ~isfinite(spm_type(Q.dt(1),'maxval')),
Q.pinfo = [1 0 0]'; % float or double, so scalefactor of 1
else
% Need to determine the range of intensities
if isfinite(spm_type(P.dt(1),'maxval')),
% Integer types have a defined maximum value
maxv = spm_type(P.dt(1),'maxval')*P.pinfo(1) + P.pinfo(2);
else
% Need to find the max and min values in original image
mx = -Inf;
mn = Inf;
for pl=1:P.dim(3),
tmp = spm_slice_vol(P,spm_matrix([0 0 pl]),P.dim(1:2),0);
tmp = tmp(isfinite(tmp));
mx = max(max(tmp),mx);
mn = min(min(tmp),mn);
end
maxv = max(mx,-mn);
end
sf = maxv/spm_type(Q.dt(1),'maxval');
Q.pinfo = [sf 0 0]';
end
end
end
% compute parameters for spm_conv_vol
%-----------------------------------------------------------------------
s = s./VOX; % voxel anisotropy
s1 = s/sqrt(8*log(2)); % FWHM -> Gaussian parameter
x = round(6*s1(1)); x = -x:x; x = spm_smoothkern(s(1),x,1); x = x/sum(x);
y = round(6*s1(2)); y = -y:y; y = spm_smoothkern(s(2),y,1); y = y/sum(y);
z = round(6*s1(3)); z = -z:z; z = spm_smoothkern(s(3),z,1); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
if isstruct(Q), Q = spm_create_vol(Q); end;
spm_conv_vol(P,Q,x,y,z,-[i,j,k]);
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_imag_api.m
|
.m
|
antx-master/xspm8/spm_eeg_inv_imag_api.m
| 15,840 |
utf_8
|
169f5a7cb18e2a5ae436135b1c16203c
|
function varargout = spm_eeg_inv_imag_api(varargin)
% API for EEG/MEG source reconstruction interface
% FORMAT:
% FIG = SPM_EEG_INV_IMAG_API launch spm_eeg_inv_imag_api GUI.
% SPM_EEG_INV_IMAG_API('callback_name', ...) invoke the named callback.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jeremie Mattout
% $Id: spm_eeg_inv_imag_api.m 4260 2011-03-23 13:42:21Z vladimir $
spm('Clear');
% Launch API
%==========================================================================
if nargin < 2
% open figure
%----------------------------------------------------------------------
fig = openfig(mfilename,'reuse');
set(fig,'name',[spm('ver') ': ' get(fig,'name')]);
Rect = spm('WinSize','Menu');
S0 = spm('WinSize','0',1);
set(fig,'units','pixels');
Fdim = get(fig,'position');
set(fig,'position',[S0(1)+Rect(1) S0(2)+Rect(2) Fdim(3) Fdim(4)]);
handles = guihandles(fig);
% Use system color scheme for figure:
%----------------------------------------------------------------------
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
handles.fig = fig;
guidata(fig,handles);
% intialise with D
%----------------------------------------------------------------------
try
D = spm_eeg_inv_check(varargin{1});
set(handles.DataFile,'String',D.fname);
set(handles.Exit,'enable','on')
cd(D.path);
handles.D = D;
Reset(fig, [], handles);
guidata(fig,handles);
end
% INVOKE NAMED SUBFUNCTION OR CALLBACK
%--------------------------------------------------------------------------
elseif ischar(varargin{1})
if nargout
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
else
error('Wrong input format.');
end
% MAIN FUNCTIONS FOR MODEL SEPCIFICATION AND INVERSION
%==========================================================================
% --- Executes on button press in CreateMeshes.
%--------------------------------------------------------------------------
function CreateMeshes_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_mesh_ui(handles.D, handles.D.val, 0);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Reg2tem.
%--------------------------------------------------------------------------
function Reg2tem_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_mesh_ui(handles.D, handles.D.val, 1);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Data Reg.
%--------------------------------------------------------------------------
function DataReg_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_datareg_ui(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Forward Model.
%--------------------------------------------------------------------------
function Forward_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_forward_ui(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Invert.
%--------------------------------------------------------------------------
function Inverse_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_invert_ui(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in contrast.
%--------------------------------------------------------------------------
function contrast_Callback(hObject, eventdata, handles)
handles.D = spm_eeg_inv_results_ui(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Image.
%--------------------------------------------------------------------------
function Image_Callback(hObject, eventdata,handles)
handles.D.inv{handles.D.val}.contrast.display = 1;
handles.D = spm_eeg_inv_Mesh2Voxels(handles.D);
Reset(hObject, eventdata, handles);
% LOAD AND EXIT
%==========================================================================
% --- Executes on button press in Load.
%--------------------------------------------------------------------------
function Load_Callback(hObject, eventdata, handles)
[S, sts] = spm_select(1, 'mat', 'Select M/EEG mat file');
if ~sts, return; end
D = spm_eeg_load(S);
[ok, D] = check(D, 'sensfid');
if ~ok
if check(D, 'basic')
warndlg(['The requested file is not ready for source reconstruction.'...
'See Matlab window for details.']);
else
warndlg('The meeg file is corrupt or incomplete');
end
return
end
set(handles.DataFile,'String',D.fname);
set(handles.Exit,'enable','on');
cd(D.path);
handles.D = D;
Reset(hObject, eventdata, handles);
% --- Executes on button press in Exit.
%--------------------------------------------------------------------------
function Exit_Callback(hObject, eventdata, handles)
D = handles.D;
D.save;
varargout{1} = handles.D;
assignin('base','D',handles.D)
% FUCNTIONS FOR MANAGING DIFFERENT MODELS
%==========================================================================
% --- Executes on button press in new.
%--------------------------------------------------------------------------
function new_Callback(hObject, eventdata, handles)
D = handles.D;
if ~isfield(D,'inv')
val = 1;
elseif isempty(D.inv)
val = 1;
else
val = length(D.inv) + 1;
D.inv{val} = D.inv{D.val};
end
% set D in handles and update analysis specific buttons
%--------------------------------------------------------------------------
D.val = val;
D = set_CommentDate(D);
handles.D = D;
set(handles.CreateMeshes,'enable','on')
set(handles.Reg2tem,'enable','on')
Reset(hObject, eventdata, handles);
% --- Executes on button press in next.
%--------------------------------------------------------------------------
function next_Callback(hObject, eventdata, handles)
if handles.D.val < length(handles.D.inv)
handles.D.val = handles.D.val + 1;
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in previous.
%--------------------------------------------------------------------------
function previous_Callback(hObject, eventdata, handles)
if handles.D.val > 1
handles.D.val = handles.D.val - 1;
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in clear.
%--------------------------------------------------------------------------
function clear_Callback(hObject, eventdata, handles)
try
inv.comment = handles.D.inv{handles.D.val}.comment;
inv.date = handles.D.inv{handles.D.val}.date;
handles.D.inv{handles.D.val} = inv;
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in delete.
%--------------------------------------------------------------------------
function delete_Callback(hObject, eventdata, handles)
if ~isempty(handles.D.inv)
try
str = handles.D.inv{handles.D.val}.comment;
warndlg({'you are about to delete:',str{1}});
uiwait
end
handles.D.inv(handles.D.val) = [];
handles.D.val = handles.D.val - 1;
end
Reset(hObject, eventdata, handles);
% Auxillary functions
%==========================================================================
function Reset(hObject, eventdata, handles)
% Check to see if a new analysis is required
%--------------------------------------------------------------------------
try
set(handles.DataFile,'String',handles.D.fname);
end
if ~isfield(handles.D,'inv')
new_Callback(hObject, eventdata, handles)
return
end
if isempty(handles.D.inv)
new_Callback(hObject, eventdata, handles)
return
end
try
val = handles.D.val;
handles.D.inv{val};
catch
handles.D.val = 1;
val = 1;
end
% analysis specification buttons
%--------------------------------------------------------------------------
Q = handles.D.inv{val};
% === This is for backward compatibility with SPM8b. Can be removed after
% some time
if isfield(Q, 'mesh') &&...
isfield(Q.mesh, 'tess_ctx') && ~isa(Q.mesh.tess_ctx, 'char')
warning(['This is an old version of SPM8b inversion. ',...
'You can only review and export solutions. ',...
'Clear and invert again to update']);
Q = rmfield(Q, {'mesh', 'datareg', 'forward'});
end
% =========================================================================
set(handles.new, 'enable','on','value',0)
set(handles.clear, 'enable','on','value',0)
set(handles.delete, 'enable','on','value',0)
set(handles.next, 'value',0)
set(handles.previous, 'value',0)
if val < length(handles.D.inv)
set(handles.next, 'enable','on')
end
if val > 1
set(handles.previous,'enable','on')
end
if val == 1
set(handles.previous,'enable','off')
end
if val == length(handles.D.inv)
set(handles.next, 'enable','off')
end
try
str = sprintf('%i: %s',val,Q.comment{1});
catch
try
str = sprintf('%i: %s',val,Q.comment);
catch
str = sprintf('%i',val);
end
end
set(handles.val, 'Value',val,'string',str);
% condition specification
%--------------------------------------------------------------------------
try
handles.D.con = max(handles.D.con,1);
if handles.D.con > length(handles.D.inv{val}.inverse.J);
handles.D.con = 1;
end
catch
try
handles.D.con = length(handles.D.inv{val}.inverse.J);
catch
handles.D.con = 0;
end
end
if handles.D.con
str = sprintf('condition %d',handles.D.con);
set(handles.con,'String',str,'Enable','on','Value',0)
else
set(handles.con,'Enable','off','Value',0)
end
% check anaylsis buttons
%--------------------------------------------------------------------------
set(handles.DataReg, 'enable','off')
set(handles.Forward, 'enable','off')
set(handles.Inverse, 'enable','off')
set(handles.contrast,'enable','off')
set(handles.Image, 'enable','off')
set(handles.CheckReg, 'enable','off','Value',0)
set(handles.CheckMesh, 'enable','off','Value',0)
set(handles.CheckForward, 'enable','off','Value',0)
set(handles.CheckInverse, 'enable','off','Value',0)
set(handles.CheckContrast,'enable','off','Value',0)
set(handles.CheckImage, 'enable','off','Value',0)
set(handles.Movie, 'enable','off','Value',0)
set(handles.Vis3D, 'enable','off','Value',0)
set(handles.Image, 'enable','off','Value',0)
set(handles.CreateMeshes,'enable','on')
set(handles.Reg2tem,'enable','on')
if isfield(Q, 'mesh')
set(handles.DataReg, 'enable','on')
set(handles.CheckMesh,'enable','on')
if isfield(Q,'datareg') && isfield(Q.datareg, 'sensors')
set(handles.Forward, 'enable','on')
set(handles.CheckReg,'enable','on')
if isfield(Q,'forward') && isfield(Q.forward, 'vol')
set(handles.Inverse, 'enable','on')
set(handles.CheckForward,'enable','on')
end
end
end
if isfield(Q,'inverse') && isfield(Q, 'method')
set(handles.CheckInverse,'enable','on')
if isfield(Q.inverse,'J')
set(handles.contrast, 'enable','on')
set(handles.Movie, 'enable','on')
set(handles.Vis3D, 'enable','on')
if isfield(Q,'contrast')
set(handles.CheckContrast,'enable','on')
set(handles.Image, 'enable','on')
if isfield(Q.contrast,'fname')
set(handles.CheckImage,'enable','on')
end
end
end
end
try
if strcmp(handles.D.inv{handles.D.val}.method,'Imaging')
set(handles.CheckInverse,'String','mip');
set(handles.PST,'Enable','on');
else
set(handles.CheckInverse,'String','dip');
set(handles.PST,'Enable','off');
end
end
set(handles.fig,'Pointer','arrow')
assignin('base','D',handles.D)
guidata(hObject,handles);
% Set Comment and Date for new inverse analysis
%--------------------------------------------------------------------------
function S = set_CommentDate(D)
clck = fix(clock);
if clck(5) < 10
clck = [num2str(clck(4)) ':0' num2str(clck(5))];
else
clck = [num2str(clck(4)) ':' num2str(clck(5))];
end
D.inv{D.val}.date = strvcat(date,clck);
D.inv{D.val}.comment = inputdlg('Comment/Label for this analysis:');
S = D;
% CHECKS AND DISPLAYS
%==========================================================================
% --- Executes on button press in CheckMesh.
%--------------------------------------------------------------------------
function CheckMesh_Callback(hObject, eventdata, handles)
spm_eeg_inv_checkmeshes(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckReg.
%--------------------------------------------------------------------------
function CheckReg_Callback(hObject, eventdata, handles)
% check and display registration
%--------------------------------------------------------------------------
spm_eeg_inv_checkdatareg(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckForward.
%--------------------------------------------------------------------------
function CheckForward_Callback(hObject, eventdata, handles)
spm_eeg_inv_checkforward(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckInverse.
%--------------------------------------------------------------------------
function CheckInverse_Callback(hObject, eventdata, handles)
if strcmp(handles.D.inv{handles.D.val}.method,'Imaging')
PST = str2num(get(handles.PST,'String'));
spm_eeg_invert_display(handles.D,PST);
if length(PST) == 3 && get(handles.extract, 'Value')
handles.D = spm_eeg_inv_extract_ui(handles.D, handles.D.val, PST);
end
elseif strcmp(handles.D.inv{handles.D.val}.method, 'vbecd')
spm_eeg_inv_vbecd_disp('init',handles.D);
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in Movie.
%--------------------------------------------------------------------------
function Movie_Callback(hObject, eventdata, handles)
figure(spm_figure('GetWin','Graphics'));
PST(1) = str2num(get(handles.Start,'String'));
PST(2) = str2num(get(handles.Stop ,'String'));
spm_eeg_invert_display(handles.D,PST);
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckContrast.
%--------------------------------------------------------------------------
function CheckContrast_Callback(hObject, eventdata, handles)
spm_eeg_inv_results_display(handles.D);
Reset(hObject, eventdata, handles);
% --- Executes on button press in Vis3D.
%--------------------------------------------------------------------------
function Vis3D_Callback(hObject, eventdata, handles)
Exit_Callback(hObject, eventdata, handles)
try
spm_eeg_inv_visu3D_api(handles.D);
catch
spm_eeg_review(handles.D,6,handles.D.val);
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in CheckImage.
%--------------------------------------------------------------------------
function CheckImage_Callback(hObject, eventdata, handles)
spm_eeg_inv_image_display(handles.D)
Reset(hObject, eventdata, handles);
% --- Executes on button press in con.
%--------------------------------------------------------------------------
function con_Callback(hObject, eventdata, handles)
try
handles.D.con = handles.D.con + 1;
if handles.D.con > length(handles.D.inverse.J);
handles.D.con = 1;
end
end
Reset(hObject, eventdata, handles);
% --- Executes on button press in help.
%--------------------------------------------------------------------------
function help_Callback(hObject, eventdata, handles)
edit spm_eeg_inv_help
% --- Executes on button press in group.
%--------------------------------------------------------------------------
function group_Callback(hObject, eventdata, handles)
spm_eeg_inv_group;
|
github
|
philippboehmsturm/antx-master
|
spm_smoothto8bit.m
|
.m
|
antx-master/xspm8/spm_smoothto8bit.m
| 2,427 |
utf_8
|
d81ad311f697d9c9ad9899bd8115c3ce
|
function VO = spm_smoothto8bit(V,fwhm)
% 3 dimensional convolution of an image to 8bit data in memory
% FORMAT VO = spm_smoothto8bit(V,fwhm)
% V - mapped image to be smoothed
% fwhm - FWHM of Guassian filter width in mm
% VO - smoothed volume in a form that can be used by the
% spm_*_vol.mex* functions.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_smoothto8bit.m 4310 2011-04-18 16:07:35Z guillaume $
if nargin>1 && fwhm>0,
VO = smoothto8bit(V,fwhm);
else
VO = V;
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function VO = smoothto8bit(V,fwhm)
% 3 dimensional convolution of an image to 8bit data in memory
% FORMAT VO = smoothto8bit(V,fwhm)
% V - mapped image to be smoothed
% fwhm - FWHM of Guassian filter width in mm
% VO - smoothed volume in a form that can be used by the
% spm_*_vol.mex* functions.
%_______________________________________________________________________
vx = sqrt(sum(V.mat(1:3,1:3).^2));
s = (fwhm./vx./sqrt(8*log(2)) + eps).^2;
r = cell(1,3);
for i=1:3,
r{i}.s = ceil(3.5*sqrt(s(i)));
x = -r{i}.s:r{i}.s;
r{i}.k = exp(-0.5 * (x.*x)/s(i))/sqrt(2*pi*s(i));
r{i}.k = r{i}.k/sum(r{i}.k);
end
buff = zeros([V.dim(1:2) r{3}.s*2+1]);
VO = V;
VO.dt = [spm_type('uint8') spm_platform('bigend')];
V0.dat = uint8(0);
V0.dat(VO.dim(1:3)) = uint8(0);
VO.pinfo = [];
for i=1:V.dim(3)+r{3}.s,
if i<=V.dim(3),
img = spm_slice_vol(V,spm_matrix([0 0 i]),V.dim(1:2),0);
msk = find(~isfinite(img));
img(msk) = 0;
buff(:,:,rem(i-1,r{3}.s*2+1)+1) = ...
conv2(conv2(img,r{1}.k,'same'),r{2}.k','same');
else
buff(:,:,rem(i-1,r{3}.s*2+1)+1) = 0;
end
if i>r{3}.s,
kern = zeros(size(r{3}.k'));
kern(rem((i:(i+r{3}.s*2))',r{3}.s*2+1)+1) = r{3}.k';
img = reshape(buff,[prod(V.dim(1:2)) r{3}.s*2+1])*kern;
img = reshape(img,V.dim(1:2));
ii = i-r{3}.s;
mx = max(img(:));
mn = min(img(:));
if mx==mn, mx=mn+eps; end
VO.pinfo(1:2,ii) = [(mx-mn)/255 mn]';
VO.dat(:,:,ii) = uint8(round((img-mn)*(255/(mx-mn))));
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_review_switchDisplay.m
|
.m
|
antx-master/xspm8/spm_eeg_review_switchDisplay.m
| 26,701 |
utf_8
|
a75c0568a1bf5e7efc01a71adf3e3e20
|
function [D] = spm_eeg_review_switchDisplay(D)
% Switch between displays in the M/EEG Review facility
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_eeg_review_switchDisplay.m 4136 2010-12-09 22:22:28Z guillaume $
try % only if already displayed stuffs
handles = rmfield(D.PSD.handles,'PLOT');
D.PSD.handles = handles;
end
switch D.PSD.VIZU.modality
case 'source'
delete(findobj('tag','plotEEG'));
[D] = visuRecon(D);
case 'info'
[D] = DataInfo(D);
set(D.PSD.handles.hfig,'userdata',D)
otherwise % plot data (EEG/MEG/OTHER)
try
y = D.data.y(:,D.PSD.VIZU.xlim(1):D.PSD.VIZU.xlim(2));
% ! accelerates memory mapping reading
catch
D.PSD.VIZU.xlim = [1,min([5e2,D.Nsamples])];
end
switch D.PSD.VIZU.type
case 1
delete(findobj('tag','plotEEG'))
[D] = standardData(D);
cameratoolbar('resetcamera')
try cameratoolbar('close'); end
case 2
delete(findobj('tag','plotEEG'))
[D] = scalpData(D);
cameratoolbar('resetcamera')
try cameratoolbar('close'); end
end
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Standard EEG/MEG data plot
function [D] = standardData(D)
% POS = get(D.PSD.handles.hfig,'position');
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
scb = 6;
case 'meg'
I = D.PSD.MEG.I;
scb = 6;
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
scb = 6;
case 'other'
I = D.PSD.other.I;
scb = []; % no scalp interpolation button
end
if isempty(I)
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','No channel of this type in the SPM data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
else
if ~strcmp(D.transform.ID,'time')
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','Not for time-frequency data !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
else
D.PSD.VIZU.type = 1;
% add buttons
object.type = 'buttons';
object.options.multSelect = 0;
object.list = [2;3;4;5;scb];
switch D.PSD.type
case 'continuous'
object.list = [object.list;9];
case 'epoched'
object.list = [object.list;7;11];
if strcmp(D.type,'single')
object.list = [object.list;13];
end
end
D = spm_eeg_review_uis(D,object);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 'SPM-like' EEG/MEG data plot
function [D] = scalpData(D)
% POS = get(D.PSD.handles.hfig,'position');
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
case 'meg'
I = D.PSD.MEG.I;
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
case 'other'
I = D.PSD.other.I;
end
if isempty(I)
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','No channel of this type in the SPM data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
else
if strcmp(D.PSD.type,'continuous')
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','Only for epoched data !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
else
D.PSD.VIZU.type = 2;
% add buttons
object.type = 'buttons';
object.list = [5;7];
if strcmp(D.transform.ID,'time') % only for time data!
object.options.multSelect = 1;
object.list = [object.list;4;6;11];
else
object.options.multSelect = 0;
end
if strcmp(D.type,'single')
object.list = [object.list;13];
end
D = spm_eeg_review_uis(D,object);
% add axes (!!give channels!!)
switch D.PSD.VIZU.modality
case 'eeg'
I = D.PSD.EEG.I;
ylim = D.PSD.EEG.VIZU.ylim;
case 'meg'
I = D.PSD.MEG.I;
ylim = D.PSD.MEG.VIZU.ylim;
case 'megplanar'
I = D.PSD.MEGPLANAR.I;
ylim = D.PSD.MEGPLANAR.VIZU.ylim;
case 'other'
I = D.PSD.other.I;
ylim = D.PSD.other.VIZU.ylim;
end
object.type = 'axes';
object.what = 'scalp';
object.options.channelPlot = I;
object.options.ylim = ylim;
D = spm_eeg_review_uis(D,object);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% RENDERING OF INVERSE SOLUTIONS
function [D] = visuRecon(D)
POS = get(D.PSD.handles.hfig,'position');
if ~~D.PSD.source.VIZU.current
isInv = D.PSD.source.VIZU.isInv;
Ninv = length(isInv);
if D.PSD.source.VIZU.current > Ninv
D.PSD.source.VIZU.current = 1;
end
invN = isInv(D.PSD.source.VIZU.current);
pst = D.PSD.source.VIZU.pst;
F = D.PSD.source.VIZU.F;
ID = D.PSD.source.VIZU.ID;
% create uitabs for inverse solutions
hInv = D.PSD.handles.tabs.hp;
[h] = spm_uitab(hInv,D.PSD.source.VIZU.labels,...
D.PSD.source.VIZU.callbacks,'plotEEG',...
D.PSD.source.VIZU.current);
D.PSD.handles.SubTabs_inv = h;
trN = D.PSD.trials.current(1);
model = D.other.inv{invN}.inverse;
D.PSD.source.VIZU.J = zeros(model.Nd,size(model.T,1));
D.PSD.source.VIZU.J(model.Is,:) = model.J{trN}*model.T';
D.PSD.source.VIZU.miJ = min(min(D.PSD.source.VIZU.J));
D.PSD.source.VIZU.maJ = max(max(D.PSD.source.VIZU.J));
J = D.PSD.source.VIZU.J;
miJ = D.PSD.source.VIZU.miJ;
maJ = D.PSD.source.VIZU.maJ;
time = (model.pst-0).^2;
indTime = find(time==min(time));
gridTime = model.pst(indTime);
% create axes
object.type = 'axes';
object.what = 'source';
object.options.Ninv = Ninv;
object.options.miJ = miJ;
object.options.maJ = maJ;
object.options.pst = pst;
D = spm_eeg_review_uis(D,object);
% plot BMC free energies in appropriate axes
if Ninv>1
if isnan(ID(invN))
xF = find(isnan(ID));
else
xF = find(abs(ID-ID(invN))<eps);
end
if length(xF)>1
D.PSD.handles.hbar = bar(D.PSD.handles.BMCplot,...
xF ,F(xF)-min(F(xF)),...
'barwidth',0.5,...
'FaceColor',0.5*[1 1 1],...
'visible','off',...
'tag','plotEEG');
D.PSD.handles.BMCcurrent = plot(D.PSD.handles.BMCplot,...
find(xF==invN),0,'ro',...
'visible','off',...
'tag','plotEEG');
set(D.PSD.handles.BMCplot,...
'xtick',xF,...
'xticklabel',D.PSD.source.VIZU.labels(xF),...
'xlim',[0,length(xF)+1]);
drawnow
end
end
% Create mesh and related objects
Dmesh = D.other.inv{invN}.mesh;
mesh.vertices = Dmesh.tess_mni.vert;
mesh.faces = Dmesh.tess_mni.face;
options.texture = J(:,indTime);
options.hfig = D.PSD.handles.hfig;
options.ParentAxes = D.PSD.handles.axes;
options.tag = 'plotEEG';
options.visible = 'off';
[out] = spm_eeg_render(mesh,options);
D.PSD.handles.mesh = out.handles.p;
D.PSD.handles.BUTTONS.transp = out.handles.transp;
D.PSD.handles.colorbar = out.handles.hc;
D.PSD.handles.BUTTONS.ct1 = out.handles.s1;
D.PSD.handles.BUTTONS.ct2 = out.handles.s2;
% add spheres if constrained inverse solution
if isfield(model,'dipfit')...
|| ~isequal(model.xyz,zeros(1,3))
try
xyz = model.dipfit.Lpos;
radius = model.dipfit.radius;
catch
xyz = model.xyz';
radius = model.rad(1);
end
Np = size(xyz,2);
[x,y,z] = sphere(20);
axes(D.PSD.handles.axes)
for i=1:Np
fvc = surf2patch(x.*radius+xyz(1,i),...
y.*radius+xyz(2,i),z.*radius+xyz(3,i));
D.PSD.handles.dipSpheres(i) = patch(fvc,...
'parent',D.PSD.handles.axes,...
'facecolor',[1 1 1],...
'edgecolor','none',...
'facealpha',0.5,...
'tag','dipSpheres');
end
axis(D.PSD.handles.axes,'tight');
end
% plot time courses
switch D.PSD.source.VIZU.timeCourses
case 1
Jp(1,:) = min(J,[],1);
Jp(2,:) = max(J,[],1);
D.PSD.source.VIZU.plotTC = plot(D.PSD.handles.axes2,...
model.pst,Jp',...
'color',0.5*[1 1 1],...
'visible','off');
% Add virtual electrode
try
ve = D.PSD.source.VIZU.ve;
catch
[mj ve] = max(max(abs(J),[],2));
D.PSD.source.VIZU.ve =ve;
end
Jve = J(D.PSD.source.VIZU.ve,:);
try
qC = model.qC(ve).*diag(model.qV)';
ci = 1.64*sqrt(qC);
D.PSD.source.VIZU.pve2 = plot(D.PSD.handles.axes2,...
model.pst,Jve +ci,'b:',model.pst,Jve -ci,'b:');
end
D.PSD.source.VIZU.pve = plot(D.PSD.handles.axes2,...
model.pst,Jve,...
'color','b',...
'visible','off');
otherwise
% this is meant to be extended for displaying something
% else than just J (e.g. J^2, etc...)
end
D.PSD.source.VIZU.lineTime = line('parent',D.PSD.handles.axes2,...
'xdata',[gridTime;gridTime],...
'ydata',[miJ;maJ],...
'visible','off');
set(D.PSD.handles.axes2,...
'ylim',[miJ;maJ]);
% create buttons
object.type = 'buttons';
object.list = [7;8;10];
object.options.multSelect = 0;
object.options.pst = pst;
object.options.gridTime = gridTime;
D = spm_eeg_review_uis(D,object);
% create info text
object.type = 'text';
object.what = 'source';
D = spm_eeg_review_uis(D,object);
% set graphical object visible
set(D.PSD.handles.mesh,'visible','on')
set(D.PSD.handles.colorbar,'visible','on')
set(D.PSD.handles.axes2,'visible','on')
set(D.PSD.source.VIZU.lineTime,'visible','on')
set(D.PSD.source.VIZU.plotTC,'visible','on')
set(D.PSD.source.VIZU.pve,'visible','on')
try
set(D.PSD.handles.BMCplot,'visible','on');
set(D.PSD.handles.hbar,'visible','on');
set(D.PSD.handles.BMCcurrent,'visible','on');
set(D.PSD.handles.BMCpanel,'visible','on');
end
set(D.PSD.handles.hfig,'userdata',D)
else
uicontrol('style','text',...
'units','normalized','Position',[0.14 0.84 0.7 0.04],...
'string','There is no (imaging) inverse source reconstruction in this data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG')
labels{1} = '1';
callbacks{1} = [];
hInv = D.PSD.handles.tabs.hp;
spm_uitab(hInv,labels,callbacks,'plotEEG');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% GET DATA INFO
function [D] = DataInfo(D)
switch D.PSD.VIZU.uitable
case 'off'
% delete graphical objects from other main tabs
delete(findobj('tag','plotEEG'));
% create info text
object.type = 'text';
object.what = 'data';
D = spm_eeg_review_uis(D,object);
% add buttons
object.type = 'buttons';
object.list = [14,15];
D = spm_eeg_review_uis(D,object);
set(D.PSD.handles.BUTTONS.showSensors,...
'position',[0.7 0.9 0.25 0.02]);
set(D.PSD.handles.BUTTONS.saveHistory,...
'string','save history as script',...
'position',[0.7 0.87 0.25 0.02]);
case 'on'
if isempty(D.PSD.VIZU.fromTab) || ~isequal(D.PSD.VIZU.fromTab,'info')
% delete graphical objects from other main tabs
delete(findobj('tag','plotEEG'));
% create info text
object.type = 'text';
object.what = 'data';
D = spm_eeg_review_uis(D,object);
% Create uitabs for channels and trials
try
D.PSD.VIZU.info;
catch
D.PSD.VIZU.info = 4;
end
labels = {'channels','trials','inv','history'};
callbacks = {'spm_eeg_review_callbacks(''visu'',''main'',''info'',1)',...,...
'spm_eeg_review_callbacks(''visu'',''main'',''info'',2)'...
'spm_eeg_review_callbacks(''visu'',''main'',''info'',3)',...
'spm_eeg_review_callbacks(''visu'',''main'',''info'',4)'};
[h] = spm_uitab(D.PSD.handles.tabs.hp,labels,callbacks,'plotEEG',D.PSD.VIZU.info,0.9);
D.PSD.handles.infoTabs = h;
else
% delete info table (if any)
try delete(D.PSD.handles.infoUItable);end
% delete info message (if any)
try delete(D.PSD.handles.message);end
% delete buttons if any
try delete(D.PSD.handles.BUTTONS.OKinfo);end
try delete(D.PSD.handles.BUTTONS.showSensors);end
try delete(D.PSD.handles.BUTTONS.saveHistory);end
end
% add table and buttons
object.type = 'buttons';
object.list = [];
switch D.PSD.VIZU.info
case 1 % channels info
object.list = [object.list;12;14];
nc = length(D.channels);
table = cell(nc,5);
for i=1:nc
table{i,1} = D.channels(i).label;
table{i,2} = D.channels(i).type;
if D.channels(i).bad
table{i,3} = 'yes';
else
table{i,3} = 'no';
end
if ~isempty(D.channels(i).X_plot2D)
table{i,4} = 'yes';
else
table{i,4} = 'no';
end
table{i,5} = D.channels(i).units;
end
colnames = {'label','type','bad','position','units'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.55 0.7],...
'tag','plotEEG');
D.PSD.handles.infoUItable = ht;
D.PSD.handles.infoUItable2 = hc;
D = spm_eeg_review_uis(D,object); % this adds the buttons
case 2 % trials info
object.list = [object.list;12];
ok = 1;
if strcmp(D.type,'continuous')
try
ne = length(D.trials(1).events);
if ne == 0
ok = 0;
end
catch
ne = 0;
ok = 0;
end
if ne > 0
table = cell(ne,3);
for i=1:ne
table{i,1} = D.trials(1).label;
table{i,2} = D.trials(1).events(i).type;
table{i,3} = num2str(D.trials(1).events(i).value);
if ~isempty(D.trials(1).events(i).duration)
table{i,4} = num2str(D.trials(1).events(i).duration);
else
table{i,4} = [];
end
table{i,5} = num2str(D.trials(1).events(i).time);
table{i,6} = 'Undefined';
table{i,7} = num2str(D.trials(1).onset);
end
colnames = {'label','type','value','duration','time','bad','onset'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.74 0.7],...
'tag','plotEEG');
else
POS = get(D.PSD.handles.infoTabs.hp,'position');
D.PSD.handles.message = uicontrol('style','text','units','normalized',...
'Position',[0.14 0.84 0.7 0.04].*repmat(POS(3:4),1,2),...
'string','There is no event in this data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG');
end
else
nt = length(D.trials);
table = cell(nt,3);
if strcmp(D.type,'single')
for i=1:nt
table{i,1} = D.trials(i).label;
ne = length(D.trials(i).events);
if ne == 0 || ((ne == 1) && isequal(D.trials(i).events(1).type, 'no events'))
table{i,2} = 'no events';
table{i,3} = 'no events';
table{i,4} = 'no events';
table{i,5} = 'no events';
elseif ne >1
table{i,2} = 'multiple events';
table{i,3} = 'multiple events';
table{i,4} = 'multiple events';
table{i,5} = 'multiple events';
else
table{i,2} = D.trials(i).events.type;
table{i,3} = num2str(D.trials(i).events.value);
if ~isempty(D.trials(i).events.duration)
table{i,4} = num2str(D.trials(i).events.duration);
else
table{i,4} = 'Undefined';
end
table{i,5} = num2str(D.trials(i).events.time);
end
if D.trials(i).bad
table{i,6} = 'yes';
else
table{i,6} = 'no';
end
table{i,7} = num2str(D.trials(i).onset);
end
colnames = {'label','type','value','duration','time','bad','onset'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.74 0.7],...
'tag','plotEEG');
else
for i=1:nt
table{i,1} = D.trials(i).label;
table{i,2} = num2str(D.trials(i).repl);
if D.trials(i).bad
table{i,3} = 'yes';
else
table{i,3} = 'no';
end
end
colnames = {'label','nb of repl','bad'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.32 0.7],...
'tag','plotEEG');
end
end
if ok
D.PSD.handles.infoUItable = ht;
D.PSD.handles.infoUItable2 = hc;
D = spm_eeg_review_uis(D,object); % this adds the buttons
end
case 3 % inv info
object.list = [object.list;12];
isInv = D.PSD.source.VIZU.isInv;
% isInv = 1:length(D.other.inv);
if numel(isInv) >= 1 %D.PSD.source.VIZU.current ~= 0
Ninv = length(isInv);
table = cell(Ninv,12);
for i=1:Ninv
try
table{i,1} = [D.other.inv{isInv(i)}.comment{1},' '];
catch
table{i,1} = ' ';
end
table{i,2} = [D.other.inv{isInv(i)}.date(1,:)];
try
table{i,3} = [D.other.inv{isInv(i)}.inverse.modality];
catch
try
table{i,3} = [D.other.inv{isInv(i)}.modality];
catch
table{i,3} = '?';
end
end
table{i,4} = [D.other.inv{isInv(i)}.method];
try
table{i,5} = [num2str(length(D.other.inv{isInv(i)}.inverse.Is))];
catch
try
table{i,5} = [num2str(D.other.inv{isInv(i)}.inverse.n_dip)];
catch
table{i,5} = '?';
end
end
try
table{i,6} = [D.other.inv{isInv(i)}.inverse.type];
catch
table{i,6} = '?';
end
try
table{i,7} = [num2str(floor(D.other.inv{isInv(i)}.inverse.woi(1))),...
' to ',num2str(floor(D.other.inv{isInv(i)}.inverse.woi(2))),' ms'];
catch
table{i,7} = [num2str(floor(D.other.inv{isInv(i)}.inverse.pst(1))),...
' to ',num2str(floor(D.other.inv{isInv(i)}.inverse.pst(end))),' ms'];
end
try
if D.other.inv{isInv(i)}.inverse.Han
han = 'yes';
else
han = 'no';
end
table{i,8} = [han];
catch
table{i,8} = ['?'];
end
try
table{i,9} = [num2str(D.other.inv{isInv(i)}.inverse.lpf),...
' to ',num2str(D.other.inv{isInv(i)}.inverse.hpf), 'Hz'];
catch
table{i,9} = ['?'];
end
try
table{i,10} = [num2str(size(D.other.inv{isInv(i)}.inverse.T,2))];
catch
table{i,10} = '?';
end
try
table{i,11} = [num2str(D.other.inv{isInv(i)}.inverse.R2)];
catch
table{i,11} = '?';
end
table{i,12} = [num2str(sum(D.other.inv{isInv(i)}.inverse.F))];
end
colnames = {'label','date','modality','model','#dipoles','method',...
'pst','hanning','band pass','#modes','%var','log[p(y|m)]'};
[ht,hc] = spm_uitable('set',table,colnames);
set(ht,'units','normalized');
set(hc,'position',[0.1 0.05 0.8 0.7],...
'tag','plotEEG');
D.PSD.handles.infoUItable = ht;
D.PSD.handles.infoUItable2 = hc;
D = spm_eeg_review_uis(D,object); % this adds the buttons
else
POS = get(D.PSD.handles.infoTabs.hp,'position');
D.PSD.handles.message = uicontrol('style','text','units','normalized',...
'Position',[0.14 0.84 0.7 0.04].*repmat(POS(3:4),1,2),...
'string','There is no source reconstruction in this data file !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG');
end
case 4 % history info
object.list = [object.list;15];
table = spm_eeg_history(D);
if ~isempty(table)
colnames = {'Process','function called','input file','output file'};
[ht,hc] = spm_uitable(table,colnames);
set(ht,'units','normalized','editable',0);
set(hc,'position',[0.1 0.05 0.8 0.7],...
'tag','plotEEG');
D.PSD.handles.infoUItable = ht;
D.PSD.handles.infoUItable2 = hc;
else
POS = get(D.PSD.handles.infoTabs.hp,'position');
D.PSD.handles.message = uicontrol('style','text','units','normalized',...
'Position',[0.14 0.84 0.7 0.04].*repmat(POS(3:4),1,2),...
'string','The history of this file is not available !',...
'BackgroundColor',0.95*[1 1 1],...
'tag','plotEEG');
end
D = spm_eeg_review_uis(D,object); % this adds the buttons
end
% update data info if action called from 'info' tab...
if ~isempty(D.PSD.VIZU.fromTab) && isequal(D.PSD.VIZU.fromTab,'info')
[str] = spm_eeg_review_callbacks('get','dataInfo');
set(D.PSD.handles.infoText,'string',str)
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_dcm_bma_results.m
|
.m
|
antx-master/xspm8/spm_dcm_bma_results.m
| 10,490 |
utf_8
|
cfe23c82927c89ef91f7d28a226bff0e
|
function spm_dcm_bma_results(BMS,method)
% Plot histograms from BMA for selected modulatory and driving input
% FORMAT spm_dcm_bma_results(BMS,mod_in,drive_in,method)
%
% Input:
% BMS - BMS.mat file
% method - inference method (FFX or RFX)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Maria Joao
% $Id: spm_dcm_bma_results.m 6071 2014-06-27 12:52:33Z guillaume $
if nargin < 1
fname = spm_select(1,'^BMS.mat$','select BMS.mat file');
else
fname = BMS;
end
% load BMS file
%--------------------------------------------------------------------------
load(fname)
% Check BMS/BMA method used
%--------------------------------------------------------------------------
if nargin < 2
ff = fieldnames(BMS.DCM);
Nff = numel(ff);
if Nff==2
method = spm_input('Inference method','+1','b','FFX|RFX',['ffx';'rfx']);
else % pick the one available if only one method
method = char(ff);
end
end
% select method
%--------------------------------------------------------------------------
if isfield(BMS.DCM,method)
switch method
case 'ffx'
if isempty(BMS.DCM.ffx.bma)
error('No BMA analysis for FFX in BMS file!');
else
Nsamp = BMS.DCM.ffx.bma.nsamp;
amat = BMS.DCM.ffx.bma.a;
bmat = BMS.DCM.ffx.bma.b;
cmat = BMS.DCM.ffx.bma.c;
dmat = BMS.DCM.ffx.bma.d;
end
disp('Loading model space...')
load(BMS.DCM.ffx.data)
load(subj(1).sess(1).model(1).fname)
case 'rfx'
if isempty(BMS.DCM.rfx.bma)
error('No BMA analysis for RFX in BMS file!');
else
Nsamp = BMS.DCM.rfx.bma.nsamp;
amat = BMS.DCM.rfx.bma.a;
bmat = BMS.DCM.rfx.bma.b;
cmat = BMS.DCM.rfx.bma.c;
dmat = BMS.DCM.rfx.bma.d;
end
disp('Loading model space...')
load(BMS.DCM.rfx.data)
load(subj(1).sess(1).model(1).fname)
end
else
msgbox(sprintf('No %s analysis in current BMS.mat file!',method))
return
end
% number of regions, mod. inputs and names
%--------------------------------------------------------------------------
n = size(amat,2); % #region
m = size(bmat,3); % #drv/mod inputs
mi = size(cmat,2);
% Look for modulatory inputs
mod_input = [];
for ii=1:m
% look for bits of B not full of zeros
tmp = squeeze(bmat(:,:,ii,:));
if any(tmp(:))
mod_input = [mod_input ii];
end
end
% Look for effective driving inputs
drive_input = [];
for ii=1:m
% look for bits of not full of zeros
tmp = any(cmat(:,ii,:));
if sum(tmp)
drive_input = [drive_input ii];
end
end
% Non linear model ? If so find the driving regions
if ~isempty(dmat)
nonLin = 1;
mod_reg = [];
for ii=1:n
% look for bits of D not full of zeros
tmp = squeeze(dmat(:,:,ii,:));
if any(tmp(:))
mod_reg = [mod_reg ii];
end
end
else
nonLin = 0;
mod_reg = [];
end
if isfield(DCM.Y,'name')
for i=1:n,
region(i).name = DCM.Y.name{i};
end
else
for i=1:n,
str = sprintf('Region %d',i);
region(i).name = spm_input(['Name for ',str],'+1','s');
end
end
bins = Nsamp/100;
% intrinsic connection density
%--------------------------------------------------------------------------
F = spm_figure('GetWin','Graphics');
set(F,'name','BMA: results');
FS = spm('FontSizes');
usd.amat = amat;
usd.bmat = bmat;
usd.cmat = cmat;
usd.dmat = dmat;
usd.region = region;
usd.n = n;
usd.m = m;
usd.ni = mi;
usd.FS = FS;
usd.drive_input = drive_input;
usd.mod_input = mod_input;
if nonLin
usd.mod_reg = mod_reg;
end
usd.bins = bins;
usd.Nsamp = Nsamp;
set(F,'userdata',usd);
clf(F);
labels = {'a: int.'};
callbacks = {@plot_a};
for ii = mod_input
labels{end+1} = ['b: mod. i#',num2str(ii)];
callbacks{end+1} = @plot_b;
end
for ii = drive_input
labels{end+1} = ['c: drv. i#',num2str(ii)];
callbacks{end+1} = @plot_c;
end
if nonLin
for ii = mod_reg
labels{end+1} = ['d: mod. r#',num2str(ii)];
callbacks{end+1} = @plot_d;
end
end
[handles] = spm_uitab(F,labels,callbacks,'BMA_parameters',1);
set(handles.htab,'backgroundcolor',[1 1 1])
set(handles.hh,'backgroundcolor',[1 1 1])
set(handles.hp,'HighlightColor',0.8*[1 1 1])
set(handles.hp,'backgroundcolor',[1 1 1])
feval(@plot_a,F)
%==========================================================================
function plot_a(F)
try
F;
catch
F = get(gco,'parent');
end
H = findobj(F,'tag','BMA_parameters','type','uipanel');
hc = intersect(findobj('tag','bma_results'),get(H,'children'));
if ~isempty(hc)
delete(hc)
end
ud = get(F,'userdata');
titlewin = 'BMA: intrinsic connections (a)';
hTitAx = axes('Parent',H,'Position',[0.2,0.04,0.6,0.02],...
'Visible','off','tag','bma_results');
text(0.55,0,titlewin,'Parent',hTitAx,'HorizontalAlignment','center',...
'VerticalAlignment','baseline','FontWeight','Bold','FontSize',ud.FS(12))
for i=1:ud.n,
for j=1:ud.n,
k=(i-1)*ud.n+j;
subplot(ud.n,ud.n,k);
if (i==j)
axis off
else
hist(squeeze(ud.amat(i,j,:)),ud.bins,'r');
amax = max(abs(ud.amat(i,j,:)))*1.05; % enlarge scale by 5%
if amax > 0
xlim([-amax amax])
else % case where parameter is constrained to be 0.
xlim([-10 10])
end
set(gca,'YTickLabel',[]);
set(gca,'FontSize',12);
title(sprintf('%s to %s',ud.region(j).name,ud.region(i).name));
end
end
end
%==========================================================================
function plot_b
hf = get(gco,'parent');
ud = get(hf,'userdata');
H = findobj(hf,'tag','BMA_parameters','type','uipanel');
hc = intersect(findobj('tag','bma_results'),get(H,'children'));
if ~isempty(hc)
delete(hc)
end
% spot the bmod input index from the fig name
ht = intersect(findobj('style','pushbutton'),get(hf,'children'));
ht = findobj(ht,'flat','Fontweight','bold');
t_str = get(ht,'string');
b_ind = str2num(t_str(strfind(t_str,'#')+1:end));
i_mod = find(ud.mod_input==b_ind);
titlewin = ['BMA: modulatory connections (b',num2str(b_ind),')'];
hTitAx = axes('Parent',H,'Position',[0.2,0.04,0.6,0.02],...
'Visible','off','tag','bma_results');
text(0.55,0,titlewin,'Parent',hTitAx,'HorizontalAlignment','center',...
'VerticalAlignment','baseline','FontWeight','Bold','FontSize',ud.FS(12))
for i=1:ud.n,
for j=1:ud.n,
k=(i-1)*ud.n+j;
subplot(ud.n,ud.n,k);
if (i==j)
axis off
else
hist(squeeze(ud.bmat(i,j,ud.mod_input(i_mod),:)),ud.bins,'r');
bmax = max(abs(ud.bmat(i,j,ud.mod_input(i_mod),:)))*1.05; % enlarge scale by 5%
if bmax > 0
xlim([-bmax bmax])
else % case where parameter is constrained to be 0.
xlim([-10 10])
end
set(gca,'YTickLabel',[]);
set(gca,'FontSize',12);
title(sprintf('%s to %s',ud.region(j).name,ud.region(i).name));
end
end
end
%==========================================================================
function plot_c
hf = get(gco,'parent');
ud = get(hf,'userdata');
H = findobj(hf,'tag','BMA_parameters','type','uipanel');
hc = intersect(findobj('tag','bma_results'),get(H,'children'));
if ~isempty(hc)
delete(hc)
end
% spot the c_drv input index from the fig name
ht = intersect(findobj('style','pushbutton'),get(hf,'children'));
ht = findobj(ht,'flat','Fontweight','bold');
t_str = get(ht,'string');
c_ind = str2num(t_str(strfind(t_str,'#')+1:end));
i_drv = find(ud.drive_input==c_ind);
titlewin = ['BMA: input connections (c',num2str(c_ind),')'];
hTitAx = axes('Parent',H,'Position',[0.2,0.04,0.6,0.02],...
'Visible','off','tag','bma_results');
text(0.55,0,titlewin,'Parent',hTitAx,'HorizontalAlignment','center',...
'VerticalAlignment','baseline','FontWeight','Bold','FontSize',ud.FS(12))
for j=1:ud.n,
subplot(1,ud.n,j);
if length(find(ud.cmat(j,ud.drive_input(i_drv),:)==0))==ud.Nsamp
plot([0 0],[0 1],'k');
else
hist(squeeze(ud.cmat(j,ud.drive_input(i_drv),:)),ud.bins,'r');
cmax = max(abs(ud.cmat(j,ud.drive_input(i_drv),:)))*1.05; % enlarge scale by 5%
if cmax > 0
xlim([-cmax cmax])
else % case where parameter is constrained to be 0.
xlim([-10 10])
end
end
set(gca,'YTickLabel',[]);
set(gca,'FontSize',12);
title(sprintf('%s ',ud.region(j).name));
end
%==========================================================================
function plot_d
hf = get(gco,'parent');
ud = get(hf,'userdata');
H = findobj(hf,'tag','BMA_parameters','type','uipanel');
hc = intersect(findobj('tag','bma_results'),get(H,'children'));
if ~isempty(hc)
delete(hc)
end
% spot the d_reg input index from the fig name
ht = intersect(findobj('style','pushbutton'),get(hf,'children'));
ht = findobj(ht,'flat','Fontweight','bold');
t_str = get(ht,'string');
d_ind = str2num(t_str(strfind(t_str,'#')+1:end));
i_mreg = find(ud.mod_reg==d_ind);
titlewin = ['BMA: non-linear connections (d',num2str(d_ind),')'];
hTitAx = axes('Parent',H,'Position',[0.2,0.04,0.6,0.02],...
'Visible','off','tag','bma_results');
text(0.55,0,titlewin,'Parent',hTitAx,'HorizontalAlignment','center',...
'VerticalAlignment','baseline','FontWeight','Bold','FontSize',ud.FS(12))
for i=1:ud.n,
for j=1:ud.n,
k=(i-1)*ud.n+j;
subplot(ud.n,ud.n,k);
if (i==j)
axis off
else
hist(squeeze(ud.dmat(i,j,ud.mod_reg(i_mreg),:)),ud.bins,'r');
dmax = max(abs(ud.dmat(i,j,ud.mod_reg(i_mreg),:)))*1.05; % enlarge scale by 5%
if dmax > 0
xlim([-dmax dmax])
else % case where parameter is constrained to be 0.
xlim([-10 10])
end
set(gca,'YTickLabel',[]);
set(gca,'FontSize',12);
title(sprintf('%s to %s',ud.region(j).name,ud.region(i).name));
end
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_check_filename.m
|
.m
|
antx-master/xspm8/spm_check_filename.m
| 2,311 |
utf_8
|
b8de0a161ecbb9d70247bbf51873bb0e
|
function V = spm_check_filename(V)
% Checks paths are valid and tries to restore path names
% FORMAT V = spm_check_filename(V)
%
% V - struct array of file handles
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_check_filename.m 3934 2010-06-17 14:58:25Z guillaume $
if isdeployed, return; end
% check filenames
%--------------------------------------------------------------------------
for i = 1:length(V)
% see if file exists
%----------------------------------------------------------------------
if ~spm_existfile(V(i).fname)
% try current directory
%------------------------------------------------------------------
[p,n,e] = fileparts(V(i).fname);
fname = which([n,e]);
if ~isempty(fname)
V(i).fname = fname;
else
% try parent directory
%--------------------------------------------------------------
cwd = pwd;
cd('..')
fname = which([n,e]);
if ~isempty(fname)
V(i).fname = fname;
else
% try children of parent
%----------------------------------------------------------
V = spm_which_filename(V);
cd(cwd)
return
end
cd(cwd)
end
end
end
%==========================================================================
function V = spm_which_filename(V)
% get children directories of parent
%--------------------------------------------------------------------------
cwd = pwd;
cd('..')
gwd = genpath(pwd);
addpath(gwd);
% cycle through handles
%--------------------------------------------------------------------------
for i = 1:length(V)
try
% get relative path (directory and filename) and find in children
%------------------------------------------------------------------
j = strfind(V(i).fname,filesep);
fname = which(fname(j(end - 1):end));
if ~isempty(fname)
V(i).fname = fname;
end
end
end
% reset paths
%--------------------------------------------------------------------------
rmpath(gwd);
cd(cwd);
|
github
|
philippboehmsturm/antx-master
|
spm_defs.m
|
.m
|
antx-master/xspm8/spm_defs.m
| 11,688 |
utf_8
|
217cf06b73a160542c57789ec5490b4f
|
function out = spm_defs(job)
% Various deformation field utilities.
% FORMAT out = spm_defs(job)
% job - a job created via spm_config_defs.m and spm_jobman.m
% out - a struct with fields
% .def - file name of created deformation field
% .warped - file names of warped images
%
% See spm_config_defs.m for more information.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_defs.m 4194 2011-02-05 18:08:06Z ged $
[Def,mat] = get_comp(job.comp);
[dpath ipath] = get_paths(job);
out.def = save_def(Def,mat,strvcat(job.ofname),dpath);
out.warped = apply_def(Def,mat,strvcat(job.fnames),ipath,job.interp);
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_comp(job)
% Return the composition of a number of deformation fields.
if isempty(job),
error('Empty list of jobs in composition');
end;
[Def,mat] = get_job(job{1});
for i=2:numel(job),
Def1 = Def;
mat1 = mat;
[Def,mat] = get_job(job{i});
M = inv(mat1);
for j=1:size(Def{1},3)
d0 = {double(Def{1}(:,:,j)), double(Def{2}(:,:,j)),double(Def{3}(:,:,j))};
d{1} = M(1,1)*d0{1}+M(1,2)*d0{2}+M(1,3)*d0{3}+M(1,4);
d{2} = M(2,1)*d0{1}+M(2,2)*d0{2}+M(2,3)*d0{3}+M(2,4);
d{3} = M(3,1)*d0{1}+M(3,2)*d0{2}+M(3,3)*d0{3}+M(3,4);
Def{1}(:,:,j) = single(spm_sample_vol(Def1{1},d{:},[1,NaN]));
Def{2}(:,:,j) = single(spm_sample_vol(Def1{2},d{:},[1,NaN]));
Def{3}(:,:,j) = single(spm_sample_vol(Def1{3},d{:},[1,NaN]));
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_job(job)
% Determine what is required, and pass the relevant bit of the
% job out to the appropriate function.
fn = fieldnames(job);
fn = fn{1};
switch fn
case {'comp'}
[Def,mat] = get_comp(job.(fn));
case {'def'}
[Def,mat] = get_def(job.(fn));
case {'dartel'}
[Def,mat] = get_dartel(job.(fn));
case {'sn2def'}
[Def,mat] = get_sn2def(job.(fn));
case {'inv'}
[Def,mat] = get_inv(job.(fn));
case {'id'}
[Def,mat] = get_id(job.(fn));
case {'idbbvox'}
[Def,mat] = get_idbbvox(job.(fn));
otherwise
error('Unrecognised job type');
end;
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_sn2def(job)
% Convert a SPM _sn.mat file into a deformation field, and return it.
vox = job.vox;
bb = job.bb;
sn = load(job.matname{1});
if any(isfinite(bb(:))) || any(isfinite(vox)),
[bb0,vox0] = spm_get_bbox(sn.VG(1), 'old');
if any(~isfinite(vox)), vox = vox0; end;
if any(~isfinite(bb)), bb = bb0; end;
bb = sort(bb);
vox = abs(vox);
% Adjust bounding box slightly - so it rounds to closest voxel.
bb(:,1) = round(bb(:,1)/vox(1))*vox(1);
bb(:,2) = round(bb(:,2)/vox(2))*vox(2);
bb(:,3) = round(bb(:,3)/vox(3))*vox(3);
M = sn.VG(1).mat;
vxg = sqrt(sum(M(1:3,1:3).^2));
ogn = M\[0 0 0 1]';
ogn = ogn(1:3)';
% Convert range into range of voxels within template image
x = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1);
y = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2);
z = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3);
og = -vxg.*ogn;
of = -vox.*(round(-bb(1,:)./vox)+1);
M1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1];
M2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1];
mat = sn.VG(1).mat*inv(M1)*M2;
% dim = [length(x) length(y) length(z)];
else
dim = sn.VG(1).dim;
x = 1:dim(1);
y = 1:dim(2);
z = 1:dim(3);
mat = sn.VG(1).mat;
end
[X,Y] = ndgrid(x,y);
st = size(sn.Tr);
if (prod(st) == 0),
affine_only = true;
basX = 0;
basY = 0;
basZ = 0;
else
affine_only = false;
basX = spm_dctmtx(sn.VG(1).dim(1),st(1),x-1);
basY = spm_dctmtx(sn.VG(1).dim(2),st(2),y-1);
basZ = spm_dctmtx(sn.VG(1).dim(3),st(3),z-1);
end,
Def = single(0);
Def(numel(x),numel(y),numel(z)) = 0;
Def = {Def; Def; Def};
for j=1:length(z)
if (~affine_only)
tx = reshape( reshape(sn.Tr(:,:,:,1),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );
ty = reshape( reshape(sn.Tr(:,:,:,2),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );
tz = reshape( reshape(sn.Tr(:,:,:,3),st(1)*st(2),st(3)) *basZ(j,:)', st(1), st(2) );
X1 = X + basX*tx*basY';
Y1 = Y + basX*ty*basY';
Z1 = z(j) + basX*tz*basY';
end
Mult = sn.VF.mat*sn.Affine;
if (~affine_only)
X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4);
Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4);
Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4);
else
X2= Mult(1,1)*X + Mult(1,2)*Y + (Mult(1,3)*z(j) + Mult(1,4));
Y2= Mult(2,1)*X + Mult(2,2)*Y + (Mult(2,3)*z(j) + Mult(2,4));
Z2= Mult(3,1)*X + Mult(3,2)*Y + (Mult(3,3)*z(j) + Mult(3,4));
end
Def{1}(:,:,j) = single(X2);
Def{2}(:,:,j) = single(Y2);
Def{3}(:,:,j) = single(Z2);
end;
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_def(job)
% Load a deformation field saved as an image
P = [repmat(job{:},3,1), [',1,1';',1,2';',1,3']];
V = spm_vol(P);
Def = cell(3,1);
Def{1} = spm_load_float(V(1));
Def{2} = spm_load_float(V(2));
Def{3} = spm_load_float(V(3));
mat = V(1).mat;
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_dartel(job)
% Integrate a DARTEL flow field
N = nifti(job.flowfield{1});
y = spm_dartel_integrate(N.dat,job.times,job.K);
Def = cell(3,1);
if all(job.times == [0 1]),
M = single(N.mat);
mat = N.mat0;
else
M = single(N.mat0);
mat = N.mat;
end
Def{1} = y(:,:,:,1)*M(1,1) + y(:,:,:,2)*M(1,2) + y(:,:,:,3)*M(1,3) + M(1,4);
Def{2} = y(:,:,:,1)*M(2,1) + y(:,:,:,2)*M(2,2) + y(:,:,:,3)*M(2,3) + M(2,4);
Def{3} = y(:,:,:,1)*M(3,1) + y(:,:,:,2)*M(3,2) + y(:,:,:,3)*M(3,3) + M(3,4);
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_id(job)
% Get an identity transform based on an image volume.
N = nifti(job.space{1});
d = [size(N.dat),1];
d = d(1:3);
mat = N.mat;
Def = cell(3,1);
[y1,y2,y3] = ndgrid(1:d(1),1:d(2),1:d(3));
Def{1} = single(y1*mat(1,1) + y2*mat(1,2) + y3*mat(1,3) + mat(1,4));
Def{2} = single(y1*mat(2,1) + y2*mat(2,2) + y3*mat(2,3) + mat(2,4));
Def{3} = single(y1*mat(3,1) + y2*mat(3,2) + y3*mat(3,3) + mat(3,4));
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_idbbvox(job)
% Get an identity transform based on bounding box and voxel size.
% This will produce a transversal image.
d = floor(diff(job.bb)./job.vox);
d(d == 0) = 1;
mat = diag([-1 1 1 1])*spm_matrix([job.bb(1,:) 0 0 0 job.vox]);
Def = cell(3,1);
[y1,y2,y3] = ndgrid(1:d(1),1:d(2),1:d(3));
Def{1} = single(y1*mat(1,1) + y2*mat(1,2) + y3*mat(1,3) + mat(1,4));
Def{2} = single(y1*mat(2,1) + y2*mat(2,2) + y3*mat(2,3) + mat(2,4));
Def{3} = single(y1*mat(3,1) + y2*mat(3,2) + y3*mat(3,3) + mat(3,4));
%_______________________________________________________________________
%_______________________________________________________________________
function [Def,mat] = get_inv(job)
% Invert a deformation field (derived from a composition of deformations)
VT = spm_vol(job.space{:});
[Def0,mat0] = get_comp(job.comp);
M0 = mat0;
M1 = inv(VT.mat);
M0(4,:) = [0 0 0 1];
M1(4,:) = [0 0 0 1];
[Def{1},Def{2},Def{3}] = spm_invdef(Def0{:},VT.dim(1:3),M1,M0);
mat = VT.mat;
%_______________________________________________________________________
%_______________________________________________________________________
function [dpath,ipath] = get_paths(job)
switch char(fieldnames(job.savedir))
case 'savepwd'
dpath = pwd;
ipath = pwd;
case 'savesrc'
dpath = get_dpath(job);
ipath = '';
case 'savedef'
dpath = get_dpath(job);
ipath = dpath;
case 'saveusr'
dpath = job.savedir.saveusr{1};
ipath = dpath;
end
%_______________________________________________________________________
%_______________________________________________________________________
function dpath = get_dpath(job)
% Determine what is required, and pass the relevant bit of the
% job out to the appropriate function.
fn = fieldnames(job);
fn = fn{1};
switch fn
case {'comp'}
dpath = get_dpath(job.(fn){1});
case {'def'}
dpath = fileparts(job.(fn){1});
case {'dartel'}
dpath = fileparts(job.(fn).flowfield{1});
case {'sn2def'}
dpath = fileparts(job.(fn).matname{1});
case {'inv'}
dpath = fileparts(job.(fn).space{1});
case {'id'}
dpath = fileparts(job.(fn).space{1});
otherwise
error('Unrecognised job type');
end;
%_______________________________________________________________________
%_______________________________________________________________________
function fname = save_def(Def,mat,ofname,odir)
% Save a deformation field as an image
if isempty(ofname), fname = {}; return; end;
fname = {fullfile(odir,['y_' ofname '.nii'])};
dim = [size(Def{1},1) size(Def{1},2) size(Def{1},3) 1 3];
dtype = 'FLOAT32';
off = 0;
scale = 1;
inter = 0;
dat = file_array(fname{1},dim,dtype,off,scale,inter);
N = nifti;
N.dat = dat;
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Aligned';
N.mat0_intent = 'Aligned';
N.intent.code = 'VECTOR';
N.intent.name = 'Mapping';
N.descrip = 'Deformation field';
create(N);
N.dat(:,:,:,1,1) = Def{1};
N.dat(:,:,:,1,2) = Def{2};
N.dat(:,:,:,1,3) = Def{3};
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ofnames = apply_def(Def,mat,fnames,odir,intrp)
% Warp an image or series of images according to a deformation field
intrp = [intrp*[1 1 1], 0 0 0];
ofnames = cell(size(fnames,1),1);
for i=1:size(fnames,1),
V = spm_vol(fnames(i,:));
M = inv(V.mat);
[pth,nam,ext,num] = spm_fileparts(deblank(fnames(i,:)));
if isempty(odir)
% use same path as source image
opth = pth;
else
% use prespecified path
opth = odir;
end
ofnames{i} = fullfile(opth,['w',nam,ext]);
Vo = struct('fname',ofnames{i},...
'dim',[size(Def{1},1) size(Def{1},2) size(Def{1},3)],...
'dt',V.dt,...
'pinfo',V.pinfo,...
'mat',mat,...
'n',V.n,...
'descrip',V.descrip);
ofnames{i} = [ofnames{i} num];
C = spm_bsplinc(V,intrp);
Vo = spm_create_vol(Vo);
for j=1:size(Def{1},3)
d0 = {double(Def{1}(:,:,j)), double(Def{2}(:,:,j)),double(Def{3}(:,:,j))};
d{1} = M(1,1)*d0{1}+M(1,2)*d0{2}+M(1,3)*d0{3}+M(1,4);
d{2} = M(2,1)*d0{1}+M(2,2)*d0{2}+M(2,3)*d0{3}+M(2,4);
d{3} = M(3,1)*d0{1}+M(3,2)*d0{2}+M(3,3)*d0{3}+M(3,4);
dat = spm_bsplins(C,d{:},intrp);
Vo = spm_write_plane(Vo,dat,j);
end;
end;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_sp.m
|
.m
|
antx-master/xspm8/spm_sp.m
| 39,708 |
utf_8
|
180830974ed2715dc2f976a356081a60
|
function varargout = spm_sp(varargin)
% Orthogonal (design) matrix space setting & manipulation
% FORMAT varargout = spm_spc(action,varargin)
%
% This function computes the different projectors related to the row
% and column spaces X. It should be used to avoid redundant computation
% of svd on large X matrix. It is divided into actions that set up the
% space, (Create,Set,...) and actions that compute projections (pinv,
% pinvXpX, pinvXXp, ...) This is motivated by the problem of rounding
% errors that can invalidate some computation and is a tool to work
% with spaces.
%
% The only thing that is not easily computed is the null space of
% the line of X (assuming size(X,1) > size(X,2)).
% To get this space (a basis of it or a projector on it) use spm_sp on X'.
%
% The only restriction on the use of the space structure is when X is
% so big that you can't fit X and its svd in memory at the same time.
% Otherwise, the use of spm_sp will generally speed up computations and
% optimise memory use.
%
% Note that since the design matrix is stored in the space structure,
% there is no need to keep a separate copy of it.
%
% ----------------
%
% The structure is:
% x = struct(...
% 'X', [],... % Mtx
% 'tol', [],... % tolerance
% 'ds', [],... % vectors of singular values
% 'u', [],... % u as in X = u*diag(ds)*v'
% 'v', [],... % v as in X = u*diag(ds)*v'
% 'rk', [],... % rank
% 'oP', [],... % orthogonal projector on X
% 'oPp', [],... % orthogonal projector on X'
% 'ups', [],... % space in which this one is embeded
% 'sus', []); % subspace
%
% The basic required fields are X, tol, ds, u, v, rk.
%
% ======================================================================
%
% FORMAT x = spm_sp('Set',X)
% Set up space structure, storing matrix, singular values, rank & tolerance
% X - a (design) matrix (2D)
% x - the corresponding space structure, with basic fields filled in
% The SVD is an "economy size" svd, using MatLab's svd(X,0)
%
%
% FORMAT r = spm_sp('oP',x[,Y])
% FORMAT r = spm_sp('oPp',x[,Y])
% Return orthogonal projectors, or orthogonal projection of data Y (if passed)
% x - space structure of matrix X
% r - ('oP' usage) ortho. projection matrix projecting into column space of x.X
% - ('oPp' usage) ortho. projection matrix projecting into row space of x.X
% Y - data (optional)
% - If data are specified then the corresponding projection of data is
% returned. This is usually more efficient that computing and applying
% the projection matrix directly.
%
%
% FORMAT pX = spm_sp('pinv',x)
% Returns a pseudo-inverse of X - pinv(X) - computed efficiently
% x - space structure of matrix X
% pX - pseudo-inverse of X
% This is the same as MatLab's pinv - the Moore-Penrose pseudoinverse
% ( Note that because size(pinv(X)) == size(X'), it is not generally )
% ( useful to compute pinv(X)*Data sequentially (as is the case for )
% ( 'res' or 'oP') )
%
%
% FORMAT pXpX = spm_sp('pinvxpx',x)
% Returns a pseudo-inverse of X'X - pinv(X'*X) - computed efficiently
% x - space structure of matrix X
% pXpX - pseudo-inverse of (X'X)
% ( Note that because size(pinv(X'*X)) == [size(X,2) size(X,2)], )
% ( it is not useful to compute pinv(X'X)*Data sequentially unless )
% ( size(X,1) < size(X,2) )
%
%
% FORMAT XpX = spm_sp('xpx',x)
% Returns (X'X) - computed efficiently
% x - space structure of matrix X
% XpX - (X'X)
%
%
% FORMAT pXXp = spm_sp('pinvxxp',x)
% Returns a pseudo-inverse of XX' - pinv(X*X') - computed efficiently
% x - space structure of matrix X
% pXXp - pseudo-inverse of (XX')
%
%
% FORMAT XXp = spm_sp('xxp',x)
% Returns (XX') - computed efficiently
% x - space structure of matrix X
% XXp - (XX')
%
%
% FORMAT b = spm_sp('isinsp',x,c[,tol])
% FORMAT b = spm_sp('isinspp',x,c[,tol])
% Check whether vectors c are in the column/row space of X
% x - space structure of matrix X
% c - vector(s) (Multiple vectors passed as a matrix)
% tol - (optional) tolerance (for rounding error)
% [defaults to tolerance specified in space structure: x.tol]
% b - ('isinsp' usage) true if c is in the column space of X
% - ('isinspp' usage) true if c is in the column space of X
%
% FORMAT b = spm_sp('eachinsp',x,c[,tol])
% FORMAT b = spm_sp('eachinspp',x,c[,tol])
% Same as 'isinsp' and 'isinspp' but returns a logical row vector of
% length size(c,2).
%
% FORMAT N = spm_sp('n',x)
% Simply returns the null space of matrix X (same as matlab NULL)
% (Null space = vectors associated with zero eigenvalues)
% x - space structure of matrix X
% N - null space
%
%
% FORMAT r = spm_sp('nop',x[,Y])
% Orthogonal projector onto null space of X, or projection of data Y (if passed)
% x - space structure of matrix X
% Y - (optional) data
% r - (if no Y passed) orthogonal projection matrix into the null space of X
% - (if Y passed ) orthogonal projection of data into the null space of X
% ( Note that if xp = spm_sp('set',x.X'), we have: )
% ( spm_sp('nop',x) == spm_sp('res',xp) )
% ( or, equivalently: )
% ( spm_sp('nop',x) + spm_sp('oP',xp) == eye(size(xp.X,1)); )
%
%
% FORMAT r = spm_sp('res',x[,Y])
% Returns residual formaing matrix wirit column space of X, or residuals (if Y)
% x - space structure of matrix X
% Y - (optional) data
% r - (if no Y passed) residual forming matrix for design matrix X
% - (if Y passed ) residuals, i.e. residual forming matrix times data
% ( This will be more efficient than
% ( spm_sp('res',x)*Data, when size(X,1) > size(X,2)
% Note that this can also be seen as the orthogonal projector onto the
% null space of x.X' (which is not generally computed in svd, unless
% size(X,1) < size(X,2)).
%
%
% FORMAT oX = spm_sp('ox', x)
% FORMAT oXp = spm_sp('oxp',x)
% Returns an orthonormal basis for X ('ox' usage) or X' ('oxp' usage)
% x - space structure of matrix X
% oX - orthonormal basis for X - same as orth(x.X)
% xOp - *an* orthonormal for X' (but not the same as orth(x.X'))
%
%
% FORMAT b = spm_sp('isspc',x)
% Check a variable is a structure with the right fields for a space structure
% x - candidate variable
% b - true if x is a structure with fieldnames corresponding to spm_sp('create')
%
%
% FORMAT [b,e] = spm_sp('issetspc',x)
% Test whether a variable is a space structure with the basic fields set
% x - candidate variable
% b - true is x is a structure with fieldnames corresponding to
% spm_sp('Create'), which has it's basic fields filled in.
% e - string describing why x fails the issetspc test (if it does)
% This is simply a gateway function combining spm_sp('isspc',x) with
% the internal subfunction sf_isset, which checks that the basic fields
% are not empty. See sf_isset (below).
%
%-----------------------------------------------------------------------
% SUBFUNCTIONS:
%
% FORMAT b = sf_isset(x)
% Checks that the basic fields are non-empty (doesn't check they're right!)
% x - space structure
% b - true if the basic fields are non-empty
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean-Baptiste Poline
% $Id: spm_sp.m 1143 2008-02-07 19:33:33Z spm $
if nargin==0
error('Do what? no arguments given...')
else
action = varargin{1};
end
%- check the very basics arguments
switch lower(action),
case {'create','set','issetspc','isspc'}
%- do nothing
otherwise,
if nargin==1, error('No space : can''t do much!'), end
[ok,str] = spm_sp('issetspc',varargin{2});
if ~ok, error(str), else, sX = varargin{2}; end;
end;
switch lower(action),
case 'create' %-Create space structure
%=======================================================================
% x = spm_sp('Create')
varargout = {sf_create};
case 'set' %-Set singular values, space basis, rank & tolerance
%=======================================================================
% x = spm_sp('Set',X)
if nargin==1 error('No design matrix : can''t do much!'),
else X = varargin{2}; end
if isempty(X), varargout = {sf_create}; return, end
%- only sets plain matrices
%- check X has 2 dim only
if max(size(size(X))) > 2, error('Too many dim in the set'), end
if ~isnumeric(X), error('only sets numeric matrices'), end
varargout = {sf_set(X)};
case {'p', 'transp'} %-Transpose space of X
%=======================================================================
switch nargin
case 2
varargout = {sf_transp(sX)};
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'op', 'op:'} %-Orthogonal projectors on space of X
%=======================================================================
% r = spm_sp('oP', sX[,Y])
% r = spm_sp('oP:', sX[,Y]) %- set to 0 less than tolerence values
%
% if isempty(Y) returns as if Y not given
%-----------------------------------------------------------------------
switch nargin
case 2
switch lower(action),
case 'op'
varargout = {sf_op(sX)};
case 'op:'
varargout = {sf_tol(sf_op(sX),sX.tol)};
end %- switch lower(action),
case 3
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action),
case 'op'
varargout = {sf_op(sX)*Y};
case 'op:'
varargout = {sf_tol(sf_op(sX)*Y,sX.tol)};
end % switch lower(action)
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'opp', 'opp:'} %-Orthogonal projectors on space of X'
%=======================================================================
% r = spm_sp('oPp',sX[,Y])
% r = spm_sp('oPp:',sX[,Y]) %- set to 0 less than tolerence values
%
% if isempty(Y) returns as if Y not given
%-----------------------------------------------------------------------
switch nargin
case 2
switch lower(action),
case 'opp'
varargout = {sf_opp(sX)};
case 'opp:'
varargout = {sf_tol(sf_opp(sX),sX.tol)};
end %- switch lower(action),
case 3
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case 'opp'
varargout = {sf_opp(sX)*Y};
case 'opp:'
varargout = {sf_tol(sf_opp(sX)*Y,sX.tol)};
end % switch lower(action)
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'x-','x-:'} %-Pseudo-inverse of X - pinv(X)
%=======================================================================
% = spm_sp('x-',x)
switch nargin
case 2
switch lower(action),
case {'x-'}
varargout = { sf_pinv(sX) };
case {'x-:'}
varargout = {sf_tol( sf_pinv(sX), sf_t(sX) )};
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'x-'}
varargout = { sf_pinv(sX)*Y };
case {'x-:'}
varargout = {sf_tol( sf_pinv(sX)*Y, sf_t(sX) )};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'xp-','xp-:','x-p','x-p:'} %- Pseudo-inverse of X'
%=======================================================================
% pX = spm_sp('xp-',x)
switch nargin
case 2
switch lower(action),
case {'xp-','x-p'}
varargout = { sf_pinvxp(sX) };
case {'xp-:','x-p:'}
varargout = {sf_tol( sf_pinvxp(sX), sf_t(sX) )};
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'xp-','x-p'}
varargout = { sf_pinvxp(sX)*Y };
case {'xp-:','x-p:'}
varargout = {sf_tol( sf_pinvxp(sX)*Y, sf_t(sX) )};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'cukxp-','cukxp-:'} %- Coordinates of pinv(X') in the base of uk
%=======================================================================
% pX = spm_sp('cukxp-',x)
switch nargin
case 2
switch lower(action),
case {'cukxp-'}
varargout = { sf_cukpinvxp(sX) };
case {'cukxp-:'}
varargout = {sf_tol(sf_cukpinvxp(sX),sX.tol)};
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'cukxp-'}
varargout = { sf_cukpinvxp(sX)*Y };
case {'cukxp-:'}
varargout = {sf_tol(sf_cukpinvxp(sX)*Y,sX.tol)};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'cukx','cukx:'} %- Coordinates of X in the base of uk
%=======================================================================
% pX = spm_sp('cukx',x)
switch nargin
case 2
switch lower(action),
case {'cukx'}
varargout = { sf_cukx(sX) };
case {'cukx:'}
varargout = {sf_tol(sf_cukx(sX),sX.tol)};
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'cukx'}
varargout = { sf_cukx(sX)*Y };
case {'cukx:'}
varargout = {sf_tol(sf_cukx(sX)*Y,sX.tol)};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'rk'} %- Returns rank
%=======================================================================
varargout = { sf_rk(sX) };
case {'ox', 'oxp'} %-Orthonormal basis sets for X / X'
%=======================================================================
% oX = spm_sp('ox', x)
% oXp = spm_sp('oxp',x)
if sf_rk(sX) > 0
switch lower(action)
case 'ox'
varargout = {sf_uk(sX)};
case 'oxp'
varargout = {sf_vk(sX)};
end
else
switch lower(action)
case 'ox'
varargout = {zeros(sf_s1(sX),1)};
case 'oxp'
varargout = {zeros(sf_s2(sX),1)};
end
end
case {'x', 'xp'} %- X / X' robust to spm_sp changes
%=======================================================================
% X = spm_sp('x', x)
% X' = spm_sp('xp',x)
switch lower(action)
case 'x', varargout = {sX.X};
case 'xp', varargout = {sX.X'};
end
case {'xi', 'xpi'} %- X(:,i) / X'(:,i) robust to spm_sp changes
%=======================================================================
% X = spm_sp('xi', x)
% X' = spm_sp('xpi',x)
i = varargin{3}; % NO CHECKING on i !!! assumes correct
switch lower(action)
case 'xi', varargout = {sX.X(:,i)};
case 'xpi', varargout = {sX.X(i,:)'};
end
case {'uk','uk:'} %- Returns u(:,1:r)
%=======================================================================
% pX = spm_sp('uk',x)
% Notice the difference with 'ox' : 'ox' always returns a basis of the
% proper siwe while this returns empty if rank is null
warning('can''t you use ox ?');
switch nargin
case 2
switch lower(action),
case {'uk'}
varargout = { sf_uk(sX) };
case {'uk:'}
varargout = { sf_tol(sf_uk(sX),sX.tol) };
end
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_rk(sX), error(['Dim dont match ' action]); end
switch lower(action),
case {'uk'}
varargout = { sf_uk(sX)*Y };
case {'uk:'}
varargout = {sf_tol(sf_uk(sX)*Y,sX.tol)};
end
otherwise
error(['too many input argument in spm_sp ' action]);
end % switch nargin
case {'pinvxpx', 'xpx-', 'pinvxpx:', 'xpx-:',} %- Pseudo-inv of (X'X)
%=======================================================================
% pXpX = spm_sp('pinvxpx',x [,Y])
switch nargin
case 2
switch lower(action),
case {'xpx-','pinvxpx'}
varargout = {sf_pinvxpx(sX)};
case {'xpx-:','pinvxpx:'}
varargout = {sf_tol(sf_pinvxpx(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'xpx-','pinvxpx'}
varargout = {sf_pinvxpx(sX)*Y};
case {'xpx-:','pinvxpx:'}
varargout = {sf_tol(sf_pinvxpx(sX)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'xpx','xpx:'} %-Computation of (X'*X)
%=======================================================================
% XpX = spm_sp('xpx',x [,Y])
switch nargin
case 2
switch lower(action),
case {'xpx'}
varargout = {sf_xpx(sX)};
case {'xpx:'}
varargout = {sf_tol(sf_xpx(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'xpx'}
varargout = {sf_xpx(sX)*Y};
case {'xpx:'}
varargout = {sf_tol(sf_xpx(sX)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'cx->cu','cx->cu:'} %-coordinates in the basis of X -> basis u
%=======================================================================
%
% returns cu such that sX.X*cx == sX.u*cu
switch nargin
case 2
switch lower(action),
case {'cx->cu'}
varargout = {sf_cxtwdcu(sX)};
case {'cx->cu:'}
varargout = {sf_tol(sf_cxtwdcu(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'cx->cu'}
varargout = {sf_cxtwdcu(sX)*Y};
case {'cx->cu:'}
varargout = {sf_tol(sf_cxtwdcu(sX)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'xxp-','xxp-:','pinvxxp','pinvxxp:'} %-Pseudo-inverse of (XX')
%=======================================================================
% pXXp = spm_sp('pinvxxp',x [,Y])
switch nargin
case 2
switch lower(action),
case {'xxp-','pinvxxp'}
varargout = {sf_pinvxxp(sX)};
case {'xxp-:','pinvxxp:'}
varargout = {sf_tol(sf_pinvxxp(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action),
case {'xxp-','pinvxxp'}
varargout = {sf_pinvxxp(sX)*Y};
case {'xxp-:','pinvxxp:'}
varargout = {sf_tol(sf_pinvxxp(sX)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'xxp','xxp:'} %-Computation of (X*X')
%=======================================================================
% XXp = spm_sp('xxp',x)
switch nargin
case 2
switch lower(action),
case {'xxp'}
varargout = {sf_xxp(sX)};
case {'xxp:'}
varargout = {sf_tol(sf_xxp(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action),
case {'xxp'}
varargout = {sf_xxpY(sX,Y)};
case {'xxp:'}
varargout = {sf_tol(sf_xxpY(sX,Y),sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'^p','^p:'} %-Computation of v*(diag(s.^n))*v'
%=======================================================================
switch nargin
case {2,3}
if nargin==2, n = 1; else n = varargin{3}; end;
if ~isnumeric(n), error('~isnumeric(n)'), end;
switch lower(action),
case {'^p'}
varargout = {sf_jbp(sX,n)};
case {'^p:'}
varargout = {sf_tol(sf_jbp(sX,n),sX.tol)};
end %-
case 4
n = varargin{3};
if ~isnumeric(n), error('~isnumeric(n)'), end;
Y = varargin{4};
if isempty(Y), varargout = {spm_sp(action,sX,n)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'^p'}
varargout = {sf_jbp(sX,n)*Y};
case {'^p:'}
varargout = {sf_tol(sf_jbp(sX,n)*Y,sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'^','^:'} %-Computation of v*(diag(s.^n))*v'
%=======================================================================
switch nargin
case {2,3}
if nargin==2, n = 1; else n = varargin{3}; end;
if ~isnumeric(n), error('~isnumeric(n)'), end;
switch lower(action),
case {'^'}
varargout = {sf_jb(sX,n)};
case {'^:'}
varargout = {sf_tol(sf_jb(sX,n),sX.tol)};
end %-
case 4
n = varargin{3};
if ~isnumeric(n), error('~isnumeric(n)'), end;
Y = varargin{4};
if isempty(Y), varargout = {spm_sp(action,sX,n)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action),
case {'^'}
varargout = {sf_jbY(sX,n,Y)};
case {'^:'}
varargout = {sf_tol(sf_jbY(sX,n,Y),sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'n'} %-Null space of sX
%=======================================================================
switch nargin
case 2
varargout = {sf_n(sX)};
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'np'} %-Null space of sX'
%=======================================================================
switch nargin
case 2
varargout = {sf_n(sf_transp(sX))};
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'nop', 'nop:'} %- project(or)(ion) into null space
%=======================================================================
%
%
%
switch nargin
case 2
switch lower(action),
case {'nop'}
n = sf_n(sX);
varargout = {n*n'};
case {'nop:'}
n = sf_n(sX);
varargout = {sf_tol(n*n',sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s2(sX), error('Dim dont match'); end;
switch lower(action),
case {'nop'}
n = sf_n(sX);
varargout = {n*(n'*Y)};
case {'nop:'}
n = sf_n(sX);
varargout = {sf_tol(n*(n'*Y),sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'nopp', 'nopp:'} %- projector(ion) into null space of X'
%=======================================================================
%
%
switch nargin
case 2
switch lower(action),
case {'nopp'}
varargout = {spm_sp('nop',sf_transp(sX))};
case {'nopp:'}
varargout = {spm_sp('nop:',sf_transp(sX))};
end %-
case 3
switch lower(action),
case {'nopp'}
varargout = {spm_sp('nop',sf_transp(sX),varargin{3})};
case {'nopp:'}
varargout = {spm_sp('nop:',sf_transp(sX),varargin{3})};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {'res', 'r','r:'} %-Residual formaing matrix / residuals
%=======================================================================
% r = spm_sp('res',sX[,Y])
%
%- 'res' will become obsolete : use 'r' or 'r:' instead
%- At some stage, should be merged with 'nop'
switch nargin
case 2
switch lower(action)
case {'r','res'}
varargout = {sf_r(sX)};
case {'r:','res:'}
varargout = {sf_tol(sf_r(sX),sX.tol)};
end %-
case 3
%- check dimensions of Y
Y = varargin{3};
if isempty(Y), varargout = {spm_sp(action,sX)}; return, end
if size(Y,1) ~= sf_s1(sX), error('Dim dont match'); end;
switch lower(action)
case {'r','res'}
varargout = {sf_rY(sX,Y)};
case {'r:','res:'}
varargout = {sf_tol(sf_rY(sX,Y),sX.tol)};
end %-
otherwise
error('too many input argument in spm_sp');
end % switch nargin
case {':'}
%=======================================================================
% spm_sp(':',sX [,Y [,tol]])
%- Sets Y and tol according to arguments
if nargin > 4
error('too many input argument in spm_sp');
else
if nargin > 3
if isnumeric(varargin{4}), tol = varargin{4};
else error('tol must be numeric');
end
else
tol = sX.tol;
end
if nargin > 2
Y = varargin{3}; %- if isempty, returns empty, end
else
Y = sX.X;
end
end
varargout = {sf_tol(Y,tol)};
case {'isinsp', 'isinspp'} %- is in space or is in dual space
%=======================================================================
% b = spm_sp('isinsp',x,c[,tol])
% b = spm_sp('isinspp',x,c[,tol])
%-Check whether vectors are in row/column space of X
%-Check arguments
%-----------------------------------------------------------------------
if nargin<3, error('insufficient arguments - action,x,c required'), end
c = varargin{3}; %- if isempty(c), dim wont match exept for empty sp.
if nargin<4, tol=sX.tol; else, tol = varargin{4}; end
%-Compute according to case
%-----------------------------------------------------------------------
switch lower(action)
case 'isinsp'
%-Check dimensions
if size(sX.X,1) ~= size(c,1)
warning('Vector dim don''t match col. dim : not in space !');
varargout = { 0 }; return;
end
varargout = {all(all( abs(sf_op(sX)*c - c) <= tol ))};
case 'isinspp'
%- check dimensions
if size(sX.X,2) ~= size(c,1)
warning('Vector dim don''t match row dim : not in space !');
varargout = { 0 }; return;
end
varargout = {all(all( abs(sf_opp(sX)*c - c) <= tol ))};
end
case {'eachinsp', 'eachinspp'} %- each column of c in space or in dual space
%=======================================================================
% b = spm_sp('eachinsp',x,c[,tol])
% b = spm_sp('eachinspp',x,c[,tol])
%-Check whether vectors are in row/column space of X
%-Check arguments
%-----------------------------------------------------------------------
if nargin<3, error('insufficient arguments - action,x,c required'), end
c = varargin{3}; %- if isempty(c), dim wont match exept for empty sp.
if nargin<4, tol=sX.tol; else, tol = varargin{4}; end
%-Compute according to case
%-----------------------------------------------------------------------
switch lower(action)
case 'eachinsp'
%-Check dimensions
if size(sX.X,1) ~= size(c,1)
warning('Vector dim don''t match col. dim : not in space !');
varargout = { 0 }; return;
end
varargout = {all( abs(sf_op(sX)*c - c) <= tol )};
case 'eachinspp'
%- check dimensions
if size(sX.X,2) ~= size(c,1)
warning('Vector dim don''t match row dim : not in space !');
varargout = { 0 }; return;
end
varargout = {all( abs(sf_opp(sX)*c - c) <= tol )};
end
case '==' % test wether two spaces are the same
%=======================================================================
% b = spm_sp('==',x1,X2)
if nargin~=3, error('too few/many input arguments - need 3');
else X2 = varargin{3}; end;
if isempty(sX.X)
if isempty(X2),
warning('Both spaces empty');
varargout = { 1 };
else
warning('one space empty');
varargout = { 0 };
end;
else
x2 = spm_sp('Set',X2);
maxtol = max(sX.tol,x2.tol);
varargout = { all( spm_sp('isinsp',sX,X2,maxtol)) & ...
all( spm_sp('isinsp',x2,sX.X,maxtol) ) };
%- I have encountered one case where the max of tol was needed.
end;
case 'isspc' %-Space structure check
%=======================================================================
% [b,str] = spm_sp('isspc',x)
if nargin~=2, error('too few/many input arguments - need 2'), end
%-Check we've been passed a structure
if ~isstruct(varargin{2}), varargout={0}; return, end
%-Go through required field names checking their existance
% (Get fieldnames once and compare: isfield doesn't work for multiple )
% (fields, and repeated calls to isfield would result in unnecessary )
% (replicate calls to fieldnames(varargin{2}). )
b = 1;
fnames = fieldnames(varargin{2});
for str = fieldnames(sf_create)'
b = b & any(strcmp(str,fnames));
if ~b, break, end
end
if nargout > 1,
if b, str = 'ok'; else, str = 'not a space'; end;
varargout = {b,str};
else, varargout = {b}; end;
case 'issetspc' %-Is this a completed space structure?
%=======================================================================
% [b,e] = spm_sp('issetspc',x)
if nargin~=2, error('too few/many input arguments - need 2'), end
if ~spm_sp('isspc',varargin{2})
varargout = {0,'not a space structure (wrong fieldnames)'};
elseif ~sf_isset(varargin{2})
%-Basic fields aren't filled in
varargout = {0,'space not defined (use ''set'')'};
else
varargout = {1,'OK!'};
end
case 'size' %- gives the size of sX
%=======================================================================
% size = spm_sp('size',x,dim)
%
if nargin > 3, error('too many input arguments'), end
if nargin == 2, dim = []; else dim = varargin{3}; end
if ~isempty(dim)
switch dim
case 1, varargout = { sf_s1(sX) };
case 2, varargout = { sf_s2(sX) };
otherwise, error(['unknown dimension in ' action]);
end
else %- assumes want both dim
switch nargout
case {0,1}
varargout = { sf_si(sX) };
case 2
varargout = { sf_s1(sX), sf_s2(sX) };
otherwise
error(['too many output arg in ' mfilename ' ' action]);
end
end
otherwise
%=======================================================================
error(['Invalid action (',action,')'])
%=======================================================================
end % (case lower(action))
%=======================================================================
%- S U B - F U N C T I O N S
%=======================================================================
%
% The rule I tried to follow is that the space structure is accessed
% only in this sub function part : any sX.whatever should be
% prohibited elsewhere .... still a lot to clean !!!
function x = sf_create
%=======================================================================
x = struct(...
'X', [],... % Matrix
'tol', [],... % tolerance
'ds', [],... % vectors of singular values
'u', [],... % u as in X = u*diag(ds)*v'
'v', [], ... % v as in X = u*diag(ds)*v'
'rk', [],... % rank
'oP', [],... % orthogonal projector on X
'oPp', [],... % orthogonal projector on X'
'ups', [],... % space in which this one is embeded
'sus', []); % subspace
function x = sf_set(X)
%=======================================================================
x = sf_create;
x.X = X;
%-- Compute the svd with svd(X,0) : find all the singular values of x.X
%-- SVD(FULL(A)) will usually perform better than SVDS(A,MIN(SIZE(A)))
%- if more column that lines, performs on X'
if size(X,1) < size(X,2)
[x.v, s, x.u] = svd(full(X'),0);
else
[x.u, s, x.v] = svd(full(X),0);
end
x.ds = diag(s); clear s;
%-- compute the tolerance
x.tol = max(size(x.X))*max(abs(x.ds))*eps;
%-- compute the rank
x.rk = sum(x.ds > x.tol);
function x = sf_transp(x)
%=======================================================================
%
%- Tranpspose the space : note that tmp is not touched, therefore
%- only contains the address, no duplication of data is performed.
x.X = x.X';
tmp = x.v;
x.v = x.u;
x.u = tmp;
tmp = x.oP;
x.oP = x.oPp;
x.oPp = tmp;
clear tmp;
function b = sf_isset(x)
%=======================================================================
b = ~( isempty(x.X) |...
isempty(x.u) |...
isempty(x.v) |...
isempty(x.ds) |...
isempty(x.tol) |...
isempty(x.rk) );
function s1 = sf_s1(x)
%=======================================================================
s1 = size(x.X,1);
function s2 = sf_s2(x)
%=======================================================================
s2 = size(x.X,2);
function si = sf_si(x)
%=======================================================================
si = size(x.X);
function r = sf_rk(x)
%=======================================================================
r = x.rk;
function uk = sf_uk(x)
%=======================================================================
uk = x.u(:,1:sf_rk(x));
function vk = sf_vk(x)
%=======================================================================
vk = x.v(:,1:sf_rk(x));
function sk = sf_sk(x)
%=======================================================================
sk = x.ds(1:sf_rk(x));
function t = sf_t(x)
%=======================================================================
t = x.tol;
function x = sf_tol(x,t)
%=======================================================================
x(abs(x) < t) = 0;
function op = sf_op(sX)
%=======================================================================
if sX.rk > 0
op = sX.u(:,[1:sX.rk])*sX.u(:,[1:sX.rk])';
else
op = zeros( size(sX.X,1) );
end;
%!!!! to implement : a clever version of sf_opY (see sf_rY)
function opp = sf_opp(sX)
%=======================================================================
if sX.rk > 0
opp = sX.v(:,[1:sX.rk])*sX.v(:,[1:sX.rk])';
else
opp = zeros( size(sX.X,2) );
end;
%!!!! to implement : a clever version of sf_oppY (see sf_rY)
function px = sf_pinv(sX)
%=======================================================================
r = sX.rk;
if r > 0
px = sX.v(:,1:r)*diag( ones(r,1)./sX.ds(1:r) )*sX.u(:,1:r)';
else
px = zeros(size(sX.X,2),size(sX.X,1));
end
function px = sf_pinvxp(sX)
%=======================================================================
r = sX.rk;
if r > 0
px = sX.u(:,1:r)*diag( ones(r,1)./sX.ds(1:r) )*sX.v(:,1:r)';
else
px = zeros(size(sX.X));
end
function px = sf_pinvxpx(sX)
%=======================================================================
r = sX.rk;
if r > 0
px = sX.v(:,1:r)*diag( sX.ds(1:r).^(-2) )*sX.v(:,1:r)';
else
px = zeros(size(sX.X,2));
end
function px = sf_jbp(sX,n)
%=======================================================================
r = sX.rk;
if r > 0
px = sX.v(:,1:r)*diag( sX.ds(1:r).^(n) )*sX.v(:,1:r)';
else
px = zeros(size(sX.X,2));
end
function x = sf_jb(sX,n)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.u(:,1:r)*diag( sX.ds(1:r).^(n) )*sX.u(:,1:r)';
else
x = zeros(size(sX.X,1));
end
function y = sf_jbY(sX,n,Y)
%=======================================================================
r = sX.rk;
if r > 0
y = ( sX.u(:,1:r)*diag(sX.ds(1:r).^n) )*(sX.u(:,1:r)'*Y);
else
y = zeros(size(sX.X,1),size(Y,2));
end
%!!!! to implement : a clever version of sf_jbY (see sf_rY)
function x = sf_cxtwdcu(sX)
%=======================================================================
%- coordinates in sX.X -> coordinates in sX.u(:,1:rk)
x = diag(sX.ds)*sX.v';
function x = sf_cukpinvxp(sX)
%=======================================================================
%- coordinates of pinv(sX.X') in the basis sX.u(:,1:rk)
r = sX.rk;
if r > 0
x = diag( ones(r,1)./sX.ds(1:r) )*sX.v(:,1:r)';
else
x = zeros( size(sX.X,2) );
end
function x = sf_cukx(sX)
%=======================================================================
%- coordinates of sX.X in the basis sX.u(:,1:rk)
r = sX.rk;
if r > 0
x = diag( sX.ds(1:r) )*sX.v(:,1:r)';
else
x = zeros( size(sX.X,2) );
end
function x = sf_xpx(sX)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.v(:,1:r)*diag( sX.ds(1:r).^2 )*sX.v(:,1:r)';
else
x = zeros(size(sX.X,2));
end
function x = sf_xxp(sX)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.u(:,1:r)*diag( sX.ds(1:r).^2 )*sX.u(:,1:r)';
else
x = zeros(size(sX.X,1));
end
function x = sf_xxpY(sX,Y)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.u(:,1:r)*diag( sX.ds(1:r).^2 )*(sX.u(:,1:r)'*Y);
else
x = zeros(size(sX.X,1),size(Y,2));
end
function x = sf_pinvxxp(sX)
%=======================================================================
r = sX.rk;
if r > 0
x = sX.u(:,1:r)*diag( sX.ds(1:r).^(-2) )*sX.u(:,1:r)';
else
x = zeros(size(sX.X,1));
end
function n = sf_n(sX)
%=======================================================================
% if the null space is in sX.v, returns it
% otherwise, performs Gramm Schmidt orthogonalisation.
%
%
r = sX.rk;
[q p]= size(sX.X);
if r > 0
if q >= p %- the null space is entirely in v
if r == p, n = zeros(p,1); else, n = sX.v(:,r+1:p); end
else %- only part of n is in v: same as computing the null sp of sX'
n = null(sX.X);
%----- BUG !!!! in that part ----------------------------------------
%- v = zeros(p,p-q); j = 1; i = 1; z = zeros(p,1);
%- while i <= p
%- o = z; o(i) = 1; vpoi = [sX.v(i,:) v(i,1:j-1)]';
%- o = sf_tol(o - [sX.v v(:,1:j-1)]*vpoi,sX.tol);
%- if any(o), v(:,j) = o/((o'*o)^(1/2)); j = j + 1; end;
%- i = i + 1; %- if i>p, error('gramm shmidt error'); end;
%- end
%- n = [sX.v(:,r+1:q) v];
%--------------------------------------------------------------------
end
else
n = eye(p);
end
function r = sf_r(sX)
%=======================================================================
%-
%- returns the residual forming matrix for the space sX
%- for internal use. doesn't Check whether oP exist.
r = eye(size(sX.X,1)) - sf_op(sX) ;
function Y = sf_rY(sX,Y)
%=======================================================================
% r = spm_sp('r',sX[,Y])
%
%- tries to minimise the computation by looking whether we should do
%- I - u*(u'*Y) or n*(n'*Y) as in 'nop'
r = sX.rk;
[q p]= size(sX.X);
if r > 0 %- else returns the input;
if r < q-r %- we better do I - u*u'
Y = Y - sX.u(:,[1:r])*(sX.u(:,[1:r])'*Y); % warning('route1');
else
%- is it worth computing the n ortho basis ?
if size(Y,2) < 5*q
Y = sf_r(sX)*Y; % warning('route2');
else
n = sf_n(sf_transp(sX)); % warning('route3');
Y = n*(n'*Y);
end
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_dicom_essentials.m
|
.m
|
antx-master/xspm8/spm_dicom_essentials.m
| 3,266 |
utf_8
|
586ff55f155ffdd002e53be7402aa26f
|
function hdr1 = spm_dicom_essentials(hdr0)
% Remove unused fields from DICOM header
% FORMAT hdr1 = spm_dicom_essentials(hdr0)
% hdr0 - original DICOM header
% hdr1 - Stripped down DICOM header.
%
% With lots of DICOM files, the size of all the headers can become too
% big for all the fields to be saved. The idea here is to strip down
% the headers to their essentials.
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_dicom_essentials.m 4385 2011-07-08 16:53:38Z guillaume $
used_fields = {...
'AcquisitionDate',...
'AcquisitionNumber',...
'AcquisitionTime',...
'BitsAllocated',...
'BitsStored',...
'CSAImageHeaderInfo',...
'Columns',...
'EchoNumbers',...
'EchoTime',...
'Filename',...
'FlipAngle',...
'HighBit',...
'ImageOrientationPatient',...
'ImagePositionPatient',...
'ImageType',...
'InstanceNumber',...
'MagneticFieldStrength',...
'Manufacturer',...
'Modality',...
'MRAcquisitionType',...
'PatientID',...
'PatientsName',...
'PixelRepresentation',...
'PixelSpacing',...
'Private_0029_1110',...
'Private_0029_1210',...
'ProtocolName',...
'RepetitionTime',...
'RescaleIntercept',...
'RescaleSlope',...
'Rows',...
'SOPClassUID',...
'SamplesperPixel',...
'ScanningSequence',...
'SequenceName',...
'SeriesDescription',...
'SeriesInstanceUID',...
'SeriesNumber',...
'SliceNormalVector',...
'SliceThickness',...
'SpacingBetweenSlices',...
'StartOfPixelData',...
'StudyDate',...
'StudyTime',...
'TransferSyntaxUID',...
'VROfPixelData',...
'ScanOptions'};
fnames = fieldnames(hdr0);
for i=1:numel(used_fields)
if ismember(used_fields{i},fnames)
hdr1.(used_fields{i}) = hdr0.(used_fields{i});
end
end
Private_spectroscopy_fields = {...
'Columns',...
'Rows',...
'ImageOrientationPatient',...
'ImagePositionPatient',...
'SliceThickness',...
'PixelSpacing',...
'VoiPhaseFoV',...
'VoiReadoutFoV',...
'VoiThickness'};
if isfield(hdr1,'Private_0029_1110')
hdr1.Private_0029_1110 = ...
getfields(hdr1.Private_0029_1110,...
Private_spectroscopy_fields);
end
if isfield(hdr1,'Private_0029_1210')
hdr1.Private_0029_1210 = ...
getfields(hdr1.Private_0029_1210,...
Private_spectroscopy_fields);
end
if isfield(hdr1,'CSAImageHeaderInfo')
CSAImageHeaderInfo_fields = {...
'SliceNormalVector',...
'NumberOfImagesInMosaic',...
'AcquisitionMatrixText',...
'ICE_Dims'};
hdr1.CSAImageHeaderInfo = ...
getfields(hdr1.CSAImageHeaderInfo,...
CSAImageHeaderInfo_fields);
end
if isfield(hdr1,'CSASeriesHeaderInfo')
CSASeriesHeaderInfo_fields = {};
hdr1.CSASeriesHeaderInfo = ...
getfields(hdr1.CSASeriesHeaderInfo,...
CSASeriesHeaderInfo_fields);
end
function str1 = getfields(str0,names)
str1 = [];
for i=1:numel(names)
for j=1:numel(str0)
if strcmp(str0(j).name,names{i})
str1 = [str1,str0(j)];
end
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_ecat2nifti.m
|
.m
|
antx-master/xspm8/spm_ecat2nifti.m
| 16,572 |
utf_8
|
753e9a7e6e367abce74e0a0c4878f6c5
|
function N = spm_ecat2nifti(fname,opts)
% Import ECAT 7 images from CTI PET scanners.
% FORMAT N = spm_ecat2nifti(fname)
% fname - name of ECAT file
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Roger Gunn
% $Id: spm_ecat2nifti.m 3691 2010-01-20 17:08:30Z guillaume $
if nargin==1
opts = struct('ext','.nii');
else
if opts.ext(1) ~= '.', opts.ext = ['.' opts.ext]; end
end
fp = fopen(fname,'r','ieee-be');
if fp == -1,
error(['Can''t open "' fname '".']);
return;
end
mh = ECAT7_mheader(fp);
if ~strcmp(mh.MAGIC_NUMBER,'MATRIX70v') &&...
~strcmp(mh.MAGIC_NUMBER,'MATRIX71v') &&...
~strcmp(mh.MAGIC_NUMBER,'MATRIX72v'),
error(['"' fname '" does not appear to be ECAT 7 format.']);
fclose(fp);
return;
end
if mh.FILE_TYPE ~= 7,
error(['"' fname '" does not appear to be an image file.']);
fclose(fp);
return;
end
list = s7_matlist(fp);
matches = find((list(:,4) == 1) | (list(:,4) == 2));
llist = list(matches,:);
for i=1:size(llist,1),
sh(i) = ECAT7_sheader(fp,llist(i,2));
end;
fclose(fp);
for i=1:size(llist,1),
dim = [sh(i).X_DIMENSION sh(i).Y_DIMENSION sh(i).Z_DIMENSION];
dtype = [4 1];
off = 512*llist(i,2);
scale = sh(i).SCALE_FACTOR*mh.ECAT_CALIBRATION_FACTOR;
inter = 0;
dati = file_array(fname,dim,dtype,off,scale,inter);
dircos = diag([-1 -1 -1]);
step = ([sh(i).X_PIXEL_SIZE sh(i).Y_PIXEL_SIZE sh(i).Z_PIXEL_SIZE]*10);
start = -(dim(1:3)'/2).*step';
mat = [[dircos*diag(step) dircos*start] ; [0 0 0 1]];
matnum = sprintf('%.8x',list(i,1));
[pth,nam,ext] = fileparts(fname);
fnameo = fullfile(pwd,[nam '_' matnum opts.ext]);
dato = file_array(fnameo,dim,[4 spm_platform('bigend')],0,scale,inter);
N = nifti;
N.dat = dato;
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'aligned';
N.mat0_intent = 'scanner';
N.descrip = sh(i).ANNOTATION;
N.timing = struct('toffset',sh(i).FRAME_START_TIME/1000,'tspace',sh(i).FRAME_DURATION/1000);
create(N);
for j=1:dim(3),
N.dat(:,:,j) = dati(:,:,j);
end;
N.extras = struct('mh',mh,'sh',sh(i));
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
%S7_MATLIST List the available matrixes in an ECAT 7 file.
% LIST = S7_MATLIST(FP) lists the available matrixes
% in the file specified by FP.
%
% Columns in LIST:
% 1 - Matrix identifier.
% 2 - Matrix subheader record number
% 3 - Last record number of matrix data block.
% 4 - Matrix status:
% 1 - exists - rw
% 2 - exists - ro
% 3 - matrix deleted
%
function list = s7_matlist(fp)
% I believe fp should be opened with:
% fp = fopen(filename,'r','ieee-be');
fseek(fp,512,'bof');
block = fread(fp,128,'int');
if size(block,1) ~= 128
list = [];
return;
end;
block = reshape(block,4,32);
list = [];
while block(2,1) ~= 2,
if block(1,1)+block(4,1) ~= 31,
list = []; return;
end;
list = [list block(:,2:32)];
fseek(fp,512*(block(2,1)-1),'bof');
block = fread(fp,128,'int');
if size(block,1) ~= 128, list = []; return; end;
block = reshape(block,4,32);
end
list = [list block(:,2:(block(4,1)+1))];
list = list';
return;
%_______________________________________________________________________
%_______________________________________________________________________
function SHEADER=ECAT7_sheader(fid,record)
%
% Sub header read routine for ECAT 7 image files
%
% Roger Gunn, 260298
off = (record-1)*512;
status = fseek(fid, off,'bof');
data_type = fread(fid,1,'uint16',0);
num_dimensions = fread(fid,1,'uint16',0);
x_dimension = fread(fid,1,'uint16',0);
y_dimension = fread(fid,1,'uint16',0);
z_dimension = fread(fid,1,'uint16',0);
x_offset = fread(fid,1,'float32',0);
y_offset = fread(fid,1,'float32',0);
z_offset = fread(fid,1,'float32',0);
recon_zoom = fread(fid,1,'float32',0);
scale_factor = fread(fid,1,'float32',0);
image_min = fread(fid,1,'int16',0);
image_max = fread(fid,1,'int16',0);
x_pixel_size = fread(fid,1,'float32',0);
y_pixel_size = fread(fid,1,'float32',0);
z_pixel_size = fread(fid,1,'float32',0);
frame_duration = fread(fid,1,'uint32',0);
frame_start_time = fread(fid,1,'uint32',0);
filter_code = fread(fid,1,'uint16',0);
x_resolution = fread(fid,1,'float32',0);
y_resolution = fread(fid,1,'float32',0);
z_resolution = fread(fid,1,'float32',0);
num_r_elements = fread(fid,1,'float32',0);
num_angles = fread(fid,1,'float32',0);
z_rotation_angle = fread(fid,1,'float32',0);
decay_corr_fctr = fread(fid,1,'float32',0);
corrections_applied = fread(fid,1,'uint32',0);
gate_duration = fread(fid,1,'uint32',0);
r_wave_offset = fread(fid,1,'uint32',0);
num_accepted_beats = fread(fid,1,'uint32',0);
filter_cutoff_frequency = fread(fid,1,'float32',0);
filter_resolution = fread(fid,1,'float32',0);
filter_ramp_slope = fread(fid,1,'float32',0);
filter_order = fread(fid,1,'uint16',0);
filter_scatter_fraction = fread(fid,1,'float32',0);
filter_scatter_slope = fread(fid,1,'float32',0);
annotation = fread(fid,40,'char',0);
mt_1_1 = fread(fid,1,'float32',0);
mt_1_2 = fread(fid,1,'float32',0);
mt_1_3 = fread(fid,1,'float32',0);
mt_2_1 = fread(fid,1,'float32',0);
mt_2_2 = fread(fid,1,'float32',0);
mt_2_3 = fread(fid,1,'float32',0);
mt_3_1 = fread(fid,1,'float32',0);
mt_3_2 = fread(fid,1,'float32',0);
mt_3_3 = fread(fid,1,'float32',0);
rfilter_cutoff = fread(fid,1,'float32',0);
rfilter_resolution = fread(fid,1,'float32',0);
rfilter_code = fread(fid,1,'uint16',0);
rfilter_order = fread(fid,1,'uint16',0);
zfilter_cutoff = fread(fid,1,'float32',0);
zfilter_resolution = fread(fid,1,'float32',0);
zfilter_code = fread(fid,1,'uint16',0);
zfilter_order = fread(fid,1,'uint16',0);
mt_4_1 = fread(fid,1,'float32',0);
mt_4_2 = fread(fid,1,'float32',0);
mt_4_3 = fread(fid,1,'float32',0);
scatter_type = fread(fid,1,'uint16',0);
recon_type = fread(fid,1,'uint16',0);
recon_views = fread(fid,1,'uint16',0);
fill = fread(fid,1,'uint16',0);
annotation = deblank(char(annotation.*(annotation>0))');
SHEADER = struct('DATA_TYPE', data_type, ...
'NUM_DIMENSIONS', num_dimensions, ...
'X_DIMENSION', x_dimension, ...
'Y_DIMENSION', y_dimension, ...
'Z_DIMENSION', z_dimension, ...
'X_OFFSET', x_offset, ...
'Y_OFFSET', y_offset, ...
'Z_OFFSET', z_offset, ...
'RECON_ZOOM', recon_zoom, ...
'SCALE_FACTOR', scale_factor, ...
'IMAGE_MIN', image_min, ...
'IMAGE_MAX', image_max, ...
'X_PIXEL_SIZE', x_pixel_size, ...
'Y_PIXEL_SIZE', y_pixel_size, ...
'Z_PIXEL_SIZE', z_pixel_size, ...
'FRAME_DURATION', frame_duration, ...
'FRAME_START_TIME', frame_start_time, ...
'FILTER_CODE', filter_code, ...
'X_RESOLUTION', x_resolution, ...
'Y_RESOLUTION', y_resolution, ...
'Z_RESOLUTION', z_resolution, ...
'NUM_R_ELEMENTS', num_r_elements, ...
'NUM_ANGLES', num_angles, ...
'Z_ROTATION_ANGLE', z_rotation_angle, ...
'DECAY_CORR_FCTR', decay_corr_fctr, ...
'CORRECTIONS_APPLIED', corrections_applied, ...
'GATE_DURATION', gate_duration, ...
'R_WAVE_OFFSET', r_wave_offset, ...
'NUM_ACCEPTED_BEATS', num_accepted_beats, ...
'FILTER_CUTOFF_FREQUENCY', filter_cutoff_frequency, ...
'FILTER_RESOLUTION', filter_resolution, ...
'FILTER_RAMP_SLOPE', filter_ramp_slope, ...
'FILTER_ORDER', filter_order, ...
'FILTER_SCATTER_CORRECTION', filter_scatter_fraction, ...
'FILTER_SCATTER_SLOPE', filter_scatter_slope, ...
'ANNOTATION', annotation, ...
'MT_1_1', mt_1_1, ...
'MT_1_2', mt_1_2, ...
'MT_1_3', mt_1_3, ...
'MT_2_1', mt_2_1, ...
'MT_2_2', mt_2_2, ...
'MT_2_3', mt_2_3, ...
'MT_3_1', mt_3_1, ...
'MT_3_2', mt_3_2, ...
'MT_3_3', mt_3_3, ...
'RFILTER_CUTOFF', rfilter_cutoff, ...
'RFILTER_RESOLUTION', rfilter_resolution, ...
'RFILTER_CODE', rfilter_code, ...
'RFILTER_ORDER', rfilter_order, ...
'ZFILTER_CUTOFF', zfilter_cutoff, ...
'ZFILTER_RESOLUTION', zfilter_resolution, ...
'ZFILTER_CODE', zfilter_code, ...
'ZFILTER_ORDER', zfilter_order, ...
'MT_4_1', mt_4_1, ...
'MT_4_2', mt_4_2, ...
'MT_4_3', mt_4_3, ...
'SCATTER_TYPE', scatter_type, ...
'RECON_TYPE', recon_type, ...
'RECON_VIEWS', recon_views, ...
'FILL', fill);
return;
%_______________________________________________________________________
function [MHEADER]=ECAT7_mheader(fid)
%
% Main header read routine for ECAT 7 image files
%
% Roger Gunn, 260298
status = fseek(fid, 0,'bof');
magic_number = fread(fid,14,'char',0);
original_file_name = fread(fid,32,'char',0);
sw_version = fread(fid,1,'uint16',0);
system_type = fread(fid,1,'uint16',0);
file_type = fread(fid,1,'uint16',0);
serial_number = fread(fid,10,'char',0);
scan_start_time = fread(fid,1,'uint32',0);
isotope_name = fread(fid,8,'char',0);
isotope_halflife = fread(fid,1,'float32',0);
radiopharmaceutical = fread(fid,32,'char',0);
gantry_tilt = fread(fid,1,'float32',0);
gantry_rotation = fread(fid,1,'float32',0);
bed_elevation = fread(fid,1,'float32',0);
intrinsic_tilt = fread(fid,1,'float32',0);
wobble_speed = fread(fid,1,'uint16',0);
transm_source_type = fread(fid,1,'uint16',0);
distance_scanned = fread(fid,1,'float32',0);
transaxial_fov = fread(fid,1,'float32',0);
angular_compression = fread(fid,1,'uint16',0);
coin_samp_mode = fread(fid,1,'uint16',0);
axial_samp_mode = fread(fid,1,'uint16',0);
ecat_calibration_factor = fread(fid,1,'float32',0);
calibration_units = fread(fid,1,'uint16',0);
calibration_units_type = fread(fid,1,'uint16',0);
compression_code = fread(fid,1,'uint16',0);
study_type = fread(fid,12,'char',0);
patient_id = fread(fid,16,'char',0);
patient_name = fread(fid,32,'char',0);
patient_sex = fread(fid,1,'char',0);
patient_dexterity = fread(fid,1,'char',0);
patient_age = fread(fid,1,'float32',0);
patient_height = fread(fid,1,'float32',0);
patient_weight = fread(fid,1,'float32',0);
patient_birth_date = fread(fid,1,'uint32',0);
physician_name = fread(fid,32,'char',0);
operator_name = fread(fid,32,'char',0);
study_description = fread(fid,32,'char',0);
acquisition_type = fread(fid,1,'uint16',0);
patient_orientation = fread(fid,1,'uint16',0);
facility_name = fread(fid,20,'char',0);
num_planes = fread(fid,1,'uint16',0);
num_frames = fread(fid,1,'uint16',0);
num_gates = fread(fid,1,'uint16',0);
num_bed_pos = fread(fid,1,'uint16',0);
init_bed_position = fread(fid,1,'float32',0);
bed_position = zeros(15,1);
for bed=1:15,
tmp = fread(fid,1,'float32',0);
if ~isempty(tmp), bed_position(bed) = tmp; end;
end;
plane_separation = fread(fid,1,'float32',0);
lwr_sctr_thres = fread(fid,1,'uint16',0);
lwr_true_thres = fread(fid,1,'uint16',0);
upr_true_thres = fread(fid,1,'uint16',0);
user_process_code = fread(fid,10,'char',0);
acquisition_mode = fread(fid,1,'uint16',0);
bin_size = fread(fid,1,'float32',0);
branching_fraction = fread(fid,1,'float32',0);
dose_start_time = fread(fid,1,'uint32',0);
dosage = fread(fid,1,'float32',0);
well_counter_corr_factor = fread(fid,1,'float32',0);
data_units = fread(fid,32,'char',0);
septa_state = fread(fid,1,'uint16',0);
fill = fread(fid,1,'uint16',0);
magic_number = deblank(char(magic_number.*(magic_number>32))');
original_file_name = deblank(char(original_file_name.*(original_file_name>0))');
serial_number = deblank(char(serial_number.*(serial_number>0))');
isotope_name = deblank(char(isotope_name.*(isotope_name>0))');
radiopharmaceutical = deblank(char(radiopharmaceutical.*(radiopharmaceutical>0))');
study_type = deblank(char(study_type.*(study_type>0))');
patient_id = deblank(char(patient_id.*(patient_id>0))');
patient_name = deblank(char(patient_name.*(patient_name>0))');
patient_sex = deblank(char(patient_sex.*(patient_sex>0))');
patient_dexterity = deblank(char(patient_dexterity.*(patient_dexterity>0))');
physician_name = deblank(char(physician_name.*(physician_name>0))');
operator_name = deblank(char(operator_name.*(operator_name>0))');
study_description = deblank(char(study_description.*(study_description>0))');
facility_name = deblank(char(facility_name.*(facility_name>0))');
user_process_code = deblank(char(user_process_code.*(user_process_code>0))');
data_units = deblank(char(data_units.*(data_units>0))');
MHEADER = struct('MAGIC_NUMBER', magic_number, ...
'ORIGINAL_FILE_NAME', original_file_name, ...
'SW_VERSION', sw_version, ...
'SYSTEM_TYPE', system_type, ...
'FILE_TYPE', file_type, ...
'SERIAL_NUMBER', serial_number, ...
'SCAN_START_TIME', scan_start_time, ...
'ISOTOPE_NAME', isotope_name, ...
'ISOTOPE_HALFLIFE', isotope_halflife, ...
'RADIOPHARMACEUTICAL', radiopharmaceutical, ...
'GANTRY_TILT', gantry_tilt, ...
'GANTRY_ROTATION', gantry_rotation, ...
'BED_ELEVATION', bed_elevation, ...
'INTRINSIC_TILT', intrinsic_tilt, ...
'WOBBLE_SPEED', wobble_speed, ...
'TRANSM_SOURCE_TYPE', transm_source_type, ...
'DISTANCE_SCANNED', distance_scanned, ...
'TRANSAXIAL_FOV', transaxial_fov, ...
'ANGULAR_COMPRESSION', angular_compression, ...
'COIN_SAMP_MODE', coin_samp_mode, ...
'AXIAL_SAMP_MODE', axial_samp_mode, ...
'ECAT_CALIBRATION_FACTOR', ecat_calibration_factor, ...
'CALIBRATION_UNITS', calibration_units, ...
'CALIBRATION_UNITS_TYPE', calibration_units_type, ...
'COMPRESSION_CODE', compression_code, ...
'STUDY_TYPE', study_type, ...
'PATIENT_ID', patient_id, ...
'PATIENT_NAME', patient_name, ...
'PATIENT_SEX', patient_sex, ...
'PATIENT_DEXTERITY', patient_dexterity, ...
'PATIENT_AGE', patient_age, ...
'PATIENT_HEIGHT', patient_height, ...
'PATIENT_WEIGHT', patient_weight, ...
'PATIENT_BIRTH_DATE', patient_birth_date, ...
'PHYSICIAN_NAME', physician_name, ...
'OPERATOR_NAME', operator_name, ...
'STUDY_DESCRIPTION', study_description, ...
'ACQUISITION_TYPE', acquisition_type, ...
'PATIENT_ORIENTATION', patient_orientation, ...
'FACILITY_NAME', facility_name, ...
'NUM_PLANES', num_planes, ...
'NUM_FRAMES', num_frames, ...
'NUM_GATES', num_gates, ...
'NUM_BED_POS', num_bed_pos, ...
'INIT_BED_POSITION', init_bed_position, ...
'BED_POSITION', bed_position, ...
'PLANE_SEPARATION', plane_separation, ...
'LWR_SCTR_THRES', lwr_sctr_thres, ...
'LWR_TRUE_THRES', lwr_true_thres, ...
'UPR_TRUE_THRES', upr_true_thres, ...
'USER_PROCESS_CODE', user_process_code, ...
'ACQUISITION_MODE', acquisition_mode, ...
'BIN_SIZE', bin_size, ...
'BRANCHING_FRACTION', branching_fraction, ...
'DOSE_START_TIME', dose_start_time, ...
'DOSAGE', dosage, ...
'WELL_COUNTER_CORR_FACTOR', well_counter_corr_factor, ...
'DATA_UNITS', data_units, ...
'SEPTA_STATE', septa_state, ...
'FILL', fill);
return;
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_platform.m
|
.m
|
antx-master/xspm8/spm_platform.m
| 8,916 |
utf_8
|
1ead463af23059fb998f62b124a12a6d
|
function varargout=spm_platform(varargin)
% Platform specific configuration parameters for SPM
%
% FORMAT ans = spm_platform(arg)
% arg - optional string argument, can be
% - 'bigend' - return whether this architecture is bigendian
% - 0 - is little endian
% - 1 - is big endian
% - 'filesys' - type of filesystem
% - 'unx' - UNIX
% - 'win' - DOS
% - 'sepchar' - returns directory separator
% - 'user' - returns username
% - 'host' - returns system's host name
% - 'tempdir' - returns name of temp directory
% - 'drives' - returns string containing valid drive letters
%
% FORMAT PlatFontNames = spm_platform('fonts')
% Returns structure with fields named after the generic (UNIX) fonts, the
% field containing the name of the platform specific font.
%
% FORMAT PlatFontName = spm_platform('font',GenFontName)
% Maps generic (UNIX) FontNames to platform specific FontNames
%
% FORMAT PLATFORM = spm_platform('init',comp)
% Initialises platform specific parameters in persistent PLATFORM
% (External gateway to init_platform(comp) subfunction)
% comp - computer to use [defaults to MATLAB's `computer`]
% PLATFORM - copy of persistent PLATFORM
%
% FORMAT spm_platform
% Initialises platform specific parameters in persistent PLATFORM
% (External gateway to init_platform(computer) subfunction)
%
% ----------------
% SUBFUNCTIONS:
%
% FORMAT init_platform(comp)
% Initialise platform specific parameters in persistent PLATFORM
% comp - computer to use [defaults to MATLAB's `computer`]
%
%--------------------------------------------------------------------------
%
% Since calls to spm_platform will be made frequently, most platform
% specific parameters are stored as a structure in the persistent variable
% PLATFORM. Subsequent calls use the information from this persistent
% variable, if it exists.
%
% Platform specific definitions are contained in the data structures at
% the beginning of the init_platform subfunction at the end of this
% file.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Matthew Brett
% $Id: spm_platform.m 4137 2010-12-15 17:18:32Z guillaume $
%-Initialise
%--------------------------------------------------------------------------
persistent PLATFORM
if isempty(PLATFORM), PLATFORM = init_platform; end
if nargin==0, return, end
switch lower(varargin{1}), case 'init' %-(re)initialise
%==========================================================================
init_platform(varargin{2:end});
varargout = {PLATFORM};
case 'bigend' %-Return endian for this architecture
%==========================================================================
varargout = {PLATFORM.bigend};
case 'filesys' %-Return file system
%==========================================================================
varargout = {PLATFORM.filesys};
case 'sepchar' %-Return file separator character
%==========================================================================
warning('use filesep instead (supported by MathWorks)')
varargout = {PLATFORM.sepchar};
case 'rootlen' %-Return length in chars of root directory name
%=======================================================================
varargout = {PLATFORM.rootlen};
case 'user' %-Return user string
%==========================================================================
varargout = {PLATFORM.user};
case 'host' %-Return hostname
%==========================================================================
varargout = {PLATFORM.host};
case 'drives' %-Return drives
%==========================================================================
varargout = {PLATFORM.drives};
case 'tempdir' %-Return temporary directory
%==========================================================================
twd = getenv('SPMTMP');
if isempty(twd)
twd = tempdir;
end
varargout = {twd};
case {'font','fonts'} %-Map default font names to platform font names
%==========================================================================
if nargin<2, varargout={PLATFORM.font}; return, end
switch lower(varargin{2})
case 'times'
varargout = {PLATFORM.font.times};
case 'courier'
varargout = {PLATFORM.font.courier};
case 'helvetica'
varargout = {PLATFORM.font.helvetica};
case 'symbol'
varargout = {PLATFORM.font.symbol};
otherwise
warning(['Unknown font ',varargin{2},', using default'])
varargout = {PLATFORM.font.helvetica};
end
otherwise %-Unknown Action string
%==========================================================================
error('Unknown Action string')
%==========================================================================
end
%==========================================================================
%- S U B - F U N C T I O N S
%==========================================================================
function PLATFORM = init_platform(comp) %-Initialise platform variables
%==========================================================================
if nargin<1
comp = computer;
if any(comp=='-') % Octave
if isunix
switch uname.machine
case 'x86_64'
comp = 'GLNXA64';
case {'i586','i686'}
comp = 'GLNX86';
end
elseif ispc
comp = 'PCWIN';
elseif ismac
comp = 'MACI';
end
end
end
%-Platform definitions
%--------------------------------------------------------------------------
PDefs = {'PCWIN', 'win', 0;...
'PCWIN64', 'win', 0;...
'MAC', 'unx', 1;...
'MACI', 'unx', 0;...
'MACI64', 'unx', 0;...
'SOL2', 'unx', 1;...
'SOL64', 'unx', 1;...
'GLNX86', 'unx', 0;...
'GLNXA64', 'unx', 0};
PDefs = cell2struct(PDefs,{'computer','filesys','endian'},2);
%-Which computer?
%--------------------------------------------------------------------------
[issup, ci] = ismember(comp,{PDefs.computer});
if ~issup
error([comp ' not supported architecture for ' spm('Ver')]);
end
%-Set byte ordering
%--------------------------------------------------------------------------
PLATFORM.bigend = PDefs(ci).endian;
%-Set filesystem type
%--------------------------------------------------------------------------
PLATFORM.filesys = PDefs(ci).filesys;
%-File separator character
%--------------------------------------------------------------------------
PLATFORM.sepchar = filesep;
%-Username
%--------------------------------------------------------------------------
switch PLATFORM.filesys
case 'unx'
PLATFORM.user = getenv('USER');
case 'win'
PLATFORM.user = getenv('USERNAME');
otherwise
error(['Don''t know filesystem ',PLATFORM.filesys])
end
if isempty(PLATFORM.user), PLATFORM.user = 'anonymous'; end
%-Hostname
%--------------------------------------------------------------------------
[sts, Host] = system('hostname');
if sts
if strcmp(PLATFORM.filesys,'win')
Host = getenv('COMPUTERNAME');
else
Host = getenv('HOSTNAME');
end
Host = regexp(Host,'(.*?)\.','tokens','once');
else
Host = Host(1:end-1);
end
PLATFORM.host = Host;
%-Drives
%--------------------------------------------------------------------------
PLATFORM.drives = '';
if strcmp(PLATFORM.filesys,'win')
driveLett = cellstr(char(('C':'Z')'));
for i=1:numel(driveLett)
if exist([driveLett{i} ':\'],'dir')
PLATFORM.drives = [PLATFORM.drives driveLett{i}];
end
end
end
%-Fonts
%--------------------------------------------------------------------------
switch comp
case {'MAC','MACI','MACI64'}
PLATFORM.font.helvetica = 'TrebuchetMS';
PLATFORM.font.times = 'Times';
PLATFORM.font.courier = 'Courier';
PLATFORM.font.symbol = 'Symbol';
case {'SOL2','SOL64','GLNX86','GLNXA64'}
PLATFORM.font.helvetica = 'Helvetica';
PLATFORM.font.times = 'Times';
PLATFORM.font.courier = 'Courier';
PLATFORM.font.symbol = 'Symbol';
case {'PCWIN','PCWIN64'}
PLATFORM.font.helvetica = 'Arial Narrow';
PLATFORM.font.times = 'Times New Roman';
PLATFORM.font.courier = 'Courier New';
PLATFORM.font.symbol = 'Symbol';
end
|
github
|
philippboehmsturm/antx-master
|
spm_vb_graphcut.m
|
.m
|
antx-master/xspm8/spm_vb_graphcut.m
| 6,187 |
utf_8
|
e66c1e4a9a6d484998db51df14cba084
|
function labels = spm_vb_graphcut(labels,index,I,W,depth,grnd_type,CUTOFF,DIM)
% Recursive bi-partition of a graph using the isoperimetric algorithm
%
% FORMAT labels = spm_vb_graphcut(labels,index,I,W,depth,grnd_type,CUTOFF,DIM)
%
% labels each voxel is lableled depending on whihc segment is belongs
% index index of current node set in labels vector
% I InMask XYZ voxel (node set) indices
% W weight matrix i.e. adjacency matrix containing edge weights
% of graph
% depth depth of recursion
% grnd_type 'random' or 'max' - ground node selected at random or the
% node with maximal degree
% CUTOFF minimal number of voxels in a segment of the partition
% DIM dimensions of data
%__________________________________________________________________________
%
% Recursive bi-partition of a graph using the isoperimetric algorithm by
% Grady et al. This routine is adapted from "The Graph Analysis Toolbox:
% Image Processing on Arbitrary Graphs", available through Matlab Central
% File Exchange. See also Grady, L. Schwartz, E. L. (2006) "Isoperimetric
% graph partitioning for image segmentation",
% IEEE Trans Pattern Anal Mach Intell, 28(3),pp469-75
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Lee Harrison
% $Id: spm_vb_graphcut.m 2923 2009-03-23 18:34:51Z guillaume $
try, grnd_type; catch, grnd_type = 'random'; end
%-Initialize
s = rand('twister'); rand('seed',0);
N = length(index);
terminate = 0;
%-Partition current graph
if N > CUTOFF
reject = 1;
d = sum(W,2); % "degree" of each node
switch grnd_type
case 'max'
id = find(d==max(d));
ground = id(ceil(rand(1)*length(id)));
case 'random'
ground = ceil(rand(1)*N);
end
while reject == 1,
if N < 1e5, method = 'direct'; else, method = 'cg'; end
parts = bipartition(W,CUTOFF,ground,method);
nparts = [length(parts{1}),length(parts{2})];
if min(nparts) < CUTOFF, terminate = 1; break, end
for k = 1:2, % check if partitions are contiguous
bw = zeros(DIM(1),DIM(2),DIM(3));
bw(I(parts{k})) = 1;
[tmp,NUM] = spm_bwlabel(bw,6);
if NUM > 1
reject = 1;
ground = ceil(rand(1)*N); % re-select ground node
fprintf('depth %1.0f, partition %1.0f of 2, reject ',depth,k); fprintf('\n')
break
else
reject = 0;
fprintf('depth %1.0f, partition %1.0f of 2, accept ',depth,k);
fprintf('\n')
end
end
end
else
terminate = 1;
end
if terminate
labels = labels;
fprintf('depth %1.0f, end of branch ',depth);
fprintf('\n')
rand('twister',s);
else
%Accept partition and update labels
tmpInd = find(labels>labels(index(1)));
labels(tmpInd) = labels(tmpInd) + 1; %Make room for new class
labels(index(parts{2})) = labels(index(parts{2})) + 1; %Mark new class
%Continue recursion on each partition
if nparts(1) > CUTOFF
labels = spm_vb_graphcut(labels,index(parts{1}),I(parts{1}),...
W(parts{1},parts{1}),depth + 1,grnd_type,CUTOFF,DIM);
end
if nparts(2) > CUTOFF
labels = spm_vb_graphcut(labels,index(parts{2}),I(parts{2}),...
W(parts{2},parts{2}),depth + 1,grnd_type,CUTOFF,DIM);
end
end
%==========================================================================
% function parts = bipartition(W,CUTOFF,ground,method)
%==========================================================================
function parts = bipartition(W,CUTOFF,ground,method)
% Computes bi-partition of a graph using isoperimetric algorithm.
% FORMAT parts = bipartition(W,CUTOFF,ground,method)
% parts 1x2 cell containing indices of each partition
% W weight matrix
% CUTOFF minimal number of voxels in a segment of the partition
% ground ground node index
% method used to solve L0*x0=d0. Options are 'direct' or 'cg', which
% x0 = L0\d0 or preconditioned conjugate gradients (see Matlab
% rountine pcg.m)
try, method; catch, method = 'direct'; end
%-Laplacian matrix
d = sum(W,2);
L = diag(d) - W;
N = length(d);
%-Compute reduced Laplacian matrix, i.e. remove ground node
index = [1:(ground-1),(ground+1):N];
d0 = d(index);
L0 = L(index,index);
%-Solve system of equations L0*x0=d0
switch method
case 'direct'
x0 = L0\d0;
case 'cg'
x0 = pcg(L0,d0,[],N,diag(d0));
end
%-Error catch if numerical instability occurs (due to ill-conditioned or
%singular matrix)
minVal = min(min(x0));
if minVal < 0
x0(find(x0 < 0)) = max(max(x0)) + 1;
end
%-Re-insert ground point
x0 = [x0(1:(ground-1));0;x0((ground):(N-1))];
%-Remove sparseness of output
x0 = full(x0);
%-Determine cut point (ratio cut method)
indicator = sparse(N,1);
%-Sort values
sortX = sortrows([x0,[1:N]'],1)';
%-Find total volume
totalVolume = sum(d);
halfTotalVolume = totalVolume/2;
%-Calculate denominators
sortedDegree = d(sortX(2,:))';
denominators = cumsum(sortedDegree);
tmpIndex = find(denominators > halfTotalVolume);
denominators(tmpIndex) = totalVolume - denominators(tmpIndex);
%-Calculate numerators
L = L(sortX(2,:),sortX(2,:)) - diag(sortedDegree);
numerators = cumsum(sum((L - 2*triu(L)),2))';
if min(numerators) < 0
%Line used to avoid negative values due to precision issues
numerators = numerators - min(numerators) + eps;
end
%-Calculate ratios for Isoperimetric criteria
sw = warning('off','MATLAB:divideByZero');
[constant,minCut] = min(numerators(CUTOFF:(N-CUTOFF))./ ...
denominators(CUTOFF:(N-CUTOFF)));
minCut = minCut + CUTOFF - 1;
warning(sw);
%-Output partitions
parts{1} = sortX(2,1:(minCut))';
parts{2} = sortX(2,(minCut+1):N);
|
github
|
philippboehmsturm/antx-master
|
spm_preproc.m
|
.m
|
antx-master/xspm8/spm_preproc.m
| 20,562 |
utf_8
|
4fb344b9d6037ec12448af8a5f36eaff
|
function results = spm_preproc(varargin)
% Combined Segmentation and Spatial Normalisation
%
% FORMAT results = spm_preproc(V,opts)
% V - image to work with
% opts - options
% opts.tpm - n tissue probability images for each class
% opts.ngaus - number of Gaussians per class (n+1 classes)
% opts.warpreg - warping regularisation
% opts.warpco - cutoff distance for DCT basis functions
% opts.biasreg - regularisation for bias correction
% opts.biasfwhm - FWHM of Gausian form for bias regularisation
% opts.regtype - regularisation for affine part
% opts.fudge - a fudge factor
% opts.msk - unused
%__________________________________________________________________________
% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_preproc.m 4677 2012-03-05 15:39:35Z john $
opts0 = spm_get_defaults('preproc');
opts0 = rmfield(opts0,'output');
opts0.tpm = char(opts0.tpm); % In defaults, tpms are stored as cellstr
opts0.msk = '';
if ~nargin
V = spm_select(1,'image');
else
V = varargin{1};
end
if ischar(V), V = spm_vol(V); end
if nargin < 2
opts = opts0;
else
opts = varargin{2};
fnms = fieldnames(opts0);
for i=1:length(fnms)
if ~isfield(opts,fnms{i}), opts.(fnms{i}) = opts0.(fnms{i}); end
end
end
if length(opts.ngaus) ~= size(opts.tpm,1)+1
error('Number of Gaussians per class is not compatible with number of classes');
end
K = sum(opts.ngaus);
Kb = length(opts.ngaus);
lkp = [];
for k=1:Kb
lkp = [lkp ones(1,opts.ngaus(k))*k];
end
B = spm_vol(opts.tpm);
b0 = spm_load_priors(B);
d = V(1).dim(1:3);
vx = sqrt(sum(V(1).mat(1:3,1:3).^2));
sk = max([1 1 1],round(opts.samp*[1 1 1]./vx));
[x0,y0,o] = ndgrid(1:sk(1):d(1),1:sk(2):d(2),1);
z0 = 1:sk(3):d(3);
tiny = eps;
vx = sqrt(sum(V(1).mat(1:3,1:3).^2));
kron = inline('spm_krutil(a,b)','a','b');
% BENDING ENERGY REGULARIZATION for warping
%-----------------------------------------------------------------------
lam = 0.001;
d2 = max(round((V(1).dim(1:3).*vx)/opts.warpco),[1 1 1]);
kx = (pi*((1:d2(1))'-1)/d(1)/vx(1)).^2;
ky = (pi*((1:d2(2))'-1)/d(2)/vx(2)).^2;
kz = (pi*((1:d2(3))'-1)/d(3)/vx(3)).^2;
Cwarp = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^2,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^2)) +...
2*kron(kz.^1,kron(ky.^1,kx.^0)) +...
2*kron(kz.^1,kron(ky.^0,kx.^1)) +...
2*kron(kz.^0,kron(ky.^1,kx.^1)) );
Cwarp = Cwarp*opts.warpreg;
Cwarp = [Cwarp*vx(1)^4 ; Cwarp*vx(2)^4 ; Cwarp*vx(3)^4];
Cwarp = sparse(1:length(Cwarp),1:length(Cwarp),Cwarp,length(Cwarp),length(Cwarp));
B3warp = spm_dctmtx(d(3),d2(3),z0);
B2warp = spm_dctmtx(d(2),d2(2),y0(1,:)');
B1warp = spm_dctmtx(d(1),d2(1),x0(:,1));
lmR = speye(size(Cwarp));
Twarp = zeros([d2 3]);
% GAUSSIAN REGULARISATION for bias correction
%--------------------------------------------------------------------------
fwhm = opts.biasfwhm;
sd = vx(1)*V(1).dim(1)/fwhm; d3(1) = ceil(sd*2); krn_x = exp(-(0:(d3(1)-1)).^2/sd.^2)/sqrt(vx(1));
sd = vx(2)*V(1).dim(2)/fwhm; d3(2) = ceil(sd*2); krn_y = exp(-(0:(d3(2)-1)).^2/sd.^2)/sqrt(vx(2));
sd = vx(3)*V(1).dim(3)/fwhm; d3(3) = ceil(sd*2); krn_z = exp(-(0:(d3(3)-1)).^2/sd.^2)/sqrt(vx(3));
Cbias = kron(krn_z,kron(krn_y,krn_x)).^(-2)*opts.biasreg;
Cbias = sparse(1:length(Cbias),1:length(Cbias),Cbias,length(Cbias),length(Cbias));
B3bias = spm_dctmtx(d(3),d3(3),z0);
B2bias = spm_dctmtx(d(2),d3(2),y0(1,:)');
B1bias = spm_dctmtx(d(1),d3(1),x0(:,1));
lmRb = speye(size(Cbias));
Tbias = zeros(d3);
% Fudge Factor - to (approximately) account for non-independence of voxels
ff = opts.fudge;
ff = max(1,ff^3/prod(sk)/abs(det(V.mat(1:3,1:3))));
Cwarp = Cwarp*ff;
Cbias = Cbias*ff;
ll = -Inf;
llr = 0;
llrb = 0;
tol1 = 1e-4; % Stopping criterion. For more accuracy, use a smaller value
d = [size(x0) length(z0)];
f = zeros(d);
for z=1:length(z0)
f(:,:,z) = spm_sample_vol(V,x0,y0,o*z0(z),0);
end
[thresh,mx] = spm_minmax(f);
mn = zeros(K,1);
% give same results each time
st = rand('state'); % st = rng;
rand('state',0); % rng(0,'v5uniform'); % rng('defaults');
for k1=1:Kb
kk = sum(lkp==k1);
mn(lkp==k1) = rand(kk,1)*mx;
end
rand('state',st); % rng(st);
vr = ones(K,1)*mx^2;
mg = ones(K,1)/K;
if ~isempty(opts.msk)
VM = spm_vol(opts.msk);
if sum(sum((VM.mat-V(1).mat).^2)) > 1e-6 || any(VM.dim(1:3) ~= V(1).dim(1:3))
error('Mask must have the same dimensions and orientation as the image.');
end
end
Affine = eye(4);
if isfield(opts,'Affine'), % A request from Rik Henson
Affine = opts.Affine;
fprintf(1,'Using user-defined matrix for initial affine transformation\n');
end;
if ~isempty(opts.regtype)
Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff*100);
Affine = spm_maff(V,{x0,y0,z0},b0,B(1).mat,Affine,opts.regtype,ff);
end
M = B(1).mat\Affine*V(1).mat;
nm = 0;
for z=1:length(z0)
x1 = M(1,1)*x0 + M(1,2)*y0 + (M(1,3)*z0(z) + M(1,4));
y1 = M(2,1)*x0 + M(2,2)*y0 + (M(2,3)*z0(z) + M(2,4));
z1 = M(3,1)*x0 + M(3,2)*y0 + (M(3,3)*z0(z) + M(3,4));
buf(z).msk = spm_sample_priors(b0{end},x1,y1,z1,1)<(1-1/512);
fz = f(:,:,z);
%buf(z).msk = fz>thresh;
buf(z).msk = buf(z).msk & isfinite(fz) & (fz~=0);
if ~isempty(opts.msk),
msk = spm_sample_vol(VM,x0,y0,o*z0(z),0);
buf(z).msk = buf(z).msk & msk;
end
buf(z).nm = sum(buf(z).msk(:));
buf(z).f = fz(buf(z).msk);
nm = nm + buf(z).nm;
buf(z).bf(1:buf(z).nm,1) = single(1);
buf(z).dat = single(0);
if buf(z).nm,
buf(z).dat(buf(z).nm,Kb) = single(0);
end
end
clear f
finalit = 0;
spm_plot_convergence('Init','Processing','Log-likelihood','Iteration');
for iter=1:100
if finalit
% THIS CODE MAY BE USED IN FUTURE
% Reload the data for the final iteration. This iteration
% does not do any registration, so there is no need to
% mask out the background voxels.
%------------------------------------------------------------------
llrb = -0.5*Tbias(:)'*Cbias*Tbias(:);
for z=1:length(z0)
fz = spm_sample_vol(V,x0,y0,o*z0(z),0);
buf(z).msk = fz~=0;
if ~isempty(opts.msk)
msk = spm_sample_vol(VM,x0,y0,o*z0(z),0);
buf(z).msk = buf(z).msk & msk;
end
buf(z).nm = sum(buf(z).msk(:));
buf(z).f = fz(buf(z).msk);
nm = nm + buf(z).nm;
buf(z).bf(1:buf(z).nm,1) = single(1);
buf(z).dat = single(0);
if buf(z).nm
buf(z).dat(buf(z).nm,Kb) = single(0);
end
if buf(z).nm
bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);
tmp = bf(buf(z).msk);
llrb = llrb + sum(tmp);
buf(z).bf = single(exp(tmp));
end
end
% The background won't fit well any more, so increase the
% variances of these Gaussians in order to give it a chance
vr(lkp(K)) = vr(lkp(K))*8;
spm_plot_convergence('Init','Processing','Log-likelihood','Iteration');
end
% Load the warped prior probability images into the buffer
%----------------------------------------------------------------------
for z=1:length(z0)
if ~buf(z).nm, continue; end
[x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);
for k1=1:Kb
tmp = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);
buf(z).dat(:,k1) = single(tmp);
end
end
for iter1=1:10
% Estimate cluster parameters
%==================================================================
for subit=1:40
oll = ll;
mom0 = zeros(K,1)+tiny;
mom1 = zeros(K,1);
mom2 = zeros(K,1);
mgm = zeros(Kb,1);
ll = llr+llrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = double(buf(z).bf);
cr = double(buf(z).f).*bf;
q = zeros(buf(z).nm,K);
b = zeros(buf(z).nm,Kb);
s = zeros(buf(z).nm,1)+tiny;
for k1=1:Kb
pr = double(buf(z).dat(:,k1));
b(:,k1) = pr;
s = s + pr*sum(mg(lkp==k1));
end
for k1=1:Kb
b(:,k1) = b(:,k1)./s;
end
mgm = mgm + sum(b,1)';
for k=1:K
q(:,k) = mg(k)*b(:,lkp(k)) .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k));
end
sq = sum(q,2)+tiny;
ll = ll + sum(log(sq));
for k=1:K % Moments
p1 = q(:,k)./sq; mom0(k) = mom0(k) + sum(p1(:));
p1 = p1.*cr; mom1(k) = mom1(k) + sum(p1(:));
p1 = p1.*cr; mom2(k) = mom2(k) + sum(p1(:));
end
end
% Mixing proportions, Means and Variances
for k=1:K
mg(k) = (mom0(k)+eps)/(mgm(lkp(k))+eps);
mn(k) = mom1(k)/(mom0(k)+eps);
vr(k) =(mom2(k)-mom1(k)*mom1(k)/mom0(k)+1e6*eps)/(mom0(k)+eps);
vr(k) = max(vr(k),eps);
end
if subit>1 || (iter>1 && ~finalit),
spm_plot_convergence('Set',ll);
end;
if finalit, fprintf('Mix: %g\n',ll); end;
if subit == 1
ooll = ll;
elseif (ll-oll)<tol1*nm
% Improvement is small, so go to next step
break;
end
end
% Estimate bias
%==================================================================
if prod(d3)>0
for subit=1:40
% Compute objective function and its 1st and second derivatives
Alpha = zeros(prod(d3),prod(d3)); % Second derivatives
Beta = zeros(prod(d3),1); % First derivatives
ollrb = llrb;
oll = ll;
ll = llr+llrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = double(buf(z).bf);
cr = double(buf(z).f).*bf;
q = zeros(buf(z).nm,K);
for k=1:K
q(:,k) = double(buf(z).dat(:,lkp(k)))*mg(k);
end
s = sum(q,2)+tiny;
for k=1:K
q(:,k) = q(:,k)./s .* exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k));
end
sq = sum(q,2)+tiny;
ll = ll + sum(log(sq));
w1 = zeros(buf(z).nm,1);
w2 = zeros(buf(z).nm,1);
for k=1:K
tmp = q(:,k)./sq/vr(k);
w1 = w1 + tmp.*(mn(k) - cr);
w2 = w2 + tmp;
end
wt1 = zeros(d(1:2)); wt1(buf(z).msk) = 1 + cr.*w1;
wt2 = zeros(d(1:2)); wt2(buf(z).msk) = cr.*(cr.*w2 - w1);
b3 = B3bias(z,:)';
Beta = Beta + kron(b3,spm_krutil(wt1,B1bias,B2bias,0));
Alpha = Alpha + kron(b3*b3',spm_krutil(wt2,B1bias,B2bias,1));
clear w1 w2 wt1 wt2 b3
end
if finalit, fprintf('Bia: %g\n',ll); end
if subit > 1 && ~(ll>oll)
% Hasn't improved, so go back to previous solution
Tbias = oTbias;
llrb = ollrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);
buf(z).bf = single(exp(bf(buf(z).msk)));
end
break;
else
% Accept new solution
spm_plot_convergence('Set',ll);
oTbias = Tbias;
if subit > 1 && ~((ll-oll)>tol1*nm)
% Improvement is only small, so go to next step
break;
else
% Use new solution and continue the Levenberg-Marquardt iterations
Tbias = reshape((Alpha + Cbias + lmRb)\((Alpha+lmRb)*Tbias(:) + Beta),d3);
llrb = -0.5*Tbias(:)'*Cbias*Tbias(:);
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = transf(B1bias,B2bias,B3bias(z,:),Tbias);
tmp = bf(buf(z).msk);
llrb = llrb + sum(tmp);
buf(z).bf = single(exp(tmp));
end
end
end
end
if ~((ll-ooll)>tol1*nm), break; end
end
end
if finalit, break; end
% Estimate deformations
%======================================================================
mg1 = full(sparse(lkp,1,mg));
ll = llr+llrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
bf = double(buf(z).bf);
cr = double(buf(z).f).*bf;
q = zeros(buf(z).nm,Kb);
tmp = zeros(buf(z).nm,1)+tiny;
s = zeros(buf(z).nm,1)+tiny;
for k1=1:Kb
s = s + mg1(k1)*double(buf(z).dat(:,k1));
end
for k1=1:Kb
kk = find(lkp==k1);
pp = zeros(buf(z).nm,1);
for k=kk
pp = pp + exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k))*mg(k);
end
q(:,k1) = pp;
tmp = tmp+pp.*double(buf(z).dat(:,k1))./s;
end
ll = ll + sum(log(tmp));
for k1=1:Kb
buf(z).dat(:,k1) = single(q(:,k1));
end
end
for subit=1:20
oll = ll;
A = cell(3,3);
A{1,1} = zeros(prod(d2));
A{1,2} = zeros(prod(d2));
A{1,3} = zeros(prod(d2));
A{2,2} = zeros(prod(d2));
A{2,3} = zeros(prod(d2));
A{3,3} = zeros(prod(d2));
Beta = zeros(prod(d2)*3,1);
for z=1:length(z0)
if ~buf(z).nm, continue; end
[x1,y1,z1] = defs(Twarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);
b = zeros(buf(z).nm,Kb);
db1 = zeros(buf(z).nm,Kb);
db2 = zeros(buf(z).nm,Kb);
db3 = zeros(buf(z).nm,Kb);
s = zeros(buf(z).nm,1)+tiny;
ds1 = zeros(buf(z).nm,1);
ds2 = zeros(buf(z).nm,1);
ds3 = zeros(buf(z).nm,1);
p = zeros(buf(z).nm,1)+tiny;
dp1 = zeros(buf(z).nm,1);
dp2 = zeros(buf(z).nm,1);
dp3 = zeros(buf(z).nm,1);
for k1=1:Kb
[b(:,k1),db1(:,k1),db2(:,k1),db3(:,k1)] = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);
s = s + mg1(k1)* b(:,k1);
ds1 = ds1 + mg1(k1)*db1(:,k1);
ds2 = ds2 + mg1(k1)*db2(:,k1);
ds3 = ds3 + mg1(k1)*db3(:,k1);
end
for k1=1:Kb
b(:,k1) = b(:,k1)./s;
db1(:,k1) = (db1(:,k1)-b(:,k1).*ds1)./s;
db2(:,k1) = (db2(:,k1)-b(:,k1).*ds2)./s;
db3(:,k1) = (db3(:,k1)-b(:,k1).*ds3)./s;
pp = double(buf(z).dat(:,k1));
p = p + pp.*b(:,k1);
dp1 = dp1 + pp.*(M(1,1)*db1(:,k1) + M(2,1)*db2(:,k1) + M(3,1)*db3(:,k1));
dp2 = dp2 + pp.*(M(1,2)*db1(:,k1) + M(2,2)*db2(:,k1) + M(3,2)*db3(:,k1));
dp3 = dp3 + pp.*(M(1,3)*db1(:,k1) + M(2,3)*db2(:,k1) + M(3,3)*db3(:,k1));
end
clear x1 y1 z1 b db1 db2 db3 s ds1 ds2 ds3
tmp = zeros(d(1:2));
tmp(buf(z).msk) = dp1./p; dp1 = tmp;
tmp(buf(z).msk) = dp2./p; dp2 = tmp;
tmp(buf(z).msk) = dp3./p; dp3 = tmp;
b3 = B3warp(z,:)';
Beta = Beta - [...
kron(b3,spm_krutil(dp1,B1warp,B2warp,0))
kron(b3,spm_krutil(dp2,B1warp,B2warp,0))
kron(b3,spm_krutil(dp3,B1warp,B2warp,0))];
b3b3 = b3*b3';
A{1,1} = A{1,1} + kron(b3b3,spm_krutil(dp1.*dp1,B1warp,B2warp,1));
A{1,2} = A{1,2} + kron(b3b3,spm_krutil(dp1.*dp2,B1warp,B2warp,1));
A{1,3} = A{1,3} + kron(b3b3,spm_krutil(dp1.*dp3,B1warp,B2warp,1));
A{2,2} = A{2,2} + kron(b3b3,spm_krutil(dp2.*dp2,B1warp,B2warp,1));
A{2,3} = A{2,3} + kron(b3b3,spm_krutil(dp2.*dp3,B1warp,B2warp,1));
A{3,3} = A{3,3} + kron(b3b3,spm_krutil(dp3.*dp3,B1warp,B2warp,1));
clear b3 b3b3 tmp p dp1 dp2 dp3
end
Alpha = [A{1,1} A{1,2} A{1,3} ; A{1,2} A{2,2} A{2,3}; A{1,3} A{2,3} A{3,3}];
clear A
for subit1 = 1:3
if iter==1,
nTwarp = (Alpha+lmR*lam + 10*Cwarp)\((Alpha+lmR*lam)*Twarp(:) - Beta);
else
nTwarp = (Alpha+lmR*lam + Cwarp)\((Alpha+lmR*lam)*Twarp(:) - Beta);
end
nTwarp = reshape(nTwarp,[d2 3]);
nllr = -0.5*nTwarp(:)'*Cwarp*nTwarp(:);
nll = nllr+llrb;
for z=1:length(z0)
if ~buf(z).nm, continue; end
[x1,y1,z1] = defs(nTwarp,z,B1warp,B2warp,B3warp,x0,y0,z0,M,buf(z).msk);
sq = zeros(buf(z).nm,1) + tiny;
b = zeros(buf(z).nm,Kb);
s = zeros(buf(z).nm,1)+tiny;
for k1=1:Kb
b(:,k1) = spm_sample_priors(b0{k1},x1,y1,z1,k1==Kb);
s = s + mg1(k1)*b(:,k1);
end
for k1=1:Kb
sq = sq + double(buf(z).dat(:,k1)).*b(:,k1)./s;
end
clear b
nll = nll + sum(log(sq));
clear sq x1 y1 z1
end
if nll<ll
% Worse solution, so use old solution and increase regularisation
lam = lam*10;
else
% Accept new solution
ll = nll;
llr = nllr;
Twarp = nTwarp;
lam = lam*0.5;
break
end
end
spm_plot_convergence('Set',ll);
if (ll-oll)<tol1*nm, break; end
end
if ~((ll-ooll)>tol1*nm)
finalit = 1;
break; % This can be commented out.
end
end
spm_plot_convergence('Clear');
results = opts;
results.image = V;
results.tpm = B;
results.Affine = Affine;
results.Twarp = Twarp;
results.Tbias = Tbias;
results.mg = mg;
results.mn = mn;
results.vr = vr;
results.thresh = 0; %thresh;
results.ll = ll;
return
%=======================================================================
%=======================================================================
function t = transf(B1,B2,B3,T)
if ~isempty(T),
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
else
t = zeros(size(B1,1),size(B2,1));
end;
return;
%=======================================================================
%=======================================================================
function [x1,y1,z1] = defs(Twarp,z,B1,B2,B3,x0,y0,z0,M,msk)
x1a = x0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,1));
y1a = y0 + transf(B1,B2,B3(z,:),Twarp(:,:,:,2));
z1a = z0(z) + transf(B1,B2,B3(z,:),Twarp(:,:,:,3));
if nargin>=10,
x1a = x1a(msk);
y1a = y1a(msk);
z1a = z1a(msk);
end;
x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);
y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);
z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);
return;
%=======================================================================
|
github
|
philippboehmsturm/antx-master
|
spm_preproc_write.m
|
.m
|
antx-master/xspm8/spm_preproc_write.m
| 8,906 |
utf_8
|
6313e4e753e749911aac1143ba425149
|
function spm_preproc_write(p,opts)
% Write out VBM preprocessed data
% FORMAT spm_preproc_write(p,opts)
% p - results from spm_prep2sn
% opts - writing options. A struct containing these fields:
% biascor - write bias corrected image
% GM - flags for which images should be written
% WM - similar to GM
% CSF - similar to GM
%__________________________________________________________________________
% Copyright (C) 2005-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_preproc_write.m 4199 2011-02-10 20:07:17Z guillaume $
if ischar(p), p = load(p); end
if nargin==1
opts = spm_get_defaults('preproc.output');
end
if numel(p)>0
b0 = spm_load_priors(p(1).VG);
end
for i=1:numel(p)
preproc_apply(p(i),opts,b0);
end
return;
%==========================================================================
%==========================================================================
function preproc_apply(p,opts,b0)
%sopts = [opts.GM ; opts.WM ; opts.CSF];
nclasses = size(fieldnames(opts),1) - 2 ;
switch nclasses
case 3
sopts = [opts.GM ; opts.WM ; opts.CSF];
case 4
sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1];
case 5
sopts = [opts.GM ; opts.WM ; opts.CSF ; opts.EXTRA1 ; opts.EXTRA2];
otherwise
error('Unsupported number of classes!')
end
[pth,nam,ext]=fileparts(p.VF.fname);
T = p.flags.Twarp;
bsol = p.flags.Tbias;
d2 = [size(T) 1];
d = p.VF.dim(1:3);
[x1,x2,o] = ndgrid(1:d(1),1:d(2),1);
x3 = 1:d(3);
d3 = [size(bsol) 1];
B1 = spm_dctmtx(d(1),d2(1));
B2 = spm_dctmtx(d(2),d2(2));
B3 = spm_dctmtx(d(3),d2(3));
bB3 = spm_dctmtx(d(3),d3(3),x3);
bB2 = spm_dctmtx(d(2),d3(2),x2(1,:)');
bB1 = spm_dctmtx(d(1),d3(1),x1(:,1));
mg = p.flags.mg;
mn = p.flags.mn;
vr = p.flags.vr;
K = length(p.flags.mg);
Kb = length(p.flags.ngaus);
for k1=1:size(sopts,1),
%dat{k1} = zeros(d(1:3),'uint8');
dat{k1} = uint8(0);
dat{k1}(d(1),d(2),d(3)) = 0;
if sopts(k1,3),
Vt = struct('fname', fullfile(pth,['c', num2str(k1), nam, ext]),...
'dim', p.VF.dim,...
'dt', [spm_type('uint8') spm_platform('bigend')],...
'pinfo', [1/255 0 0]',...
'mat', p.VF.mat,...
'n', [1 1],...
'descrip', ['Tissue class ' num2str(k1)]);
Vt = spm_create_vol(Vt);
VO(k1) = Vt;
end;
end;
if opts.biascor,
VB = struct('fname', fullfile(pth,['m', nam, ext]),...
'dim', p.VF.dim(1:3),...
'dt', [spm_type('float32') spm_platform('bigend')],...
'pinfo', [1 0 0]',...
'mat', p.VF.mat,...
'n', [1 1],...
'descrip', 'Bias Corrected');
VB = spm_create_vol(VB);
end;
lkp = []; for k=1:Kb, lkp = [lkp ones(1,p.flags.ngaus(k))*k]; end;
spm_progress_bar('init',length(x3),['Working on ' nam],'Planes completed');
M = p.VG(1).mat\p.flags.Affine*p.VF.mat;
for z=1:length(x3),
% Bias corrected image
f = spm_sample_vol(p.VF,x1,x2,o*x3(z),0);
cr = exp(transf(bB1,bB2,bB3(z,:),bsol)).*f;
if opts.biascor,
% Write a plane of bias corrected data
VB = spm_write_plane(VB,cr,z);
end;
if any(sopts(:)),
msk = (f==0) | ~isfinite(f);
[t1,t2,t3] = defs(T,z,B1,B2,B3,x1,x2,x3,M);
q = zeros([d(1:2) Kb]);
bt = zeros([d(1:2) Kb]);
for k1=1:Kb,
bt(:,:,k1) = spm_sample_priors(b0{k1},t1,t2,t3,k1==Kb);
end;
b = zeros([d(1:2) K]);
for k=1:K,
b(:,:,k) = bt(:,:,lkp(k))*mg(k);
end;
s = sum(b,3);
for k=1:K,
p1 = exp((cr-mn(k)).^2/(-2*vr(k)))/sqrt(2*pi*vr(k)+eps);
q(:,:,lkp(k)) = q(:,:,lkp(k)) + p1.*b(:,:,k)./s;
end;
sq = sum(q,3)+eps;
sw = warning('off','MATLAB:divideByZero');
for k1=1:size(sopts,1),
tmp = q(:,:,k1);
tmp(msk) = 0;
tmp = tmp./sq;
dat{k1}(:,:,z) = uint8(round(255 * tmp));
end;
warning(sw);
end;
spm_progress_bar('set',z);
end;
spm_progress_bar('clear');
if opts.cleanup > 0,
[dat{1},dat{2},dat{3}] = clean_gwc(dat{1},dat{2},dat{3}, opts.cleanup);
end;
if any(sopts(:,3)),
for z=1:length(x3),
for k1=1:size(sopts,1),
if sopts(k1,3),
tmp = double(dat{k1}(:,:,z))/255;
spm_write_plane(VO(k1),tmp,z);
end;
end;
end;
end;
for k1=1:size(sopts,1),
if any(sopts(k1,1:2)),
so = struct('wrap',[0 0 0],'interp',1,'vox',[NaN NaN NaN],...
'bb',ones(2,3)*NaN,'preserve',0);
ovx = abs(det(p.VG(1).mat(1:3,1:3)))^(1/3);
fwhm = max(ovx./sqrt(sum(p.VF.mat(1:3,1:3).^2))-1,0.1);
dat{k1} = decimate(dat{k1},fwhm);
fn = fullfile(pth,['c', num2str(k1), nam, ext]);
dim = [size(dat{k1}) 1];
VT = struct('fname',fn,'dim',dim(1:3),...
'dt', [spm_type('uint8') spm_platform('bigend')],...
'pinfo',[1/255 0]','mat',p.VF.mat,'dat',dat{k1});
if sopts(k1,2),
spm_write_sn(VT,p,so);
end;
so.preserve = 1;
if sopts(k1,1),
VN = spm_write_sn(VT,p,so);
VN.fname = fullfile(pth,['mwc', num2str(k1), nam, ext]);
spm_write_vol(VN,VN.dat);
end;
end;
end;
return;
%==========================================================================
%==========================================================================
function [x1,y1,z1] = defs(sol,z,B1,B2,B3,x0,y0,z0,M)
x1a = x0 + transf(B1,B2,B3(z,:),sol(:,:,:,1));
y1a = y0 + transf(B1,B2,B3(z,:),sol(:,:,:,2));
z1a = z0(z) + transf(B1,B2,B3(z,:),sol(:,:,:,3));
x1 = M(1,1)*x1a + M(1,2)*y1a + M(1,3)*z1a + M(1,4);
y1 = M(2,1)*x1a + M(2,2)*y1a + M(2,3)*z1a + M(2,4);
z1 = M(3,1)*x1a + M(3,2)*y1a + M(3,3)*z1a + M(3,4);
return;
%==========================================================================
%==========================================================================
function t = transf(B1,B2,B3,T)
if ~isempty(T)
d2 = [size(T) 1];
t1 = reshape(reshape(T, d2(1)*d2(2),d2(3))*B3', d2(1), d2(2));
t = B1*t1*B2';
else
t = zeros(size(B1,1),size(B2,1),size(B3,1));
end;
return;
%==========================================================================
%==========================================================================
function dat = decimate(dat,fwhm)
% Convolve the volume in memory (fwhm in voxels).
lim = ceil(2*fwhm);
x = -lim(1):lim(1); x = spm_smoothkern(fwhm(1),x); x = x/sum(x);
y = -lim(2):lim(2); y = spm_smoothkern(fwhm(2),y); y = y/sum(y);
z = -lim(3):lim(3); z = spm_smoothkern(fwhm(3),z); z = z/sum(z);
i = (length(x) - 1)/2;
j = (length(y) - 1)/2;
k = (length(z) - 1)/2;
spm_conv_vol(dat,dat,x,y,z,-[i j k]);
return;
%==========================================================================
%==========================================================================
function [g,w,c] = clean_gwc(g,w,c, level)
if nargin<4, level = 1; end;
b = w;
b(1) = w(1);
% Build a 3x3x3 seperable smoothing kernel
%--------------------------------------------------------------------------
kx=[0.75 1 0.75];
ky=[0.75 1 0.75];
kz=[0.75 1 0.75];
sm=sum(kron(kron(kz,ky),kx))^(1/3);
kx=kx/sm; ky=ky/sm; kz=kz/sm;
th1 = 0.15;
if level==2, th1 = 0.2; end;
% Erosions and conditional dilations
%--------------------------------------------------------------------------
niter = 32;
spm_progress_bar('Init',niter,'Extracting Brain','Iterations completed');
for j=1:niter,
if j>2, th=th1; else th=0.6; end; % Dilate after two its of erosion.
for i=1:size(b,3),
gp = double(g(:,:,i));
wp = double(w(:,:,i));
bp = double(b(:,:,i))/255;
bp = (bp>th).*(wp+gp);
b(:,:,i) = uint8(round(bp));
end;
spm_conv_vol(b,b,kx,ky,kz,-[1 1 1]);
spm_progress_bar('Set',j);
end;
th = 0.05;
for i=1:size(b,3),
gp = double(g(:,:,i))/255;
wp = double(w(:,:,i))/255;
cp = double(c(:,:,i))/255;
bp = double(b(:,:,i))/255;
bp = ((bp>th).*(wp+gp))>th;
g(:,:,i) = uint8(round(255*gp.*bp./(gp+wp+cp+eps)));
w(:,:,i) = uint8(round(255*wp.*bp./(gp+wp+cp+eps)));
c(:,:,i) = uint8(round(255*(cp.*bp./(gp+wp+cp+eps)+cp.*(1-bp))));
end;
spm_progress_bar('Clear');
return;
%==========================================================================
|
github
|
philippboehmsturm/antx-master
|
spm_robust_glm.m
|
.m
|
antx-master/xspm8/spm_robust_glm.m
| 3,455 |
utf_8
|
bcb212d68b21aa060a764bdf025894e1
|
function [B, W] = spm_robust_glm(Y, X, dim, ks)
% Apply robust GLM
% FORMAT [B, W] = spm_robust_glm(Y, X, dim, ks)
% Y - data matrix
% X - design matrix
% dim - the dimension along which the function will work
% ks - offset of the weighting function (default: 3)
%
% OUTPUT:
% B - parameter estimates
% W - estimated weights
%
% Implementation of:
% Wager TD, Keller MC, Lacey SC, Jonides J.
% Increased sensitivity in neuroimaging analyses using robust regression.
% Neuroimage. 2005 May 15;26(1):99-113
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% James Kilner, Vladimir Litvak
% $Id: spm_robust_glm.m 4407 2011-07-26 12:13:00Z vladimir $
if nargin < 3 || isempty(ks)
ks = 3;
end
if nargin < 2 || isempty(dim)
dim = 1;
end
%-Remember the original data size and size of the mean
%--------------------------------------------------------------------------
origsize = size(Y);
borigsize = origsize;
borigsize(dim) = size(X, 2);
%-Convert the data to repetitions x points matrix
%--------------------------------------------------------------------------
if dim > 1
Y = shiftdim(Y, dim-1);
end
if length(origsize) > 2
Y = reshape(Y, size(Y, 1), []);
end
%-Check the design matrix and compute leverages
%--------------------------------------------------------------------------
if size(X, 1) ~= size(Y, 1)
error('The number of rows in the design matrix should match dimension of interest.');
end
H = diag(X*inv(X'*X)*X');
H = repmat(H(:), 1, size(Y, 2));
%-Rescale the data
%--------------------------------------------------------------------------
[Y, scalefactor] = spm_cond_units(Y);
%-Actual robust GLM
%--------------------------------------------------------------------------
ores=1;
nres=10;
n=0;
YY = Y;
YY(isnan(YY)) = 0;
while max(abs(ores-nres))>sqrt(1E-8)
ores=nres;
n=n+1;
if n == 1
W = ones(size(Y));
W(isnan(Y)) = 0;
end
B = zeros(size(X, 2), size(Y, 2));
for i = 1:size(Y, 2);
B(:, i) = inv(X'*diag(W(:, i))*X)*X'*diag(W(:, i))*YY(:, i);
end
if n > 200
warning('Robust GLM could not converge. Maximal number of iterations exceeded.');
break;
end
res = Y-X*B;
mad = nanmedian(abs(res-repmat(nanmedian(res), size(res, 1), 1)));
res = res./repmat(mad, size(res, 1), 1);
res = res.*H;
res = abs(res)-ks;
res(res<0)=0;
nres= (sum(res(~isnan(res)).^2));
W = (abs(res)<1) .* ((1 - res.^2).^2);
W(isnan(Y)) = 0;
W(Y == 0) = 0; %Assuming X is a real measurement
end
disp(['Robust GLM finished after ' num2str(n) ' iterations.']);
%-Restore the betas and weights to the original data dimensions
%--------------------------------------------------------------------------
B = B./scalefactor;
if length(origsize) > 2
B = reshape(B, circshift(borigsize, [1 -(dim-1)]));
W = reshape(W, circshift(origsize, [1 -(dim-1)]));
end
if dim > 1
B = shiftdim(B, length(origsize)-dim+1);
W = shiftdim(W, length(origsize)-dim+1);
end
%-Helper function
%--------------------------------------------------------------------------
function Y = nanmedian(X)
if ~any(any(isnan(X)))
Y = median(X);
else
Y = zeros(1, size(X,2));
for i = 1:size(X, 2)
Y(i) = median(X(~isnan(X(:, i)), i));
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_inv_spd.m
|
.m
|
antx-master/xspm8/spm_inv_spd.m
| 2,156 |
utf_8
|
cd4bba226b2f3ecf23302491c65f9bfe
|
function X = spm_inv_spd(A, TOL)
% inverse for symmetric positive (semi)definite matrices
% FORMAT X = spm_inv_spd(A,TOL)
%
% A - symmetric positive definite matrix (e.g. covariance or precision)
% X - inverse (should remain symmetric positive definite)
%
% TOL - tolerance: default = exp(-32)
%__________________________________________________________________________
% Copyright (C) 2011 Wellcome Trust Centre for Neuroimaging
% Ged Ridgway
% $Id: spm_inv_spd.m 4360 2011-06-14 16:46:37Z ged $
% if ~all(isfinite(A(:))), error('Matrix has non-finite elements!'); end
if nargin < 2
TOL = exp(-32);
end
[i j] = find(A);
if isempty(i)
% Special cases: empty or all-zero matrix, return identity/TOL
%----------------------------------------------------------------------
X = eye(length(A)) / TOL;
elseif all(i == j)
% diagonal matrix
%----------------------------------------------------------------------
d = diag(A);
d = invtol(d, TOL);
if issparse(A)
n = length(A);
X = sparse(1:n, 1:n, d);
else
X = diag(d);
end
elseif norm(A - A', 1) < TOL
% symmetric, try LDL factorisation (but with L->X to save memory)
%----------------------------------------------------------------------
[X D P] = ldl(full(A)); % P'*A*P = L*D*L', A = P*L*D*L'*P'
[i j d] = find(D);
% non-diagonal values indicate not positive semi-definite
if all(i == j)
d = invtol(d, TOL);
% inv(A) = P*inv(L')*inv(D)*inv(L)*P' = (L\P')'*inv(D)*(L\P')
% triangular system should be quick to solve and stay approx tri.
X = X\P';
X = X'*diag(d)*X;
if issparse(A), X = sparse(X); end
else
error('Matrix is not positive semi-definite according to ldl')
end
else
error('Matrix is not symmetric to given tolerance');
end
% if ~all(isfinite(X(:))), error('Inverse has non-finite elements!'); end
function d = invtol(d, TOL)
% compute reciprocal of values, clamped to lie between TOL and 1/TOL
if any(d < -TOL)
error('Matrix is not positive semi-definite at given tolerance')
end
d = max(d, TOL);
d = 1./d;
d = max(d, TOL);
|
github
|
philippboehmsturm/antx-master
|
spm.m
|
.m
|
antx-master/xspm8/spm.m
| 49,057 |
utf_8
|
98c0598c63fb03fb76fb44b4320b9c53
|
function varargout=spm(varargin)
% SPM: Statistical Parametric Mapping (startup function)
%_______________________________________________________________________
% ___ ____ __ __
% / __)( _ \( \/ )
% \__ \ )___/ ) ( Statistical Parametric Mapping
% (___/(__) (_/\/\_) SPM - http://www.fil.ion.ucl.ac.uk/spm/
%_______________________________________________________________________
%
% SPM (Statistical Parametric Mapping) is a package for the analysis
% functional brain mapping experiments. It is the in-house package of
% the Wellcome Trust Centre for Neuroimaging, and is available to the
% scientific community as copyright freeware under the terms of the
% GNU General Public Licence.
%
% Theoretical, computational and other details of the package are
% available in SPM's "Help" facility. This can be launched from the
% main SPM Menu window using the "Help" button, or directly from the
% command line using the command `spm_help`.
%
% Details of this release are available via the "About SPM" help topic
% (file spm.man), accessible from the SPM splash screen. (Or type
% `spm_help spm.man` in the MATLAB command window)
%
% This spm function initialises the default parameters, and displays a
% splash screen with buttons leading to the PET, fMRI and M/EEG
% modalities. Alternatively, `spm('pet')`, `spm('fmri')`, `spm('eeg')`
% (equivalently `spm pet`, `spm fmri` and `spm eeg`) lead directly to
% the respective modality interfaces.
%
% Once the modality is chosen, (and it can be toggled mid-session) the
% SPM user interface is displayed. This provides a constant visual
% environment in which data analysis is implemented. The layout has
% been designed to be simple and at the same time show all the
% facilities that are available. The interface consists of three
% windows: A menu window with pushbuttons for the SPM routines (each
% button has a 'CallBack' string which launches the appropriate
% function/script); A blank panel used for interaction with the user;
% And a graphics figure with various editing and print facilities (see
% spm_figure.m). (These windows are 'Tag'ged 'Menu', 'Interactive', and
% 'Graphics' respectively, and should be referred to by their tags
% rather than their figure numbers.)
%
% Further interaction with the user is (mainly) via questioning in the
% 'Interactive' window (managed by spm_input), and file selection
% (managed by spm_select). See the help on spm_input.m and spm_select.m for
% details on using these functions.
%
% If a "message of the day" file named spm_motd.man exists in the SPM
% directory (alongside spm.m) then it is displayed in the Graphics
% window on startup.
%
% Arguments to this routine (spm.m) lead to various setup facilities,
% mainly of use to SPM power users and programmers. See programmers
% FORMAT & help in the main body of spm.m
%
%_______________________________________________________________________
% SPM is developed by members and collaborators of the
% Wellcome Trust Centre for Neuroimaging
%-SVN ID and authorship of this program...
%-----------------------------------------------------------------------
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm.m 6128 2014-08-01 16:09:57Z guillaume $
%=======================================================================
% - FORMAT specifications for embedded CallBack functions
%=======================================================================
%( This is a multi function function, the first argument is an action )
%( string, specifying the particular action function to take. Recall )
%( MATLAB's command-function duality: `spm Welcome` is equivalent to )
%( `spm('Welcome')`. )
%
% FORMAT spm
% Defaults to spm('Welcome')
%
% FORMAT spm('Welcome')
% Clears command window, deletes all figures, prints welcome banner and
% splash screen, sets window defaults.
%
% FORMAT spm('AsciiWelcome')
% Prints ASCII welcome banner in MATLAB command window.
%
% FORMAT spm('PET') spm('FMRI') spm('EEG')
% Closes all windows and draws new Menu, Interactive, and Graphics
% windows for an SPM session. The buttons in the Menu window launch the
% main analysis routines.
%
% FORMAT spm('ChMod',Modality)
% Changes modality of SPM: Currently SPM supports PET & MRI modalities,
% each of which have a slightly different Menu window and different
% defaults. This function switches to the specified modality, setting
% defaults and displaying the relevant buttons.
%
% FORMAT spm('defaults',Modality)
% Sets default global variables for the specified modality.
%
% FORMAT [Modality,ModNum]=spm('CheckModality',Modality)
% Checks the specified modality against those supported, returns
% upper(Modality) and the Modality number, it's position in the list of
% supported Modalities.
%
% FORMAT Fmenu = spm('CreateMenuWin',Vis)
% Creates SPM menu window, 'Tag'ged 'Menu'
% F - handle of figure created
% Vis - Visibility, 'on' or 'off'
%
% Finter = FORMAT spm('CreateIntWin',Vis)
% Creates an SPM Interactive window, 'Tag'ged 'Interactive'
% F - handle of figure created
% Vis - Visibility, 'on' or 'off'
%
% FORMAT [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine)
% Robust UIsetup procedure for functions:
% Returns handles of 'Interactive' and 'Graphics' figures.
% Creates 'Interactive' figure if ~CmdLine, creates 'Graphics' figure if bGX.
% Iname - Name for 'Interactive' window
% bGX - Need a Graphics window? [default 1]
% CmdLine - CommandLine usage? [default spm('CmdLine')]
% Finter - handle of 'Interactive' figure
% Fgraph - handle of 'Graphics' figure
% CmdLine - CommandLine usage?
%
% FORMAT WS=spm('WinScale')
% Returns ratios of current display dimensions to that of a 1152 x 900
% Sun display. WS=[Xratio,Yratio,Xratio,Yratio]. Used for scaling other
% GUI elements.
% (Function duplicated in spm_figure.m, repeated to reduce inter-dependencies.)
%
% FORMAT [FS,sf] = spm('FontSize',FS)
% FORMAT [FS,sf] = spm('FontSizes',FS)
% Returns fontsizes FS scaled for the current display.
% FORMAT sf = spm('FontScale')
% Returns font scaling factor
% FS - (vector of) Font sizes to scale [default [1:36]]
% sf - font scaling factor (FS(out) = floor(FS(in)*sf)
%
% Rect = spm('WinSize',Win,raw)
% Returns sizes and positions for SPM windows.
% Win - 'Menu', 'Interactive', 'Graphics', or '0'
% - Window whose position is required. Only first character is
% examined. '0' returns size of root workspace.
% raw - If specified, then positions are for a 1152 x 900 Sun display.
% Otherwise the positions are scaled for the current display.
%
% FORMAT [c,cName] = spm('Colour')
% Returns the RGB triple and a description for the current en-vogue SPM
% colour, the background colour for the Menu and Help windows.
%
% FORMAT F = spm('FigName',Iname,F,CmdLine)
% Set name of figure F to "SPMver (User): Iname" if ~CmdLine
% Robust to absence of figure.
% Iname - Name for figure
% F (input) - Handle (or 'Tag') of figure to name [default 'Interactive']
% CmdLine - CommandLine usage? [default spm('CmdLine')]
% F (output) - Handle of figure named
%
% FORMAT Fs = spm('Show')
% Opens all SPM figure windows (with HandleVisibility) using `figure`.
% Maintains current figure.
% Fs - vector containing all HandleVisible figures (i.e. get(0,'Children'))
%
% FORMAT spm('Clear',Finter, Fgraph)
% Clears and resets SPM-GUI, clears and timestamps MATLAB command window.
% Finter - handle or 'Tag' of 'Interactive' figure [default 'Interactive']
% Fgraph - handle or 'Tag' of 'Graphics' figure [default 'Graphics']
%
% FORMAT SPMid = spm('FnBanner', Fn,FnV)
% Prints a function start banner, for version FnV of function Fn, & datestamps
% FORMAT SPMid = spm('SFnBanner',Fn,FnV)
% Prints a sub-function start banner
% FORMAT SPMid = spm('SSFnBanner',Fn,FnV)
% Prints a sub-sub-function start banner
% Fn - Function name (string)
% FnV - Function version (string)
% SPMid - ID string: [SPMver: Fn (FnV)]
%
% FORMAT SPMdir = spm('Dir',Mfile)
% Returns the directory containing the version of spm in use,
% identified as the first in MATLABPATH containing the Mfile spm (this
% file) (or Mfile if specified).
%
% FORMAT [v,r] = spm('Ver',Mfile,ReDo)
% Returns the current version (v) and release (r) of file Mfile. This
% corresponds to the Last changed Revision number extracted from the
% Subversion Id tag.
% If Mfile is absent or empty then it returns the current SPM version (v)
% and release (r), extracted from the file Contents.m in the SPM directory
% (these information are cached in a persistent variable to enable repeat
% use without recomputation).
% If Redo [default false] is true, then the cached current SPM information
% are not used but recomputed (and recached).
%
% FORMAT ver = spm('Version')
% Returns a string containing SPM version and release numbers.
%
% FORMAT v = spm('MLver')
% Returns MATLAB version, truncated to major & minor revision numbers
%
% FORMAT xTB = spm('TBs')
% Identifies installed SPM toolboxes: SPM toolboxes are defined as the
% contents of sub-directories of fullfile(spm('Dir'),'toolbox') - the
% SPM toolbox installation directory. For SPM to pick a toolbox up,
% there must be a single mfile in the directory whose name ends with
% the toolbox directory name. (I.e. A toolbox called "test" would be in
% the "test" subdirectory of spm('Dir'), with a single file named
% *test.m.) This M-file is regarded as the launch file for the
% toolbox.
% xTB - structure array containing toolbox definitions
% xTB.name - name of toolbox (taken as toolbox directory name)
% xTB.prog - launch program for toolbox
% xTB.dir - toolbox directory
%
% FORMAT spm('TBlaunch',xTB,i)
% Launch a toolbox, prepending TBdir to path if necessary
% xTB - toolbox definition structure (i.e. from spm('TBs')
% xTB.name - name of toolbox
% xTB.prog - name of program to launch toolbox
% xTB.dir - toolbox directory (prepended to path if not on path)
%
% FORMAT [v1,v2,...] = spm('GetGlobal',name1,name2,...)
% Returns values of global variables (without declaring them global)
% name1, name2,... - name strings of desired globals
% a1, a2,... - corresponding values of global variables with given names
% ([] is returned as value if global variable doesn't exist)
%
% FORMAT CmdLine = spm('CmdLine',CmdLine)
% Command line SPM usage?
% CmdLine (input) - CmdLine preference
% [defaults (missing or empty) to global defaults.cmdline,]
% [if it exists, or 0 (GUI) otherwise. ]
% CmdLine (output) - true if global CmdLine if true,
% or if on a terminal with no support for graphics windows.
%
% FORMAT spm('PopUpCB',h)
% Callback handler for PopUp UI menus with multiple callbacks as cellstr UserData
%
% FORMAT str = spm('GetUser',fmt)
% Returns current users login name, extracted from the hosting environment
% fmt - format string: If USER is defined then sprintf(fmt,USER) is returned
%
% FORMAT spm('Beep')
% Plays the keyboard beep!
%
% FORMAT spm('time')
% Returns the current time and date as hh:mm dd/mm/yyyy
%
% FORMAT spm('Pointer',Pointer)
% Changes pointer on all SPM (HandleVisible) windows to type Pointer
% Pointer defaults to 'Arrow'. Robust to absence of windows
%
% FORMAT h = spm('alert',Message,Title,CmdLine,wait)
% FORMAT h = spm('alert"',Message,Title,CmdLine,wait)
% FORMAT h = spm('alert*',Message,Title,CmdLine,wait)
% FORMAT h = spm('alert!',Message,Title,CmdLine,wait)
% Displays an alert, either in a GUI msgbox, or as text in the command window.
% ( 'alert"' uses the 'help' msgbox icon, 'alert*' the )
% ( 'error' icon, 'alert!' the 'warn' icon )
% Message - string (or cellstr) containing message to print
% Title - title string for alert
% CmdLine - CmdLine preference [default spm('CmdLine')]
% - If CmdLine is complex, then a CmdLine alert is always used,
% possibly in addition to a msgbox (the latter according
% to spm('CmdLine').)
% wait - if true, waits until user dismisses GUI / confirms text alert
% [default 0] (if doing both GUI & text, waits on GUI alert)
% h - handle of msgbox created, empty if CmdLine used
%
% FORMAT spm('Delete',file)
% Delete file(s), using spm_select and confirmation dialogs.
%
% FORMAT spm('Run',mscript)
% Run M-script(s), using spm_select.
%
% FORMAT spm('Clean')
% Clear all variables, globals, functions, MEX links and class definitions.
%
% FORMAT spm('Help',varargin)
% Merely a gateway to spm_help(varargin) - so you can type "spm help"
%
% FORMAT spm('Quit')
% Quit SPM, delete all windows and clear the command window.
%
%_______________________________________________________________________
%% hack-p
warning off;
%-Parameters
%-----------------------------------------------------------------------
Modalities = {'PET','FMRI','EEG'};
%-Format arguments
%-----------------------------------------------------------------------
if nargin == 0, Action = 'Welcome'; else Action = varargin{1}; end
%=======================================================================
switch lower(Action), case 'welcome' %-Welcome splash screen
%=======================================================================
% spm('Welcome')
spm_check_installation('basic');
defaults = spm('GetGlobal','defaults');
if isfield(defaults,'modality')
spm(defaults.modality);
return
end
%-Open startup window, set window defaults
%-----------------------------------------------------------------------
Fwelcome = openfig(fullfile(spm('Dir'),'spm_Welcome.fig'),'new','invisible');
set(Fwelcome,'name',sprintf('%s%s',spm('ver'),spm('GetUser',' (%s)')));
set(get(findobj(Fwelcome,'Type','axes'),'children'),'FontName',spm_platform('Font','Times'));
set(findobj(Fwelcome,'Tag','SPM_VER'),'String',spm('Ver'));
RectW = spm('WinSize','W',1); Rect0 = spm('WinSize','0',1);
set(Fwelcome,'Units','pixels', 'Position',...
[Rect0(1)+(Rect0(3)-RectW(3))/2, Rect0(2)+(Rect0(4)-RectW(4))/2, RectW(3), RectW(4)]);
set(Fwelcome,'Color',[1 1 1]*.8);
set(Fwelcome,'Visible','on');
%=======================================================================
case 'asciiwelcome' %-ASCII SPM banner welcome
%=======================================================================
% spm('AsciiWelcome')
disp( ' ___ ____ __ __ ');
disp( '/ __)( _ \( \/ ) ');
disp( '\__ \ )___/ ) ( Statistical Parametric Mapping ');
disp(['(___/(__) (_/\/\_) ',spm('Ver'),' - http://www.fil.ion.ucl.ac.uk/spm/']);
fprintf('\n');
%=======================================================================
case lower(Modalities) %-Initialise SPM in PET, fMRI, EEG modality
%=======================================================================
% spm(Modality)
spm_check_installation('basic');
try, feature('JavaFigures',0); end
%-Initialisation and workspace canonicalisation
%-----------------------------------------------------------------------
% local_clc;
% spm('AsciiWelcome'); fprintf('\n\nInitialising SPM');
% Modality = upper(Action); fprintf('.');
% spm_figure('close',allchild(0)); fprintf('.');
%% hack-p
close(findobj(0,'tag','Graphics'));
close(findobj(0,'tag','Menu'));
close(findobj(0,'tag','Interactive'));
Modality = upper(Action); fprintf('.');
%-Load startup global defaults
%-----------------------------------------------------------------------
spm_defaults; fprintf('.');
%-Setup for batch system
%-----------------------------------------------------------------------
spm_jobman('initcfg');
spm_select('prevdirs',[spm('Dir') filesep]);
%-Draw SPM windows
%-----------------------------------------------------------------------
if ~spm('CmdLine')
Fmenu = spm('CreateMenuWin','off'); fprintf('.');
Finter = spm('CreateIntWin','off'); fprintf('.');
else
Fmenu = [];
Finter = [];
end
Fgraph = spm_figure('Create','Graphics','Graphics','off'); fprintf('.');
spm_figure('WaterMark',Finter,spm('Ver'),'',45); fprintf('.');
Fmotd = fullfile(spm('Dir'),'spm_motd.man');
if exist(Fmotd,'file'), spm_help('!Disp',Fmotd,'',Fgraph,spm('Ver')); end
fprintf('.');
%-Setup for current modality
%-----------------------------------------------------------------------
spm('ChMod',Modality); fprintf('.');
%-Reveal windows
%-----------------------------------------------------------------------
set([Fmenu,Finter,Fgraph],'Visible','on'); fprintf('done\n\n');
%-Print present working directory
%-----------------------------------------------------------------------
fprintf('SPM present working directory:\n\t%s\n',pwd)
%=======================================================================
case 'chmod' %-Change SPM modality PET<->fMRI<->EEG
%=======================================================================
% spm('ChMod',Modality)
%-----------------------------------------------------------------------
%-Sort out arguments
%-----------------------------------------------------------------------
if nargin<2, Modality = ''; else Modality = varargin{2}; end
[Modality,ModNum] = spm('CheckModality',Modality);
%-Sort out global defaults
%-----------------------------------------------------------------------
spm('defaults',Modality);
%-Sort out visability of appropriate controls on Menu window
%-----------------------------------------------------------------------
Fmenu = spm_figure('FindWin','Menu');
if ~isempty(Fmenu)
if strcmpi(Modality,'PET')
set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' );
set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'on' );
elseif strcmpi(Modality,'FMRI')
set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'on' );
set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'on' );
else
set(findobj(Fmenu, 'Tag', 'PETFMRI'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'PET'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'FMRI'), 'Visible', 'off');
set(findobj(Fmenu, 'Tag', 'EEG'), 'Visible', 'on' );
end
set(findobj(Fmenu,'Tag','Modality'),'Value',ModNum,'UserData',ModNum);
else
warning('SPM Menu window not found');
end
%=======================================================================
case 'defaults' %-Set SPM defaults (as global variable)
%=======================================================================
% spm('defaults',Modality)
%-----------------------------------------------------------------------
if nargin<2, Modality=''; else Modality=varargin{2}; end
Modality = spm('CheckModality',Modality);
%-Re-initialise, load defaults (from spm_defaults.m) and store modality
%-----------------------------------------------------------------------
clear global defaults
spm_get_defaults('modality',Modality);
%-Addpath modality-specific toolboxes
%-----------------------------------------------------------------------
if strcmpi(Modality,'EEG') && ~isdeployed
addpath(fullfile(spm('Dir'),'external','fieldtrip'));
clear ft_defaults
clear global ft_default
ft_defaults;
addpath(fullfile(spm('Dir'),'external','bemcp'));
addpath(fullfile(spm('Dir'),'external','ctf'));
addpath(fullfile(spm('Dir'),'external','eeprobe'));
addpath(fullfile(spm('Dir'),'external','mne'));
addpath(fullfile(spm('Dir'),'external','yokogawa'));
addpath(fullfile(spm('Dir'),'toolbox', 'dcm_meeg'));
addpath(fullfile(spm('Dir'),'toolbox', 'spectral'));
addpath(fullfile(spm('Dir'),'toolbox', 'Neural_Models'));
addpath(fullfile(spm('Dir'),'toolbox', 'Beamforming'));
addpath(fullfile(spm('Dir'),'toolbox', 'MEEGtools'));
end
%-Turn output pagination off in Octave
%-----------------------------------------------------------------------
if strcmpi(spm_check_version,'octave')
try
more('off');
page_screen_output(false);
page_output_immediately(true);
end
end
%-Return defaults variable if asked
%-----------------------------------------------------------------------
if nargout, varargout = {spm_get_defaults}; end
%=======================================================================
case 'checkmodality' %-Check & canonicalise modality string
%=======================================================================
% [Modality,ModNum] = spm('CheckModality',Modality)
%-----------------------------------------------------------------------
if nargin<2, Modality=''; else Modality=upper(varargin{2}); end
if isempty(Modality)
try
Modality = spm_get_defaults('modality');
end
end
if ischar(Modality)
ModNum = find(ismember(Modalities,Modality));
else
if ~any(Modality == 1:length(Modalities))
Modality = 'ERROR';
ModNum = [];
else
ModNum = Modality;
Modality = Modalities{ModNum};
end
end
if isempty(ModNum)
if isempty(Modality)
fprintf('Modality is not set: use spm(''defaults'',''MOD''); ');
fprintf('where MOD is one of PET, FMRI, EEG.\n');
end
error('Unknown Modality.');
end
varargout = {upper(Modality),ModNum};
%=======================================================================
case 'createmenuwin' %-Create SPM menu window
%=======================================================================
% Fmenu = spm('CreateMenuWin',Vis)
%-----------------------------------------------------------------------
if nargin<2, Vis='on'; else Vis=varargin{2}; end
%-Close any existing 'Menu' 'Tag'ged windows
%-----------------------------------------------------------------------
delete(spm_figure('FindWin','Menu'))
Fmenu = openfig(fullfile(spm('Dir'),'spm_Menu.fig'),'new','invisible');
set(Fmenu,'name',sprintf('%s%s: Menu',spm('ver'),spm('GetUser',' (%s)')));
S0 = spm('WinSize','0',1);
SM = spm('WinSize','M');
set(Fmenu,'Units','pixels', 'Position',[S0(1) S0(2) 0 0] + SM);
%-Set SPM colour
%-----------------------------------------------------------------------
set(findobj(Fmenu,'Tag', 'frame'),'backgroundColor',spm('colour'));
set(Fmenu,'Color',[1 1 1]*.8);
try
if ismac
b = findobj(Fmenu,'Style','pushbutton');
set(b,'backgroundColor',get(b(1),'backgroundColor')+0.002);
end
end
%-Set Utils
%-----------------------------------------------------------------------
set(findobj(Fmenu,'Tag', 'Utils'), 'String',{'Utils...',...
'CD',...
'PWD',...
'Run M-file',...
'Load MAT-file',...
'Save MAT-file',...
'Delete files',...
'Show SPM'});
set(findobj(Fmenu,'Tag', 'Utils'), 'UserData',{...
['spm(''FnBanner'',''CD'');' ...
'cd(spm_select(1,''dir'',''Select new working directory''));' ...
'spm(''alert"'',{''New working directory:'',['' '',pwd]},''CD'',1);'],...
['spm(''FnBanner'',''PWD'');' ...
'spm(''alert"'',{''Present working directory:'',['' '',pwd]},''PWD'',1);'],...
['spm(''FnBanner'',''Run M-file'');' ...
'spm(''Run'');'],...
['spm(''FnBanner'',''Load MAT-file'');' ...
'load(spm_select(1,''mat'',''Select MAT-file''));'],...
['spm(''FnBanner'',''Save MAT-file'');' ...
'save(spm_input(''Output filename'',1,''s''));'],...
['spm(''FnBanner'',''Delete files'');' ...
'spm(''Delete'');'],...
['spm(''FnBanner'',''Show SPM'');' ...
'spm(''Show'');']});
%-Set Toolboxes
%-----------------------------------------------------------------------
xTB = spm('tbs');
if ~isempty(xTB)
set(findobj(Fmenu,'Tag', 'Toolbox'),'String',{'Toolbox:' xTB.name });
set(findobj(Fmenu,'Tag', 'Toolbox'),'UserData',xTB);
else
set(findobj(Fmenu,'Tag', 'Toolbox'),'Visible','off')
end
set(Fmenu,'Visible',Vis);
varargout = {Fmenu};
%=======================================================================
case 'createintwin' %-Create SPM interactive window
%=======================================================================
% Finter = spm('CreateIntWin',Vis)
%-----------------------------------------------------------------------
if nargin<2, Vis='on'; else Vis=varargin{2}; end
%-Close any existing 'Interactive' 'Tag'ged windows
%-----------------------------------------------------------------------
delete(spm_figure('FindWin','Interactive'))
%-Create SPM Interactive window
%-----------------------------------------------------------------------
FS = spm('FontSizes');
PF = spm_platform('fonts');
S0 = spm('WinSize','0',1);
SI = spm('WinSize','I');
Finter = figure('IntegerHandle','off',...
'Tag','Interactive',...
'Name',spm('Ver'),...
'NumberTitle','off',...
'Units','pixels',...
'Position',[S0(1) S0(2) 0 0] + SI,...
'Resize','on',...
'Color',[1 1 1]*.8,...
'MenuBar','none',...
'DefaultTextFontName',PF.helvetica,...
'DefaultTextFontSize',FS(10),...
'DefaultAxesFontName',PF.helvetica,...
'DefaultUicontrolBackgroundColor',[1 1 1]*.7,...
'DefaultUicontrolFontName',PF.helvetica,...
'DefaultUicontrolFontSize',FS(10),...
'DefaultUicontrolInterruptible','on',...
'Renderer','painters',...
'Visible',Vis);
varargout = {Finter};
%=======================================================================
case 'fnuisetup' %-Robust UI setup for main SPM functions
%=======================================================================
% [Finter,Fgraph,CmdLine] = spm('FnUIsetup',Iname,bGX,CmdLine)
%-----------------------------------------------------------------------
if nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end
if nargin<3, bGX=1; else bGX=varargin{3}; end
if nargin<2, Iname=''; else Iname=varargin{2}; end
if CmdLine
Finter = spm_figure('FindWin','Interactive');
if ~isempty(Finter), spm_figure('Clear',Finter), end
%if ~isempty(Iname), fprintf('%s:\n',Iname), end
else
Finter = spm_figure('GetWin','Interactive');
spm_figure('Clear',Finter)
if ~isempty(Iname)
str = sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname);
else
str = '';
end
set(Finter,'Name',str)
end
if bGX
Fgraph = spm_figure('GetWin','Graphics');
spm_figure('Clear',Fgraph)
else
Fgraph = spm_figure('FindWin','Graphics');
end
varargout = {Finter,Fgraph,CmdLine};
%=======================================================================
case 'winscale' %-Window scale factors (to fit display)
%=======================================================================
% WS = spm('WinScale')
%-----------------------------------------------------------------------
S0 = spm('WinSize','0',1);
if all(ismember(S0(:),[0 1]))
varargout = {[1 1 1 1]};
return;
end
tmp = [S0(3)/1152 (S0(4)-50)/900];
varargout = {min(tmp)*[1 1 1 1]};
% Make sure that aspect ratio is about right - for funny shaped screens
% varargout = {[S0(3)/1152 (S0(4)-50)/900 S0(3)/1152 (S0(4)-50)/900]};
%=======================================================================
case {'fontsize','fontsizes','fontscale'} %-Font scaling
%=======================================================================
% [FS,sf] = spm('FontSize',FS)
% [FS,sf] = spm('FontSizes',FS)
% sf = spm('FontScale')
%-----------------------------------------------------------------------
if nargin<2, FS=1:36; else FS=varargin{2}; end
offset = 1;
%try, if ismac, offset = 1.4; end; end
sf = offset + 0.85*(min(spm('WinScale'))-1);
if strcmpi(Action,'fontscale')
varargout = {sf};
else
varargout = {ceil(FS*sf),sf};
end
%=======================================================================
case 'winsize' %-Standard SPM window locations and sizes
%=======================================================================
% Rect = spm('WinSize',Win,raw)
%-----------------------------------------------------------------------
if nargin<3, raw=0; else raw=1; end
if nargin<2, Win=''; else Win=varargin{2}; end
Rect = [[108 466 400 445];...
[108 045 400 395];...
[515 015 600 865];...
[326 310 500 280]];
if isempty(Win)
%-All windows
elseif upper(Win(1))=='M'
%-Menu window
Rect = Rect(1,:);
elseif upper(Win(1))=='I'
%-Interactive window
Rect = Rect(2,:);
elseif upper(Win(1))=='G'
%-Graphics window
Rect = Rect(3,:);
elseif upper(Win(1))=='W'
%-Welcome window
Rect = Rect(4,:);
elseif Win(1)=='0'
%-Root workspace
Rect = get(0, 'MonitorPosition');
if all(ismember(Rect(:),[0 1]))
warning('SPM:noDisplay','Unable to open display.');
end
if size(Rect,1) > 1 % Multiple Monitors
%-Use Monitor containing the Pointer
pl = get(0,'PointerLocation');
Rect(:,[3 4]) = Rect(:,[3 4]) + Rect(:,[1 2]);
w = find(pl(1)>=Rect(:,1) & pl(1)<=Rect(:,3) &...
pl(2)>=Rect(:,2) & pl(2)<=Rect(:,4));
if numel(w)~=1, w = 1; end
Rect = Rect(w,:);
%-Make sure that the format is [x y width height]
Rect(1,[3 4]) = Rect(1,[3 4]) - Rect(1,[1 2]) + 1;
end
else
error('Unknown Win type');
end
if ~raw
WS = repmat(spm('WinScale'),size(Rect,1),1);
Rect = Rect.*WS;
end
varargout = {Rect};
%=======================================================================
case 'colour' %-SPM interface colour
%=======================================================================
% spm('Colour')
%-----------------------------------------------------------------------
%-Pre-developmental livery
% varargout = {[1.0,0.2,0.3],'fightening red'};
%-Developmental livery
% varargout = {[0.7,1.0,0.7],'flourescent green'};
%-Alpha release livery
% varargout = {[0.9,0.9,0.5],'over-ripe banana'};
%-Beta release livery
% varargout = {[0.9 0.8 0.9],'blackcurrant purple'};
%-Distribution livery
varargout = {[0.8 0.8 1.0],'vile violet'};
try
varargout = {spm_get_defaults('ui.colour'),'bluish'};
end
%=======================================================================
case 'figname' %-Robust SPM figure naming
%=======================================================================
% F = spm('FigName',Iname,F,CmdLine)
%-----------------------------------------------------------------------
if nargin<4, CmdLine=spm('CmdLine'); else CmdLine=varargin{4}; end
if nargin<3, F='Interactive'; else F=varargin{3}; end
if nargin<2, Iname=''; else Iname=varargin{2}; end
%if ~isempty(Iname), fprintf('\t%s\n',Iname), end
if CmdLine, varargout={[]}; return, end
F = spm_figure('FindWin',F);
if ~isempty(F) && ~isempty(Iname)
set(F,'Name',sprintf('%s (%s): %s',spm('ver'),spm('GetUser'),Iname))
end
varargout={F};
%=======================================================================
case 'show' %-Bring visible MATLAB windows to the fore
%=======================================================================
% Fs = spm('Show')
%-----------------------------------------------------------------------
cF = get(0,'CurrentFigure');
Fs = get(0,'Children');
Fs = findobj(Fs,'flat','Visible','on');
for F=Fs(:)', figure(F), end
try, figure(cF), set(0,'CurrentFigure',cF); end
varargout={Fs};
%=======================================================================
case 'clear' %-Clear SPM GUI
%=======================================================================
% spm('Clear',Finter, Fgraph)
%-----------------------------------------------------------------------
if nargin<3, Fgraph='Graphics'; else Fgraph=varargin{3}; end
if nargin<2, Finter='Interactive'; else Finter=varargin{2}; end
spm_figure('Clear',Fgraph)
spm_figure('Clear',Finter)
spm('Pointer','Arrow')
spm_conman('Initialise','reset');
local_clc;
fprintf('\n');
%evalin('base','clear')
%=======================================================================
case {'fnbanner','sfnbanner','ssfnbanner'} %-Text banners for functions
%=======================================================================
% SPMid = spm('FnBanner', Fn,FnV)
% SPMid = spm('SFnBanner',Fn,FnV)
% SPMid = spm('SSFnBanner',Fn,FnV)
%-----------------------------------------------------------------------
time = spm('time');
str = spm('ver');
if nargin>=2, str = [str,': ',varargin{2}]; end
if nargin>=3
v = regexp(varargin{3},'\$Rev: (\d*) \$','tokens','once');
if ~isempty(v)
str = [str,' (v',v{1},')'];
else
str = [str,' (v',varargin{3},')'];
end
end
switch lower(Action)
case 'fnbanner'
tab = '';
wid = 72;
lch = '=';
case 'sfnbanner'
tab = sprintf('\t');
wid = 72-8;
lch = '-';
case 'ssfnbanner'
tab = sprintf('\t\t');
wid = 72-2*8;
lch = '-';
end
fprintf('\n%s%s',tab,str)
fprintf('%c',repmat(' ',1,wid-length([str,time])))
fprintf('%s\n%s',time,tab)
fprintf('%c',repmat(lch,1,wid)),fprintf('\n')
varargout = {str};
%=======================================================================
case 'dir' %-Identify specific (SPM) directory
%=======================================================================
% spm('Dir',Mfile)
%-----------------------------------------------------------------------
if nargin<2, Mfile='spm'; else Mfile=varargin{2}; end
SPMdir = which(Mfile);
if isempty(SPMdir) %-Not found or full pathname given
if exist(Mfile,'file')==2 %-Full pathname
SPMdir = Mfile;
else
error(['Can''t find ',Mfile,' on MATLABPATH']);
end
end
SPMdir = fileparts(SPMdir);
varargout = {SPMdir};
%=======================================================================
case 'ver' %-SPM version
%=======================================================================
% [SPMver, SPMrel] = spm('Ver',Mfile,ReDo)
%-----------------------------------------------------------------------
if nargin > 3, warning('This usage of "spm ver" is now deprecated.'); end
if nargin ~= 3, ReDo = false; else ReDo = logical(varargin{3}); end
if nargin == 1 || (nargin > 1 && isempty(varargin{2}))
Mfile = '';
else
Mfile = which(varargin{2});
if isempty(Mfile)
error('Can''t find %s on MATLABPATH.',varargin{2});
end
end
v = spm_version(ReDo);
if isempty(Mfile)
varargout = {v.Release v.Version};
else
unknown = struct('file',Mfile,'id','???','date','','author','');
if ~isdeployed
fp = fopen(Mfile,'rt');
if fp == -1, error('Can''t read %s.',Mfile); end
str = fread(fp,Inf,'*uchar');
fclose(fp);
str = char(str(:)');
r = regexp(str,['\$Id: (?<file>\S+) (?<id>[0-9]+) (?<date>\S+) ' ...
'(\S+Z) (?<author>\S+) \$'],'names','once');
if isempty(r), r = unknown; end
else
r = unknown;
end
varargout = {r(1).id v.Release};
end
%=======================================================================
case 'version' %-SPM version
%=======================================================================
% v = spm('Version')
%-----------------------------------------------------------------------
[v, r] = spm('Ver');
varargout = {sprintf('%s (%s)',v,r)};
%=======================================================================
case 'mlver' %-MATLAB major & point version number
%=======================================================================
% v = spm('MLver')
%-----------------------------------------------------------------------
v = version; tmp = find(v=='.');
if length(tmp)>1, varargout={v(1:tmp(2)-1)}; end
%=======================================================================
case 'tbs' %-Identify installed toolboxes
%=======================================================================
% xTB = spm('TBs')
%-----------------------------------------------------------------------
% Toolbox directory
%-----------------------------------------------------------------------
Tdir = fullfile(spm('Dir'),'toolbox');
%-List of potential installed toolboxes directories
%-----------------------------------------------------------------------
if exist(Tdir,'dir')
d = dir(Tdir);
d = {d([d.isdir]).name};
d = {d{cellfun('isempty',regexp(d,'^\.'))}};
else
d = {};
end
%-Look for a "main" M-file in each potential directory
%-----------------------------------------------------------------------
xTB = [];
for i = 1:length(d)
tdir = fullfile(Tdir,d{i});
fn = cellstr(spm_select('List',tdir,['^.*' d{i} '\.m$']));
if ~isempty(fn{1}),
xTB(end+1).name = strrep(d{i},'_','');
xTB(end).prog = spm_str_manip(fn{1},'r');
xTB(end).dir = tdir;
end
end
varargout{1} = xTB;
%=======================================================================
case 'tblaunch' %-Launch an SPM toolbox
%=======================================================================
% xTB = spm('TBlaunch',xTB,i)
%-----------------------------------------------------------------------
if nargin < 3, i = 1; else i = varargin{3}; end
if nargin < 2, xTB = spm('TBs'); else xTB = varargin{2}; end
if i > 0
%-Addpath (& report)
%-------------------------------------------------------------------
if isempty(strfind(path,xTB(i).dir))
if ~isdeployed, addpath(xTB(i).dir,'-begin'); end
spm('alert"',{'Toolbox directory prepended to MATLAB path:',...
xTB(i).dir},...
[xTB(i).name,' toolbox'],1);
end
%-Launch
%-------------------------------------------------------------------
evalin('base',xTB(i).prog);
end
%=======================================================================
case 'getglobal' %-Get global variable cleanly
%=======================================================================
% varargout = spm('GetGlobal',varargin)
%-----------------------------------------------------------------------
wg = who('global');
for i=1:nargin-1
if any(strcmp(wg,varargin{i+1}))
eval(['global ',varargin{i+1},', tmp=',varargin{i+1},';'])
varargout{i} = tmp;
else
varargout{i} = [];
end
end
%=======================================================================
case 'cmdline' %-SPM command line mode?
%=======================================================================
% CmdLine = spm('CmdLine',CmdLine)
%-----------------------------------------------------------------------
if nargin<2, CmdLine=[]; else CmdLine=varargin{2}; end
if isempty(CmdLine)
try
CmdLine = spm_get_defaults('cmdline');
catch
CmdLine = 0;
end
end
varargout = { CmdLine | ...
(get(0,'ScreenDepth')==0) | ...
strcmpi(spm_check_version,'octave') };
%=======================================================================
case 'popupcb' %-Callback handling utility for PopUp menus
%=======================================================================
% spm('PopUpCB',h)
%-----------------------------------------------------------------------
if nargin<2, h=gcbo; else h=varargin{2}; end
v = get(h,'Value');
if v==1, return, end
set(h,'Value',1)
CBs = get(h,'UserData');
CB = CBs{v-1};
if ischar(CB)
evalin('base',CB)
elseif isa(CB,'function_handle')
feval(CB);
elseif iscell(CB)
feval(CB{:});
else
error('Invalid CallBack.');
end
%=======================================================================
case 'getuser' %-Get user name
%=======================================================================
% str = spm('GetUser',fmt)
%-----------------------------------------------------------------------
str = spm_platform('user');
if ~isempty(str) && nargin>1, str = sprintf(varargin{2},str); end
varargout = {str};
%=======================================================================
case 'beep' %-Produce beep sound
%=======================================================================
% spm('Beep')
%-----------------------------------------------------------------------
beep;
%=======================================================================
case 'time' %-Return formatted date/time string
%=======================================================================
% [timestr, date_vec] = spm('Time')
%-----------------------------------------------------------------------
tmp = clock;
varargout = {sprintf('%02d:%02d:%02d - %02d/%02d/%4d',...
tmp(4),tmp(5),floor(tmp(6)),tmp(3),tmp(2),tmp(1)), tmp};
%=======================================================================
case 'memory'
%=======================================================================
% m = spm('Memory')
%-----------------------------------------------------------------------
maxmemdef = 200*1024*1024; % 200 MB
%m = spm_get_defaults('stats.maxmem');
m = maxmemdef;
varargout = {m};
%=======================================================================
case 'pointer' %-Set mouse pointer in all MATLAB windows
%=======================================================================
% spm('Pointer',Pointer)
%-----------------------------------------------------------------------
if nargin<2, Pointer='Arrow'; else Pointer=varargin{2}; end
set(get(0,'Children'),'Pointer',lower(Pointer))
%=======================================================================
case {'alert','alert"','alert*','alert!'} %-Alert dialogs
%=======================================================================
% h = spm('alert',Message,Title,CmdLine,wait)
%-----------------------------------------------------------------------
%- Globals
%-----------------------------------------------------------------------
if nargin<5, wait = 0; else wait = varargin{5}; end
if nargin<4, CmdLine = []; else CmdLine = varargin{4}; end
if nargin<3, Title = ''; else Title = varargin{3}; end
if nargin<2, Message = ''; else Message = varargin{2}; end
Message = cellstr(Message);
if isreal(CmdLine)
CmdLine = spm('CmdLine',CmdLine);
CmdLine2 = 0;
else
CmdLine = spm('CmdLine');
CmdLine2 = 1;
end
timestr = spm('Time');
SPMv = spm('ver');
switch(lower(Action))
case 'alert', icon = 'none'; str = '--- ';
case 'alert"', icon = 'help'; str = '~ - ';
case 'alert*', icon = 'error'; str = '* - ';
case 'alert!', icon = 'warn'; str = '! - ';
end
if CmdLine || CmdLine2
Message(strcmp(Message,'')) = {' '};
tmp = sprintf('%s: %s',SPMv,Title);
fprintf('\n %s%s %s\n\n',str,tmp,repmat('-',1,62-length(tmp)))
fprintf(' %s\n',Message{:})
fprintf('\n %s %s\n\n',repmat('-',1,62-length(timestr)),timestr)
h = [];
end
if ~CmdLine
tmp = max(size(char(Message),2),42) - length(SPMv) - length(timestr);
str = sprintf('%s %s %s',SPMv,repmat(' ',1,tmp-4),timestr);
h = msgbox([{''};Message(:);{''};{''};{str}],...
sprintf('%s%s: %s',SPMv,spm('GetUser',' (%s)'),Title),...
icon,'non-modal');
drawnow
set(h,'windowstyle','modal');
end
if wait
if isempty(h)
input(' press ENTER to continue...');
else
uiwait(h)
h = [];
end
end
if nargout, varargout = {h}; end
%=======================================================================
case 'run' %-Run script(s)
%=======================================================================
% spm('Run',mscript)
%-----------------------------------------------------------------------
if nargin<2
[mscript, sts] = spm_select(Inf,'.*\.m$','Select M-file(s) to run');
if ~sts || isempty(mscript), return; end
else
mscript = varargin{2};
end
mscript = cellstr(mscript);
for i=1:numel(mscript)
if isdeployed
[p,n,e] = fileparts(mscript{i});
if isempty(p), p = pwd; end
if isempty(e), e = '.m'; end
mscript{i} = fullfile(p,[n e]);
fid = fopen(mscript{i});
if fid == -1, error('Cannot open %s',mscript{i}); end
S = fscanf(fid,'%c');
fclose(fid);
try
evalin('base',S);
catch
fprintf('Execution failed: %s\n',mscript{i});
rethrow(lasterror);
end
else
try
run(mscript{i});
catch
fprintf('Execution failed: %s\n',mscript{i});
rethrow(lasterror);
end
end
end
%=======================================================================
case 'delete' %-Delete file(s)
%=======================================================================
% spm('Delete',file)
%-----------------------------------------------------------------------
if nargin<2
[P, sts] = spm_select(Inf,'.*','Select file(s) to delete');
if ~sts, return; end
else
P = varargin(2:end);
end
P = cellstr(P); P = P(:);
n = numel(P);
if n==0 || (n==1 && isempty(P{1})), return; end
if n<4
str=[{' '};P];
elseif n<11
str=[{' '};P;{' ';sprintf('(%d files)',n)}];
else
str=[{' '};P(1:min(n,10));{'...';' ';sprintf('(%d files)',n)}];
end
if spm_input(str,-1,'bd','delete|cancel',[1,0],[],'confirm file delete')
feval(@spm_unlink,P{:});
spm('alert"',P,'file delete',1);
end
%=======================================================================
case 'clean' %-Clean MATLAB workspace
%=======================================================================
% spm('Clean')
%-----------------------------------------------------------------------
evalin('base','clear all');
evalc('clear classes');
%=======================================================================
case 'help' %-Pass through for spm_help
%=======================================================================
% spm('Help',varargin)
%-----------------------------------------------------------------------
if nargin>1, spm_help(varargin{2:end}), else spm_help, end
%=======================================================================
case 'quit' %-Quit SPM and clean up
%=======================================================================
% spm('Quit')
%-----------------------------------------------------------------------
% spm_figure('close',allchild(0));
% local_clc;
% fprintf('Bye for now...\n\n');
%% hack-p
close(findobj(0,'tag','Graphics'));
close(findobj(0,'tag','Menu'));
close(findobj(0,'tag','Interactive'));
%=======================================================================
otherwise %-Unknown action string
%=======================================================================
error('Unknown action string');
%=======================================================================
end
%=======================================================================
function local_clc %-Clear command window
%=======================================================================
if ~isdeployed
clc;
end
%=======================================================================
function v = spm_version(ReDo) %-Retrieve SPM version
%=======================================================================
persistent SPM_VER;
v = SPM_VER;
if isempty(SPM_VER) || (nargin > 0 && ReDo)
v = struct('Name','','Version','','Release','','Date','');
try
if isdeployed
% in deployed mode, M-files are encrypted
% (even if first two lines of Contents.m "should" be preserved)
vfile = fullfile(spm('Dir'),'Contents.txt');
else
vfile = fullfile(spm('Dir'),'Contents.m');
end
fid = fopen(vfile,'rt');
if fid == -1, error(str); end
l1 = fgetl(fid); l2 = fgetl(fid);
fclose(fid);
l1 = strtrim(l1(2:end)); l2 = strtrim(l2(2:end));
t = textscan(l2,'%s','delimiter',' '); t = t{1};
v.Name = l1; v.Date = t{4};
v.Version = t{2}; v.Release = t{3}(2:end-1);
catch
error('Can''t obtain SPM Revision information.');
end
SPM_VER = v;
end
|
github
|
philippboehmsturm/antx-master
|
spm_orthviews.m
|
.m
|
antx-master/xspm8/spm_orthviews.m
| 84,666 |
utf_8
|
4edf17c77a1c5d30eb009dd4cd64b24b
|
function varargout = spm_orthviews(action,varargin)
% Display orthogonal views of a set of images
% FORMAT H = spm_orthviews('Image',filename[,position])
% filename - name of image to display
% area - position of image {relative}
% - area(1) - position x
% - area(2) - position y
% - area(3) - size x
% - area(4) - size y
% H - handle for ortho sections
%
% FORMAT spm_orthviews('Redraw')
% Redraws the images
%
% FORMAT spm_orthviews('Reposition',centre)
% centre - X, Y & Z coordinates of centre voxel
%
% FORMAT spm_orthviews('Space'[,handle[,M,dim]])
% handle - the view to define the space by, optionally with extra
% transformation matrix and dimensions (e.g. one of the blobs
% of a view)
% with no arguments - puts things into mm space
%
% FORMAT H = spm_orthviews('Caption', handle, string, [Property, Value])
% handle - the view to which a caption should be added
% string - the caption text to add
% optional: Property-Value pairs, e.g. 'FontWeight', 'Bold'
%
% H - the handle to the object whose String property has the caption
%
% FORMAT spm_orthviews('BB',bb)
% bb - bounding box
% [loX loY loZ
% hiX hiY hiZ]
%
% FORMAT spm_orthviews('MaxBB')
% sets the bounding box big enough display the whole of all images
%
% FORMAT spm_orthviews('Resolution'[,res])
% res - resolution (mm)
% sets the sampling resolution for all images. The effective resolution
% will be the minimum of res and the voxel sizes of all images. If no
% resolution is specified, the minimum of 1mm and the voxel sizes of the
% images is used.
%
% FORMAT spm_orthviews('Zoom'[,fov[,res]])
% fov - half width of field of view (mm)
% res - resolution (mm)
% sets the displayed part and sampling resolution for all images. The
% image display will be centered at the current crosshair position. The
% image region [xhairs-fov xhairs+fov] will be shown.
% If no argument is given or fov == Inf, the image display will be reset to
% "Full Volume". If fov == 0, the image will be zoomed to the bounding box
% from spm_get_bbox for the non-zero voxels of the image. If fov is NaN,
% then a threshold can be entered, and spm_get_bbox will be used to derive
% the bounding box of the voxels above this threshold.
% Optionally, the display resolution can be set as well.
%
% FORMAT spm_orthviews('Delete', handle)
% handle - image number to delete
%
% FORMAT spm_orthviews('Reset')
% clears the orthogonal views
%
% FORMAT spm_orthviews('Pos')
% returns the co-ordinate of the crosshairs in millimetres in the
% standard space.
%
% FORMAT spm_orthviews('Pos', i)
% returns the voxel co-ordinate of the crosshairs in the image in the
% ith orthogonal section.
%
% FORMAT spm_orthviews('Xhairs','off') OR spm_orthviews('Xhairs')
% disables the cross-hairs on the display.
%
% FORMAT spm_orthviews('Xhairs','on')
% enables the cross-hairs.
%
% FORMAT spm_orthviews('Interp',hld)
% sets the hold value to hld (see spm_slice_vol).
%
% FORMAT spm_orthviews('AddBlobs',handle,XYZ,Z,mat,name)
% Adds blobs from a pointlist to the image specified by the handle(s).
% handle - image number to add blobs to
% XYZ - blob voxel locations
% Z - blob voxel intensities
% mat - matrix from voxels to millimeters of blob.
% name - a name for this blob
% This method only adds one set of blobs, and displays them using a
% split colour table.
%
% FORMAT spm_orthviews('SetBlobsMax', vn, bn, mx)
% Set maximum value for blobs overlay number bn of view number vn to mx.
%
% FORMAT spm_orthviews('AddColouredBlobs',handle,XYZ,Z,mat,colour,name)
% Adds blobs from a pointlist to the image specified by the handle(s).
% handle - image number to add blobs to
% XYZ - blob voxel locations
% Z - blob voxel intensities
% mat - matrix from voxels to millimeters of blob.
% colour - the 3 vector containing the colour that the blobs should be
% name - a name for this blob
% Several sets of blobs can be added in this way, and it uses full colour.
% Although it may not be particularly attractive on the screen, the colour
% blobs print well.
%
% FORMAT spm_orthviews('AddColourBar',handle,blobno)
% Adds colourbar for a specified blob set.
% handle - image number
% blobno - blob number
%
% FORMAT spm_orthviews('RemoveBlobs',handle)
% Removes all blobs from the image specified by the handle(s).
%
% FORMAT spm_orthviews('Addtruecolourimage',handle,filename,colourmap,prop,mx,mn)
% Adds blobs from an image in true colour.
% handle - image number to add blobs to [default: 1]
% filename - image containing blob data [default: request via GUI]
% colourmap - colormap to display blobs in [default: GUI input]
% prop - intensity proportion of activation cf grayscale [default: 0.4]
% mx - maximum intensity to scale to [maximum value in activation image]
% mn - minimum intensity to scale to [minimum value in activation image]
%
% FORMAT spm_orthviews('Register',hReg)
% hReg - Handle of HandleGraphics object to build registry in.
% See spm_XYZreg for more information.
%
% FORMAT spm_orthviews('AddContext',handle)
% handle - image number to add context menu to
%
% FORMAT spm_orthviews('RemoveContext',handle)
% handle - image number to remove context menu from
%
% FORMAT spm_orthviews('ZoomMenu',zoom,res)
% FORMAT [zoom, res] = spm_orthviews('ZoomMenu')
% zoom - A list of predefined zoom values
% res - A list of predefined resolutions
% This list is used by spm_image and spm_orthviews('addcontext',...) to
% create the 'Zoom' menu. The values can be retrieved by calling
% spm_orthviews('ZoomMenu') with 2 output arguments. Values of 0, NaN and
% Inf are treated specially, see the help for spm_orthviews('Zoom' ...).
%__________________________________________________________________________
%
% PLUGINS
% The display capabilities of spm_orthviews can be extended with plugins.
% These are located in the spm_orthviews subdirectory of the SPM
% distribution.
% The functionality of plugins can be accessed via calls to
% spm_orthviews('plugin_name', plugin_arguments). For detailed descriptions
% of each plugin see help spm_orthviews/spm_ov_'plugin_name'.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner et al
% $Id: spm_orthviews.m 6071 2014-06-27 12:52:33Z guillaume $
% The basic fields of st are:
% n - the number of images currently being displayed
% vols - a cell array containing the data on each of the
% displayed images.
% Space - a mapping between the displayed images and the
% mm space of each image.
% bb - the bounding box of the displayed images.
% centre - the current centre of the orthogonal views
% callback - a callback to be evaluated on a button-click.
% xhairs - crosshairs off/on
% hld - the interpolation method
% fig - the figure that everything is displayed in
% mode - the position/orientation of the sagittal view.
% - currently always 1
%
% st.registry.hReg \_ See spm_XYZreg for documentation
% st.registry.hMe /
%
% For each of the displayed images, there is a non-empty entry in the
% vols cell array. Handles returned by "spm_orthviews('Image',.....)"
% indicate the position in the cell array of the newly created ortho-view.
% Operations on each ortho-view require the handle to be passed.
%
% When a new image is displayed, the cell entry contains the information
% returned by spm_vol (type help spm_vol for more info). In addition,
% there are a few other fields, some of which are documented here:
%
% premul - a matrix to premultiply the .mat field by. Useful
% for re-orienting images.
% window - either 'auto' or an intensity range to display the
% image with.
% mapping - Mapping of image intensities to grey values. Currently
% one of 'linear', 'histeq', loghisteq',
% 'quadhisteq'. Default is 'linear'.
% Histogram equalisation depends on the image toolbox
% and is only available if there is a license available
% for it.
% ax - a cell array containing an element for the three
% views. The fields of each element are handles for
% the axis, image and crosshairs.
%
% blobs - optional. Is there for using to superimpose blobs.
% vol - 3D array of image data
% mat - a mapping from vox-to-mm (see spm_vol, or
% help on image formats).
% max - maximum intensity for scaling to. If it
% does not exist, then images are auto-scaled.
%
% There are two colouring modes: full colour, and split
% colour. When using full colour, there should be a
% 'colour' field for each cell element. When using
% split colourscale, there is a handle for the colorbar
% axis.
%
% colour - if it exists it contains the
% red,green,blue that the blobs should be
% displayed in.
% cbar - handle for colorbar (for split colourscale).
%
% PLUGINS
% The plugin concept has been developed to extend the display capabilities
% of spm_orthviews without the need to rewrite parts of it. Interaction
% between spm_orthviews and plugins takes place
% a) at startup: The subfunction 'reset_st' looks for folders
% 'spm_orthviews' in spm('Dir') and each toolbox
% folder. Files with a name spm_ov_PLUGINNAME.m in any of
% these folders will be treated as plugins.
% For each such file, PLUGINNAME will be added to the list
% st.plugins{:}.
% The subfunction 'add_context' calls each plugin with
% feval(['spm_ov_', st.plugins{k}], ...
% 'context_menu', i, parent_menu)
% Each plugin may add its own submenu to the context
% menu.
% b) at redraw: After images and blobs of st.vols{i} are drawn, the
% struct st.vols{i} is checked for field names that occur in
% the plugin list st.plugins{:}. For each matching entry, the
% corresponding plugin is called with the command 'redraw':
% feval(['spm_ov_', st.plugins{k}], ...
% 'redraw', i, TM0, TD, CM0, CD, SM0, SD);
% The values of TM0, TD, CM0, CD, SM0, SD are defined in the
% same way as in the redraw subfunction of spm_orthviews.
% It is up to the plugin to do all necessary redraw
% operations for its display contents. Each displayed item
% must have set its property 'HitTest' to 'off' to let events
% go through to the underlying axis, which is responsible for
% callback handling. The order in which plugins are called is
% undefined.
global st;
persistent zoomlist;
persistent reslist;
if isempty(st), reset_st; end
if nargin == 0, action = ''; end
if ~any(strcmpi(action,{'reposition','pos'}))
spm('Pointer','Watch');
end
switch lower(action)
case 'image',
H = specify_image(varargin{1});
if ~isempty(H)
if numel(varargin)>=2
st.vols{H}.area = varargin{2};
else
st.vols{H}.area = [0 0 1 1];
end
if isempty(st.bb), st.bb = maxbb; end
resolution;
bbox;
cm_pos;
end
varargout{1} = H;
mmcentre = mean(st.Space*[maxbb';1 1],2)';
st.centre = mmcentre(1:3);
redraw_all
case 'caption'
vh = valid_handles(varargin{1});
nh = numel(vh);
xlh = nan(nh, 1);
for i = 1:nh
xlh(i) = get(st.vols{vh(i)}.ax{3}.ax, 'XLabel');
if iscell(varargin{2})
if i <= length(varargin{2})
set(xlh(i), 'String', varargin{2}{i});
end
else
set(xlh(i), 'String', varargin{2});
end
for np = 4:2:nargin
property = varargin{np-1};
value = varargin{np};
set(xlh(i), property, value);
end
end
varargout{1} = xlh;
case 'bb',
if ~isempty(varargin) && all(size(varargin{1})==[2 3]), st.bb = varargin{1}; end
bbox;
redraw_all;
case 'redraw',
redraw_all;
eval(st.callback);
if isfield(st,'registry'),
spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe);
end
case 'reposition',
if isempty(varargin), tmp = findcent;
else tmp = varargin{1}; end
if numel(tmp) == 3
h = valid_handles(st.snap);
if ~isempty(h)
tmp = st.vols{h(1)}.mat * ...
round(st.vols{h(1)}.mat\[tmp(:); 1]);
end
st.centre = tmp(1:3);
end
redraw_all;
eval(st.callback);
if isfield(st,'registry')
spm_XYZreg('SetCoords',st.centre,st.registry.hReg,st.registry.hMe);
end
cm_pos;
case 'setcoords',
st.centre = varargin{1};
st.centre = st.centre(:);
redraw_all;
eval(st.callback);
cm_pos;
case 'space',
if numel(varargin)<1
st.Space = eye(4);
st.bb = maxbb;
resolution;
bbox;
redraw_all;
else
space(varargin{:});
resolution;
bbox;
redraw_all;
end
case 'maxbb',
st.bb = maxbb;
bbox;
redraw_all;
case 'resolution',
resolution(varargin{:});
bbox;
redraw_all;
case 'window',
if numel(varargin)<2
win = 'auto';
elseif numel(varargin{2})==2
win = varargin{2};
end
for i=valid_handles(varargin{1})
st.vols{i}.window = win;
end
redraw(varargin{1});
case 'delete',
my_delete(varargin{1});
case 'move',
move(varargin{1},varargin{2});
% redraw_all;
case 'reset',
my_reset;
case 'pos',
if isempty(varargin)
H = st.centre(:);
else
H = pos(varargin{1});
end
varargout{1} = H;
case 'interp',
st.hld = varargin{1};
redraw_all;
case 'xhairs',
xhairs(varargin{1});
case 'register',
register(varargin{1});
case 'addblobs',
addblobs(varargin{:});
% redraw(varargin{1});
case 'setblobsmax'
st.vols{varargin{1}}.blobs{varargin{2}}.max = varargin{3};
spm_orthviews('redraw')
case 'addcolouredblobs',
addcolouredblobs(varargin{:});
% redraw(varargin{1});
case 'addimage',
addimage(varargin{1}, varargin{2});
% redraw(varargin{1});
case 'addcolouredimage',
addcolouredimage(varargin{1}, varargin{2},varargin{3});
% redraw(varargin{1});
case 'addtruecolourimage',
if nargin < 2
varargin(1) = {1};
end
if nargin < 3
varargin(2) = {spm_select(1, 'image', 'Image with activation signal')};
end
if nargin < 4
actc = [];
while isempty(actc)
actc = getcmap(spm_input('Colourmap for activation image', '+1','s'));
end
varargin(3) = {actc};
end
if nargin < 5
varargin(4) = {0.4};
end
if nargin < 6
actv = spm_vol(varargin{2});
varargin(5) = {max([eps maxval(actv)])};
end
if nargin < 7
varargin(6) = {min([0 minval(actv)])};
end
addtruecolourimage(varargin{1}, varargin{2},varargin{3}, varargin{4}, ...
varargin{5}, varargin{6});
% redraw(varargin{1});
case 'addcolourbar',
addcolourbar(varargin{1}, varargin{2});
case {'removeblobs','rmblobs'},
rmblobs(varargin{1});
redraw(varargin{1});
case 'addcontext',
if nargin == 1
handles = 1:24;
else
handles = varargin{1};
end
addcontexts(handles);
case {'removecontext','rmcontext'},
if nargin == 1
handles = 1:24;
else
handles = varargin{1};
end
rmcontexts(handles);
case 'context_menu',
c_menu(varargin{:});
case 'valid_handles',
if nargin == 1
handles = 1:24;
else
handles = varargin{1};
end
varargout{1} = valid_handles(handles);
case 'zoom',
zoom_op(varargin{:});
case 'zoommenu',
if isempty(zoomlist)
zoomlist = [NaN 0 5 10 20 40 80 Inf];
reslist = [1 1 .125 .25 .5 .5 1 1 ];
end
if nargin >= 3
if all(cellfun(@isnumeric,varargin(1:2))) && ...
numel(varargin{1})==numel(varargin{2})
zoomlist = varargin{1}(:);
reslist = varargin{2}(:);
else
warning('spm_orthviews:zoom',...
'Invalid zoom or resolution list.')
end
end
if nargout > 0
varargout{1} = zoomlist;
end
if nargout > 1
varargout{2} = reslist;
end
otherwise,
addonaction = strcmpi(st.plugins,action);
if any(addonaction)
feval(['spm_ov_' st.plugins{addonaction}],varargin{:});
end
end
spm('Pointer','Arrow');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addblobs(handle, xyz, t, mat, name)
global st
if nargin < 5
name = '';
end;
for i=valid_handles(handle),
if ~isempty(xyz),
rcp = round(xyz);
dim = max(rcp,[],2)';
off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));
vol = zeros(dim)+NaN;
vol(off) = t;
vol = reshape(vol,dim);
st.vols{i}.blobs=cell(1,1);
mx = max([eps max(t)]);
mn = min([0 min(t)]);
st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx, 'min',mn,'name',name);
addcolourbar(handle,1);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addimage(handle, fname)
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else
vol = spm_vol(fname);
end;
mat = vol.mat;
st.vols{i}.blobs=cell(1,1);
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
st.vols{i}.blobs{1} = struct('vol',vol,'mat',mat,'max',mx,'min',mn);
addcolourbar(handle,1);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcolouredblobs(handle, xyz, t, mat, colour, name)
if nargin < 6
name = '';
end;
global st
for i=valid_handles(handle),
if ~isempty(xyz),
rcp = round(xyz);
dim = max(rcp,[],2)';
off = rcp(1,:) + dim(1)*(rcp(2,:)-1 + dim(2)*(rcp(3,:)-1));
vol = zeros(dim)+NaN;
vol(off) = t;
vol = reshape(vol,dim);
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else
bset = numel(st.vols{i}.blobs)+1;
end;
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
st.vols{i}.blobs{bset} = struct('vol',vol, 'mat',mat, ...
'max',mx, 'min',mn, ...
'colour',colour, 'name',name);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcolouredimage(handle, fname,colour)
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else
vol = spm_vol(fname);
end;
mat = vol.mat;
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else
bset = numel(st.vols{i}.blobs)+1;
end;
mx = max([eps maxval(vol)]);
mn = min([0 minval(vol)]);
st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx,'min',mn,'colour',colour);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addtruecolourimage(handle,fname,colourmap,prop,mx,mn)
% adds true colour image to current displayed image
global st
for i=valid_handles(handle),
if isstruct(fname),
vol = fname(1);
else
vol = spm_vol(fname);
end;
mat = vol.mat;
if ~isfield(st.vols{i},'blobs'),
st.vols{i}.blobs=cell(1,1);
bset = 1;
else
bset = numel(st.vols{i}.blobs)+1;
end;
c = struct('cmap', colourmap,'prop',prop);
st.vols{i}.blobs{bset} = struct('vol',vol,'mat',mat,'max',mx, ...
'min',mn,'colour',c);
addcolourbar(handle,bset);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function addcolourbar(vh,bh)
global st
if st.mode == 0,
axpos = get(st.vols{vh}.ax{2}.ax,'Position');
else
axpos = get(st.vols{vh}.ax{1}.ax,'Position');
end;
st.vols{vh}.blobs{bh}.cbar = axes('Parent',st.fig,...
'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1) (axpos(2)+0.005) 0.05 (axpos(4)-0.01)],...
'Box','on', 'YDir','normal', 'XTickLabel',[], 'XTick',[]);
if isfield(st.vols{vh}.blobs{bh},'name')
ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function rmblobs(handle)
global st
for i=valid_handles(handle),
if isfield(st.vols{i},'blobs'),
for j=1:numel(st.vols{i}.blobs),
if isfield(st.vols{i}.blobs{j},'cbar') && ishandle(st.vols{i}.blobs{j}.cbar),
delete(st.vols{i}.blobs{j}.cbar);
end;
end;
st.vols{i} = rmfield(st.vols{i},'blobs');
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function register(hreg)
global st
tmp = uicontrol('Position',[0 0 1 1],'Visible','off','Parent',st.fig);
h = valid_handles(1:24);
if ~isempty(h),
tmp = st.vols{h(1)}.ax{1}.ax;
st.registry = struct('hReg',hreg,'hMe', tmp);
spm_XYZreg('Add2Reg',st.registry.hReg,st.registry.hMe, 'spm_orthviews');
else
warning('Nothing to register with');
end;
st.centre = spm_XYZreg('GetCoords',st.registry.hReg);
st.centre = st.centre(:);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function xhairs(arg1)
global st
st.xhairs = 0;
opt = 'on';
if ~strcmp(arg1,'on'),
opt = 'off';
else
st.xhairs = 1;
end;
for i=valid_handles(1:24),
for j=1:3,
set(st.vols{i}.ax{j}.lx,'Visible',opt);
set(st.vols{i}.ax{j}.ly,'Visible',opt);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function H = pos(arg1)
global st
H = [];
for arg1=valid_handles(arg1),
is = inv(st.vols{arg1}.premul*st.vols{arg1}.mat);
H = is(1:3,1:3)*st.centre(:) + is(1:3,4);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function my_reset
global st
if ~isempty(st) && isfield(st,'registry') && ishandle(st.registry.hMe),
delete(st.registry.hMe); st = rmfield(st,'registry');
end;
my_delete(1:24);
reset_st;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function my_delete(arg1)
global st
% remove blobs (and colourbars, if any)
rmblobs(arg1);
% remove displayed axes
for i=valid_handles(arg1),
kids = get(st.fig,'Children');
for j=1:3,
if any(kids == st.vols{i}.ax{j}.ax),
set(get(st.vols{i}.ax{j}.ax,'Children'),'DeleteFcn','');
delete(st.vols{i}.ax{j}.ax);
end;
end;
st.vols{i} = [];
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function resolution(arg1)
global st
if nargin == 0
res = 1; % Default minimum resolution 1mm
else
res = arg1;
end
for i=valid_handles(1:24)
% adapt resolution to smallest voxel size of displayed images
res = min([res,sqrt(sum((st.vols{i}.mat(1:3,1:3)).^2))]);
end
res = res/mean(svd(st.Space(1:3,1:3)));
Mat = diag([res res res 1]);
st.Space = st.Space*Mat;
st.bb = st.bb/res;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function move(handle,pos)
global st
for handle = valid_handles(handle),
st.vols{handle}.area = pos;
end;
bbox;
% redraw(valid_handles(handle));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function bb = maxbb
global st
mn = [Inf Inf Inf];
mx = -mn;
for i=valid_handles(1:24)
premul = st.Space \ st.vols{i}.premul;
bb = spm_get_bbox(st.vols{i}, 'fv', premul);
mx = max([bb ; mx]);
mn = min([bb ; mn]);
end;
bb = [mn ; mx];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function space(arg1,M,dim)
global st
if ~isempty(st.vols{arg1})
num = arg1;
if nargin < 2
M = st.vols{num}.mat;
dim = st.vols{num}.dim(1:3);
end;
Mat = st.vols{num}.premul(1:3,1:3)*M(1:3,1:3);
vox = sqrt(sum(Mat.^2));
if det(Mat(1:3,1:3))<0, vox(1) = -vox(1); end;
Mat = diag([vox 1]);
Space = (M)/Mat;
bb = [1 1 1; dim];
bb = [bb [1;1]];
bb=bb*Mat';
bb=bb(:,1:3);
bb=sort(bb);
st.Space = Space;
st.bb = bb;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function zoom_op(varargin)
global st
if nargin > 0
fov = varargin{1};
else
fov = Inf;
end
if nargin > 1
res = varargin{2};
else
res = Inf;
end
if isinf(fov)
st.bb = maxbb;
elseif isnan(fov) || fov == 0
current_handle = valid_handles(1:24);
if numel(current_handle) > 1 % called from check reg context menu
current_handle = get_current_handle;
end
if fov == 0
% zoom to bounding box of current image ~= 0
thr = 'nz';
else
% zoom to bounding box of current image > chosen threshold
thr = spm_input('Threshold (Y > ...)', '+1', 'r', '0', 1);
end
premul = st.Space \ st.vols{current_handle}.premul;
st.bb = spm_get_bbox(st.vols{current_handle}, thr, premul);
else
vx = sqrt(sum(st.Space(1:3,1:3).^2));
vx = vx.^(-1);
pos = spm_orthviews('pos');
pos = st.Space\[pos ; 1];
pos = pos(1:3)';
st.bb = [pos-fov*vx; pos+fov*vx];
end;
resolution(res);
bbox;
redraw_all;
if isfield(st.vols{1},'sdip')
spm_eeg_inv_vbecd_disp('RedrawDip');
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function H = specify_image(arg1)
global st
H=[];
if isstruct(arg1),
V = arg1(1);
else
try
V = spm_vol(arg1);
catch
fprintf('Can not use image "%s"\n', arg1);
return;
end;
end;
if numel(V)>1, V=V(1); end
ii = 1;
while ~isempty(st.vols{ii}), ii = ii + 1; end;
DeleteFcn = ['spm_orthviews(''Delete'',' num2str(ii) ');'];
V.ax = cell(3,1);
for i=1:3,
ax = axes('Visible','off','Parent',st.fig,'DeleteFcn',DeleteFcn,...
'YDir','normal','ButtonDownFcn',@repos_start);
d = image(0,'Tag','Transverse','Parent',ax,...
'DeleteFcn',DeleteFcn);
set(ax,'Ydir','normal','ButtonDownFcn',@repos_start);
lx = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn,'Color',[0 0 1]);
ly = line(0,0,'Parent',ax,'DeleteFcn',DeleteFcn,'Color',[0 0 1]);
if ~st.xhairs,
set(lx,'Visible','off');
set(ly,'Visible','off');
end;
V.ax{i} = struct('ax',ax,'d',d,'lx',lx,'ly',ly);
end;
V.premul = eye(4);
V.window = 'auto';
V.mapping = 'linear';
st.vols{ii} = V;
H = ii;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function repos_start(varargin)
% don't use right mouse button to start reposition
if ~strcmpi(get(gcbf,'SelectionType'),'alt')
set(gcbf,'windowbuttonmotionfcn',@repos_move, 'windowbuttonupfcn',@repos_end);
spm_orthviews('reposition');
end
%_______________________________________________________________________
%_______________________________________________________________________
function repos_move(varargin)
spm_orthviews('reposition');
%_______________________________________________________________________
%_______________________________________________________________________
function repos_end(varargin)
set(gcbf,'windowbuttonmotionfcn','', 'windowbuttonupfcn','');
%_______________________________________________________________________
%_______________________________________________________________________
function addcontexts(handles)
for ii = valid_handles(handles),
addcontext(ii);
end;
spm_orthviews('reposition',spm_orthviews('pos'));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function rmcontexts(handles)
global st
for ii = valid_handles(handles),
for i=1:3,
set(st.vols{ii}.ax{i}.ax,'UIcontextmenu',[]);
st.vols{ii}.ax{i} = rmfield(st.vols{ii}.ax{i},'cm');
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function bbox
global st
Dims = diff(st.bb)'+1;
TD = Dims([1 2])';
CD = Dims([1 3])';
if st.mode == 0, SD = Dims([3 2])'; else SD = Dims([2 3])'; end;
un = get(st.fig,'Units');set(st.fig,'Units','Pixels');
sz = get(st.fig,'Position');set(st.fig,'Units',un);
sz = sz(3:4);
sz(2) = sz(2)-40;
for i=valid_handles(1:24),
area = st.vols{i}.area(:);
area = [area(1)*sz(1) area(2)*sz(2) area(3)*sz(1) area(4)*sz(2)];
if st.mode == 0,
sx = area(3)/(Dims(1)+Dims(3))/1.02;
else
sx = area(3)/(Dims(1)+Dims(2))/1.02;
end;
sy = area(4)/(Dims(2)+Dims(3))/1.02;
s = min([sx sy]);
offy = (area(4)-(Dims(2)+Dims(3))*1.02*s)/2 + area(2);
sky = s*(Dims(2)+Dims(3))*0.02;
if st.mode == 0,
offx = (area(3)-(Dims(1)+Dims(3))*1.02*s)/2 + area(1);
skx = s*(Dims(1)+Dims(3))*0.02;
else
offx = (area(3)-(Dims(1)+Dims(2))*1.02*s)/2 + area(1);
skx = s*(Dims(1)+Dims(2))*0.02;
end;
% Transverse
set(st.vols{i}.ax{1}.ax,'Units','pixels', ...
'Position',[offx offy s*Dims(1) s*Dims(2)],...
'Units','normalized','Xlim',[0 TD(1)]+0.5,'Ylim',[0 TD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
% Coronal
set(st.vols{i}.ax{2}.ax,'Units','Pixels',...
'Position',[offx offy+s*Dims(2)+sky s*Dims(1) s*Dims(3)],...
'Units','normalized','Xlim',[0 CD(1)]+0.5,'Ylim',[0 CD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
% Sagittal
if st.mode == 0,
set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',...
'Position',[offx+s*Dims(1)+skx offy s*Dims(3) s*Dims(2)],...
'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
else
set(st.vols{i}.ax{3}.ax,'Units','Pixels', 'Box','on',...
'Position',[offx+s*Dims(1)+skx offy+s*Dims(2)+sky s*Dims(2) s*Dims(3)],...
'Units','normalized','Xlim',[0 SD(1)]+0.5,'Ylim',[0 SD(2)]+0.5,...
'Visible','on','XTick',[],'YTick',[]);
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function redraw_all
redraw(1:24);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function mx = maxval(vol)
if isstruct(vol),
mx = -Inf;
for i=1:vol.dim(3),
tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0);
imx = max(tmp(isfinite(tmp)));
if ~isempty(imx),mx = max(mx,imx);end
end;
else
mx = max(vol(isfinite(vol)));
end;
%_______________________________________________________________________
%_______________________________________________________________________
function mn = minval(vol)
if isstruct(vol),
mn = Inf;
for i=1:vol.dim(3),
tmp = spm_slice_vol(vol,spm_matrix([0 0 i]),vol.dim(1:2),0);
imn = min(tmp(isfinite(tmp)));
if ~isempty(imn),mn = min(mn,imn);end
end;
else
mn = min(vol(isfinite(vol)));
end;
%_______________________________________________________________________
%_______________________________________________________________________
function redraw(arg1)
global st
bb = st.bb;
Dims = round(diff(bb)'+1);
is = inv(st.Space);
cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);
for i = valid_handles(arg1),
M = st.Space\st.vols{i}.premul*st.vols{i}.mat;
TM0 = [ 1 0 0 -bb(1,1)+1
0 1 0 -bb(1,2)+1
0 0 1 -cent(3)
0 0 0 1];
TM = inv(TM0*M);
TD = Dims([1 2]);
CM0 = [ 1 0 0 -bb(1,1)+1
0 0 1 -bb(1,3)+1
0 1 0 -cent(2)
0 0 0 1];
CM = inv(CM0*M);
CD = Dims([1 3]);
if st.mode ==0,
SM0 = [ 0 0 1 -bb(1,3)+1
0 1 0 -bb(1,2)+1
1 0 0 -cent(1)
0 0 0 1];
SM = inv(SM0*M);
SD = Dims([3 2]);
else
SM0 = [ 0 -1 0 +bb(2,2)+1
0 0 1 -bb(1,3)+1
1 0 0 -cent(1)
0 0 0 1];
SM = inv(SM0*M);
SD = Dims([2 3]);
end;
try
imgt = spm_slice_vol(st.vols{i},TM,TD,st.hld)';
imgc = spm_slice_vol(st.vols{i},CM,CD,st.hld)';
imgs = spm_slice_vol(st.vols{i},SM,SD,st.hld)';
ok = true;
catch
fprintf('Image "%s" can not be resampled\n', st.vols{i}.fname);
ok = false;
end
if ok,
% get min/max threshold
if strcmp(st.vols{i}.window,'auto')
mn = -Inf;
mx = Inf;
else
mn = min(st.vols{i}.window);
mx = max(st.vols{i}.window);
end;
% threshold images
imgt = max(imgt,mn); imgt = min(imgt,mx);
imgc = max(imgc,mn); imgc = min(imgc,mx);
imgs = max(imgs,mn); imgs = min(imgs,mx);
% compute intensity mapping, if histeq is available
if license('test','image_toolbox') == 0
st.vols{i}.mapping = 'linear';
end;
switch st.vols{i}.mapping,
case 'linear',
case 'histeq',
% scale images to a range between 0 and 1
imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);
imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);
imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);
img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024);
imgt = reshape(img(1:numel(imgt1)),size(imgt1));
imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));
imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));
mn = 0;
mx = 1;
case 'quadhisteq',
% scale images to a range between 0 and 1
imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);
imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);
imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);
img = histeq([imgt1(:).^2; imgc1(:).^2; imgs1(:).^2],1024);
imgt = reshape(img(1:numel(imgt1)),size(imgt1));
imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));
imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));
mn = 0;
mx = 1;
case 'loghisteq',
sw = warning('off','MATLAB:log:logOfZero');
imgt = log(imgt-min(imgt(:)));
imgc = log(imgc-min(imgc(:)));
imgs = log(imgs-min(imgs(:)));
warning(sw);
imgt(~isfinite(imgt)) = 0;
imgc(~isfinite(imgc)) = 0;
imgs(~isfinite(imgs)) = 0;
% scale log images to a range between 0 and 1
imgt1=(imgt-min(imgt(:)))/(max(imgt(:)-min(imgt(:)))+eps);
imgc1=(imgc-min(imgc(:)))/(max(imgc(:)-min(imgc(:)))+eps);
imgs1=(imgs-min(imgs(:)))/(max(imgs(:)-min(imgs(:)))+eps);
img = histeq([imgt1(:); imgc1(:); imgs1(:)],1024);
imgt = reshape(img(1:numel(imgt1)),size(imgt1));
imgc = reshape(img(numel(imgt1)+(1:numel(imgc1))),size(imgc1));
imgs = reshape(img(numel(imgt1)+numel(imgc1)+(1:numel(imgs1))),size(imgs1));
mn = 0;
mx = 1;
end;
% recompute min/max for display
if strcmp(st.vols{i}.window,'auto')
mx = -inf; mn = inf;
end;
if ~isempty(imgt),
tmp = imgt(isfinite(imgt));
mx = max([mx max(max(tmp))]);
mn = min([mn min(min(tmp))]);
end;
if ~isempty(imgc),
tmp = imgc(isfinite(imgc));
mx = max([mx max(max(tmp))]);
mn = min([mn min(min(tmp))]);
end;
if ~isempty(imgs),
tmp = imgs(isfinite(imgs));
mx = max([mx max(max(tmp))]);
mn = min([mn min(min(tmp))]);
end;
if mx==mn, mx=mn+eps; end;
if isfield(st.vols{i},'blobs'),
if ~isfield(st.vols{i}.blobs{1},'colour'),
% Add blobs for display using the split colourmap
scal = 64/(mx-mn);
dcoff = -mn*scal;
imgt = imgt*scal+dcoff;
imgc = imgc*scal+dcoff;
imgs = imgs*scal+dcoff;
if isfield(st.vols{i}.blobs{1},'max'),
mx = st.vols{i}.blobs{1}.max;
else
mx = max([eps maxval(st.vols{i}.blobs{1}.vol)]);
st.vols{i}.blobs{1}.max = mx;
end;
if isfield(st.vols{i}.blobs{1},'min'),
mn = st.vols{i}.blobs{1}.min;
else
mn = min([0 minval(st.vols{i}.blobs{1}.vol)]);
st.vols{i}.blobs{1}.min = mn;
end;
vol = st.vols{i}.blobs{1}.vol;
M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{1}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])';
%tmpt_z = find(tmpt==0);tmpt(tmpt_z) = NaN;
%tmpc_z = find(tmpc==0);tmpc(tmpc_z) = NaN;
%tmps_z = find(tmps==0);tmps(tmps_z) = NaN;
sc = 64/(mx-mn);
off = 65.51-mn*sc;
msk = find(isfinite(tmpt)); imgt(msk) = off+tmpt(msk)*sc;
msk = find(isfinite(tmpc)); imgc(msk) = off+tmpc(msk)*sc;
msk = find(isfinite(tmps)); imgs(msk) = off+tmps(msk)*sc;
cmap = get(st.fig,'Colormap');
if size(cmap,1)~=128
figure(st.fig)
spm_figure('Colormap','gray-hot')
end;
redraw_colourbar(i,1,[mn mx],(1:64)'+64);
elseif isstruct(st.vols{i}.blobs{1}.colour),
% Add blobs for display using a defined
% colourmap
% colourmaps
gryc = (0:63)'*ones(1,3)/63;
actc = ...
st.vols{1}.blobs{1}.colour.cmap;
actp = ...
st.vols{1}.blobs{1}.colour.prop;
% scale grayscale image, not isfinite -> black
imgt = scaletocmap(imgt,mn,mx,gryc,65);
imgc = scaletocmap(imgc,mn,mx,gryc,65);
imgs = scaletocmap(imgs,mn,mx,gryc,65);
gryc = [gryc; 0 0 0];
% get max for blob image
if isfield(st.vols{i}.blobs{1},'max'),
cmx = st.vols{i}.blobs{1}.max;
else
cmx = max([eps maxval(st.vols{i}.blobs{1}.vol)]);
end;
if isfield(st.vols{i}.blobs{1},'min'),
cmn = st.vols{i}.blobs{1}.min;
else
cmn = -cmx;
end;
% get blob data
vol = st.vols{i}.blobs{1}.vol;
M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{1}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])';
% actimg scaled round 0, black NaNs
topc = size(actc,1)+1;
tmpt = scaletocmap(tmpt,cmn,cmx,actc,topc);
tmpc = scaletocmap(tmpc,cmn,cmx,actc,topc);
tmps = scaletocmap(tmps,cmn,cmx,actc,topc);
actc = [actc; 0 0 0];
% combine gray and blob data to
% truecolour
imgt = reshape(actc(tmpt(:),:)*actp+ ...
gryc(imgt(:),:)*(1-actp), ...
[size(imgt) 3]);
imgc = reshape(actc(tmpc(:),:)*actp+ ...
gryc(imgc(:),:)*(1-actp), ...
[size(imgc) 3]);
imgs = reshape(actc(tmps(:),:)*actp+ ...
gryc(imgs(:),:)*(1-actp), ...
[size(imgs) 3]);
csz = size(st.vols{i}.blobs{1}.colour.cmap);
cdata = reshape(st.vols{i}.blobs{1}.colour.cmap, [csz(1) 1 csz(2)]);
redraw_colourbar(i,1,[cmn cmx],cdata);
else
% Add full colour blobs - several sets at once
scal = 1/(mx-mn);
dcoff = -mn*scal;
wt = zeros(size(imgt));
wc = zeros(size(imgc));
ws = zeros(size(imgs));
imgt = repmat(imgt*scal+dcoff,[1,1,3]);
imgc = repmat(imgc*scal+dcoff,[1,1,3]);
imgs = repmat(imgs*scal+dcoff,[1,1,3]);
cimgt = zeros(size(imgt));
cimgc = zeros(size(imgc));
cimgs = zeros(size(imgs));
colour = zeros(numel(st.vols{i}.blobs),3);
for j=1:numel(st.vols{i}.blobs) % get colours of all images first
if isfield(st.vols{i}.blobs{j},'colour'),
colour(j,:) = reshape(st.vols{i}.blobs{j}.colour, [1 3]);
else
colour(j,:) = [1 0 0];
end;
end;
%colour = colour/max(sum(colour));
for j=1:numel(st.vols{i}.blobs),
if isfield(st.vols{i}.blobs{j},'max'),
mx = st.vols{i}.blobs{j}.max;
else
mx = max([eps max(st.vols{i}.blobs{j}.vol(:))]);
st.vols{i}.blobs{j}.max = mx;
end;
if isfield(st.vols{i}.blobs{j},'min'),
mn = st.vols{i}.blobs{j}.min;
else
mn = min([0 min(st.vols{i}.blobs{j}.vol(:))]);
st.vols{i}.blobs{j}.min = mn;
end;
vol = st.vols{i}.blobs{j}.vol;
M = st.Space\st.vols{i}.premul*st.vols{i}.blobs{j}.mat;
tmpt = spm_slice_vol(vol,inv(TM0*M),TD,[0 NaN])';
tmpc = spm_slice_vol(vol,inv(CM0*M),CD,[0 NaN])';
tmps = spm_slice_vol(vol,inv(SM0*M),SD,[0 NaN])';
% check min/max of sampled image
% against mn/mx as given in st
tmpt(tmpt(:)<mn) = mn;
tmpc(tmpc(:)<mn) = mn;
tmps(tmps(:)<mn) = mn;
tmpt(tmpt(:)>mx) = mx;
tmpc(tmpc(:)>mx) = mx;
tmps(tmps(:)>mx) = mx;
tmpt = (tmpt-mn)/(mx-mn);
tmpc = (tmpc-mn)/(mx-mn);
tmps = (tmps-mn)/(mx-mn);
tmpt(~isfinite(tmpt)) = 0;
tmpc(~isfinite(tmpc)) = 0;
tmps(~isfinite(tmps)) = 0;
cimgt = cimgt + cat(3,tmpt*colour(j,1),tmpt*colour(j,2),tmpt*colour(j,3));
cimgc = cimgc + cat(3,tmpc*colour(j,1),tmpc*colour(j,2),tmpc*colour(j,3));
cimgs = cimgs + cat(3,tmps*colour(j,1),tmps*colour(j,2),tmps*colour(j,3));
wt = wt + tmpt;
wc = wc + tmpc;
ws = ws + tmps;
cdata=permute(shiftdim((1/64:1/64:1)'* ...
colour(j,:),-1),[2 1 3]);
redraw_colourbar(i,j,[mn mx],cdata);
end;
imgt = repmat(1-wt,[1 1 3]).*imgt+cimgt;
imgc = repmat(1-wc,[1 1 3]).*imgc+cimgc;
imgs = repmat(1-ws,[1 1 3]).*imgs+cimgs;
imgt(imgt<0)=0; imgt(imgt>1)=1;
imgc(imgc<0)=0; imgc(imgc>1)=1;
imgs(imgs<0)=0; imgs(imgs>1)=1;
end;
else
scal = 64/(mx-mn);
dcoff = -mn*scal;
imgt = imgt*scal+dcoff;
imgc = imgc*scal+dcoff;
imgs = imgs*scal+dcoff;
end;
set(st.vols{i}.ax{1}.d,'HitTest','off', 'Cdata',imgt);
set(st.vols{i}.ax{1}.lx,'HitTest','off',...
'Xdata',[0 TD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1));
set(st.vols{i}.ax{1}.ly,'HitTest','off',...
'Ydata',[0 TD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1));
set(st.vols{i}.ax{2}.d,'HitTest','off', 'Cdata',imgc);
set(st.vols{i}.ax{2}.lx,'HitTest','off',...
'Xdata',[0 CD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1));
set(st.vols{i}.ax{2}.ly,'HitTest','off',...
'Ydata',[0 CD(2)]+0.5,'Xdata',[1 1]*(cent(1)-bb(1,1)+1));
set(st.vols{i}.ax{3}.d,'HitTest','off','Cdata',imgs);
if st.mode ==0,
set(st.vols{i}.ax{3}.lx,'HitTest','off',...
'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(2)-bb(1,2)+1));
set(st.vols{i}.ax{3}.ly,'HitTest','off',...
'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(cent(3)-bb(1,3)+1));
else
set(st.vols{i}.ax{3}.lx,'HitTest','off',...
'Xdata',[0 SD(1)]+0.5,'Ydata',[1 1]*(cent(3)-bb(1,3)+1));
set(st.vols{i}.ax{3}.ly,'HitTest','off',...
'Ydata',[0 SD(2)]+0.5,'Xdata',[1 1]*(bb(2,2)+1-cent(2)));
end;
if ~isempty(st.plugins) % process any addons
for k = 1:numel(st.plugins),
if isfield(st.vols{i},st.plugins{k}),
feval(['spm_ov_', st.plugins{k}], ...
'redraw', i, TM0, TD, CM0, CD, SM0, SD);
end;
end;
end;
end;
end;
drawnow;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function redraw_colourbar(vh,bh,interval,cdata)
global st
if isfield(st.vols{vh}.blobs{bh},'cbar')
if st.mode == 0,
axpos = get(st.vols{vh}.ax{2}.ax,'Position');
else
axpos = get(st.vols{vh}.ax{1}.ax,'Position');
end;
% only scale cdata if we have out-of-range truecolour values
if ndims(cdata)==3 && max(cdata(:))>1
cdata=cdata./max(cdata(:));
end;
image([0 1],interval,cdata,'Parent',st.vols{vh}.blobs{bh}.cbar);
set(st.vols{vh}.blobs{bh}.cbar, ...
'Position',[(axpos(1)+axpos(3)+0.05+(bh-1)*.1)...
(axpos(2)+0.005) 0.05 (axpos(4)-0.01)],...
'YDir','normal','XTickLabel',[],'XTick',[]);
if isfield(st.vols{vh}.blobs{bh},'name')
ylabel(st.vols{vh}.blobs{bh}.name,'parent',st.vols{vh}.blobs{bh}.cbar);
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function centre = findcent
global st
obj = get(st.fig,'CurrentObject');
centre = [];
cent = [];
cp = [];
for i=valid_handles(1:24),
for j=1:3,
if ~isempty(obj),
if (st.vols{i}.ax{j}.ax == obj),
cp = get(obj,'CurrentPoint');
end;
end;
if ~isempty(cp),
cp = cp(1,1:2);
is = inv(st.Space);
cent = is(1:3,1:3)*st.centre(:) + is(1:3,4);
switch j,
case 1,
cent([1 2])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,2)-1];
case 2,
cent([1 3])=[cp(1)+st.bb(1,1)-1 cp(2)+st.bb(1,3)-1];
case 3,
if st.mode ==0,
cent([3 2])=[cp(1)+st.bb(1,3)-1 cp(2)+st.bb(1,2)-1];
else
cent([2 3])=[st.bb(2,2)+1-cp(1) cp(2)+st.bb(1,3)-1];
end;
end;
break;
end;
end;
if ~isempty(cent), break; end;
end;
if ~isempty(cent), centre = st.Space(1:3,1:3)*cent(:) + st.Space(1:3,4); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function handles = valid_handles(handles)
global st;
if isempty(st) || ~isfield(st,'vols')
handles = [];
else
handles = handles(:)';
handles = handles(handles<=24 & handles>=1 & ~rem(handles,1));
for h=handles,
if isempty(st.vols{h}), handles(handles==h)=[]; end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function reset_st
global st
fig = spm_figure('FindWin','Graphics');
bb = []; %[ [-78 78]' [-112 76]' [-50 85]' ];
st = struct('n', 0, 'vols',[], 'bb',bb,'Space',eye(4),'centre',[0 0 0],'callback',';','xhairs',1,'hld',1,'fig',fig,'mode',1,'plugins',{{}},'snap',[]);
st.vols = cell(24,1);
xTB = spm('TBs');
if ~isempty(xTB)
pluginbase = {spm('Dir') xTB.dir};
else
pluginbase = {spm('Dir')};
end
for k = 1:numel(pluginbase)
pluginpath = fullfile(pluginbase{k},'spm_orthviews');
if isdir(pluginpath)
pluginfiles = dir(fullfile(pluginpath,'spm_ov_*.m'));
if ~isempty(pluginfiles)
if ~isdeployed, addpath(pluginpath); end
% fprintf('spm_orthviews: Using Plugins in %s\n', pluginpath);
for l = 1:numel(pluginfiles)
[p, pluginname, e, v] = spm_fileparts(pluginfiles(l).name);
st.plugins{end+1} = strrep(pluginname, 'spm_ov_','');
% fprintf('%s\n',st.plugins{k});
end;
end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function img = scaletocmap(inpimg,mn,mx,cmap,miscol)
if nargin < 5, miscol=1;end
cml = size(cmap,1);
scf = (cml-1)/(mx-mn);
img = round((inpimg-mn)*scf)+1;
img(img<1) = 1;
img(img>cml) = cml;
img(~isfinite(img)) = miscol;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cmap = getcmap(acmapname)
% get colormap of name acmapname
if ~isempty(acmapname),
cmap = evalin('base',acmapname,'[]');
if isempty(cmap), % not a matrix, is .mat file?
[p, f, e] = fileparts(acmapname);
acmat = fullfile(p, [f '.mat']);
if exist(acmat, 'file'),
s = struct2cell(load(acmat));
cmap = s{1};
end;
end;
end;
if size(cmap, 2)~=3,
warning('Colormap was not an N by 3 matrix')
cmap = [];
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function item_parent = addcontext(volhandle)
global st;
%create context menu
fg = spm_figure('Findwin','Graphics');set(0,'CurrentFigure',fg);
%contextmenu
item_parent = uicontextmenu;
%contextsubmenu 0
item00 = uimenu(item_parent, 'Label','unknown image');
spm_orthviews('context_menu','image_info',item00,volhandle);
item0a = uimenu(item_parent, 'UserData','pos_mm', 'Callback','spm_orthviews(''context_menu'',''repos_mm'');','Separator','on');
item0b = uimenu(item_parent, 'UserData','pos_vx', 'Callback','spm_orthviews(''context_menu'',''repos_vx'');');
item0c = uimenu(item_parent, 'UserData','v_value');
%contextsubmenu 1
item1 = uimenu(item_parent,'Label','Zoom','Separator','on');
[zl, rl] = spm_orthviews('ZoomMenu');
for cz = numel(zl):-1:1
if isinf(zl(cz))
czlabel = 'Full Volume';
elseif isnan(zl(cz))
czlabel = 'BBox, this image > ...';
elseif zl(cz) == 0
czlabel = 'BBox, this image nonzero';
else
czlabel = sprintf('%dx%d mm', 2*zl(cz), 2*zl(cz));
end
item1_x = uimenu(item1, 'Label',czlabel,...
'Callback', sprintf(...
'spm_orthviews(''context_menu'',''zoom'',%d,%d)',...
zl(cz),rl(cz)));
if isinf(zl(cz)) % default display is Full Volume
set(item1_x, 'Checked','on');
end
end
%contextsubmenu 2
checked={'off','off'};
checked{st.xhairs+1} = 'on';
item2 = uimenu(item_parent,'Label','Crosshairs');
item2_1 = uimenu(item2, 'Label','on', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''on'');','Checked',checked{2});
item2_2 = uimenu(item2, 'Label','off', 'Callback','spm_orthviews(''context_menu'',''Xhair'',''off'');','Checked',checked{1});
%contextsubmenu 3
if st.Space == eye(4)
checked = {'off', 'on'};
else
checked = {'on', 'off'};
end;
item3 = uimenu(item_parent,'Label','Orientation');
item3_1 = uimenu(item3, 'Label','World space', 'Callback','spm_orthviews(''context_menu'',''orientation'',3);','Checked',checked{2});
item3_2 = uimenu(item3, 'Label','Voxel space (1st image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',2);','Checked',checked{1});
item3_3 = uimenu(item3, 'Label','Voxel space (this image)', 'Callback','spm_orthviews(''context_menu'',''orientation'',1);','Checked','off');
%contextsubmenu 3
if isempty(st.snap)
checked = {'off', 'on'};
else
checked = {'on', 'off'};
end;
item3 = uimenu(item_parent,'Label','Snap to Grid');
item3_1 = uimenu(item3, 'Label','Don''t snap', 'Callback','spm_orthviews(''context_menu'',''snap'',3);','Checked',checked{2});
item3_2 = uimenu(item3, 'Label','Snap to 1st image', 'Callback','spm_orthviews(''context_menu'',''snap'',2);','Checked',checked{1});
item3_3 = uimenu(item3, 'Label','Snap to this image', 'Callback','spm_orthviews(''context_menu'',''snap'',1);','Checked','off');
%contextsubmenu 4
if st.hld == 0,
checked = {'off', 'off', 'on'};
elseif st.hld > 0,
checked = {'off', 'on', 'off'};
else
checked = {'on', 'off', 'off'};
end;
item4 = uimenu(item_parent,'Label','Interpolation');
item4_1 = uimenu(item4, 'Label','NN', 'Callback','spm_orthviews(''context_menu'',''interpolation'',3);', 'Checked',checked{3});
item4_2 = uimenu(item4, 'Label','Bilin', 'Callback','spm_orthviews(''context_menu'',''interpolation'',2);','Checked',checked{2});
item4_3 = uimenu(item4, 'Label','Sinc', 'Callback','spm_orthviews(''context_menu'',''interpolation'',1);','Checked',checked{1});
%contextsubmenu 5
% item5 = uimenu(item_parent,'Label','Position', 'Callback','spm_orthviews(''context_menu'',''position'');');
%contextsubmenu 6
item6 = uimenu(item_parent,'Label','Image','Separator','on');
item6_1 = uimenu(item6, 'Label','Window');
item6_1_1 = uimenu(item6_1, 'Label','local');
item6_1_1_1 = uimenu(item6_1_1, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window'',2);');
item6_1_1_2 = uimenu(item6_1_1, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window'',1);');
item6_1_2 = uimenu(item6_1, 'Label','global');
item6_1_2_1 = uimenu(item6_1_2, 'Label','auto', 'Callback','spm_orthviews(''context_menu'',''window_gl'',2);');
item6_1_2_2 = uimenu(item6_1_2, 'Label','manual', 'Callback','spm_orthviews(''context_menu'',''window_gl'',1);');
if license('test','image_toolbox') == 1
offon = {'off', 'on'};
checked = offon(strcmp(st.vols{volhandle}.mapping, ...
{'linear', 'histeq', 'loghisteq', 'quadhisteq'})+1);
item6_2 = uimenu(item6, 'Label','Intensity mapping');
item6_2_1 = uimenu(item6_2, 'Label','local');
item6_2_1_1 = uimenu(item6_2_1, 'Label','Linear', 'Checked',checked{1}, ...
'Callback','spm_orthviews(''context_menu'',''mapping'',''linear'');');
item6_2_1_2 = uimenu(item6_2_1, 'Label','Equalised histogram', 'Checked',checked{2}, ...
'Callback','spm_orthviews(''context_menu'',''mapping'',''histeq'');');
item6_2_1_3 = uimenu(item6_2_1, 'Label','Equalised log-histogram', 'Checked',checked{3}, ...
'Callback','spm_orthviews(''context_menu'',''mapping'',''loghisteq'');');
item6_2_1_4 = uimenu(item6_2_1, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ...
'Callback','spm_orthviews(''context_menu'',''mapping'',''quadhisteq'');');
item6_2_2 = uimenu(item6_2, 'Label','global');
item6_2_2_1 = uimenu(item6_2_2, 'Label','Linear', 'Checked',checked{1}, ...
'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''linear'');');
item6_2_2_2 = uimenu(item6_2_2, 'Label','Equalised histogram', 'Checked',checked{2}, ...
'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''histeq'');');
item6_2_2_3 = uimenu(item6_2_2, 'Label','Equalised log-histogram', 'Checked',checked{3}, ...
'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''loghisteq'');');
item6_2_2_4 = uimenu(item6_2_2, 'Label','Equalised squared-histogram', 'Checked',checked{4}, ...
'Callback','spm_orthviews(''context_menu'',''mapping_gl'',''quadhisteq'');');
end;
%contextsubmenu 7
item7 = uimenu(item_parent,'Label','Blobs');
item7_1 = uimenu(item7, 'Label','Add blobs');
item7_1_1 = uimenu(item7_1, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',2);');
item7_1_2 = uimenu(item7_1, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_blobs'',1);');
item7_2 = uimenu(item7, 'Label','Add image');
item7_2_1 = uimenu(item7_2, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_image'',2);');
item7_2_2 = uimenu(item7_2, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_image'',1);');
item7_3 = uimenu(item7, 'Label','Add colored blobs','Separator','on');
item7_3_1 = uimenu(item7_3, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',2);');
item7_3_2 = uimenu(item7_3, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_blobs'',1);');
item7_4 = uimenu(item7, 'Label','Add colored image');
item7_4_1 = uimenu(item7_4, 'Label','local', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',2);');
item7_4_2 = uimenu(item7_4, 'Label','global', 'Callback','spm_orthviews(''context_menu'',''add_c_image'',1);');
item7_5 = uimenu(item7, 'Label','Remove blobs', 'Visible','off','Separator','on');
item7_6 = uimenu(item7, 'Label','Remove colored blobs','Visible','off');
item7_6_1 = uimenu(item7_6, 'Label','local', 'Visible','on');
item7_6_2 = uimenu(item7_6, 'Label','global','Visible','on');
item7_7 = uimenu(item7, 'Label','Set blobs max', 'Visible','off');
for i=1:3,
set(st.vols{volhandle}.ax{i}.ax,'UIcontextmenu',item_parent);
st.vols{volhandle}.ax{i}.cm = item_parent;
end;
% process any plugins
for k = 1:numel(st.plugins),
feval(['spm_ov_', st.plugins{k}], ...
'context_menu', volhandle, item_parent);
if k==1
h = get(item_parent,'Children');
set(h(1),'Separator','on');
end
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function c_menu(varargin)
global st
switch lower(varargin{1}),
case 'image_info',
if nargin <3,
current_handle = get_current_handle;
else
current_handle = varargin{3};
end;
if isfield(st.vols{current_handle},'fname'),
[p,n,e,v] = spm_fileparts(st.vols{current_handle}.fname);
if isfield(st.vols{current_handle},'n')
v = sprintf(',%d',st.vols{current_handle}.n);
end;
set(varargin{2}, 'Label',[n e v]);
end;
delete(get(varargin{2},'children'));
if exist('p','var')
item1 = uimenu(varargin{2}, 'Label', p);
end;
if isfield(st.vols{current_handle},'descrip'),
item2 = uimenu(varargin{2}, 'Label',...
st.vols{current_handle}.descrip);
end;
dt = st.vols{current_handle}.dt(1);
item3 = uimenu(varargin{2}, 'Label', sprintf('Data type: %s', spm_type(dt)));
str = 'Intensity: varied';
if size(st.vols{current_handle}.pinfo,2) == 1,
if st.vols{current_handle}.pinfo(2),
str = sprintf('Intensity: Y = %g X + %g',...
st.vols{current_handle}.pinfo(1:2)');
else
str = sprintf('Intensity: Y = %g X', st.vols{current_handle}.pinfo(1)');
end;
end;
item4 = uimenu(varargin{2}, 'Label',str);
item5 = uimenu(varargin{2}, 'Label', 'Image dims', 'Separator','on');
item51 = uimenu(varargin{2}, 'Label',...
sprintf('%dx%dx%d', st.vols{current_handle}.dim(1:3)));
prms = spm_imatrix(st.vols{current_handle}.mat);
item6 = uimenu(varargin{2}, 'Label','Voxel size', 'Separator','on');
item61 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', prms(7:9)));
item7 = uimenu(varargin{2}, 'Label','Origin', 'Separator','on');
item71 = uimenu(varargin{2}, 'Label',...
sprintf('%.2f %.2f %.2f', prms(1:3)));
R = spm_matrix([0 0 0 prms(4:6)]);
item8 = uimenu(varargin{2}, 'Label','Rotations', 'Separator','on');
item81 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(1,1:3)));
item82 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(2,1:3)));
item83 = uimenu(varargin{2}, 'Label', sprintf('%.2f %.2f %.2f', R(3,1:3)));
item9 = uimenu(varargin{2},...
'Label','Specify other image...',...
'Callback','spm_orthviews(''context_menu'',''swap_img'');',...
'Separator','on');
case 'repos_mm',
oldpos_mm = spm_orthviews('pos');
newpos_mm = spm_input('New Position (mm)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_mm),3);
spm_orthviews('reposition',newpos_mm);
case 'repos_vx'
current_handle = get_current_handle;
oldpos_vx = spm_orthviews('pos', current_handle);
newpos_vx = spm_input('New Position (voxels)','+1','r',sprintf('%.2f %.2f %.2f',oldpos_vx),3);
newpos_mm = st.vols{current_handle}.mat*[newpos_vx;1];
spm_orthviews('reposition',newpos_mm(1:3));
case 'zoom'
zoom_all(varargin{2:end});
bbox;
redraw_all;
case 'xhair',
spm_orthviews('Xhairs',varargin{2});
cm_handles = get_cm_handles;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Crosshairs'),'Children');
set(z_handle,'Checked','off'); %reset check
if strcmp(varargin{2},'off'), op = 1; else op = 2; end
set(z_handle(op),'Checked','on');
end;
case 'orientation',
cm_handles = get_cm_handles;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Orientation'),'Children');
set(z_handle,'Checked','off');
end;
if varargin{2} == 3,
spm_orthviews('Space');
for i = 1:numel(cm_handles),
z_handle = findobj(cm_handles(i),'label','World space');
set(z_handle,'Checked','on');
end;
elseif varargin{2} == 2,
spm_orthviews('Space',1);
for i = 1:numel(cm_handles),
z_handle = findobj(cm_handles(i),'label',...
'Voxel space (1st image)');
set(z_handle,'Checked','on');
end;
else
spm_orthviews('Space',get_current_handle);
z_handle = findobj(st.vols{get_current_handle}.ax{1}.cm, ...
'label','Voxel space (this image)');
set(z_handle,'Checked','on');
return;
end;
case 'snap',
cm_handles = get_cm_handles;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children');
set(z_handle,'Checked','off');
end;
if varargin{2} == 3,
st.snap = [];
elseif varargin{2} == 2,
st.snap = 1;
else
st.snap = get_current_handle;
z_handle = get(findobj(st.vols{get_current_handle}.ax{1}.cm,'label','Snap to Grid'),'Children');
set(z_handle(1),'Checked','on');
return;
end;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Snap to Grid'),'Children');
set(z_handle(varargin{2}),'Checked','on');
end;
case 'interpolation',
tmp = [-4 1 0];
st.hld = tmp(varargin{2});
cm_handles = get_cm_handles;
for i = 1:numel(cm_handles),
z_handle = get(findobj(cm_handles(i),'label','Interpolation'),'Children');
set(z_handle,'Checked','off');
set(z_handle(varargin{2}),'Checked','on');
end;
redraw_all;
case 'window',
current_handle = get_current_handle;
if varargin{2} == 2,
spm_orthviews('window',current_handle);
else
if isnumeric(st.vols{current_handle}.window)
defstr = sprintf('%.2f %.2f', st.vols{current_handle}.window);
else
defstr = '';
end;
[w yp] = spm_input('Range','+1','e',defstr,[1 inf]);
while numel(w) < 1 || numel(w) > 2
uiwait(warndlg('Window must be one or two numbers','Wrong input size','modal'));
[w yp] = spm_input('Range',yp,'e',defstr,[1 inf]);
end
if numel(w) == 1
w(2) = w(1)+eps;
end
spm_orthviews('window',current_handle,w);
end;
case 'window_gl',
if varargin{2} == 2,
for i = 1:numel(get_cm_handles),
st.vols{i}.window = 'auto';
end;
else
current_handle = get_current_handle;
if isnumeric(st.vols{current_handle}.window)
defstr = sprintf('%d %d', st.vols{current_handle}.window);
else
defstr = '';
end;
[w yp] = spm_input('Range','+1','e',defstr,[1 inf]);
while numel(w) < 1 || numel(w) > 2
uiwait(warndlg('Window must be one or two numbers','Wrong input size','modal'));
[w yp] = spm_input('Range',yp,'e',defstr,[1 inf]);
end
if numel(w) == 1
w(2) = w(1)+eps;
end
for i = 1:numel(get_cm_handles),
st.vols{i}.window = w;
end;
end;
redraw_all;
case 'mapping',
checked = strcmp(varargin{2}, ...
{'linear', 'histeq', 'loghisteq', ...
'quadhisteq'});
checked = checked(end:-1:1); % Handles are stored in inverse order
current_handle = get_current_handle;
cm_handles = get_cm_handles;
st.vols{current_handle}.mapping = varargin{2};
z_handle = get(findobj(cm_handles(current_handle), ...
'label','Intensity mapping'),'Children');
for k = 1:numel(z_handle)
c_handle = get(z_handle(k), 'Children');
set(c_handle, 'checked', 'off');
set(c_handle(checked), 'checked', 'on');
end;
redraw_all;
case 'mapping_gl',
checked = strcmp(varargin{2}, ...
{'linear', 'histeq', 'loghisteq', 'quadhisteq'});
checked = checked(end:-1:1); % Handles are stored in inverse order
cm_handles = get_cm_handles;
for k = valid_handles(1:24),
st.vols{k}.mapping = varargin{2};
z_handle = get(findobj(cm_handles(k), ...
'label','Intensity mapping'),'Children');
for l = 1:numel(z_handle)
c_handle = get(z_handle(l), 'Children');
set(c_handle, 'checked', 'off');
set(c_handle(checked), 'checked', 'on');
end;
end;
redraw_all;
case 'swap_img',
current_handle = get_current_handle;
newimg = spm_select(1,'image','select new image');
if ~isempty(newimg)
new_info = spm_vol(newimg);
fn = fieldnames(new_info);
for k=1:numel(fn)
st.vols{current_handle}.(fn{k}) = new_info.(fn{k});
end;
spm_orthviews('context_menu','image_info',get(gcbo, 'parent'));
redraw_all;
end
case 'add_blobs',
% Add blobs to the image - in split colortable
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
spm_input('!DeleteInputObj');
[SPM,xSPM] = spm_getSPM;
if ~isempty(SPM)
for i = 1:numel(cm_handles),
addblobs(cm_handles(i),xSPM.XYZ,xSPM.Z,xSPM.M);
% Add options for removing blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);');
if varargin{2} == 1,
item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);');
end;
% Add options for setting maxima for blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Set blobs max');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''setblobsmax'',2);');
if varargin{2} == 1,
uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''setblobsmax'',1);');
end;
end;
redraw_all;
end
case 'remove_blobs',
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
for i = 1:numel(cm_handles),
rmblobs(cm_handles(i));
% Remove options for removing blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');
delete(get(c_handle,'Children'));
set(c_handle,'Visible','off');
% Remove options for setting maxima for blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Set blobs max');
set(c_handle,'Visible','off');
end;
redraw_all;
case 'add_image',
% Add blobs to the image - in split colortable
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
spm_input('!DeleteInputObj');
fname = spm_select(1,'image','select image');
if ~isempty(fname)
for i = 1:numel(cm_handles),
addimage(cm_handles(i),fname);
% Add options for removing blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove blobs');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
item7_3_1 = uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''remove_blobs'',2);');
if varargin{2} == 1,
item7_3_2 = uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''remove_blobs'',1);');
end;
% Add options for setting maxima for blobs
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Set blobs max');
set(c_handle,'Visible','on');
delete(get(c_handle,'Children'));
uimenu(c_handle,'Label','local','Callback','spm_orthviews(''context_menu'',''setblobsmax'',2);');
if varargin{2} == 1,
uimenu(c_handle,'Label','global','Callback','spm_orthviews(''context_menu'',''setblobsmax'',1);');
end;
end;
redraw_all;
end
case 'add_c_blobs',
% Add blobs to the image - in full colour
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
spm_input('!DeleteInputObj');
[SPM,xSPM] = spm_getSPM;
if ~isempty(SPM)
c = spm_input('Colour','+1','m',...
'Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
hlabel = sprintf('%s (%s)',xSPM.title,c_names{c});
for i = 1:numel(cm_handles),
addcolouredblobs(cm_handles(i),xSPM.XYZ,xSPM.Z,xSPM.M,colours(c,:),xSPM.title);
addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs));
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs');
ch_c_handle = get(c_handle,'Children');
set(c_handle,'Visible','on');
%set(ch_c_handle,'Visible',on');
item7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);',...
'UserData',c);
if varargin{2} == 1,
item7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',...
'UserData',c);
end;
end;
redraw_all;
end
case 'remove_c_blobs',
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle; end;
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
for i = 1:numel(cm_handles),
if isfield(st.vols{cm_handles(i)},'blobs'),
for j = 1:numel(st.vols{cm_handles(i)}.blobs),
if all(st.vols{cm_handles(i)}.blobs{j}.colour == colours(varargin{3},:));
if isfield(st.vols{cm_handles(i)}.blobs{j},'cbar')
delete(st.vols{cm_handles(i)}.blobs{j}.cbar);
end
st.vols{cm_handles(i)}.blobs(j) = [];
break;
end;
end;
rm_c_menu = findobj(st.vols{cm_handles(i)}.ax{1}.cm,'Label','Remove colored blobs');
delete(gcbo);
if isempty(st.vols{cm_handles(i)}.blobs),
st.vols{cm_handles(i)} = rmfield(st.vols{cm_handles(i)},'blobs');
set(rm_c_menu, 'Visible', 'off');
end;
end;
end;
redraw_all;
case 'add_c_image',
% Add truecolored image
cm_handles = valid_handles(1:24);
if varargin{2} == 2, cm_handles = get_current_handle;end;
spm_input('!DeleteInputObj');
fname = spm_select([1 Inf],'image','select image(s)');
for k = 1:size(fname,1)
c = spm_input(sprintf('Image %d: Colour',k),'+1','m','Red blobs|Yellow blobs|Green blobs|Cyan blobs|Blue blobs|Magenta blobs',[1 2 3 4 5 6],1);
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
c_names = {'red';'yellow';'green';'cyan';'blue';'magenta'};
hlabel = sprintf('%s (%s)',fname(k,:),c_names{c});
for i = 1:numel(cm_handles),
addcolouredimage(cm_handles(i),fname(k,:),colours(c,:));
addcolourbar(cm_handles(i),numel(st.vols{cm_handles(i)}.blobs));
c_handle = findobj(findobj(st.vols{cm_handles(i)}.ax{1}.cm,'label','Blobs'),'Label','Remove colored blobs');
ch_c_handle = get(c_handle,'Children');
set(c_handle,'Visible','on');
%set(ch_c_handle,'Visible',on');
item7_4_1 = uimenu(ch_c_handle(2),'Label',hlabel,'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',2,c);','UserData',c);
if varargin{2} == 1
item7_4_2 = uimenu(ch_c_handle(1),'Label',hlabel,'ForegroundColor',colours(c,:),...
'Callback','c = get(gcbo,''UserData'');spm_orthviews(''context_menu'',''remove_c_blobs'',1,c);',...
'UserData',c);
end
end
redraw_all;
end
case 'setblobsmax'
if varargin{2} == 1
% global
cm_handles = valid_handles(1:24);
mx = -inf;
for i = 1:numel(cm_handles)
if ~isfield(st.vols{cm_handles(i)}, 'blobs'), continue, end
for j = 1:numel(st.vols{cm_handles(i)}.blobs)
mx = max(mx, st.vols{cm_handles(i)}.blobs{j}.max);
end
end
mx = spm_input('Maximum value', '+1', 'r', mx, 1);
for i = 1:numel(cm_handles)
if ~isfield(st.vols{cm_handles(i)}, 'blobs'), continue, end
for j = 1:numel(st.vols{cm_handles(i)}.blobs)
st.vols{cm_handles(i)}.blobs{j}.max = mx;
end
end
else
% local (should handle coloured blobs, but not implemented yet)
cm_handle = get_current_handle;
colours = [1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1];
if ~isfield(st.vols{cm_handle}, 'blobs'), return, end
for j = 1:numel(st.vols{cm_handle}.blobs)
if nargin < 4 || ...
all(st.vols{cm_handle}.blobs{j}.colour == colours(varargin{3},:))
mx = st.vols{cm_handle}.blobs{j}.max;
mx = spm_input('Maximum value', '+1', 'r', mx, 1);
st.vols{cm_handle}.blobs{j}.max = mx;
end
end
end
redraw_all;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function current_handle = get_current_handle
cm_handle = get(gca,'UIContextMenu');
cm_handles = get_cm_handles;
current_handle = find(cm_handles==cm_handle);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cm_pos
global st
for i = 1:numel(valid_handles(1:24)),
if isfield(st.vols{i}.ax{1},'cm')
set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_mm'),...
'Label',sprintf('mm: %.1f %.1f %.1f',spm_orthviews('pos')));
pos = spm_orthviews('pos',i);
set(findobj(st.vols{i}.ax{1}.cm,'UserData','pos_vx'),...
'Label',sprintf('vx: %.1f %.1f %.1f',pos));
set(findobj(st.vols{i}.ax{1}.cm,'UserData','v_value'),...
'Label',sprintf('Y = %g',spm_sample_vol(st.vols{i},pos(1),pos(2),pos(3),st.hld)));
end
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function cm_handles = get_cm_handles
global st
cm_handles = [];
for i=valid_handles(1:24),
cm_handles = [cm_handles st.vols{i}.ax{1}.cm];
end
return;
%_______________________________________________________________________
%_______________________________________________________________________
function zoom_all(zoom,res)
global st
cm_handles = get_cm_handles;
zoom_op(zoom,res);
for i = 1:numel(cm_handles)
z_handle = get(findobj(cm_handles(i),'label','Zoom'),'Children');
set(z_handle,'Checked','off');
if isinf(zoom)
set(findobj(z_handle,'Label','Full Volume'),'Checked','on');
elseif zoom > 0
set(findobj(z_handle,'Label',sprintf('%dx%d mm', 2*zoom, 2*zoom)),'Checked','on');
end % leave all unchecked if either bounding box option was chosen
end
return;
|
github
|
philippboehmsturm/antx-master
|
spm_FcUtil.m
|
.m
|
antx-master/xspm8/spm_FcUtil.m
| 30,975 |
utf_8
|
0d64cc7e875dbb54242a27a69ebaee99
|
function varargout = spm_FcUtil(varargin)
% Contrast utilities
% FORMAT varargout = spm_FcUtil(action,varargin)
%_______________________________________________________________________
%
% spm_FcUtil is a multi-function function containing various utilities
% for contrast construction and manipulation. In general, it accepts
% design matrices as plain matrices or as space structures setup by
% spm_sp (that is preferable in general).
%
% The use of spm_FcUtil should help with robustness issues and
% maintainability of SPM. % Note that when space structures are passed
% as arguments is is assummed that their basic fields are filled in.
% See spm_sp for details of (design) space structures and their
% manipulation.
%
%
% ======================================================================
% case 'fconfields' %- fields of F contrast
% Fc = spm_FcUtil('FconFields')
%
%- simply returns the fields of a contrast structure.
%
%=======================================================================
% case 'set' %- Create an F contrast
% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)
%
%- Set will fill in the contrast structure, in particular
%- c (in the contrast space), X1o (the space actually tested) and
%- X0 (the space left untested), such that space([X1o X0]) == sX.
%- STAT is either 'F' or 'T';
%- name is a string descibing the contrast.
%
%- There are three ways to set a contrast :
%- set_action is 'c','c+' : value can then be zeros.
%- dimensions are in X',
%- f c+ is used, value is projected onto sX';
%- iX0 is set to 'c' or 'c+';
%- set_action is 'iX0' : defines the indices of the columns
%- that will not be tested. Can be empty.
%- set_action is 'X0' : defines the space that will remain
%- unchanged. The orthogonal complement is
%- tested; iX0 is set to 'X0';
%-
%=======================================================================
% case 'isfcon' %- Is it an F contrast ?
% b = spm_FcUtil('IsFcon',Fc)
%
%=======================================================================
% case 'fconedf' %- F contrast edf
% [edf_tsp edf_Xsp] = spm_FcUtil('FconEdf', Fc, sX [, V])
%
%- compute the effective degrees of freedom of the numerator edf_tsp
%- and (optionally) the denominator edf_Xsp of the contrast.
%
%=======================================================================
% case 'hsqr' %-Extra sum of squares sqr matrix for beta's from contrast
% hsqr = spm_FcUtil('Hsqr',Fc, sX)
%
%- This computes the matrix hsqr such that a the numerator of an F test
%- will be beta'*hsqr'*hsqr*beta
%
%=======================================================================
% case 'h' %-Extra sum of squares matrix for beta's from contrast
% H = spm_FcUtil('H',Fc, sX)
%
%- This computes the matrix H such that a the numerator of an F test
%- will be beta'*H*beta
%-
%=======================================================================
% case 'yc' %- Fitted data corrected for confounds defined by Fc
% Yc = spm_FcUtil('Yc',Fc, sX, b)
%
%- Input : b : the betas
%- Returns the corrected data Yc for given contrast. Y = Yc + Y0 + error
%
%=======================================================================
% case 'y0' %- Confounds data defined by Fc
% Y0 = spm_FcUtil('Y0',Fc, sX, b)
%
%- Input : b : the betas
%- Returns the confound data Y0 for a given contrast. Y = Yc + Y0 + error
%
%=======================================================================
% case {'|_'} %- Fc orthogonalisation
% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)
%
%- Orthogonolise a (list of) contrasts Fc1 wrt a (list of) contrast Fc2
%- such that the space these contrasts test are orthogonal.
%- If contrasts are not estimable contrasts, works with the estimable
%- part. In any case, returns estimable contrasts.
%
%=======================================================================
% case {'|_?'} %- Are contrasts orthogonals
% b = spm_FcUtil('|_?',Fc1, sX [, Fc2])
%
%- Tests whether a (list of) contrast is orthogonal. Works with the
%- estimable part if they are not estimable. With only one argument,
%- tests whether the list is made of orthogonal contrasts. With Fc2
%- provided, tests whether the two (list of) contrast are orthogonal.
%
%=======================================================================
% case 'in' %- Fc1 is in list of contrasts Fc2
% [iFc2 iFc1] = spm_FcUtil('In', Fc1, sX, Fc2)
%
%- Tests wether a (list of) contrast Fc1 is in a list of contrast Fc2.
%- returns the indices iFc2 where element of Fc1 have been found
%- in Fc2 and the indices iFc1 of the element of Fc1 found in Fc2.
%- These indices are not necessarily unique.
%
%=======================================================================
% case '~unique' %- Fc list unique
% idx = spm_FcUtil('~unique', Fc, sX)
%
%- returns indices ofredundant contrasts in Fc
%- such that Fc(idx) = [] makes Fc unique.
%
%=======================================================================
% case {'0|[]','[]|0'} %- Fc is null or empty
% b = spm_FcUtil('0|[]', Fc, sX)
%
%- NB : for the "null" part, checks if the contrast is in the null space
%- of sX (completely non estimable !)
%=======================================================================
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean-Baptiste Poline
% $Id: spm_FcUtil.m 4137 2010-12-15 17:18:32Z guillaume $
%-Format arguments
%-----------------------------------------------------------------------
if nargin==0, error('do what? no arguments given...')
else action = varargin{1}; end
switch lower(action),
case 'fconfields' %- fields of F contrast
%=======================================================================
% Fc = spm_FcUtil('FconFields')
if nargout > 1, error('Too many output arguments: FconFields'), end
if nargin > 1, error('Too many input arguments: FconFields'), end
varargout = {sf_FconFields};
case {'set','v1set'} %- Create an F contrast
%=======================================================================
% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)
%
% Sets the contrast structure with set_action either 'c', 'X0' or 'iX0'
% resp. for a contrast, the null hyp. space or the indices of which.
% STAT can be 'T' or 'F'.
%
% If not set by iX0 (in which case field .iX0 containes the indices),
% field .iX0 is set as a string containing the set_action: {'X0','c','c+','ukX0'}
%
% if STAT is T, then set_action should be 'c' or 'c+'
% (at the moment, just a warning...)
% if STAT is T and set_action is 'c' or 'c+', then
% checks whether it is a real T.
%
% 'v1set' is NOT provided for backward compatibility so far ...
%-check # arguments...
%--------------------------------------------------------------------------
if nargin<6, error('insufficient arguments'), end
if nargout > 1, error('Too many output arguments Set'), end
%-check arguments...
%--------------------------------------------------------------------------
if ~ischar(varargin{2}), error('~ischar(name)'), end
if ~(varargin{3}=='F'||varargin{3}=='T'||varargin{3}=='P'),
error('~(STAT==F|STAT==T|STAT==P)'), end
if ~ischar(varargin{4}), error('~ischar(varargin{4})');
else set_action = varargin{4}; end
sX = varargin{6};
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end
if isempty(sX.X), error('Empty space X in Set'); end
Fc = sf_FconFields;
%- use the name as a flag to insure that F-contrast has been
%- properly created;
Fc.name = varargin{2};
Fc.STAT = varargin{3};
if Fc.STAT=='T' && ~(any(strcmp(set_action,{'c+','c'})))
warning('enter T stat with contrast - here no check rank == 1');
end
[sC sL] = spm_sp('size',sX);
%- allow to define the contrast the old (version 1) way ?
%- NO. v1 = strcmp(action,'v1set');
switch set_action,
case {'c','c+'}
Fc.iX0 = set_action;
c = spm_sp(':', sX, varargin{5});
if isempty(c)
[Fc.X1o.ukX1o Fc.X0.ukX0] = spm_SpUtil('+c->Tsp',sX,[]);
%- v1 [Fc.X1o Fc.X0] = spm_SpUtil('c->Tsp',sX,[]);
Fc.c = c;
elseif size(c,1) ~= sL,
error(['not contrast dim. in ' mfilename ' ' set_action]);
else
if strcmp(set_action,'c+')
if ~spm_sp('isinspp',sX,c), c = spm_sp('oPp:',sX,c); end
end;
if Fc.STAT=='T' && ~sf_is_T(sX,c)
%- Could be make more self-correcting by giving back an F
error('trying to define a t that looks like an F');
end
Fc.c = c;
[Fc.X1o.ukX1o Fc.X0.ukX0] = spm_SpUtil('+c->Tsp',sX,c);
%- v1 [Fc.X1o Fc.X0] = spm_SpUtil('c->Tsp',sX,c);
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% 'option given for completeness - not for SPM use'
case {'X0'}
warning('option given for completeness - not for SPM use');
Fc.iX0 = set_action;
X0 = spm_sp(':', sX, varargin{5});
if isempty(X0),
Fc.c = spm_sp('xpx',sX);
Fc.X1o.ukX1o = spm_sp('cukx',sX);
Fc.X0.ukX0 = [];
elseif size(X0,1) ~= sC,
error('dimension of X0 wrong in Set');
else
Fc.c = spm_SpUtil('X0->c',sX,X0);
Fc.X0.ukX0 = spm_sp('ox',sX)'*X0;
Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);
end
case 'ukX0'
warning('option given for completeness - not for SPM use');
Fc.iX0 = set_action;
if isempty(ukX0),
Fc.c = spm_sp('xpx',sX);
Fc.X1o.ukX1o = spm_sp('cukx',sX);
Fc.X0.ukX0 = [];
elseif size(ukX0,1) ~= spm_sp('rk',sX),
error('dimension of cukX0 wrong in Set');
else
Fc.c = spm_SpUtil('+X0->c',sX,ukX0);
Fc.X0.ukX0 = ukX0;
Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case 'iX0'
iX0 = varargin{5};
iX0 = spm_SpUtil('iX0check',iX0,sL);
Fc.iX0 = iX0;
Fc.X0.ukX0 = spm_sp('ox',sX)' * spm_sp('Xi',sX,iX0);
if isempty(iX0),
Fc.c = spm_sp('xpx',sX);
Fc.X1o.ukX1o = spm_sp('cukx',sX);
else
Fc.c = spm_SpUtil('i0->c',sX,iX0);
Fc.X1o.ukX1o = spm_SpUtil('+c->Tsp',sX,Fc.c);
end
otherwise
error('wrong action in Set ');
end
varargout = {Fc};
case 'x0' % spm_FcUtil('X0',Fc,sX)
%=======================================================================
if nargin ~= 3,
error('too few/many input arguments - need 2');
else
Fc = varargin{2}; sX = varargin{3};
end
if nargout ~= 1, error('too few/many output arguments - need 1'), end
if ~sf_IsFcon(Fc), error('argument is not a contrast struct'), end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end
varargout = {sf_X0(Fc,sX)};
case 'x1o' % spm_FcUtil('X1o',Fc,sX)
%=======================================================================
if nargin ~= 3,
error('too few/many input arguments - need 2');
else
Fc = varargin{2}; sX = varargin{3};
end
if nargout ~= 1, error('too few/many output arguments - need 1'), end
if ~sf_IsFcon(Fc), error('argument is not a contrast struct'), end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end
varargout = {sf_X1o(Fc,sX)};
case 'isfcon' %- Is it an F contrast ?
%=======================================================================
% yes_no = spm_FcUtil('IsFcon',Fc)
if nargin~=2, error('too few/many input arguments - need 2'), end
if ~isstruct(varargin{2}), varargout={0};
else varargout = {sf_IsFcon(varargin{2})};
end
case 'fconedf' %- F contrast edf
%=======================================================================
% [edf_tsp edf_Xsp] = spm_FcUtil('FconEdf', Fc, sX [, V])
if nargin<3, error('Insufficient arguments'), end
if nargout >= 3, error('Too many output argument.'), end
Fc = varargin{2};
sX = varargin{3};
if nargin == 4, V = varargin{4}; else V = []; end
if ~sf_IsFcon(Fc), error('Fc must be Fcon'), end
if ~spm_sp('isspc',sX)
sX = spm_sp('set',sX); end
if ~sf_isempty_X1o(Fc)
[trMV, trMVMV] = spm_SpUtil('trMV',sf_X1o(Fc,sX),V);
else
trMV = 0;
trMVMV = 0;
end
if ~trMVMV, edf_tsp = 0; warning('edf_tsp = 0'),
else edf_tsp = trMV^2/trMVMV; end;
if nargout == 2
[trRV, trRVRV] = spm_SpUtil('trRV',sX,V);
if ~trRVRV, edf_Xsp = 0; warning('edf_Xsp = 0'),
else edf_Xsp = trRV^2/trRVRV; end;
varargout = {edf_tsp, edf_Xsp};
else
varargout = {edf_tsp};
end
%=======================================================================
%=======================================================================
% parts that use F contrast
%=======================================================================
%=======================================================================
%
% Quick reference : L : can be lists of ...
%-------------------------
% ('Hsqr',Fc, sX) : Out: Hsqr / ESS = b' * Hsqr' * Hsqr * b
% ('H',Fc, sX) : Out: H / ESS = b' * H * b
% ('Yc',Fc, sX, b) : Out: Y corrected = X*b - X0*X0- *Y
% ('Y0',Fc, sX, b) : Out: Y0 = X0*X0- *Y
% ('|_',LFc1, sX, LFc2) : Out: Fc1 orthog. wrt Fc2
% ('|_?',LFc1,sX [,LFc2]): Out: is Fc2 ortho to Fc1 or is Fc1 ortho ?
% ('In', LFc1, sX, LFc2) : Out: indices of Fc2 if "in", 0 otherwise
% ('~unique', LFc, sX) : Out: indices of redundant contrasts
% ('0|[]', Fc, sX) : Out: 1 if Fc is zero or empty, 0 otherwise
case 'hsqr' %-Extra sum of squares matrix for beta's from contrast
%=======================================================================
% hsqr = spm_FcUtil('Hsqr',Fc, sX)
if nargin<3, error('Insufficient arguments'), end
if nargout>1, error('Too many output argument.'), end
Fc = varargin{2};
sX = varargin{3};
if ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end
if ~sf_IsSet(Fc), error('Fcon must be set'); end; %-
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
if sf_isempty_X1o(Fc)
if ~sf_isempty_X0(Fc)
%- assumes that X0 is sX.X
%- warning(' Empty X1o in spm_FcUtil(''Hsqr'',Fc,sX) ');
varargout = { zeros(1,spm_sp('size',sX,2)) };
else
error(' Fc must be set ');
end
else
varargout = { sf_Hsqr(Fc,sX) };
end
case 'h' %-Extra sum of squares matrix for beta's from contrast
%=======================================================================
% H = spm_FcUtil('H',Fc, sX)
% Empty and zeros dealing :
% This routine never returns an empty matrix.
% If sf_isempty_X1o(Fc) | isempty(Fc.c) it explicitly
% returns a zeros projection matrix.
if nargin<2, error('Insufficient arguments'), end
if nargout>1, error('Too many output argument.'), end
Fc = varargin{2};
sX = varargin{3};
if ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end
if ~sf_IsSet(Fc), error('Fcon must be set'); end; %-
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
if sf_isempty_X1o(Fc)
if ~sf_isempty_X0(Fc)
%- assumes that X0 is sX.X
%- warning(' Empty X1o in spm_FcUtil(''H'',Fc,sX) ');
varargout = { zeros(spm_sp('size',sX,2)) };
else
error(' Fc must be set ');
end
else
varargout = { sf_H(Fc,sX) };
end
case 'yc' %- Fitted data corrected for confounds defined by Fc
%=======================================================================
% Yc = spm_FcUtil('Yc',Fc, sX, b)
if nargin < 4, error('Insufficient arguments'), end
if nargout > 1, error('Too many output argument.'), end
Fc = varargin{2}; sX = varargin{3}; b = varargin{4};
if ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end
if ~sf_IsSet(Fc), error('Fcon must be set'); end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
% if ~spm_FcUtil('Rcompatible',Fc,sX), ...
% error('sX and Fc must be compatible'), end;
if spm_sp('size',sX,2) ~= size(b,1),
error('sX and b must be compatible'), end;
if sf_isempty_X1o(Fc)
if ~sf_isempty_X0(Fc)
%- if space of interest empty or null, returns zeros !
varargout = { zeros(spm_sp('size',sX,1),size(b,2)) };
else
error(' Fc must be set ');
end
else
varargout = { sf_Yc(Fc,sX,b) };
end
case 'y0' %- Fitted data corrected for confounds defined by Fc
%=======================================================================
% Y0 = spm_FcUtil('Y0',Fc, sX, b)
if nargin < 4, error('Insufficient arguments'), end
if nargout > 1, error('Too many output argument.'), end
Fc = varargin{2}; sX = varargin{3}; b = varargin{4};
if ~sf_IsFcon(Fc), error('Fc must be F-contrast'), end
if ~sf_IsSet(Fc), error('Fcon must be set'); end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
if spm_sp('size',sX,2) ~= size(b,1),
error('sX and b must be compatible'), end;
if sf_isempty_X1o(Fc)
if ~sf_isempty_X0(Fc)
%- if space of interest empty or null, returns zeros !
varargout = { sX.X*b };
else
error(' Fc must be set ');
end
else
varargout = { sf_Y0(Fc,sX,b) };
end
case {'|_'} %- Fc orthogonalisation
%=======================================================================
% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)
% returns Fc1 orthogonolised wrt Fc2
if nargin < 4, error('Insufficient arguments'), end
if nargout > 1, error('Too many output argument.'), end
Fc1 = varargin{2}; sX = varargin{3}; Fc2 = varargin{4};
%-check arguments
%-----------------------------------------------------------------------
L1 = length(Fc1);
if ~L1, warning('no contrast given to |_'); varargout = {[]}; return; end
for i=1:L1
if ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end
end
L2 = length(Fc2);
if ~L2, error('must have at least a contrast in Fc2'); end
for i=1:L2
if ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be a contrast'), end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
%-create an F-contrast for all the Fc2
%--------------------------------------------------------------------------
str = Fc2(1).name; for i=2:L2 str = [str ' ' Fc2(i).name]; end;
Fc2 = spm_FcUtil('Set',str,'F','c+',cat(2,Fc2(:).c),sX);
if sf_isempty_X1o(Fc2) || sf_isnull(Fc2,sX)
varargout = {Fc1};
else
for i=1:L1
if sf_isempty_X1o(Fc1(i)) || sf_isnull(Fc1(i),sX)
%- Fc1(i) is an [] or 0 contrast : ortho to anything;
out(i) = Fc1(i);
else
out(i) = sf_fcortho(Fc1(i), sX, Fc2);
end
end
varargout = {out};
end
case {'|_?'} %- Are contrasts orthogonals
%=======================================================================
% b = spm_FcUtil('|_?',Fc1, sX [, Fc2])
if nargin < 3, error('Insufficient arguments'), end
Fc1 = varargin{2}; sX = varargin{3};
if nargin > 3, Fc2 = varargin{4}; else Fc2 = []; end;
if isempty(Fc1), error('give at least one non empty contrast'), end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
for i=1:length(Fc1)
if ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end
end
for i=1:length(Fc2)
if ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be a contrast'), end
end
varargout = { sf_Rortho(Fc1,sX,Fc2) };
case 'in' %- Fc1 is in list of contrasts Fc2
%=======================================================================
% [iFc2 iFc1] = spm_FcUtil('In', Fc1, sX, Fc2)
% returns indice of Fc2 if "in", 0 otherwise
% NB : If T- stat, the routine checks whether Fc.c is of
% size one. This is ensure if contrast is set
% or manipulated (ortho ..) with spm_FcUtil
% note that the algorithmn works \emph{only because} Fc2(?).c
% and Fc1.c are in space(X')
if nargin < 4, error('Insufficient arguments'), end
if nargout > 2, error('Too many output argument.'), end
Fc1 = varargin{2}; Fc2 = varargin{4}; sX = varargin{3};
L1 = length(Fc1);
if ~L1, warning('no contrast given to in');
if nargout == 2, varargout = {[] []};
else varargout = {[]}; end;
return;
end
for i=1:L1
if ~sf_IsFcon(Fc1(i)), error('Fc1(i) must be a contrast'), end
end
L2 = length(Fc2);
if ~L2, error('must have at least a contrast in Fc2'); end
for i=1:L2
if ~sf_IsFcon(Fc2(i)), error('Fc2(i) must be F-contrast'), end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
[idxFc2 idxFc1] = sf_in(Fc1, sX, Fc2);
if isempty(idxFc2), idxFc2 = 0; end
if isempty(idxFc1), idxFc1 = 0; end
switch nargout
case {0,1}
varargout = { idxFc2 };
case 2
varargout = { idxFc2 idxFc1 };
otherwise
error('Too many or not enough output arguments');
end
case '~unique' %- Fc list unique
%=======================================================================
% idx = spm_FcUtil('~unique', Fc, sX)
%- returns indices of redundant contrasts in Fc
%- such that Fc(idx) = [] makes Fc unique.
%- if already unique returns []
if nargin ~= 3, error('Insufficient/too many arguments'), end
Fc = varargin{2}; sX = varargin{3};
%----------------------------
L1 = length(Fc);
if ~L1, warning('no contrast given '); varargout = {[]}; return; end
for i=1:L1
if ~sf_IsFcon(Fc(i)), error('Fc(i) must be a contrast'), end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
%----------------------------
varargout = { unique(sf_notunique(Fc, sX))};
case {'0|[]','[]|0'} %- Fc is null or empty
%=======================================================================
% b = spm_FcUtil('0|[]', Fc, sX)
% returns 1 if F-contrast is empty or null; assumes the contrast is set.
if nargin ~= 3, error('Insufficient/too many arguments'), end
Fc = varargin{2}; sX = varargin{3};
%----------------------------
L1 = length(Fc);
if ~L1, warning('no contrast given to |_'); varargout = {[]}; return; end
for i=1:L1
if ~sf_IsFcon(Fc(i)), error('Fc(i) must be a contrast'), end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',sX); end;
%----------------------------
idx = [];
for i=1:L1
if sf_isempty_X1o(Fc(i)) || sf_isnull(Fc(i),sX), idx = [idx i]; end
end
if isempty(idx)
varargout = {0};
else
varargout = {idx};
end
%=======================================================================
otherwise
%=======================================================================
error('Unknown action string in spm_FcUtil')
end; %---- switch lower(action),
%=======================================================================
%=======================================================================
% Sub Functions
%=======================================================================
%=======================================================================
%=======================================================================
% Fcon = spm_FcUtil('FconFields')
function Fc = sf_FconFields
Fc = struct(...
'name', '',...
'STAT', '',...
'c', [],...
'X0', struct('ukX0',[]),...
'iX0', [],...
'X1o', struct('ukX1o',[]),...
'eidf', [],...
'Vcon', [],...
'Vspm', []);
%=======================================================================
% used internally. Minimum contrast structure
function minFc = sf_MinFcFields
minFc = struct(...
'name', '',...
'STAT', '',...
'c', [],...
'X0', [],...
'X1o', []);
%=======================================================================
% yes_no = spm_FcUtil('IsFcon',Fc)
function b = sf_IsFcon(Fc)
%- check that minimum fields of a contrast are in Fc
b = 1;
minnames = fieldnames(sf_MinFcFields);
FCnames = fieldnames(Fc);
for str = minnames'
b = b & any(strcmp(str,FCnames));
if ~b, break, end
end
%=======================================================================
% used internally; To be set, a contrast structure should have
% either X1o or X0 non empty. X1o can be non empty because c
% is non empty.
function b = sf_IsSet(Fc)
b = ~sf_isempty_X0(Fc) | ~sf_isempty_X1o(Fc);
%=======================================================================
% used internally
%
function v = sf_ver(Fc)
if isstruct(Fc.X0), v = 2; else v = 1; end
%=======================================================================
% used internally
function b = sf_isempty_X1o(Fc)
if sf_ver(Fc) > 1,
b = isempty(Fc.X1o.ukX1o);
%- consistency check
if b ~= isempty(Fc.c),
Fc.c, Fc.X1o.ukX1o, error('Contrast internally not consistent');
end
else
b = isempty(Fc.X1o);
%- consistency check
if b ~= isempty(Fc.c),
Fc.c, Fc.X1o, error('Contrast internally not consistent');
end
end
%=======================================================================
% used internally
function b = sf_X1o(Fc,sX)
if sf_ver(Fc) > 1,
b = spm_sp('ox',sX)*Fc.X1o.ukX1o;
else
b = Fc.X1o;
end
%=======================================================================
% used internally
function b = sf_X0(Fc,sX)
if sf_ver(Fc) > 1,
b = spm_sp('ox',sX)*Fc.X0.ukX0;
else
b = Fc.X0;
end
%=======================================================================
% used internally
function b = sf_isempty_X0(Fc)
if sf_ver(Fc) > 1,
b = isempty(Fc.X0.ukX0);
else
b = isempty(Fc.X0);
end
%=======================================================================
% Hsqr = spm_Fcutil('Hsqr',Fc,sX)
function hsqr = sf_Hsqr(Fc,sX)
%
% Notations : H equiv to X1o, H = uk*a1, X = uk*ax, r = rk(sX),
% sX.X is (n,p), H is (n,q), a1 is (r,q), ax is (r,p)
% oxa1 is an orthonormal basis for a1, oxa1 is (r,qo<=q)
% Algorithm :
% v1 : Y'*H*(H'*H)-*H'*Y = b'*X'*H*(H'*H)-*H'*X*b
% = b'*X'*oxH*oxH'*X*b
% so hsrq is set to oxH'*X, a (q,n)*(n,p) op. + computation of oxH
% v2 : X'*H*(H'*H)-*H'*X = ax'*uk'*uk*a1*(a1'*uk'*uk*a1)-*a1'*uk'*uk*ax
% = ax'*a1*(a1'*a1)-*a1'*ax
% = ax'*oxa1*oxa1'*ax
%
% so hsrq is set to oxa1'*ax : a (qo,r)*(r,p) operation! -:))
% + computation of oxa1.
%-**** fprintf('v%d\n',sf_ver(Fc));
if sf_ver(Fc) > 1,
hsqr = spm_sp('ox',spm_sp('set',Fc.X1o.ukX1o))' * spm_sp('cukx',sX);
else
hsqr = spm_sp('ox',spm_sp('set',Fc.X1o))'*spm_sp('x',sX);
end
%=======================================================================
% H = spm_FcUtil('H',Fc)
function H = sf_H(Fc,sX)
%
% Notations : H equiv to X1o, H = uk*a1, X = uk*ax
% Algorithm :
% v1 : Y'*H*(H'*H)-*H'*Y = b'*X'*H*(H'*H)-*H'*X*b
% = b'*c*(H'*H)-*c'*b
% = b'*c*(c'*(X'*X)-*c)-*c'*b
%- v1 : Note that pinv(Fc.X1o' * Fc.X1o) is not too bad
%- because dimensions are only (q,q). See sf_hsqr for notations.
%- Fc.c and Fc.X1o should match. This is ensure by using FcUtil.
%-**** fprintf('v%d\n',sf_ver(Fc));
if sf_ver(Fc) > 1,
hsqr = sf_Hsqr(Fc,sX);
H = hsqr' * hsqr;
else
H = Fc.c * pinv(Fc.X1o' * Fc.X1o) * Fc.c';
% H = {c*spm_sp('x-',spm_sp('Set',c'*spm_sp('xpx-',sX)*c) )*c'}
end
%=======================================================================
% Yc = spm_FcUtil('Yc',Fc,sX,b)
function Yc = sf_Yc(Fc,sX,b)
Yc = sX.X*spm_sp('xpx-',sX)*sf_H(Fc,sX)*b;
%=======================================================================
% Y0 = spm_FcUtil('Y0',Fc,sX,b)
function Y0 = sf_Y0(Fc,sX,b)
Y0 = sX.X*(eye(spm_sp('size',sX,2)) - spm_sp('xpx-',sX)*sf_H(Fc,sX))*b;
%=======================================================================
% Fc = spm_FcUtil('|_',Fc1, sX, Fc2)
function Fc1o = sf_fcortho(Fc1, sX, Fc2)
%--- use the space facility to ensure the proper tolerance dealing...
c1_2 = Fc1.c - sf_H(Fc2,sX)*spm_sp('xpx-:',sX,Fc1.c);
Fc1o = spm_FcUtil('Set',['(' Fc1.name ' |_ (' Fc2.name '))'], ...
Fc1.STAT, 'c+',c1_2,sX);
%- In the large (scans) dimension :
%- c = sX.X'*spm_sp('r:',spm_sp('set',Fc2.X1o),Fc1.X1o);
%- Fc1o = spm_FcUtil('Set',['(' Fc1.name ' |_ (' Fc2.name '))'], ...
%- Fc1.STAT, 'c',c,sX);
%=======================================================================
function b = sf_Rortho(Fc1,sX,Fc2)
if isempty(Fc2)
if length(Fc1) <= 1, b = 0;
else
c1 = cat(2,Fc1(:).c);
b = ~any(any( abs(triu(c1'*spm_sp('xpx-:',sX,c1), 1)) > sX.tol));
end
else
c1 = cat(2,Fc1(:).c); c2 = cat(2,Fc2(:).c);
b = ~any(any( abs(c1'*spm_sp('xpx-:',sX,c2)) > sX.tol ));
end
%=======================================================================
% b = spm_FcUtil('0|[]', Fc, sX)
%- returns 1 if F-contrast is empty or null; assumes the contrast is set.
%- Assumes that if Fc.c contains only zeros, so does Fc.X1o.
%- this is ensured if spm_FcUtil is used
function boul = sf_isnull(Fc,sX)
%
boul = ~any(any(spm_sp('oPp:',sX,Fc.c)));
%=======================================================================
% Fc = spm_FcUtil('Set',name, STAT, set_action, value, sX)
function boul = sf_is_T(sX,c)
%- assumes that the dimensions are OK
%- assumes c is not empty
%- Does NOT assumes that c is space of sX'
%- A rank of zero can be defined
%- if the rank == 1, checks whether same directions
boul = 1;
if ~spm_sp('isinspp',sX,c), c = spm_sp('oPp:',sX,c); end;
if rank(c) > 1 || any(any(c'*c < 0)), boul = 0; end;
%=======================================================================
function [idxFc2, idxFc1] = sf_in(Fc1, sX, Fc2)
L2 = length(Fc2);
L1 = length(Fc1);
idxFc1 = []; idxFc2 = [];
for j=1:L1
%- project Fc1(j).c if not estimable
if ~spm_sp('isinspp',sX,Fc1(j).c), %- warning ?
c1 = spm_sp('oPp:',sX,Fc1(j).c);
else
c1 = Fc1(j).c;
end
sc1 = spm_sp('Set',c1);
S = Fc1(j).STAT;
boul = 0;
for i =1:L2
if Fc2(i).STAT == S
%- the same statistics. else just go on to the next contrast
boul = spm_sp('==',sc1,spm_sp('oPp',sX,Fc2(i).c));
%- if they are the same space and T stat (same direction),
%- then check wether they are in the same ORIENTATION
%- works because size(X1o,2) == 1, else .* with (Fc1(j).c'*Fc2(i).c)
if boul && S == 'T'
atmp = sf_X1o(Fc1(j),sX);
btmp = sf_X1o(Fc2(i),sX);
boul = ~any(any( (atmp' * btmp) < 0 ));
end
%- note the indices
if boul, idxFc1 = [idxFc1 j]; idxFc2 = [idxFc2 i]; end
end
end
end %- for j=1:L1
%=======================================================================
function idx = sf_notunique(Fc, sX)
%- works recursively ...
%- and use the fact that [] + i == []
%- quite long for large sets ...
l = length(Fc);
if l == 1, idx = [];
else
idx = [ (1+sf_in(Fc(1),sX,Fc(2:l))) (1+sf_notunique(Fc(2:l), sX))];
end
|
github
|
philippboehmsturm/antx-master
|
spm_read_hdr.m
|
.m
|
antx-master/xspm8/spm_read_hdr.m
| 5,627 |
utf_8
|
785bdd356119ce704a546f3774cd819e
|
function [hdr,otherendian] = spm_read_hdr(fname)
% Read (SPM customised) Analyze header
% FORMAT [hdr,otherendian] = spm_read_hdr(fname)
% fname - .hdr filename
% hdr - structure containing Analyze header
% otherendian - byte swapping necessary flag
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_read_hdr.m 4310 2011-04-18 16:07:35Z guillaume $
fid = fopen(fname,'r','native');
otherendian = 0;
if (fid > 0)
dime = read_dime(fid);
if dime.dim(1)<0 || dime.dim(1)>15, % Appears to be other-endian
% Re-open other-endian
fclose(fid);
if spm_platform('bigend'), fid = fopen(fname,'r','ieee-le');
else fid = fopen(fname,'r','ieee-be'); end;
otherendian = 1;
dime = read_dime(fid);
end;
hk = read_hk(fid);
hist = read_hist(fid);
hdr.hk = hk;
hdr.dime = dime;
hdr.hist = hist;
% SPM specific bit - unused
%if hdr.hk.sizeof_hdr > 348,
% spmf = read_spmf(fid,dime.dim(5));
% if ~isempty(spmf),
% hdr.spmf = spmf;
% end;
%end;
fclose(fid);
else
hdr = [];
otherendian = NaN;
%error(['Problem opening header file (' fopen(fid) ').']);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function hk = read_hk(fid)
% read (struct) header_key
%-----------------------------------------------------------------------
fseek(fid,0,'bof');
hk.sizeof_hdr = fread(fid,1,'int32');
hk.data_type = mysetstr(fread(fid,10,'uchar'))';
hk.db_name = mysetstr(fread(fid,18,'uchar'))';
hk.extents = fread(fid,1,'int32');
hk.session_error = fread(fid,1,'int16');
hk.regular = mysetstr(fread(fid,1,'uchar'))';
hk.hkey_un0 = mysetstr(fread(fid,1,'uchar'))';
if isempty(hk.hkey_un0), error(['Problem reading "hk" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dime = read_dime(fid)
% read (struct) image_dimension
%-----------------------------------------------------------------------
fseek(fid,40,'bof');
dime.dim = fread(fid,8,'int16')';
dime.vox_units = mysetstr(fread(fid,4,'uchar'))';
dime.cal_units = mysetstr(fread(fid,8,'uchar'))';
dime.unused1 = fread(fid,1,'int16');
dime.datatype = fread(fid,1,'int16');
dime.bitpix = fread(fid,1,'int16');
dime.dim_un0 = fread(fid,1,'int16');
dime.pixdim = fread(fid,8,'float')';
dime.vox_offset = fread(fid,1,'float');
dime.funused1 = fread(fid,1,'float');
dime.funused2 = fread(fid,1,'float');
dime.funused3 = fread(fid,1,'float');
dime.cal_max = fread(fid,1,'float');
dime.cal_min = fread(fid,1,'float');
dime.compressed = fread(fid,1,'int32');
dime.verified = fread(fid,1,'int32');
dime.glmax = fread(fid,1,'int32');
dime.glmin = fread(fid,1,'int32');
if isempty(dime.glmin), error(['Problem reading "dime" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function hist = read_hist(fid)
% read (struct) data_history
%-----------------------------------------------------------------------
fseek(fid,148,'bof');
hist.descrip = mysetstr(fread(fid,80,'uchar'))';
hist.aux_file = mysetstr(fread(fid,24,'uchar'))';
hist.orient = fread(fid,1,'uchar');
hist.origin = fread(fid,5,'int16')';
hist.generated = mysetstr(fread(fid,10,'uchar'))';
hist.scannum = mysetstr(fread(fid,10,'uchar'))';
hist.patient_id = mysetstr(fread(fid,10,'uchar'))';
hist.exp_date = mysetstr(fread(fid,10,'uchar'))';
hist.exp_time = mysetstr(fread(fid,10,'uchar'))';
hist.hist_un0 = mysetstr(fread(fid,3,'uchar'))';
hist.views = fread(fid,1,'int32');
hist.vols_added = fread(fid,1,'int32');
hist.start_field= fread(fid,1,'int32');
hist.field_skip = fread(fid,1,'int32');
hist.omax = fread(fid,1,'int32');
hist.omin = fread(fid,1,'int32');
hist.smax = fread(fid,1,'int32');
hist.smin = fread(fid,1,'int32');
if isempty(hist.smin), error(['Problem reading "hist" of header file (' fopen(fid) ').']); end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function spmf = read_spmf(fid,n)
% Read SPM specific fields
% This bit may be used in the future for extending the Analyze header.
fseek(fid,348,'bof');
mgc = fread(fid,1,'int32'); % Magic number
if mgc ~= 20020417, spmf = []; return; end;
for j=1:n,
spmf(j).mat = fread(fid,16,'double'); % Orientation information
spmf(j).unused = fread(fid,384,'uchar'); % Extra unused stuff
if length(spmf(j).unused)<384,
error(['Problem reading "spmf" of header file (' fopen(fid) ').']);
end;
spmf(j).mat = reshape(spmf(j).mat,[4 4]);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function out = mysetstr(in)
tmp = find(in == 0);
tmp = min([min(tmp) length(in)]);
out = char([in(1:tmp)' zeros(1,length(in)-(tmp))])';
return;
%_______________________________________________________________________
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_inv_visu3D_api.m
|
.m
|
antx-master/xspm8/spm_eeg_inv_visu3D_api.m
| 28,460 |
utf_8
|
31ed5e0329581a73574a4b7986a89440
|
function varargout = spm_eeg_inv_visu3D_api(varargin)
% SPM_EEG_INV_VISU3D_API M-file for spm_eeg_inv_visu3D_api.fig
% - FIG = SPM_EEG_INV_VISU3D_API launch spm_eeg_inv_visu3D_api GUI.
% - D = SPM_EEG_INV_VISU3D_API(D) open with D
% - SPM_EEG_INV_VISU3D_API(filename) where filename is the eeg/meg .mat file
% - SPM_EEG_INV_VISU3D_API('callback_name', ...) invoke the named callback.
%
% Last Modified by GUIDE v2.5 18-Feb-2011 14:23:27
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jeremie Mattout
% $Id: spm_eeg_inv_visu3D_api.m 4211 2011-02-23 16:00:02Z vladimir $
% INITIALISATION CODE
%--------------------------------------------------------------------------
if nargin == 0 || nargin == 1 % LAUNCH GUI
% open new api
%----------------------------------------------------------------------
fig = openfig(mfilename,'new');
handles = guihandles(fig);
handles.fig = fig;
guidata(fig,handles);
set(fig,'Color',get(0,'defaultUicontrolBackgroundColor'));
% load D if possible and try to open
%----------------------------------------------------------------------
try
handles.D = spm_eeg_inv_check(varargin{1});
set(handles.DataFile,'String',handles.D.fname)
spm_eeg_inv_visu3D_api_OpeningFcn(fig, [], handles)
end
% return figure handle if necessary
%----------------------------------------------------------------------
if nargout > 0
varargout{1} = fig;
end
elseif ischar(varargin{1})
try
if (nargout)
[varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard
else
feval(varargin{:}); % FEVAL switchyard
end
catch
disp(lasterror);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes just before spm_eeg_inv_visu3D_api is made visible.
function spm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% LOAD DATA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
D = handles.D;
catch
D = spm_eeg_load(spm_select(1, '.mat', 'Select EEG/MEG mat file'));
end
if ~isfield(D,'inv')
error('Please specify and invert a forward model\n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% GET RESULTS (default: current or last analysis)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure(handles.fig);
axes(handles.sensors_axes);
try, val = D.val; catch, val = 1; D.val = 1; end
try, con = D.con; catch, con = 1; D.con = 1; end
if (D.con == 0) || (D.con > length(D.inv{D.val}.inverse.J))
con = 1; D.con = 1;
end
handles.D = D;
set(handles.DataFile,'String',D.fname);
set(handles.next,'String',sprintf('model %i',val));
set(handles.con, 'String',sprintf('condition %i',con));
set(handles.fig,'name',['Source visualisation -' D.fname])
if strcmp(D.inv{val}.method,'ECD')
warndlg('Please create an imaging solution');
guidata(hObject,handles);
return
end
set(handles.LogEv,'String',num2str(D.inv{val}.inverse.F));
set(handles.LogEv,'Enable','inactive');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OBSERVED ACTIVITY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% start with response
%--------------------------------------------------------------------------
try
% Load Gain or Lead field matrix
%----------------------------------------------------------------------
dimT = 256;
dimS = D.inv{val}.inverse.Nd;
Is = D.inv{val}.inverse.Is;
L = D.inv{val}.inverse.L;
U = D.inv{val}.inverse.U;
T = D.inv{val}.inverse.T;
Y = D.inv{val}.inverse.Y{con};
Ts = ceil(linspace(1,size(T,1),dimT));
% source data
%----------------------------------------------------------------------
set(handles.Activity,'Value',1);
J = sparse(dimS,dimT);
J(Is,:) = D.inv{val}.inverse.J{con}*T(Ts,:)';
handles.dimT = dimT;
handles.dimS = dimS;
handles.pst = D.inv{val}.inverse.pst(Ts);
handles.srcs_data = J;
handles.Nmax = max(abs(J(:)));
handles.Is = Is;
% sensor data
%----------------------------------------------------------------------
if ~iscell(U)
U = {U'};
end
A = spm_pinv(spm_cat(spm_diag(U))')';
handles.sens_data = A*Y*T(Ts,:)';
handles.pred_data = A*L*J(Is,:);
catch
warndlg({'Please invert your model';'inverse solution not valid'});
return
end
% case 'windowed response' or contrast'
%--------------------------------------------------------------------------
try
JW = sparse(dimS,1);
GW = sparse(dimS,1);
JW(Is,:) = D.inv{val}.contrast.JW{con};
GW(Is,:) = D.inv{val}.contrast.GW{con};
handles.woi = D.inv{val}.contrast.woi;
handles.fboi = D.inv{val}.contrast.fboi;
handles.W = D.inv{val}.contrast.W(Ts,:);
handles.srcs_data_w = JW;
handles.sens_data_w = handles.sens_data*handles.W(:,1);
handles.pred_data_w = handles.pred_data*handles.W(:,1);
handles.srcs_data_ev = GW;
handles.sens_data_ev = sum((handles.sens_data*handles.W).^2,2);
handles.pred_data_ev = sum((handles.pred_data*handles.W).^2,2);
set(handles.Activity,'enable','on');
catch
set(handles.Activity,'enable','off');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LOAD CORTICAL MESH (default: Individual)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
vert = D.inv{val}.mesh.tess_mni.vert;
face = D.inv{val}.mesh.tess_mni.face;
set(handles.Template, 'Value',1);
set(handles.Individual,'Value',0);
catch
try
vert = D.inv{val}.mesh.tess_ctx.vert;
face = D.inv{val}.mesh.tess_ctx.face;
set(handles.Template, 'Value',0);
set(handles.Individual,'Value',1);
catch
warndlg('There is no mesh associated with these data');
return
end
end
handles.vert = vert;
handles.face = face;
handles.grayc = sqrt(sum((vert.^2),2)); handles.grayc = handles.grayc'/max(handles.grayc);
clear vert face
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SLIDER INITIALISATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
set(handles.slider_transparency,'Min',0,'Max',1,'Value',1,'sliderstep',[0.01 0.05]);
set(handles.slider_srcs_up, 'Min',0,'Max',1,'Value',0,'sliderstep',[0.01 0.05]);
set(handles.slider_srcs_down, 'Min',0,'Max',1,'Value',1,'sliderstep',[0.01 0.05]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INITIAL SOURCE LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
axes(handles.sources_axes);
cla; axis off
set(handles.slider_time, 'Enable','on');
set(handles.time_bin, 'Enable','on');
set(handles.slider_time, 'Value',1);
set(handles.time_bin, 'String',num2str(fix(handles.pst(1))));
set(handles.slider_time, 'Min',1,'Max',handles.dimT,'sliderstep',[1/(handles.dimT-1) 2/(handles.dimT-1)]);
set(handles.checkbox_absv,'Enable','on','Value',1);
set(handles.checkbox_norm,'Enable','on','Value',0);
srcs_disp = full(abs(handles.srcs_data(:,1)));
handles.fig1 = patch('vertices',handles.vert,'faces',handles.face,'FaceVertexCData',srcs_disp);
% display
%--------------------------------------------------------------------------
set(handles.fig1,'FaceColor',[.5 .5 .5],'EdgeColor','none');
shading interp
lighting gouraud
camlight
zoom off
lightangle(0,270);lightangle(270,0),lightangle(0,0),lightangle(90,0);
material([.1 .1 .4 .5 .4]);
view(140,15);
axis image
handles.colorbar = colorbar;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LOAD SENSOR FILE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Ic = {};
if iscell(D.inv{val}.inverse.Ic)
for i = 1:numel(D.inv{val}.inverse.Ic)
if i == 1
Ic{i} = 1:length(D.inv{val}.inverse.Ic{i});
else
Ic{i} = Ic{i-1}(end)+(1:length(D.inv{val}.inverse.Ic{i}));
end
end
else
Ic{1} = 1:length(D.inv{val}.inverse.Ic);
end
handles.Ic = Ic;
coor = D.coor2D(full(spm_cat(D.inv{val}.inverse.Ic)));
xp = coor(1,:)';
yp = coor(2,:)';
x = linspace(min(xp),max(xp),64);
y = linspace(min(yp),max(yp),64);
[xm,ym] = meshgrid(x,y);
handles.sens_coord = [xp yp];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INITIAL SENSOR LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(D.inv{val}.inverse, 'modality')
set(handles.modality, 'String', D.inv{val}.inverse.modality);
else
set(handles.modality, 'String', 'MEEG'); % This is for backward compatibility with old DCM-IMG
end
figure(handles.fig)
axes(handles.sensors_axes);
cla; axis off
im = get(handles.modality, 'Value');
ic = handles.Ic{im};
disp = full(handles.sens_data(ic,1));
imagesc(x,y,griddata(xp(ic),yp(ic),disp,xm,ym));
axis image xy off
handles.sens_coord_x = x;
handles.sens_coord_y = y;
handles.sens_coord2D_X = xm;
handles.sens_coord2D_Y = ym;
hold on
handles.sensor_loc = plot(handles.sens_coord(ic,1),handles.sens_coord(ic,2),'o','MarkerFaceColor',[1 1 1]/2,'MarkerSize',6);
set(handles.checkbox_sensloc,'Value',1);
hold off
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% INITIAL SENSOR LEVEL DISPLAY - PREDICTED
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
axes(handles.pred_axes); cla;
disp = full(handles.pred_data(ic,1));
imagesc(x,y,griddata(xp(ic),yp(ic),disp,xm,ym));
axis image xy off
drawnow
guidata(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UPDATE SOURCE LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function UpDate_Display_SRCS(hObject,handles)
axes(handles.sources_axes);
if isfield(handles,'fig1')
ActToDisp = get(handles.Activity,'Value');
A = get(handles.checkbox_absv,'Value');
N = get(handles.checkbox_norm,'Value');
switch ActToDisp
% case 1: response (J)
%------------------------------------------------------------------
case 1
TS = fix(get(handles.slider_time,'Value'));
if A
srcs_disp = abs(handles.srcs_data(:,TS));
else
srcs_disp = handles.srcs_data(:,TS);
end
if N
if A
handles.Vmin = 0;
handles.Vmax = handles.Nmax;
else
handles.Vmin = -handles.Nmax;
handles.Vmax = handles.Nmax;
end
else
handles.Vmin = min(srcs_disp);
handles.Vmax = max(srcs_disp);
end
% case 2: Windowed response (JW)
%------------------------------------------------------------------
case 2
handles.Vmin = min(handles.srcs_data_w);
handles.Vmax = max(handles.srcs_data_w);
srcs_disp = handles.srcs_data_w;
% case 3: Evoked power (JWWJ)
%------------------------------------------------------------------
case 3
handles.Vmin = min(handles.srcs_data_ev);
handles.Vmax = max(handles.srcs_data_ev);
srcs_disp = handles.srcs_data_ev;
% case 4: Induced power (JWWJ)
%------------------------------------------------------------------
case 4
handles.Vmin = min(handles.srcs_data_ind);
handles.Vmax = max(handles.srcs_data_ind);
srcs_disp = handles.srcs_data_ind;
end
set(handles.fig1,'FaceVertexCData',full(srcs_disp));
set(handles.sources_axes,'CLim',[handles.Vmin handles.Vmax]);
set(handles.sources_axes,'CLimMode','manual');
end
% Adjust the threshold
%--------------------------------------------------------------------------
Set_colormap(hObject, [], handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% UPDATE SENSOR LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function UpDate_Display_SENS(hObject,handles)
TypOfDisp = get(handles.sens_display,'Value');
ActToDisp = get(handles.Activity,'Value');
im = get(handles.modality, 'Value');
ic = handles.Ic{im};
% topography
%--------------------------------------------------------------------------
if TypOfDisp == 1
% responses at one pst
%----------------------------------------------------------------------
if ActToDisp == 1
TS = fix(get(handles.slider_time,'Value'));
sens_disp = handles.sens_data(ic,TS);
pred_disp = handles.pred_data(ic,TS);
% contrast
%----------------------------------------------------------------------
elseif ActToDisp == 2
sens_disp = handles.sens_data_w;
pred_disp = handles.pred_data_w;
% power
%----------------------------------------------------------------------
elseif ActToDisp == 3
sens_disp = handles.sens_data_ev;
pred_disp = handles.pred_data_ev;
end
axes(handles.sensors_axes);
disp = griddata(handles.sens_coord(ic,1),handles.sens_coord(ic,2),full(sens_disp),handles.sens_coord2D_X,handles.sens_coord2D_Y);
imagesc(handles.sens_coord_x,handles.sens_coord_y,disp);
axis image xy off
% add sensor locations
%----------------------------------------------------------------------
try, delete(handles.sensor_loc); end
hold(handles.sensors_axes, 'on');
handles.sensor_loc = plot(handles.sensors_axes,...
handles.sens_coord(ic,1),handles.sens_coord(ic,2),'o','MarkerFaceColor',[1 1 1]/2,'MarkerSize',6);
hold(handles.sensors_axes, 'off');
axes(handles.pred_axes);
disp = griddata(handles.sens_coord(ic,1),handles.sens_coord(ic,2),full(pred_disp),handles.sens_coord2D_X,handles.sens_coord2D_Y);
imagesc(handles.sens_coord_x,handles.sens_coord_y,disp);
axis image xy off;
checkbox_sensloc_Callback(hObject, [], handles);
% time series
%--------------------------------------------------------------------------
elseif TypOfDisp == 2
axes(handles.sensors_axes)
daspect('auto')
handles.fig2 = ...
plot(handles.pst,handles.sens_data(ic, :),'b-.',handles.pst,handles.pred_data(ic, :),'r:');
if ActToDisp > 1
hold on
Scal = norm(handles.sens_data,1)/norm(handles.W,1);
plot(handles.pst,handles.W*Scal,'k')
hold off
end
axis on tight;
axes(handles.pred_axes); cla, axis off
end
% Adjust the threshold
%--------------------------------------------------------------------------
Set_colormap(hObject, [], handles);
guidata(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% LOAD DATA FILE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function DataFile_Callback(hObject, eventdata, handles)
S = get(handles.DataFile,'String');
try
D = spm_eeg_ldata(S);
catch
LoadData_Callback(hObject, eventdata, handles);
end
% --- Executes on button press in LoadData.
function LoadData_Callback(hObject, eventdata, handles)
S = spm_select(1, '.mat', 'Select EEG/MEG mat file');
handles.D = spm_eeg_load(S);
spm_eeg_inv_visu3D_api_OpeningFcn(hObject, [], handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ACTIVITY TO DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on selection change in Activity.
function Activity_Callback(hObject, eventdata, handles)
ActToDisp = get(handles.Activity,'Value');
if ActToDisp == 1
set(handles.checkbox_absv, 'Enable','on');
set(handles.checkbox_norm, 'Enable','on');
set(handles.slider_time, 'Enable','on');
set(handles.time_bin, 'Enable','on');
else
set(handles.checkbox_norm, 'Enable','off');
set(handles.slider_time, 'Enable','off');
set(handles.time_bin, 'Enable','off');
end
if ActToDisp == 2
set(handles.checkbox_absv, 'Enable','off');
end
% update displays
%--------------------------------------------------------------------------
UpDate_Display_SRCS(hObject,handles);
UpDate_Display_SENS(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SWITCH FROM TEMPLATE MESH TO INDIVIDUAL MESH AND BACK
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Individual_Callback(hObject, eventdata, handles)
set(handles.Template,'Value',0);
try
tess_ctx = gifti(handles.D.inv{handles.D.val}.mesh.tess_ctx);
handles.vert = tess_ctx.vertices;
set(handles.Template, 'Value',0);
set(handles.Individual,'Value',1);
end
handles.grayc = sqrt(sum((handles.vert.^2)')); handles.grayc = handles.grayc'/max(handles.grayc);
set(handles.fig1,'vertices',handles.vert,'faces',handles.face);
UpDate_Display_SRCS(hObject,handles);
axes(handles.sources_axes);
axis image;
guidata(hObject,handles);
%--------------------------------------------------------------------------
function Template_Callback(hObject, eventdata, handles)
set(handles.Individual,'Value',0);
try
handles.vert = handles.D.inv{handles.D.val}.mesh.tess_mni.vert;
set(handles.Template, 'Value',1);
set(handles.Individual,'Value',0);
end
handles.grayc = sqrt(sum((handles.vert.^2)')); handles.grayc = handles.grayc'/max(handles.grayc);
set(handles.fig1,'vertices',handles.vert,'faces',handles.face);
UpDate_Display_SRCS(hObject,handles);
axes(handles.sources_axes);
axis image;
guidata(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% THRESHOLD SLIDERS - SOURCE LEVEL
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% upper threshold
% --- Executes on slider movement.
function slider_srcs_up_Callback(hObject, eventdata, handles)
Set_colormap(hObject, eventdata, handles);
%%% lower threshold
% --- Executes on slider movement.
function slider_srcs_down_Callback(hObject, eventdata, handles)
Set_colormap(hObject, eventdata, handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TRANSPARENCY SLIDER
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on slider movement.
function slider_transparency_Callback(hObject, eventdata, handles)
Transparency = get(hObject,'Value');
set(handles.fig1,'facealpha',Transparency);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NORMALISE VALUES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in checkbox_norm.
function checkbox_norm_Callback(hObject, eventdata, handles)
UpDate_Display_SRCS(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% USE ABSOLUTE VALUES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in checkbox_absv.
function checkbox_absv_Callback(hObject, eventdata, handles)
UpDate_Display_SRCS(hObject,handles);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% DISPLAY SENSOR LOCATIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on button press in checkbox_sensloc.
function checkbox_sensloc_Callback(hObject, eventdata, handles)
try
if get(handles.checkbox_sensloc,'Value')
set(handles.sensor_loc,'Visible','on');
else
set(handles.sensor_loc,'Visible','off');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TIME SLIDER - SOURCE & SENSOR LEVEL
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on slider movement.
function slider_time_Callback(hObject, eventdata, handles)
ST = fix(handles.pst(fix(get(hObject,'Value'))));
set(handles.time_bin,'String',num2str(ST));
% Source and sensor space update
%--------------------------------------------------------------------------
UpDate_Display_SRCS(hObject,handles);
UpDate_Display_SENS(hObject,handles);
% --- Callback function
function time_bin_Callback(hObject, eventdata, handles)
[i ST] = min(abs(handles.pst - str2double(get(hObject,'String'))));
set(handles.slider_time,'Value',fix(ST));
% Source and sensor space update
%--------------------------------------------------------------------------
UpDate_Display_SRCS(hObject,handles);
UpDate_Display_SENS(hObject,handles);
% --- Executes on button press in movie.
%--------------------------------------------------------------------------
function movie_Callback(hObject, eventdata, handles)
global MOVIE
for t = 1:length(handles.pst)
set(handles.slider_time,'Value',t);
ST = fix(handles.pst(t));
set(handles.time_bin,'String',num2str(ST));
UpDate_Display_SRCS(hObject,handles);
% record movie if requested
%----------------------------------------------------------------------
if MOVIE, M(t) = getframe(handles.sources_axes); end;
end
UpDate_Display_SENS(hObject,handles);
try
filename = fullfile(handles.D.path,'SourceMovie');
movie2avi(M,filename,'compression','Indeo3','FPS',24)
end
% --- Executes on button press in movie_sens.
%--------------------------------------------------------------------------
function movie_sens_Callback(hObject, eventdata, handles)
global MOVIE
for t = 1:length(handles.pst)
set(handles.slider_time,'Value',t);
ST = fix(handles.pst(t));
set(handles.time_bin,'String',num2str(ST));
UpDate_Display_SENS(hObject,handles);
% record movie if requested
%----------------------------------------------------------------------
if MOVIE, M(t) = getframe(handles.sensors_axes); end;
end
UpDate_Display_SRCS(hObject,handles);
try
filename = fullfile(handles.D.path,'SensorMovie');
movie2avi(M,filename,'compression','Indeo3','FPS',24)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% TYPE OF SENSOR LEVEL DISPLAY
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% --- Executes on selection change in sens_display.
function sens_display_Callback(hObject, eventdata, handles)
TypOfDisp = get(handles.sens_display,'Value');
% if time series
%--------------------------------------------------------------------------
if TypOfDisp == 2
set(handles.checkbox_sensloc,'Value',0);
set(handles.checkbox_sensloc,'Enable','off');
else
set(handles.checkbox_sensloc,'Value',1);
set(handles.checkbox_sensloc,'Enable','on');
end
UpDate_Display_SENS(hObject,handles);
% --- Executes on button press in Exit.
%--------------------------------------------------------------------------
function Exit_Callback(hObject, eventdata, handles)
spm_eeg_inv_visu3D_api_OutputFcn(hObject, eventdata, handles);
close(handles.fig);
% --- Executes on button press in Mip.
%--------------------------------------------------------------------------
function Mip_Callback(hObject, eventdata, handles)
ActToDisp = get(handles.Activity,'Value');
if get(handles.Activity,'Value') == 1
PST = str2num(get(handles.time_bin,'String'));
spm_eeg_invert_display(handles.D,PST);
else
spm_eeg_inv_results_display(handles.D);
end
% --- Outputs from this function are returned to the command line.
%--------------------------------------------------------------------------
function varargout = spm_eeg_inv_visu3D_api_OutputFcn(hObject, eventdata, handles)
D = handles.D;
if nargout == 1
varargout{1} = D;
end
% --- rest threshold
%--------------------------------------------------------------------------
function Set_colormap(hObject, eventdata, handles)
NewMap = jet;
% unsigned values
%--------------------------------------------------------------------------
if get(handles.checkbox_absv,'Value') || get(handles.Activity,'Value') == 3
UpTh = get(handles.slider_srcs_up, 'Value');
N = length(NewMap);
Low = fix(N*UpTh);
Hig = fix(N - N*UpTh);
i = [ones(Low,1); [1:Hig]'*N/Hig];
NewMap = NewMap(fix(i),:);
% signed values
%--------------------------------------------------------------------------
else
UpTh = get(handles.slider_srcs_up, 'Value');
DoTh = 1 - get(handles.slider_srcs_down,'Value');
N = length(NewMap)/2;
Low = fix(N - N*DoTh);
Hig = fix(N - N*UpTh);
i = [[1:Low]'*N/Low; ones(N + N - Hig - Low,1)*N; [1:Hig]'*N/Hig + N];
NewMap = NewMap(fix(i),:);
end
colormap(NewMap);
drawnow
% --- Executes on button press in next.
%--------------------------------------------------------------------------
function next_Callback(hObject, eventdata, handles)
if length(handles.D.inv) == 1
set(handles.next,'Value',0);
return
end
handles.D.val = handles.D.val + 1;
handles.D.con = 1;
if handles.D.val > length(handles.D.inv)
handles.D.val = 1;
end
set(handles.next,'String',sprintf('model %d',handles.D.val),'Value',0);
spm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)
% --- Executes on button press in previous.
%--------------------------------------------------------------------------
function con_Callback(hObject, eventdata, handles)
if length(handles.D.inv{handles.D.val}.inverse.J) == 1
set(handles.con,'Value',0);
return
end
handles.D.con = handles.D.con + 1;
if handles.D.con > length(handles.D.inv{handles.D.val}.inverse.J)
handles.D.con = 1;
end
set(handles.con,'String',sprintf('condition %d',handles.D.con),'Value',0);
spm_eeg_inv_visu3D_api_OpeningFcn(hObject, eventdata, handles)
% --- Executes on button press in VDE.
%--------------------------------------------------------------------------
function Velec_Callback(hObject, eventdata, handles)
axes(handles.sources_axes);
rotate3d off;
datacursormode off;
if isfield(handles, 'velec')
delete(handles.velec);
handles = rmfield(handles, 'velec');
end
set(handles.fig1, 'ButtonDownFcn', @Velec_ButtonDown)
guidata(hObject,handles);
function Velec_ButtonDown(hObject, eventdata)
handles = guidata(hObject);
vert = handles.vert(handles.Is, :);
coord = get(handles.sources_axes, 'CurrentPoint');
dist = sum((vert - repmat(coord(1, :), size(vert, 1), 1)).^2, 2);
[junk, ind] = min(dist);
coord = vert(ind, :);
axes(handles.sources_axes);
hold on
handles.velec = plot3(coord(1), coord(2), coord(3), 'rv', 'MarkerSize', 10);
spm_eeg_invert_display(handles.D, coord);
set(handles.fig1, 'ButtonDownFcn', '');
guidata(hObject,handles);
% --- Executes on button press in Rot.
function Rot_Callback(hObject, eventdata, handles)
%--------------------------------------------------------------------------
rotate3d(handles.sources_axes)
return
% --- Executes on selection change in modality.
function modality_Callback(hObject, eventdata, handles)
% hObject handle to modality (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns modality contents as cell array
% contents{get(hObject,'Value')} returns selected item from modality
UpDate_Display_SENS(hObject,handles)
|
github
|
philippboehmsturm/antx-master
|
spm_load.m
|
.m
|
antx-master/xspm8/spm_load.m
| 1,187 |
utf_8
|
9e2a506bf52d19a51a627ece881f02b2
|
function [x] = spm_load(f)
% function to load ascii file data as matrix
% FORMAT [x] = spm_load(f)
% f - file {ascii file containing a regular array of numbers
% x - corresponding data matrix
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_load.m 1143 2008-02-07 19:33:33Z spm $
%-Get a filename if none was passed
%-----------------------------------------------------------------------
x = [];
if nargin == 0
[f,p] = uigetfile({'*.mat';'*.txt';'*.dat'});
try
f = fullfile(p,f);
end
end
%-Load the data file into double precision matrix x
%-----------------------------------------------------------------------
try
x = load(f,'-ascii');
return
end
try
x = load(f,'-mat');
x = getdata(x);
end
if ~isnumeric(x), x = []; end
function x = getdata(s)
% get numberic data x from the fields of structure s
%--------------------------------------------------------------------------
x = [];
f = fieldnames(s);
for i = 1:length(f)
x = s.(f{i});
if isnumeric(x),return; end
if isstruct(x), x = getdata(x); end
end
|
github
|
philippboehmsturm/antx-master
|
spm_reslice.m
|
.m
|
antx-master/xspm8/spm_reslice.m
| 13,297 |
utf_8
|
831352bc3482e5f11321a4d86aac663d
|
function spm_reslice(P,flags)
% Rigid body reslicing of images
% FORMAT spm_reslice(P,flags)
%
% P - matrix or cell array 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.
%
% flags - a structure containing various options. The fields are:
%
% mask - mask output images (true/false) [default: true]
% To avoid artifactual movement-related variance the
% realigned set of images can be internally masked, within
% the set (i.e. if any image has a zero value at a voxel
% than all images have zero values at that voxel). Zero
% values occur when regions 'outside' the image are moved
% 'inside' the image during realignment.
%
% mean - write mean image (true/false) [default: true]
% The average of all the realigned scans is written to
% an image file with 'mean' prefix.
%
% interp - the B-spline interpolation method [default: 1]
% Non-finite values result in Fourier interpolation. Note
% that Fourier interpolation only works for purely rigid
% body transformations. Voxel sizes must all be identical
% and isotropic.
%
% which - values of 0, 1 or 2 are allowed [default: 2]
% 0 - don't create any resliced images.
% Useful if you only want a mean resliced image.
% 1 - don't reslice the first image.
% The first image is not actually moved, so it may
% not be necessary to resample it.
% 2 - reslice all the images.
% If which is a 2-element vector, flags.mean will be set
% to flags.which(2).
%
% wrap - three values of either 0 or 1, representing wrapping in
% each of the dimensions. For fMRI, [1 1 0] would be used.
% For PET, it would be [0 0 0]. [default: [0 0 0]]
%
% prefix - prefix for resliced images [default: 'r']
%
%__________________________________________________________________________
%
% The spatially realigned images are written to the original subdirectory
% with the same (prefixed) filename. They are all aligned with the first.
%
% Inputs:
% A series of images conforming to SPM data format (see 'Data Format'). The
% relative displacement of the images is stored in their header.
%
% Outputs:
% The routine uses information in their headers and writes the realigned
% image files to the same subdirectory with a prefix.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_reslice.m 4179 2011-01-28 13:57:20Z volkmar $
%__________________________________________________________________________
%
% The headers of the images contain a 4x4 affine transformation matrix 'M',
% usually affected bu the `realignment' and `coregistration' modules.
% What these matrices 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).
%
% 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).
%
% Several spatial transformations (realignment, coregistration,
% normalisation) can be combined into a single operation (without the
% necessity of resampling the images several times).
%
%__________________________________________________________________________
% Refs:
%
% Friston KJ, Williams SR, Howard R Frackowiak RSJ and Turner R (1995)
% Movement-related effect in fMRI time-series. Mag. Res. Med. 35:346-355
%
% W. F. Eddy, M. Fitzgerald and D. C. Noll (1996) Improved Image
% Registration by Using Fourier Interpolation. Mag. Res. Med. 36(6):923-931
%
% R. W. Cox and A. Jesmanowicz (1999) Real-Time 3D Image Registration
% for Functional MRI. Mag. Res. Med. 42(6):1014-1018
%__________________________________________________________________________
def_flags = spm_get_defaults('realign.write');
def_flags.prefix = 'r';
if nargin < 2
flags = def_flags;
else
fnms = fieldnames(def_flags);
for i=1:length(fnms)
if ~isfield(flags,fnms{i})
flags.(fnms{i}) = def_flags.(fnms{i});
end
end
end
if numel(flags.which) == 2
flags.mean = flags.which(2);
flags.which = flags.which(1);
elseif ~isfield(flags,'mean')
flags.mean = 1;
end
if ~nargin || isempty(P), P = spm_select([2 Inf],'image'); end
if iscellstr(P), P = char(P); end;
if ischar(P), P = spm_vol(P); end;
reslice_images(P,flags);
%==========================================================================
function reslice_images(P,flags)
% Reslices images volume by volume
% FORMAT reslice_images(P,flags)
% See main function for a description of the input parameters
if ~isfinite(flags.interp), % Use Fourier method
% Check for non-rigid transformations in the matrixes
for i=1:numel(P)
pp = P(1).mat\P(i).mat;
if any(abs(svd(pp(1:3,1:3))-1)>1e-7)
fprintf('\n Zooms or shears appear to be needed');
fprintf('\n (probably due to non-isotropic voxels).');
fprintf('\n These can not yet be done using the');
fprintf('\n Fourier reslicing method. Switching to');
fprintf('\n 7th degree B-spline interpolation instead.\n\n');
flags.interp = 7;
break
end
end
end
if flags.mask || flags.mean
spm_progress_bar('Init',P(1).dim(3),'Computing available voxels','planes completed');
x1 = repmat((1:P(1).dim(1))',1,P(1).dim(2));
x2 = repmat( 1:P(1).dim(2) ,P(1).dim(1),1);
if flags.mean
Count = zeros(P(1).dim(1:3));
Integral = zeros(P(1).dim(1:3));
end
if flags.mask, msk = cell(P(1).dim(3),1); end;
for x3 = 1:P(1).dim(3)
tmp = zeros(P(1).dim(1:2));
for i = 1:numel(P)
tmp = tmp + getmask(inv(P(1).mat\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap);
end
if flags.mask, msk{x3} = find(tmp ~= numel(P)); end;
if flags.mean, Count(:,:,x3) = tmp; end;
spm_progress_bar('Set',x3);
end
end
nread = numel(P);
if ~flags.mean
if flags.which == 1, nread = nread - 1; end;
if flags.which == 0, nread = 0; end;
end
spm_progress_bar('Init',nread,'Reslicing','volumes completed');
[x1,x2] = ndgrid(1:P(1).dim(1),1:P(1).dim(2));
nread = 0;
d = [flags.interp*[1 1 1]' flags.wrap(:)];
for i = 1:numel(P)
if (i>1 && flags.which==1) || flags.which==2
write_vol = 1;
else
write_vol = 0;
end
if write_vol || flags.mean
read_vol = 1;
else
read_vol = 0;
end
if read_vol
if ~isfinite(flags.interp)
v = abs(kspace3d(spm_bsplinc(P(i),[0 0 0 ; 0 0 0]'),P(1).mat\P(i).mat));
for x3 = 1:P(1).dim(3)
if flags.mean
Integral(:,:,x3) = ...
Integral(:,:,x3) + ...
nan2zero(v(:,:,x3) .* ...
getmask(inv(P(1).mat\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap));
end
if flags.mask
tmp = v(:,:,x3); tmp(msk{x3}) = NaN; v(:,:,x3) = tmp;
end
end
else
C = spm_bsplinc(P(i), d);
v = zeros(P(1).dim);
for x3 = 1:P(1).dim(3)
[tmp,y1,y2,y3] = getmask(inv(P(1).mat\P(i).mat),x1,x2,x3,P(i).dim(1:3),flags.wrap);
v(:,:,x3) = spm_bsplins(C, y1,y2,y3, d);
% v(~tmp) = 0;
if flags.mean
Integral(:,:,x3) = Integral(:,:,x3) + nan2zero(v(:,:,x3));
end
if flags.mask
tmp = v(:,:,x3); tmp(msk{x3}) = NaN; v(:,:,x3) = tmp;
end
end
end
if write_vol
VO = P(i);
[pth,nm,xt,vr] = spm_fileparts(deblank(P(i).fname));
VO.fname = fullfile(pth,[flags.prefix nm xt vr]);
VO.dim = P(1).dim(1:3);
VO.dt = P(i).dt;
VO.pinfo = P(i).pinfo;
VO.mat = P(1).mat;
VO.descrip = 'spm - realigned';
VO = spm_write_vol(VO,v);
end
nread = nread + 1;
end
spm_progress_bar('Set',nread);
end
if flags.mean
% Write integral image (16 bit signed)
%----------------------------------------------------------------------
Integral = Integral./Count;
PO = P(1);
PO = rmfield(PO,'pinfo');
[pth,nm,xt] = spm_fileparts(deblank(P(1).fname));
PO.fname = fullfile(pth,['mean' nm xt]);
PO.pinfo = [max(max(max(Integral)))/32767 0 0]';
PO.descrip = 'spm - mean image';
PO.dt = [spm_type('int16') spm_platform('bigend')];
spm_write_vol(PO,Integral);
end
spm_figure('Clear','Interactive');
%==========================================================================
function v = kspace3d(v,M)
% 3D rigid body transformation performed as shears in 1D Fourier space.
% FORMAT v1 = kspace3d(v,M)
% Inputs:
% v - the image stored as a 3D array.
% M - the rigid body transformation matrix.
% Output:
% v - the transformed image.
%
% The routine is based on the excellent papers:
% R. W. Cox and A. Jesmanowicz (1999)
% Real-Time 3D Image Registration for Functional MRI
% Magnetic Resonance in Medicine 42(6):1014-1018
%
% W. F. Eddy, M. Fitzgerald and D. C. Noll (1996)
% Improved Image Registration by Using Fourier Interpolation
% Magnetic Resonance in Medicine 36(6):923-931
%__________________________________________________________________________
[S0,S1,S2,S3] = shear_decomp(M);
d = [size(v) 1 1 1];
g = 2.^ceil(log2(d));
if any(g~=d)
tmp = v;
v = zeros(g);
v(1:d(1),1:d(2),1:d(3)) = tmp;
clear tmp;
end
% XY-shear
tmp1 = -sqrt(-1)*2*pi*([0:((g(3)-1)/2) 0 (-g(3)/2+1):-1])/g(3);
for j=1:g(2)
t = reshape( exp((j*S3(3,2) + S3(3,1)*(1:g(1)) + S3(3,4)).'*tmp1) ,[g(1) 1 g(3)]);
v(:,j,:) = real(ifft(fft(v(:,j,:),[],3).*t,[],3));
end
% XZ-shear
tmp1 = -sqrt(-1)*2*pi*([0:((g(2)-1)/2) 0 (-g(2)/2+1):-1])/g(2);
for k=1:g(3)
t = exp( (k*S2(2,3) + S2(2,1)*(1:g(1)) + S2(2,4)).'*tmp1);
v(:,:,k) = real(ifft(fft(v(:,:,k),[],2).*t,[],2));
end
% YZ-shear
tmp1 = -sqrt(-1)*2*pi*([0:((g(1)-1)/2) 0 (-g(1)/2+1):-1])/g(1);
for k=1:g(3)
t = exp( tmp1.'*(k*S1(1,3) + S1(1,2)*(1:g(2)) + S1(1,4)));
v(:,:,k) = real(ifft(fft(v(:,:,k),[],1).*t,[],1));
end
% XY-shear
tmp1 = -sqrt(-1)*2*pi*([0:((g(3)-1)/2) 0 (-g(3)/2+1):-1])/g(3);
for j=1:g(2)
t = reshape( exp( (j*S0(3,2) + S0(3,1)*(1:g(1)) + S0(3,4)).'*tmp1) ,[g(1) 1 g(3)]);
v(:,j,:) = real(ifft(fft(v(:,j,:),[],3).*t,[],3));
end
if any(g~=d), v = v(1:d(1),1:d(2),1:d(3)); end
%==========================================================================
function [S0,S1,S2,S3] = shear_decomp(A)
% Decompose rotation and translation matrix A into shears S0, S1, S2 and
% S3, such that A = S0*S1*S2*S3. The original procedure is documented in:
% R. W. Cox and A. Jesmanowicz (1999)
% Real-Time 3D Image Registration for Functional MRI
% Magnetic Resonance in Medicine 42(6):1014-1018
A0 = A(1:3,1:3);
if any(abs(svd(A0)-1)>1e-7), error('Can''t decompose matrix'); end
t = A0(2,3); if t==0, t=eps; end
a0 = pinv(A0([1 2],[2 3])')*[(A0(3,2)-(A0(2,2)-1)/t) (A0(3,3)-1)]';
S0 = [1 0 0; 0 1 0; a0(1) a0(2) 1];
A1 = S0\A0; a1 = pinv(A1([2 3],[2 3])')*A1(1,[2 3])'; S1 = [1 a1(1) a1(2); 0 1 0; 0 0 1];
A2 = S1\A1; a2 = pinv(A2([1 3],[1 3])')*A2(2,[1 3])'; S2 = [1 0 0; a2(1) 1 a2(2); 0 0 1];
A3 = S2\A2; a3 = pinv(A3([1 2],[1 2])')*A3(3,[1 2])'; S3 = [1 0 0; 0 1 0; a3(1) a3(2) 1];
s3 = A(3,4)-a0(1)*A(1,4)-a0(2)*A(2,4);
s1 = A(1,4)-a1(1)*A(2,4);
s2 = A(2,4);
S0 = [[S0 [0 0 s3]'];[0 0 0 1]];
S1 = [[S1 [s1 0 0]'];[0 0 0 1]];
S2 = [[S2 [0 s2 0]'];[0 0 0 1]];
S3 = [[S3 [0 0 0]'];[0 0 0 1]];
%==========================================================================
function [Mask,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrp)
tiny = 5e-2; % From spm_vol_utils.c
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));
Mask = true(size(y1));
if ~wrp(1), Mask = Mask & (y1 >= (1-tiny) & y1 <= (dim(1)+tiny)); end
if ~wrp(2), Mask = Mask & (y2 >= (1-tiny) & y2 <= (dim(2)+tiny)); end
if ~wrp(3), Mask = Mask & (y3 >= (1-tiny) & y3 <= (dim(3)+tiny)); end
%==========================================================================
function vo = nan2zero(vi)
vo = vi;
vo(~isfinite(vo)) = 0;
|
github
|
philippboehmsturm/antx-master
|
spm_render.m
|
.m
|
antx-master/xspm8/spm_render.m
| 13,308 |
utf_8
|
8570c1025420d1ad7f3d512eeee07ddc
|
function spm_render(dat,brt,rendfile)
% Render blobs on surface of a 'standard' brain
% FORMAT spm_render(dat,brt,rendfile)
%
% dat - a struct array of length 1 to 3
% each element is a structure containing:
% - XYZ - the x, y & z coordinates of the transformed SPM{.}
% values in units of voxels.
% - t - the SPM{.} values.
% - mat - affine matrix mapping from XYZ voxels to MNI.
% - dim - dimensions of volume from which XYZ is drawn.
% brt - brightness control:
% If NaN, then displays using the old style with hot
% metal for the blobs, and grey for the brain.
% Otherwise, it is used as a ``gamma correction'' to
% optionally brighten the blobs up a little.
% rendfile - the file containing the images to render on to (see also
% spm_surf.m) or a surface mesh file.
%
% Without arguments, spm_render acts as its own UI.
%__________________________________________________________________________
%
% spm_render prompts for details of up to three SPM{.}s that are then
% displayed superimposed on the surface of a 'standard' brain.
%
% The first is shown in red, then green then blue.
%
% The blobs which are displayed are the integral of all transformed t
% values, exponentially decayed according to their depth. Voxels that
% are 10mm behind the surface have half the intensity of ones at the
% surface.
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_render.m 4018 2010-07-27 18:22:42Z guillaume $
SVNrev = '$Rev: 4018 $';
global prevrend
if ~isstruct(prevrend)
prevrend = struct('rendfile','', 'brt',[], 'col',[]);
end
%-Parse arguments, get data if not passed as parameters
%==========================================================================
if nargin < 1
spm('FnBanner',mfilename,SVNrev);
spm('FigName','Results: render');
num = spm_input('Number of sets',1,'1 set|2 sets|3 sets',[1 2 3],1);
for i = 1:num
[SPM,xSPM] = spm_getSPM;
dat(i) = struct( 'XYZ', xSPM.XYZ,...
't', xSPM.Z',...
'mat', xSPM.M,...
'dim', xSPM.DIM);
end
showbar = 1;
else
num = length(dat);
showbar = 0;
end
%-Get surface
%--------------------------------------------------------------------------
if nargin < 3 || isempty(prevrend.rendfile)
[rendfile, sts] = spm_select(1,'mesh','Render file'); % .mat or .gii file
if ~sts, return; end
end
prevrend.rendfile = rendfile;
[p,f,e] = fileparts(rendfile);
loadgifti = false;
if strcmpi(e,'.mat')
load(rendfile);
if ~exist('rend','var') && ~exist('Matrixes','var')
loadgifti = true;
end
end
if ~strcmpi(e,'.mat') || loadgifti
try
rend = export(gifti(rendfile),'patch');
catch
error('\nCannot read render file "%s".\n', rendfile);
end
if num == 1
col = hot(256);
else
col = eye(3);
if spm_input('Which colours?','!+1','b',{'RGB','Custom'},[0 1],1)
for k = 1:num
col(k,:) = uisetcolor(col(k,:),sprintf('Colour of blob set %d',k));
end
end
end
surf_rend(dat,rend,col);
return
end
%-Get brightness & colours
%--------------------------------------------------------------------------
if nargin < 2 || isempty(prevrend.brt)
brt = 1;
if num==1
brt = spm_input('Style',1,'new|old',[1 NaN], 1);
end
if isfinite(brt)
brt = spm_input('Brighten blobs',1,'none|slightly|more|lots',[1 0.75 0.5 0.25], 1);
col = eye(3);
% ask for custom colours & get rgb values
%------------------------------------------------------------------
if spm_input('Which colours?','!+1','b',{'RGB','Custom'},[0 1],1)
for k = 1:num
col(k,:) = uisetcolor(col(k,:),sprintf('Colour of blob set %d',k));
end
end
else
col = [];
end
elseif isfinite(brt) && isempty(prevrend.col)
col = eye(3);
elseif isfinite(brt) % don't need to check prevrend.col again
col = prevrend.col;
else
col = [];
end
prevrend.brt = brt;
prevrend.col = col;
%-Perform the rendering
%==========================================================================
spm('Pointer','Watch');
if ~exist('rend','var') % Assume old format...
rend = cell(size(Matrixes,1),1);
for i=1:size(Matrixes,1),
rend{i}=struct('M',eval(Matrixes(i,:)),...
'ren',eval(Rens(i,:)),...
'dep',eval(Depths(i,:)));
rend{i}.ren = rend{i}.ren/max(max(rend{i}.ren));
end
end
if showbar, spm_progress_bar('Init', size(dat,1)*length(rend),...
'Formatting Renderings', 'Number completed'); end
for i=1:length(rend),
rend{i}.max=0;
rend{i}.data = cell(size(dat,1),1);
if issparse(rend{i}.ren),
% Assume that images have been DCT compressed
% - the SPM99 distribution was originally too big.
d = size(rend{i}.ren);
B1 = spm_dctmtx(d(1),d(1));
B2 = spm_dctmtx(d(2),d(2));
rend{i}.ren = B1*rend{i}.ren*B2';
% the depths did not compress so well with
% a straight DCT - therefore it was modified slightly
rend{i}.dep = exp(B1*rend{i}.dep*B2')-1;
end
rend{i}.ren(rend{i}.ren>=1) = 1;
rend{i}.ren(rend{i}.ren<=0) = 0;
if showbar, spm_progress_bar('Set', i); end
end
if showbar, spm_progress_bar('Clear'); end
if showbar, spm_progress_bar('Init', length(dat)*length(rend),...
'Making pictures', 'Number completed'); end
mx = zeros(length(rend),1)+eps;
mn = zeros(length(rend),1);
for j=1:length(dat),
XYZ = dat(j).XYZ;
t = dat(j).t;
dim = dat(j).dim;
mat = dat(j).mat;
for i=1:length(rend),
% transform from Talairach space to space of the rendered image
%------------------------------------------------------------------
M1 = rend{i}.M*mat;
zm = sum(M1(1:2,1:3).^2,2).^(-1/2);
M2 = diag([zm' 1 1]);
M = M2*M1;
cor = [1 1 1 ; dim(1) 1 1 ; 1 dim(2) 1; dim(1) dim(2) 1 ;
1 1 dim(3) ; dim(1) 1 dim(3) ; 1 dim(2) dim(3); dim(1) dim(2) dim(3)]';
tcor= M(1:3,1:3)*cor + M(1:3,4)*ones(1,8);
off = min(tcor(1:2,:)');
M2 = spm_matrix(-off+1)*M2;
M = M2*M1;
xyz = (M(1:3,1:3)*XYZ + M(1:3,4)*ones(1,size(XYZ,2)));
d2 = ceil(max(xyz(1:2,:)'));
% Calculate 'depth' of values
%------------------------------------------------------------------
if ~isempty(d2)
dep = spm_slice_vol(rend{i}.dep,spm_matrix([0 0 1])*inv(M2),d2,1);
z1 = dep(round(xyz(1,:))+round(xyz(2,:)-1)*size(dep,1));
if ~isfinite(brt), msk = find(xyz(3,:) < (z1+20) & xyz(3,:) > (z1-5));
else msk = find(xyz(3,:) < (z1+60) & xyz(3,:) > (z1-5)); end
else
msk = [];
end
if ~isempty(msk),
% Generate an image of the integral of the blob values.
%--------------------------------------------------------------
xyz = xyz(:,msk);
if ~isfinite(brt), t0 = t(msk);
else
dst = xyz(3,:) - z1(msk);
dst = max(dst,0);
t0 = t(msk).*exp((log(0.5)/10)*dst)';
end
X0 = full(sparse(round(xyz(1,:)), round(xyz(2,:)), t0, d2(1), d2(2)));
hld = 1; if ~isfinite(brt), hld = 0; end
X = spm_slice_vol(X0,spm_matrix([0 0 1])*M2,size(rend{i}.dep),hld);
msk = find(X<0);
X(msk) = 0;
else
X = zeros(size(rend{i}.dep));
end
% Brighten the blobs
%------------------------------------------------------------------
if isfinite(brt), X = X.^brt; end
mx(j) = max([mx(j) max(max(X))]);
mn(j) = min([mn(j) min(min(X))]);
rend{i}.data{j} = X;
if showbar, spm_progress_bar('Set', i+(j-1)*length(rend)); end
end
end
mxmx = max(mx);
mnmn = min(mn);
if showbar, spm_progress_bar('Clear'); end
Fgraph = spm_figure('GetWin','Graphics');
spm_results_ui('Clear',Fgraph);
nrow = ceil(length(rend)/2);
if showbar, hght = 0.95; else hght = 0.5; end
% subplot('Position',[0, 0, 1, hght]);
ax=axes('Parent',Fgraph,'units','normalized','Position',[0, 0, 1, hght],'Visible','off');
image(0,'Parent',ax);
set(ax,'YTick',[],'XTick',[]);
if ~isfinite(brt),
% Old style split colourmap display.
%----------------------------------------------------------------------
load Split;
colormap(split);
for i=1:length(rend),
ren = rend{i}.ren;
X = (rend{i}.data{1}-mnmn)/(mxmx-mnmn);
msk = find(X);
ren(msk) = X(msk)+(1+1.51/64);
ax=axes('Parent',Fgraph,'units','normalized',...
'Position',[rem(i-1,2)*0.5, floor((i-1)/2)*hght/nrow, 0.5, hght/nrow],...
'Visible','off');
image(ren*64,'Parent',ax);
set(ax,'DataAspectRatio',[1 1 1], ...
'PlotBoxAspectRatioMode','auto',...
'YTick',[],'XTick',[],'XDir','normal','YDir','normal');
end
else
% Combine the brain surface renderings with the blobs, and display using
% 24 bit colour.
%----------------------------------------------------------------------
for i=1:length(rend),
ren = rend{i}.ren;
X = cell(3,1);
for j=1:length(rend{i}.data),
X{j} = rend{i}.data{j}/(mxmx-mnmn)-mnmn;
end
for j=(length(rend{i}.data)+1):3
X{j}=zeros(size(X{1}));
end
rgb = zeros([size(ren) 3]);
tmp = ren.*max(1-X{1}-X{2}-X{3},0);
for k = 1:3
rgb(:,:,k) = tmp + X{1}*col(1,k) + X{2}*col(2,k) +X{3}*col(3,k);
end
rgb(rgb>1) = 1;
ax=axes('Parent',Fgraph,'units','normalized',...
'Position',[rem(i-1,2)*0.5, floor((i-1)/2)*hght/nrow, 0.5, hght/nrow],...
'nextplot','add', ...
'Visible','off');
image(rgb,'Parent',ax);
set(ax,'DataAspectRatio',[1 1 1], ...
'PlotBoxAspectRatioMode','auto',...
'YTick',[],'XTick',[],...
'XDir','normal','YDir','normal');
end
end
spm('Pointer','Arrow');
%==========================================================================
% function surf_rend(dat,rend,col)
%==========================================================================
function surf_rend(dat,rend,col)
%-Setup figure and axis
%--------------------------------------------------------------------------
Fgraph = spm_figure('GetWin','Graphics');
spm_results_ui('Clear',Fgraph);
ax0 = axes(...
'Tag', 'SPMMeshRenderBackground',...
'Parent', Fgraph,...
'Units', 'normalized',...
'Color', [1 1 1],...
'XTick', [],...
'YTick', [],...
'Position', [-0.05, -0.05, 1.05, 0.555]);
ax = axes(...
'Parent', Fgraph,...
'Units', 'normalized',...
'Position', [0.05, 0.05, 0.9, 0.4],...
'Visible', 'off');
H = spm_mesh_render('Disp',rend,struct('parent',ax));
spm_mesh_render('Overlay',H,dat,col);
try
setAllowAxesRotate(H.rotate3d, setxor(findobj(Fgraph,'Type','axes'),ax), false);
end
%-Register with MIP
%--------------------------------------------------------------------------
try % meaningless when called outside spm_results_ui
hReg = spm_XYZreg('FindReg',spm_figure('GetWin','Interactive'));
xyz = spm_XYZreg('GetCoords',hReg);
hs = mydispcursor('Create',ax,dat.mat,xyz);
spm_XYZreg('Add2Reg',hReg,hs,@mydispcursor);
end
%==========================================================================
function varargout = mydispcursor(varargin)
switch lower(varargin{1})
%======================================================================
case 'create'
%======================================================================
% hMe = mydispcursor('Create',ax,M,xyz)
ax = varargin{2};
M = varargin{3};
xyz = varargin{4};
[X,Y,Z] = sphere;
vx = sqrt(sum(M(1:3,1:3).^2));
X = X*vx(1) + xyz(1);
Y = Y*vx(2) + xyz(2);
Z = Z*vx(3) + xyz(3);
hold(ax,'on');
hs = surf(X,Y,Z,'parent',ax,...
'EdgeColor','none','FaceColor',[1 0 0],'FaceLighting', 'phong');
set(hs,'UserData',xyz);
varargout = {hs};
%=======================================================================
case 'setcoords' % Set co-ordinates
%=======================================================================
% [xyz,d] = mydispcursor('SetCoords',xyz,hMe,hC)
hMe = varargin{3};
pxyz = get(hMe,'UserData');
xyz = varargin{2};
set(hMe,'XData',get(hMe,'XData') - pxyz(1) + xyz(1));
set(hMe,'YData',get(hMe,'YData') - pxyz(2) + xyz(2));
set(hMe,'ZData',get(hMe,'ZData') - pxyz(3) + xyz(3));
set(hMe,'UserData',xyz);
varargout = {xyz,[]};
%=======================================================================
otherwise
%=======================================================================
error('Unknown action string')
end
|
github
|
philippboehmsturm/antx-master
|
spm_uitable.m
|
.m
|
antx-master/xspm8/spm_uitable.m
| 12,089 |
utf_8
|
d558e960781ada6e23daad2fcf5012c3
|
function [varargout] = spm_uitable(varargin)
% WARNING: This feature is not supported in MATLAB
% and the API and functionality may change in a future release.
% UITABLE creates a two dimensional graphic uitable component in a figure window.
% UITABLE creates a 1x1 uitable object using default property values in
% a figure window.
%
% UITABLE(numrows,numcolumns) creates a uitable object with specified
% number of rows and columns.
%
% UITABLE(data,columnNames) creates a uitable object with the specified
% data and columnNames. Data can be a cell array or a vector and
% columnNames should be cell arrays.
%
% UITABLE('PropertyName1',value1,'PropertyName2',value2,...) creates a
% uitable object with specified property values. MATLAB uses default
% property values for any property not explicitly set. The properties
% that user can set are: ColumnNames, Data, GridColor, NumColumns,
% NumRows, Position, ColumnWidth and RowHeight.
%
% UITABLE(figurehandle, ...) creates a uitable object in the figure
% window specified by the figure handle.
%
% HANDLE = UITABLE(...) creates a uitable object and returns its handle.
%
% Properties:
%
% ColumnNames: Cell array of strings for column names.
% Data: Cell array of values to be displayed in the table.
% GridColor: string, RGB vector.
% NumColumns: int specifying number of columns.
% NumRows: int specifying number of rows.
% Parent: Handle to figure or uipanel. If not specified, it is gcf.
% Position: 4 element vector specifying the position.
% ColumnWidth: int specifying the width of columns.
% RowHeight: int specifying the height of columns.
%
% Enabled: Boolean specifying if a column is enabled.
% Editable: Boolean specifying if a column is editable.
% Units: String - pixels/normalized/inches/points/centimeters.
% Visible: Boolean specifying if table is visible.
% DataChangedCallback - Callback function name or handle.
%
%
% Examples:
%
% t = uitable(3, 2);
%
% Creates a 3x2 empty uitable object in a figure window.
%
% f = figure;
% t = uitable(f, rand(5), {'A', 'B', 'C', 'D', 'E'});
%
% Creates a 5x5 uitable object in a figure window with the specified
% data and the column names.
%
% data = rand(3);
% colnames = {'X-Data', 'Y-Data', 'Z-Data'};
% t = uitable(data, colnames,'Position', [20 20 250 100]);
%
% Creates a uitable object with the specified data and column names and
% the specified Position.
%
% See also AWTCREATE, AWTINVOKE, JAVACOMPONENT, UITREE, UITREENODE
% Copyright 2002-2006 The MathWorks, Inc.
% $Revision: 6071 $ $Date: 2006/11/29 21:53:13 $
% Release: R14. This feature will not work in previous versions of MATLAB.
% $Id: spm_uitable.m 6071 2014-06-27 12:52:33Z guillaume $
% Setup and P-V parsing
if isempty(varargin)
if ~isempty(javachk('awt')) || spm_check_version('matlab','7.3') <= 0
varargout{1} = 'off';
else
varargout{1} = 'on';
end
if spm_check_version('matlab','8.4') >= 0
warning('spm_uitable disabled, use uitable.');
varargout{1} = 'off';
end
return
end
if ~isempty(javachk('awt')) || ...
spm_check_version('matlab','7.3') <= 0 || ...
spm_check_version('matlab','8.4') >= 0 % R2014b, use uitable
varargout{1} = [];
varargout{2} = [];
return;
end
if ischar(varargin{1})
switch varargin{1}
case 'set'
data = varargin{2};
columnNames = varargin{3};
[htable,hcontainer] = UiTable(data,columnNames);
varargout{1} = htable;
varargout{2} = hcontainer;
case 'get'
htable = varargin{2};
columnNames = get(htable,'columnNames');
nc = get(htable,'NumColumns');
nr = get(htable,'NumRows');
data = get(htable,'data');
data2 = cell(nr,nc);
for i=1:nc
for j=1:nr
data2{j,i} = data(j,i);
end
end
varargout{1} = data2;
varargout{2} = columnNames;
end
else
[htable,hcontainer] = UiTable(varargin{:});
varargout{1} = htable;
varargout{2} = hcontainer;
end
function [table,container] = UiTable(varargin)
error(nargoutchk(0,2,nargout));
parent = [];
numargs = nargin;
datastatus=false; columnstatus=false;
rownum = 1; colnum = 1; % Default to a 1x1 table.
position = [20 20 200 200];
combo_box_found = false;
check_box_found = false;
import com.mathworks.hg.peer.UitablePeer;
if (numargs > 0 && isscalar(varargin{1}) && ishandle(varargin{1}) && ...
isa(handle(varargin{1}), 'figure'))
parent = varargin{1};
varargin = varargin(2:end);
numargs = numargs - 1;
end
if (numargs > 0 && isscalar(varargin{1}) && ishandle(varargin{1}))
if ~isa(varargin{1}, 'javax.swing.table.DefaultTableModel')
error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{1}]);
end
data_model = varargin{1};
varargin = varargin(2:end);
numargs = numargs - 1;
elseif ((numargs > 1) && isscalar(varargin{1}) && isscalar(varargin{2}))
if(isnumeric(varargin{1}) && isnumeric(varargin{2}))
rownum = varargin{1};
colnum = varargin{2};
varargin = varargin(3:end);
numargs = numargs-2;
else
error('MATLAB:uitable:InputMustBeScalar', 'When using UITABLE numrows and numcols have to be numeric scalars.')
end
elseif ((numargs > 1) && isequal(size(varargin{2},1), 1) && iscell(varargin{2}))
if (size(varargin{1},2) == size(varargin{2},2))
if (isnumeric(varargin{1}))
varargin{1} = num2cell(varargin{1});
end
else
error('MATLAB:uitable:MustMatchInfo', 'Number of column names must match number of columns in data');
end
data = varargin{1}; datastatus = true;
coln = varargin{1+1}; columnstatus = true;
varargin = varargin(3:end);
numargs = numargs-2;
end
for i = 1:2:numargs-1
if (~ischar(varargin{i}))
error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{i}]);
end
switch lower(varargin{i})
case 'data'
if (isnumeric(varargin{i+1}))
varargin{i+1} = num2cell(varargin{i+1});
end
data = varargin{i+1};
datastatus = true;
case 'columnnames'
if(iscell(varargin{i+1}))
coln = varargin{i+1};
columnstatus = true;
else
error('MATLAB:uitable:InvalidCellArray', 'When using UITABLE Column data should be 1xn cell array')
end
case 'numrows'
if (isnumeric(varargin{i+1}))
rownum = varargin{i+1};
else
error('MATLAB:uitable:NumrowsMustBeScalar', 'numrows has to be a scalar')
end
case 'numcolumns'
if (isnumeric(varargin{i+1}))
colnum = varargin{i+1};
else
error('MATLAB:uitable:NumcolumnsMustBeScalar', 'numcolumns has to be a scalar')
end
case 'gridcolor'
if (ischar(varargin{i+1}))
gridcolor = varargin{i+1};
else if (isnumeric(varargin{i+1}) && (numel(varargin{i+1}) == 3))
gridcolor = varargin{i+1};
else
error('MATLAB:uitable:InvalidString', 'gridcolor has to be a valid string')
end
end
case 'rowheight'
if (isnumeric(varargin{i+1}))
rowheight = varargin{i+1};
else
error('MATLAB:uitable:RowheightMustBeScalar', 'rowheight has to be a scalar')
end
case 'parent'
if ishandle(varargin{i+1})
parent = varargin{i+1};
else
error('MATLAB:uitable:InvalidParent', 'parent must be a valid handle')
end
case 'position'
if (isnumeric(varargin{i+1}))
position = varargin{i+1};
else
error('MATLAB:uitable:InvalidPosition', 'position has to be a 1x4 numeric array')
end
case 'columnwidth'
if (isnumeric(varargin{i+1}))
columnwidth = varargin{i+1};
else
error('MATLAB:uitable:ColumnwidthMustBeScalar', 'columnwidth has to be a scalar')
end
otherwise
error('MATLAB:uitable:UnrecognizedParameter', ['Unrecognized parameter: ', varargin{i}]);
end
end
% ---combo/check box detection--- %
if (datastatus)
if (iscell(data))
rownum = size(data,1);
colnum = size(data,2);
combo_count =0;
check_count = 0;
combo_box_data = num2cell(zeros(1, colnum));
combo_box_column = zeros(1, colnum);
check_box_column = zeros(1, colnum);
for j = 1:rownum
for k = 1:colnum
if (iscell(data{j,k}))
combo_box_found = true;
combo_count = combo_count + 1;
combo_box_data{combo_count} = data{j,k};
combo_box_column(combo_count ) = k;
dc = data{j,k};
data{j,k} = dc{1};
else
if(islogical(data{j,k}))
check_box_found = true;
check_count = check_count + 1;
check_box_column(check_count) = k;
end
end
end
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check the validity of the parent and/or create a figure.
if isempty(parent)
parent = gcf; % Get the current figure. Create one if not available
end
if ( columnstatus && datastatus )
if(size(data,2) ~= size(coln,2))
error('MATLAB:NeedSameNumberColumns', 'Number of columns in both Data and ColumnNames should match');
end
elseif ( ~columnstatus && datastatus )
for i=1:size(data,2)
coln{i} = num2str(i);
end
columnstatus = true;
elseif ( columnstatus && ~datastatus)
error('MATLAB:uitable:NoDataProvided', 'No Data provided along with ColumnNames');
end
if (~exist('data_model', 'var'))
data_model = javax.swing.table.DefaultTableModel;
end
if exist('rownum', 'var')
data_model.setRowCount(rownum);
end
if exist('colnum', 'var')
data_model.setColumnCount(colnum);
end
table_h= UitablePeer(data_model);
% We should have valid data and column names here.
if (datastatus), table_h.setData(data); end;
if (columnstatus), table_h.setColumnNames(coln); end;
if (combo_box_found),
for i=1:combo_count
table_h.setComboBoxEditor(combo_box_data(i), combo_box_column(i));
end
end
if (check_box_found),
for i = 1: check_count
table_h.setCheckBoxEditor(check_box_column(i));
end
end
% pass the specified parent and let javacomponent decide its validity.
[obj, container] = javacomponent(table_h, position, parent);
% javacomponent returns a UDD handle for the java component passed in.
table = obj;
% Have to do a drawnow here to make the properties stick. Try to restrict
% the drawnow call to only when it is absolutely required.
flushed = false;
if exist('gridcolor', 'var')
pause(.1); drawnow;
flushed = true;
table_h.setGridColor(gridcolor);
end
if exist('rowheight', 'var')
if (~flushed)
drawnow;
end
table_h.setRowHeight(rowheight);
end
if exist('columnwidth', 'var')
table_h.setColumnWidth(columnwidth);
end;
% % Add a predestroy listener so we can call cleanup on the table.
% addlistener(table, 'ObjectBeingDestroyed', {@componentDelete});
varargout{1} = table;
varargout{2} = container;
function componentDelete(src, evd) %#ok
% Clean up the table here so it disengages all its internal listeners.
src.cleanup;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_convert.m
|
.m
|
antx-master/xspm8/spm_eeg_convert.m
| 16,945 |
utf_8
|
a71c71902f215e5d6bfa54b043e525d8
|
function D = spm_eeg_convert(S)
% Main function for converting different M/EEG formats to SPM8 format.
% FORMAT D = spm_eeg_convert(S)
% S - can be string (file name) or struct (see below)
%
% If S is a struct it can have the optional following fields:
% S.dataset - file name
% S.continuous - 1 - convert data as continuous
% 0 - convert data as epoched (requires data that is
% already epoched or a trial definition file).
% S.timewindow - [start end] in sec. Boundaries for a sub-segment of
% continuous data [default: all]
% S.outfile - output file name (default 'spm8_' + input)
% S.channels - 'all' - convert all channels
% or cell array of labels
% S.usetrials - 1 - take the trials as defined in the data [default]
% 0 - use trial definition file even though the data is
% already epoched
% S.trlfile - name of the trial definition file
% S.datatype - data type for the data file one of
% 'float32-le' [default], 'float64-le'
% S.inputformat - data type (optional) to force the use of specific data
% reader
% S.eventpadding - the additional time period around each trial for which
% the events are saved with the trial (to let the user
% keep and use for analysis events which are outside
% trial borders), in seconds. [default: 0]
% S.conditionlabel - labels for the trials in the data [default: 'Undefined']
% S.blocksize - size of blocks used internally to split large files
% [default: ~100Mb]
% S.checkboundary - 1 - check if there are breaks in the file and do not
% read across those breaks [default]
% 0 - ignore breaks (not recommended).
% S.saveorigheader - 1 - save original data header with the dataset
% 0 - do not keep the original header [default]
%
% % D - MEEG object (also written on disk)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_eeg_convert.m 4430 2011-08-12 18:47:17Z vladimir $
if ischar(S)
temp = S;
S = [];
S.dataset = temp;
end
if ~isfield(S, 'dataset')
error('Dataset must be specified.');
end
if ~isfield(S, 'outfile'), S.outfile = ['spm8_' spm_str_manip(S.dataset,'tr')]; end
if ~isfield(S, 'channels'), S.channels = 'all'; end
if ~isfield(S, 'timewindow'), S.timewindow = []; end
if ~isfield(S, 'blocksize'), S.blocksize = 3276800; end %100 Mb
if ~isfield(S, 'checkboundary'), S.checkboundary = 1; end
if ~isfield(S, 'usetrials'), S.usetrials = 1; end
if ~isfield(S, 'datatype'), S.datatype = 'float32-le'; end
if ~isfield(S, 'eventpadding'), S.eventpadding = 0; end
if ~isfield(S, 'saveorigheader'), S.saveorigheader = 0; end
if ~isfield(S, 'conditionlabel'), S.conditionlabel = 'Undefined' ; end
if ~isfield(S, 'inputformat'), S.inputformat = [] ; end
if ~iscell(S.conditionlabel)
S.conditionlabel = {S.conditionlabel};
end
%--------- Read and check header
hdr = ft_read_header(S.dataset, 'fallback', 'biosig', 'headerformat', S.inputformat);
if isfield(hdr, 'label')
[unique_label junk ind]=unique(hdr.label);
if length(unique_label)~=length(hdr.label)
warning(['Data file contains several channels with ',...
'the same name. These channels cannot be processed and will be disregarded']);
% This finds the repeating labels and removes all their occurences
sortind=sort(ind);
[junk ind2]=setdiff(hdr.label, unique_label(sortind(find(diff(sortind)==0))));
hdr.label=hdr.label(ind2);
hdr.nChans=length(hdr.label);
end
end
if ~isfield(S, 'continuous')
S.continuous = (hdr.nTrials == 1);
end
%--------- Read and prepare events
try
event = ft_read_event(S.dataset, 'detectflank', 'both', 'eventformat', S.inputformat);
if ~isempty(strmatch('UPPT001', hdr.label))
% This is s somewhat ugly fix to the specific problem with event
% coding in FIL CTF. It can also be useful for other CTF systems where the
% pulses in the event channel go downwards.
fil_ctf_events = ft_read_event(S.dataset, 'detectflank', 'down', 'type', 'UPPT001', 'trigshift', -1, 'eventformat', S.inputformat);
if ~isempty(fil_ctf_events)
[fil_ctf_events(:).type] = deal('FIL_UPPT001_down');
event = cat(1, event(:), fil_ctf_events(:));
end
end
if ~isempty(strmatch('UPPT002', hdr.label))
% This is s somewhat ugly fix to the specific problem with event
% coding in FIL CTF. It can also be useful for other CTF systems where the
% pulses in the event channel go downwards.
fil_ctf_events = ft_read_event(S.dataset, 'detectflank', 'down', 'type', 'UPPT002', 'trigshift', -1, 'eventformat', S.inputformat);
if ~isempty(fil_ctf_events)
[fil_ctf_events(:).type] = deal('FIL_UPPT002_down');
event = cat(1, event(:), fil_ctf_events(:));
end
end
% This is another FIL-specific fix that will hopefully not affect other sites
if isfield(hdr, 'orig') && isfield(hdr.orig, 'VERSION') && isequal(uint8(hdr.orig.VERSION),uint8([255 'BIOSEMI']))
ind = strcmp('STATUS', {event(:).type});
val = [event(ind).value];
if any(val>255)
bytes = dec2bin(val);
bytes = bytes(:, end-7:end);
bytes = flipdim(bytes, 2);
val = num2cell(bin2dec(bytes));
[event(ind).value] = deal(val{:});
end
end
catch
warning(['Could not read events from file ' S.dataset]);
event = [];
end
% Replace samples with time
if numel(event)>0
for i = 1:numel(event)
event(i).time = event(i).sample./hdr.Fs;
end
end
%--------- Start making the header
D = [];
D.Fsample = hdr.Fs;
%--------- Select channels
if ~strcmp(S.channels, 'all')
[junk, chansel] = spm_match_str(S.channels, hdr.label);
else
if isfield(hdr, 'nChans')
chansel = 1:hdr.nChans;
else
chansel = 1:length(hdr.label);
end
end
nchan = length(chansel);
D.channels = repmat(struct('bad', 0), 1, nchan);
if isfield(hdr, 'label')
[D.channels(:).label] = deal(hdr.label{chansel});
end
%--------- Preparations specific to reading mode (continuous/epoched)
if S.continuous
if isempty(S.timewindow)
if hdr.nTrials == 1
segmentbounds = [1 hdr.nSamples];
elseif ~S.checkboundary
segmentbounds = [1 hdr.nSamples*hdr.nTrials];
else
error('The data cannot be read without ignoring trial borders');
end
S.timewindow = segmentbounds./D.Fsample;
else
segmentbounds = round(S.timewindow.*D.Fsample);
segmentbounds(1) = max(segmentbounds(1), 1);
end
%--------- Sort events and put in the trial
if ~isempty(event)
event = rmfield(event, {'offset', 'sample'});
event = select_events(event, ...
[S.timewindow(1)-S.eventpadding S.timewindow(2)+S.eventpadding]);
end
D.trials.label = S.conditionlabel{1};
D.trials.events = event;
D.trials.onset = S.timewindow(1);
%--------- Break too long segments into blocks
nblocksamples = floor(S.blocksize/nchan);
nsampl = diff(segmentbounds)+1;
trl = [segmentbounds(1):nblocksamples:segmentbounds(2)];
if (trl(end)==segmentbounds(2))
trl = trl(1:(end-1));
end
trl = [trl(:) [trl(2:end)-1 segmentbounds(2)]'];
ntrial = size(trl, 1);
readbytrials = 0;
D.timeOnset = (trl(1,1)-1)./hdr.Fs;
D.Nsamples = nsampl;
else % Read by trials
if ~S.usetrials
if ~isfield(S, 'trl')
trl = getfield(load(S.trlfile, 'trl'), 'trl');
else
trl = S.trl;
end
trl = double(trl);
if size(trl, 2) >= 3
D.timeOnset = unique(trl(:, 3))./D.Fsample;
trl = trl(:, 1:2);
else
D.timeOnset = 0;
end
if length(D.timeOnset) > 1
error('All trials should have identical baseline');
end
try
conditionlabels = getfield(load(S.trlfile, 'conditionlabels'), 'conditionlabels');
catch
conditionlabels = S.conditionlabel;
end
if ~iscell(conditionlabels)
conditionlabels = {conditionlabels};
end
if numel(conditionlabels) == 1
conditionlabels = repmat(conditionlabels, 1, size(trl, 1));
end
readbytrials = 0;
else
try
trialind = sort([strmatch('trial', {event.type}, 'exact'), ...
strmatch('average', {event.type}, 'exact')]);
trl = [event(trialind).sample];
trl = double(trl(:));
trl = [trl trl+double([event(trialind).duration]')-1];
try
offset = unique([event(trialind).offset]);
catch
offset = [];
end
if length(offset) == 1
D.timeOnset = offset/D.Fsample;
else
D.timeOnset = 0;
end
conditionlabels = {};
for i = 1:length(trialind)
if isempty(event(trialind(i)).value)
conditionlabels{i} = S.conditionlabel{1};
else
if all(ischar(event(trialind(i)).value))
conditionlabels{i} = event(trialind(i)).value;
else
conditionlabels{i} = num2str(event(trialind(i)).value);
end
end
end
if hdr.nTrials>1 && size(trl, 1)~=hdr.nTrials
warning('Mismatch between trial definition in events and in data. Ignoring events');
readbytrials = 1;
else
readbytrials = 0;
end
event = event(setdiff(1:numel(event), trialind));
catch
if hdr.nTrials == 1
error('Could not define trials based on data. Use continuous option or trial definition file.');
else
readbytrials = 1;
end
end
end
if readbytrials
nsampl = hdr.nSamples;
ntrial = hdr.nTrials;
trl = zeros(ntrial, 2);
if exist('conditionlabels', 'var') ~= 1 || length(conditionlabels) ~= ntrial
conditionlabels = repmat(S.conditionlabel, 1, ntrial);
end
else
nsampl = unique(diff(trl, [], 2))+1;
if length(nsampl) > 1
error('All trials should have identical lengths');
end
inbounds = (trl(:,1)>=1 & trl(:, 2)<=hdr.nSamples*hdr.nTrials)';
rejected = find(~inbounds);
if ~isempty(rejected)
trl = trl(inbounds, :);
conditionlabels = conditionlabels(inbounds);
warning([S.dataset ': Trials ' num2str(rejected) ' not read - out of bounds']);
end
ntrial = size(trl, 1);
if ntrial == 0
warning([S.dataset ': No trials to read. Bailing out.']);
D = [];
return;
end
end
D.Nsamples = nsampl;
if isfield(event, 'sample')
event = rmfield(event, 'sample');
end
end
%--------- Prepare for reading the data
[outpath, outfile] = fileparts(S.outfile);
if isempty(outpath)
outpath = pwd;
end
if isempty(outfile)
outfile = 'spm8';
end
D.path = outpath;
D.fname = [outfile '.mat'];
D.data.fnamedat = [outfile '.dat'];
D.data.datatype = S.datatype;
if S.continuous
datafile = file_array(fullfile(D.path, D.data.fnamedat), [nchan nsampl], S.datatype);
else
datafile = file_array(fullfile(D.path, D.data.fnamedat), [nchan nsampl ntrial], S.datatype);
end
% physically initialise file
datafile(end,end) = 0;
spm_progress_bar('Init', ntrial, 'reading and converting'); drawnow;
if ntrial > 100, Ibar = floor(linspace(1, ntrial,100));
else Ibar = [1:ntrial]; end
%--------- Read the data
offset = 1;
for i = 1:ntrial
if readbytrials
dat = ft_read_data(S.dataset,'header', hdr, 'begtrial', i, 'endtrial', i,...
'chanindx', chansel, 'checkboundary', S.checkboundary, 'fallback', 'biosig', 'dataformat', S.inputformat);
else
dat = ft_read_data(S.dataset,'header', hdr, 'begsample', trl(i, 1), 'endsample', trl(i, 2),...
'chanindx', chansel, 'checkboundary', S.checkboundary, 'fallback', 'biosig', 'dataformat', S.inputformat);
end
% Sometimes ft_read_data returns sparse output
dat = full(dat);
if S.continuous
nblocksamples = size(dat,2);
datafile(:, offset:(offset+nblocksamples-1)) = dat;
offset = offset+nblocksamples;
else
datafile(:, :, i) = dat;
D.trials(i).label = conditionlabels{i};
D.trials(i).onset = trl(i, 1)./D.Fsample;
D.trials(i).events = select_events(event, ...
[ trl(i, 1)./D.Fsample-S.eventpadding trl(i, 2)./D.Fsample+S.eventpadding]);
end
if ismember(i, Ibar)
spm_progress_bar('Set', i);
end
end
spm_progress_bar('Clear');
% Specify sensor positions and fiducials
if isfield(hdr, 'grad')
D.sensors.meg = ft_convert_units(hdr.grad, 'mm');
end
if isfield(hdr, 'elec')
D.sensors.eeg = ft_convert_units(hdr.elec, 'mm');
else
try
D.sensors.eeg = ft_convert_units(ft_read_sens(S.dataset, 'fileformat', S.inputformat), 'mm');
% It might be that read_sens will return the grad for MEG datasets
if isfield(D.sensors.eeg, 'ori')
D.sensors.eeg = [];
end
catch
warning('Could not obtain electrode locations automatically.');
end
end
try
D.fiducials = ft_convert_units(ft_read_headshape(S.dataset, 'fileformat', S.inputformat), 'mm');
catch
warning('Could not obtain fiducials automatically.');
end
%--------- Create meeg object
D = meeg(D);
% history
D = D.history('spm_eeg_convert', S);
if isfield(hdr, 'orig')
if S.saveorigheader
D.origheader = hdr.orig;
end
% Uses fileio function to get the information about channel types stored in
% the original header. This is now mainly useful for Neuromag support but might
% have other functions in the future.
origchantypes = ft_chantype(hdr);
[sel1, sel2] = spm_match_str(D.chanlabels, hdr.label);
origchantypes = origchantypes(sel2);
if length(strmatch('unknown', origchantypes, 'exact')) ~= numel(origchantypes)
D.origchantypes = struct([]);
D.origchantypes(1).label = hdr.label(sel2);
D.origchantypes(1).type = origchantypes;
end
end
S1 = [];
S1.task = 'defaulttype';
S1.D = D;
S1.updatehistory = 0;
D = spm_eeg_prep(S1);
% Assign default EEG sensor positions if possible
if ~isempty(strmatch('EEG', D.chantype, 'exact'))
if isempty(D.sensors('EEG'))
S1 = [];
S1.task = 'defaulteegsens';
S1.updatehistory = 0;
S1.D = D;
D = spm_eeg_prep(S1);
else
S1 = [];
S1.task = 'project3D';
S1.modality = 'EEG';
S1.updatehistory = 0;
S1.D = D;
D = spm_eeg_prep(S1);
end
end
% Create 2D positions for MEG
% by projecting the 3D positions to 2D
if ~isempty(strmatch('MEG', D.chantype)) && ~isempty(D.sensors('MEG'))
S1 = [];
S1.task = 'project3D';
S1.modality = 'MEG';
S1.updatehistory = 0;
S1.D = D;
D = spm_eeg_prep(S1);
end
% If channel units are available, store them.
if isfield(hdr, 'unit')
[sel1, sel2] = spm_match_str(D.chanlabels, hdr.label);
D = units(D, sel1, hdr.unit(sel2));
end
% The conditions will later be sorted in the original order they were defined.
if isfield(S, 'trialdef')
D = condlist(D, {S.trialdef(:).conditionlabel});
end
save(D);
%==========================================================================
% select_events
%==========================================================================
function event = select_events(event, timeseg)
% Utility function to select events according to time segment
% FORMAT event = select_events(event, timeseg)
if ~isempty(event)
[time ind] = sort([event(:).time]);
selectind = ind(time>=timeseg(1) & time<=timeseg(2));
event = event(selectind);
end
|
github
|
philippboehmsturm/antx-master
|
spm_maff.m
|
.m
|
antx-master/xspm8/spm_maff.m
| 8,022 |
utf_8
|
33d6a7e3d4b7305bf9bd04c4ffb4eef5
|
function M = spm_maff(varargin)
% Affine registration to MNI space using mutual information
% FORMAT M = spm_maff(P,samp,x,b0,MF,M,regtyp,ff)
% P - filename or structure handle of image
% x - cell array of {x1,x2,x3}, where x1 and x2 are
% co-ordinates (from ndgrid), and x3 is a list of
% slice numbers to use
% b0 - a cell array of belonging probability images
% (see spm_load_priors.m).
% MF - voxel-to-world transform of belonging probability
% images
% M - starting estimates
% regtype - regularisation type
% 'mni' - registration of European brains with MNI space
% 'eastern' - registration of East Asian brains with MNI space
% 'rigid' - rigid(ish)-body registration
% 'subj' - inter-subject registration
% 'none' - no regularisation
% ff - a fudge factor (derived from the one above)
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_maff.m 4178 2011-01-27 15:12:53Z guillaume $
[buf,MG] = loadbuf(varargin{1:2});
M = affreg(buf, MG, varargin{2:end});
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [buf,MG] = loadbuf(V,x)
if ischar(V), V = spm_vol(V); end;
x1 = x{1};
x2 = x{2};
x3 = x{3};
% Load the image
V = spm_vol(V);
d = V(1).dim(1:3);
o = ones(size(x1));
d = [size(x1) length(x3)];
g = zeros(d);
spm_progress_bar('Init',V.dim(3),'Loading volume','Planes loaded');
for i=1:d(3)
g(:,:,i) = spm_sample_vol(V,x1,x2,o*x3(i),0);
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
% Convert the image to unsigned bytes
[mn,mx] = spm_minmax(g);
sw = warning('off','all');
for z=1:length(x3),
gz = g(:,:,z);
buf(z).msk = gz>mn & isfinite(gz);
buf(z).nm = sum(buf(z).msk(:));
gz = double(gz(buf(z).msk));
buf(z).g = uint8(round(gz*(255/mx)));
end;
warning(sw);
MG = V.mat;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [M,h0] = affreg(buf,MG,x,b0,MF,M,regtyp,ff)
% Do the work
x1 = x{1};
x2 = x{2};
x3 = x{3};
[mu,isig] = spm_affine_priors(regtyp);
mu = [zeros(6,1) ; mu];
isig = [zeros(6,12) ; zeros(6,6) isig];
isig = isig*ff;
Alpha0 = isig;
Beta0 = -isig*mu;
sol = M2P(M);
sol1 = sol;
ll = -Inf;
nsmp = sum(cat(1,buf.nm));
pr = struct('b',[],'db1',[],'db2',[],'db3',[]);
spm_plot_convergence('Init','Registering','Log-likelihood','Iteration');
for iter=1:200
penalty = (sol1-mu)'*isig*(sol1-mu);
T = MF\P2M(sol1)*MG;
R = derivs(MF,sol1,MG);
y1a = T(1,1)*x1 + T(1,2)*x2 + T(1,4);
y2a = T(2,1)*x1 + T(2,2)*x2 + T(2,4);
y3a = T(3,1)*x1 + T(3,2)*x2 + T(3,4);
h0 = zeros(256,length(b0)-1)+eps;
for i=1:length(x3),
if ~buf(i).nm, continue; end;
y1 = y1a(buf(i).msk) + T(1,3)*x3(i);
y2 = y2a(buf(i).msk) + T(2,3)*x3(i);
y3 = y3a(buf(i).msk) + T(3,3)*x3(i);
for k=1:size(h0,2),
pr(k).b = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0));
h0(:,k) = h0(:,k) + spm_hist(buf(i).g,pr(k).b);
end;
end;
h1 = (h0+eps);
ssh = sum(h1(:));
krn = spm_smoothkern(2,(-256:256)',0);
h1 = conv2(h1,krn,'same');
h1 = h1/ssh;
h2 = log2(h1./(sum(h1,2)*sum(h1,1)));
ll1 = sum(sum(h0.*h2))/ssh - penalty/ssh;
spm_plot_convergence('Set',ll1);
if ll1-ll<1e-5, break; end;
ll = ll1;
sol = sol1;
Alpha = zeros(12);
Beta = zeros(12,1);
for i=1:length(x3),
nz = buf(i).nm;
if ~nz, continue; end;
msk = buf(i).msk;
gi = double(buf(i).g)+1;
y1 = y1a(msk) + T(1,3)*x3(i);
y2 = y2a(msk) + T(2,3)*x3(i);
y3 = y3a(msk) + T(3,3)*x3(i);
dmi1 = zeros(nz,1);
dmi2 = zeros(nz,1);
dmi3 = zeros(nz,1);
for k=1:size(h0,2),
[pr(k).b, pr(k).db1, pr(k).db2, pr(k).db3] = spm_sample_priors(b0{k},y1,y2,y3,k==length(b0));
tmp = -h2(gi,k);
dmi1 = dmi1 + tmp.*pr(k).db1;
dmi2 = dmi2 + tmp.*pr(k).db2;
dmi3 = dmi3 + tmp.*pr(k).db3;
end;
x1m = x1(msk);
x2m = x2(msk);
x3m = x3(i);
A = [dmi1.*x1m dmi2.*x1m dmi3.*x1m...
dmi1.*x2m dmi2.*x2m dmi3.*x2m...
dmi1 *x3m dmi2 *x3m dmi3 *x3m...
dmi1 dmi2 dmi3];
Alpha = Alpha + A'*A;
Beta = Beta + sum(A,1)';
end;
drawnow;
Alpha = R'*Alpha*R;
Beta = R'*Beta;
% Gauss-Newton update
sol1 = (Alpha+Alpha0)\(Alpha*sol - Beta - Beta0);
end;
spm_plot_convergence('Clear');
M = P2M(sol);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function P = M2P(M)
% Polar decomposition parameterisation of affine transform,
% based on matrix logs
J = M(1:3,1:3);
V = sqrtm(J*J');
R = V\J;
lV = logm(V);
lR = -logm(R);
if sum(sum(imag(lR).^2))>1e-6
error('Rotations by pi are still a problem.');
else
lR = real(lR);
end
P = zeros(12,1);
P(1:3) = M(1:3,4);
P(4:6) = lR([2 3 6]);
P(7:12) = lV([1 2 3 5 6 9]);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function M = P2M(P)
% Polar decomposition parameterisation of affine transform,
% based on matrix logs
% Translations
D = P(1:3);
D = D(:);
% Rotation part
ind = [2 3 6];
T = zeros(3);
T(ind) = -P(4:6);
R = expm(T-T');
% Symmetric part (zooms and shears)
ind = [1 2 3 5 6 9];
T = zeros(3);
T(ind) = P(7:12);
V = expm(T+T'-diag(diag(T)));
M = [V*R D ; 0 0 0 1];
return;
%_______________________________________________________________________
%_______________________________________________________________________
function R = derivs(MF,P,MG)
% Numerically compute derivatives of Affine transformation matrix w.r.t.
% changes in the parameters.
R = zeros(12,12);
M0 = MF\P2M(P)*MG;
M0 = M0(1:3,:);
for i=1:12
dp = 0.000000001;
P1 = P;
P1(i) = P1(i) + dp;
M1 = MF\P2M(P1)*MG;
M1 = M1(1:3,:);
R(:,i) = (M1(:)-M0(:))/dp;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [h0,d1] = reg_unused(M)
% Try to analytically compute the first and second derivatives of a
% penalty function w.r.t. changes in parameters. It works for first
% derivatives, but I couldn't make it work for the second derivs - so
% I gave up and tried a new strategy.
T = M(1:3,1:3);
[U,S,V] = svd(T);
s = diag(S);
h0 = sum(log(s).^2);
d1s = 2*log(s)./s;
%d2s = 2./s.^2-2*log(s)./s.^2;
d1 = zeros(12,1);
for j=1:3
for i1=1:9
T1 = zeros(3,3);
T1(i1) = 1;
t1 = U(:,j)'*T1*V(:,j);
d1(i1) = d1(i1) + d1s(j)*t1;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function M = P2M_unused(P)
% SVD parameterisation of affine transform, based on matrix-logs.
% Translations
D = P(1:3);
D = D(:);
% Rotation U
ind = [2 3 6];
T = zeros(3);
T(ind) = P(4:6);
U = expm(T-T');
% Diagonal zooming matrix
S = expm(diag(P(7:9)));
% Rotation V'
T(ind) = P(10:12);
V = expm(T'-T);
M = [U*S*V' D ; 0 0 0 1];
return;
%_______________________________________________________________________
%_______________________________________________________________________
|
github
|
philippboehmsturm/antx-master
|
spm_diff.m
|
.m
|
antx-master/xspm8/spm_diff.m
| 4,795 |
utf_8
|
ad03f0b9baf443336e6690d292b28a58
|
function [varargout] = spm_diff(varargin)
% matrix high-order numerical differentiation
% FORMAT [dfdx] = spm_diff(f,x,...,n)
% FORMAT [dfdx] = spm_diff(f,x,...,n,V)
% FORMAT [dfdx] = spm_diff(f,x,...,n,'q')
%
% f - [inline] function f(x{1},...)
% x - input argument[s]
% n - arguments to differentiate w.r.t.
%
% V - cell array of matrices that allow for differentiation w.r.t.
% to a linear transformation of the parameters: i.e., returns
%
% df/dy{i}; x = V{i}y{i}; V = dx(i)/dy(i)
%
% q - flag to preclude default concatenation of dfdx
%
% dfdx - df/dx{i} ; n = i
% dfdx{p}...{q} - df/dx{i}dx{j}(q)...dx{k}(p) ; n = [i j ... k]
%
%
% - a cunning recursive routine
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_diff.m 4060 2010-09-01 17:17:36Z karl $
% create inline object
%--------------------------------------------------------------------------
f = varargin{1};
% parse input arguments
%--------------------------------------------------------------------------
if iscell(varargin{end})
x = varargin(2:(end - 2));
n = varargin{end - 1};
V = varargin{end};
q = 1;
elseif isnumeric(varargin{end})
x = varargin(2:(end - 1));
n = varargin{end};
V = cell(1,length(x));
q = 1;
elseif ischar(varargin{end})
x = varargin(2:(end - 2));
n = varargin{end - 1};
V = cell(1,length(x));
q = 0;
else
error('improper call')
end
% check transform matrices V = dxdy
%--------------------------------------------------------------------------
for i = 1:length(x)
try
V{i};
catch
V{i} = [];
end
if isempty(V{i}) && any(n == i);
V{i} = speye(length(spm_vec(x{i})));
end
end
% initialise
%--------------------------------------------------------------------------
m = n(end);
xm = spm_vec(x{m});
dx = exp(-8);
J = cell(1,size(V{m},2));
% proceed to derivatives
%==========================================================================
if length(n) == 1
% dfdx
%----------------------------------------------------------------------
f0 = feval(f,x{:});
for i = 1:length(J)
xi = x;
xmi = xm + V{m}(:,i)*dx;
xi{m} = spm_unvec(xmi,x{m});
fi = feval(f,xi{:});
J{i} = spm_dfdx(fi,f0,dx);
end
% return numeric array for first-order derivatives
%======================================================================
% vectorise f
%----------------------------------------------------------------------
f = spm_vec(f0);
% if there are no arguments to differentiate w.r.t. ...
%----------------------------------------------------------------------
if isempty(xm)
J = sparse(length(f),0);
% or there are no arguments to differentiate
%----------------------------------------------------------------------
elseif isempty(f)
J = sparse(0,length(xm));
end
% or differentiation of a vector
%----------------------------------------------------------------------
if isvec(f0) && q
% concatenate into a matrix
%------------------------------------------------------------------
if size(f0,2) == 1
J = spm_cat(J);
else
J = spm_cat(J')';
end
end
% assign output argument and return
%----------------------------------------------------------------------
varargout{1} = J;
varargout{2} = f0;
else
% dfdxdxdx....
%----------------------------------------------------------------------
f0 = cell(1,length(n));
[f0{:}] = spm_diff(f,x{:},n(1:end - 1),V);
for i = 1:length(J)
xi = x;
xmi = xm + V{m}(:,i)*dx;
xi{m} = spm_unvec(xmi,x{m});
fi = spm_diff(f,xi{:},n(1:end - 1),V);
J{i} = spm_dfdx(fi,f0{1},dx);
end
varargout = [{J} f0];
end
function dfdx = spm_dfdx(f,f0,dx)
% cell subtraction
%--------------------------------------------------------------------------
if iscell(f)
dfdx = f;
for i = 1:length(f(:))
dfdx{i} = spm_dfdx(f{i},f0{i},dx);
end
elseif isstruct(f)
dfdx = (spm_vec(f) - spm_vec(f0))/dx;
else
dfdx = (f - f0)/dx;
end
function is = isvec(v)
% isvector(v) returns true if v is 1-by-n or n-by-1 where n>=0
%__________________________________________________________________________
% vec if just two dimensions, and one (or both) unity
%--------------------------------------------------------------------------
is = length(size(v)) == 2 && isnumeric(v);
is = is && (size(v,1) == 1 || size(v,2) == 1);
|
github
|
philippboehmsturm/antx-master
|
spm_DisplayTimeSeries.m
|
.m
|
antx-master/xspm8/spm_DisplayTimeSeries.m
| 14,418 |
utf_8
|
16a41e1bf873e9a548085da219e4b413
|
function [ud] = spm_DisplayTimeSeries(y,options)
% This function builds a GUI for 'smart' time series display.
% FORMAT function [ud] = spm_DisplayTimeSeries(y,options)
% IN:
% - y: the txn data, where t is the number of time sample, and p the
% number of 'channels'
% - options: a structure (default is empty), which allows to adapt this
% function to specific needs. Optional fields are:
% .hp: the handle of the parent figure/object. This is used to
% include the time series display in a panel/figure. By default, a
% new figure will be created.
% .Fsample: the sample rate of the data (in Hz)
% .events: a nex1 structure vector containing the time indices of the
% events and their type (if any). Default is empty. Basic structure
% contains fields .time and .type (see bellow).
% .M: a pxn matrix premultiplied to the data when plotted (default is
% 1).
% .bad a px1 binary vector containing the good/bad status of the
% channels. Default is zeros(p,1).
% .transpose: a binary variable that transposes the data (useful for
% file_array display). Using options.transpose = 1 is similar to do
% something similar to plot(y'). Default is 0.
% .minY: the min value of the plotted data (used to define the main
% axes limit). Default is calculated according to the offset.
% .maxY: the max value of the plotted data (used to define the main
% axes limit). Default is calculated according to the offset.
% .minSizeWindow: minimum size of the plotted window (in number of
% time samples). {min([200,0.5*size(y,1)]}
% .maxSizeWindow: maximum size of the plotted window (in number of
% time samples). {min([5000,size(y,1)])}
% .ds: an integer giving the number of displayed time samples when
% dynamically moving the display time window. Default is 1e4. If you
% set it to Inf, no downsampling is applied.
% .callback: a string or function handle which is evaluated after
% each release of the mouse button (when moving the patch or clicking
% on the slider). Default is empty.
% .tag: a string used to tag both axes
% .pos1: a 4x1 vector containing the position of the main display
% axes {[0.13 0.3 0.775 0.655]}
% .pos2: a 4x1 vector containing the position of the global power
% display axes {[0.13 0.05 0.775 0.15]}
% .pos3: a 4x1 vector containing the position of the temporal slider
% {[0.13 0.01 0.775 0.02]}
% .itw: a vector containing the indices of data time samples
% initially displayed in the main axes {1:minSizeWindow}
% .ytick: the 'ytick' property of the main axes
% .yticklabel: the 'yticklabel' property of the main axes
% .offset: a px1 vector containing the vertical offset that has to be
% added to each of the plotted time series
% !! .ytick, .yticklabel and .offset can be used to display labelled
% time series one above each other !!
% OUT:
% - ud: a structure containing all relevant informations about the
% graphical objects created for the GUI. This is useful for maniupalting
% the figure later on (see bellow).
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Jean Daunizeau
% $Id: spm_DisplayTimeSeries.m 6295 2015-01-02 16:09:24Z guillaume $
if ~exist('options','var')
options = [];
end
% Get optional parameters if any) and set up defaults
%==========================================================================
if ~isempty(options) && isfield(options,'hp')
hp = options.hp;
else
hp = figure;
end
if ~isempty(options) && isfield(options,'Fsample')
Fsample = options.Fsample;
else
Fsample = 1;
end
if ~isempty(options) && isfield(options,'timeOnset')
timeOnset = options.timeOnset;
else
timeOnset = 0;
end
if ~isempty(options) && isfield(options,'events')
events = options.events;
else
events = [];
end
if ~isempty(options) && isfield(options,'transpose')
transpose = options.transpose;
else
transpose = 0;
end
if ~isempty(options) && isfield(options,'M')
M = options.M;
nc = size(M,1);
if ~transpose
nt = size(y,1);
else
nt = size(y,2);
end
else
M = 1;
if ~transpose
[nt,nc] = size(y);
else
[nc,nt] = size(y);
end
end
if ~isempty(options) && isfield(options,'bad')
bad = options.bad;
else
bad = zeros(nc,1);
end
if ~isempty(options) && isfield(options,'minSizeWindow')
minSizeWindow = options.minSizeWindow;
else
minSizeWindow = 200;
end
minSizeWindow = min([minSizeWindow,.5*nt]);
if ~isempty(options) && isfield(options,'maxSizeWindow')
maxSizeWindow = options.maxSizeWindow;
else
maxSizeWindow = 5000;
end
maxSizeWindow = min([maxSizeWindow,nt]);
if ~isempty(options) && isfield(options,'ds')
ds = options.ds;
else
ds = 1e4;
end
if ~isempty(options) && isfield(options,'callback')
callback = options.callback;
else
callback = [];
end
if ~isempty(options) && isfield(options,'tag')
tag = options.tag;
else
tag = '';
end
if ~isempty(options) && isfield(options,'pos1')
pos1 = options.pos1;
else
pos1 = [0.13 0.32 0.775 0.655];
end
if ~isempty(options) && isfield(options,'pos2')
pos2 = options.pos2;
else
pos2 = [0.13 0.12 0.775 0.15];
end
if ~isempty(options) && isfield(options,'pos3')
pos3 = options.pos3;
else
pos3 = [0.10 0.02 0.84 0.05];
end
if ~isempty(options) && isfield(options,'itw')
itw = options.itw;
else
itw = 1:minSizeWindow;
end
if ~isempty(options) && isfield(options,'ytick')
ytick = options.ytick;
else
ytick = [];
end
if ~isempty(options) && isfield(options,'yticklabel')
yticklabel = options.yticklabel;
else
yticklabel = [];
end
if ~isempty(options) && isfield(options,'offset')
offset = options.offset(:);
else
offset = zeros(nc,1);
end
if ~isempty(options) && isfield(options,'minY')
minY = options.minY;
else
yo = y + repmat(offset',nt,1);
minY = min(yo(:));
end
if ~isempty(options) && isfield(options,'maxY')
maxY = options.maxY;
else
try
maxY = max(yo(:));
catch
yo = y + repmat(offset',nt,1);
maxY = max(yo(:));
end
end
% Initialize display
%==========================================================================
% Get basic info about data
ud.y = y;
ud.v.bad = bad;
ud.v.transpose = transpose;
ud.v.nc = nc;
ud.v.nt = nt;
ud.v.ds = ds;
ud.v.M = M;
ud.v.mi = minY;
ud.v.ma = maxY;
ud.v.minSizeWindow = minSizeWindow;
ud.v.maxSizeWindow = maxSizeWindow;
ud.v.offset = offset;
ud.v.et = events;
ud.v.handles.hp = hp;
ud.callback = callback;
% Get downsampled global power
decim = max([1,round(nt./1000)]);
ud.v.ind = 1:decim:nt;
if ~ud.v.transpose
My = ud.v.M*y(ud.v.ind,:)';
ud.v.y2 = sum(My.^2,1);
else
My = ud.v.M*y(:,ud.v.ind);
ud.v.y2 = sum(My.^2,1);
end
mi = min(ud.v.y2);
ma = max(ud.v.y2);
if mi == 0 && ma == 0
mi = -eps;
ma = eps;
else
mi = mi - mi.*1e-3;
ma = ma + ma.*1e-3;
end
% Create axes
if spm_check_version('matlab','8.4') >= 0
dispmode = {'SortMethod','childorder'};
else
dispmode = {'drawmode','fast'};
end
ud.v.handles.axes = axes('parent',hp,...
'units','normalized',...
'position',pos1,...
'xtick',[],'xticklabel',[],...
'ytick',ytick,'yticklabel',yticklabel,...
'tag',tag,...
'nextplot','add',...
dispmode{:});
ud.v.handles.gpa = axes('parent',hp,...
'units','normalized',...
'position',pos2,...
'tag',tag,'nextplot','add','ytick',[],...
'box','off',...
'color','none',...
'ygrid','off',...
dispmode{:});
% Initialize time series
col = colormap(lines);
col = col(1:7,:);
ud.v.handles.hp = zeros(nc,1);
if ~ud.v.transpose
My = ud.v.M*y(itw,:)';
else
My = ud.v.M*y(:,itw);
end
for i=1:ud.v.nc
ii = mod(i+7,7)+1;
ud.v.handles.hp(i) = plot(ud.v.handles.axes,...
itw,My(i,:)+offset(i),...
'color',col(ii,:));
if ud.v.bad(i)
set(ud.v.handles.hp(i),'linestyle',':')
end
end
ud.v.handles.gpp = plot(ud.v.handles.gpa,...
ud.v.ind,ud.v.y2,...
'color',0.5*[1 1 1]);
% Add events if any
if ~isempty(ud.v.et)
for i=1:length(ud.v.et)
ud.v.et(i).col = mod(ud.v.et(i).type+7,7)+1;
ud.v.et(i).hp = plot(ud.v.handles.axes,...
ud.v.et(i).time.*[1 1],...
[ud.v.mi,ud.v.ma],...
'color',col(ud.v.et(i).col,:),...
'userdata',i,...
'ButtonDownFcn','set(gco,''selected'',''on'')',...
'Clipping','on');
end
end
% Add display scrolling patch and borders
ud.v.handles.pa = patch('parent',ud.v.handles.gpa,...
'xdata',[itw(1) itw(end) itw(end) itw(1)],...
'ydata',[mi mi ma ma],...
'edgecolor','none',...
'facecolor',[.5 .5 .5],...
'facealpha',0.5,...
'ButtonDownFcn',@doPatch,...
'interruptible','off');
ud.v.handles.lb = plot(ud.v.handles.gpa,...
[itw(1) itw(1)],[mi ma],...
'k',...
'buttondownfcn',@doLb,...
'interruptible','off');
ud.v.handles.rb = plot(ud.v.handles.gpa,...
[itw(end) itw(end)],[mi ma],...
'k',...
'buttondownfcn',@doRb,...
'interruptible','off');
% Adapt axes properties to display
tgrid = (0:(nt-1))./Fsample + timeOnset;
set(ud.v.handles.gpa,...
'ylim',[mi ma],...
'xlim',[1 nt]);
xtick = floor(get(ud.v.handles.gpa,'xtick'));
xtick(xtick==0) = 1;
a = cell(length(xtick),1);
for i=1:length(xtick)
a{i} = num2str(tgrid(xtick(i)),2);
end
set(ud.v.handles.gpa,...
'xtick',xtick,...
'xticklabel',a);
set(ud.v.handles.axes,...
'xlim',[itw(1) itw(end)],...
'ylim',[ud.v.mi ud.v.ma]);
% Add temporal slider
ud.v.handles.hslider = uicontrol('parent',hp,...
'style','slider',...
'units','normalized',...
'Position',pos3,...
'min',max([1,minSizeWindow/2-1]),...
'max',min([ud.v.nt,ud.v.nt-minSizeWindow/2+1]),...
'value',mean([itw(1),itw(end)]),...
'sliderstep',.1*[minSizeWindow/(ud.v.nt-1) 4*minSizeWindow/(ud.v.nt-1)],...
'callback',@doScroll,...
'userdata',ud.v.handles.gpa,...
'BusyAction','cancel',...
'Interruptible','on',...
'tooltipstring','Scroll data',...
'tag',tag);
% Store required info in global power axes
set(ud.v.handles.gpa,'userdata',ud)
axes(ud.v.handles.gpa)
% Subfunctions
%==========================================================================
function doScroll(src,evt)
gpa = get(src,'userdata');
xm = get(src,'value');
ud = get(gpa,'userdata');
sw = diff(get(ud.v.handles.axes,'xlim'));
xl = xm + [-sw./2,+sw./2];
if xl(1) >= 1 && xl(2) <= ud.v.nt
xl = round(xl);
if ~ud.v.transpose
My = ud.v.M*ud.y(xl(1):xl(2),:)';
else
My = ud.v.M*ud.y(:,xl(1):xl(2));
end
doPlot(My,xl,ud.v,1)
end
if ~isempty(ud.callback)
try eval(ud.callback);end
end
function doPatch(src,evt)
hf = gcf;
set(hf,'WindowButtonDownFcn',@doPatch,...
'WindowButtonUpFcn',@UndoPatch,...
'WindowButtonMotionFcn',{@movePatch},...
'Pointer','fleur')
function doLb(src,evt)
hf = gcf;
set(hf,'WindowButtonDownFcn',@doLb,...
'WindowButtonUpFcn',@UndoPatch,...
'WindowButtonMotionFcn',{@moveLb},...
'Pointer','left')
function doRb(src,evt)
hf = gcf;
set(hf,'WindowButtonDownFcn',@doRb,...
'WindowButtonUpFcn',@UndoPatch,...
'WindowButtonMotionFcn',{@moveRb},...
'Pointer','right')
function UndoPatch(src,evt)
ha = gca;
hf = gcf;
set(hf,'WindowButtonMotionFcn',[],...
'WindowButtonDownFcn',[],...
'WindowButtonUpFcn',[],...
'Pointer','arrow')
ud = get(ha,'userdata');
xw = get(ud.v.handles.axes,'xlim');
if ~ud.v.transpose
My = ud.v.M*ud.y(xw(1):xw(2),:)';
else
My = ud.v.M*ud.y(:,xw(1):xw(2));
end
doPlot(My,xw,ud.v,1);
if ~isempty(ud.callback)
try eval(ud.callback);end
end
function movePatch(src,evt)
ha = gca;
cp = get(ha,'CurrentPoint');
ud = get(ha,'userdata');
xm = cp(1);
sw = diff(get(ud.v.handles.axes,'xlim'));
xl = xm + [-sw./2,+sw./2];
if xl(1) >= 1 && xl(2) <= ud.v.nt
xl = round(xl);
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xl(1):decim:xl(2),:)';
else
My = ud.v.M*ud.y(:,xl(1):decim:xl(2));
end
doPlot(My,xl,ud.v,decim)
elseif xl(2) > ud.v.nt
xl = [ud.v.nt-sw,ud.v.nt];
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xl(1):decim:xl(2),:)';
else
My = ud.v.M*ud.y(:,xl(1):decim:xl(2));
end
doPlot(My,xl,ud.v,decim)
elseif xl(1) < 1
xl = [1,sw+1];
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(xl(1):decim:xl(2),:)';
else
My = ud.v.M*ud.y(:,xl(1):decim:xl(2));
end
doPlot(My,xl,ud.v,decim)
end
function moveLb(src,evt)
ha = gca;
cp = get(ha,'CurrentPoint');
cp = max([cp(1),1]);
ud = get(ha,'userdata');
xw = get(ud.v.handles.pa,'xdata');
if cp(1) <= xw(2) - ud.v.minSizeWindow ...
&& diff([cp(1) xw(2)]) <= ud.v.maxSizeWindow
cp = [round(cp(1)) xw(2)];
sw = diff(cp);
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(cp(1):decim:cp(2),:)';
else
My = ud.v.M*ud.y(:,cp(1):decim:cp(2));
end
doPlot(My,cp,ud.v,decim)
end
function moveRb(src,evt)
ha = gca;
cp = get(ha,'CurrentPoint');
ud = get(ha,'userdata');
cp = min([cp(1),ud.v.ind(end)]);
xw = get(ud.v.handles.pa,'xdata');
if xw(1) <= cp(1) - ud.v.minSizeWindow ...
&& diff([xw(1) cp(1)]) <= ud.v.maxSizeWindow
cp = [xw(1) round(cp(1))];
sw = diff(cp);
decim = max([1,round(sw./ud.v.ds)]);
if ~ud.v.transpose
My = ud.v.M*ud.y(cp(1):decim:cp(2),:)';
else
My = ud.v.M*ud.y(:,cp(1):decim:cp(2));
end
doPlot(My,cp,ud.v,decim)
end
function doPlot(y,xw,v,decim)
for i=1:v.nc
set(v.handles.hp(i),...
'xdata',xw(1):decim:xw(2),...
'ydata',y(i,:)+v.offset(i))
end
set(v.handles.axes,...
'ylim',[v.mi v.ma],'xlim',xw);
set(v.handles.pa,...
'xdata',[xw,fliplr(xw)]);
set(v.handles.lb,...
'xdata',[xw(1) xw(1)]);
set(v.handles.rb,...
'xdata',[xw(2) xw(2)]);
sw = diff(xw);
set(v.handles.hslider,...
'value',mean(xw),...
'min',max([1,sw/2-1]),...
'max',max([v.nt,v.nt-sw/2+1]),...
'sliderstep',.1*[sw/(v.nt-1) 4*sw/(v.nt-1)]);
|
github
|
philippboehmsturm/antx-master
|
loadxml.m
|
.m
|
antx-master/xspm8/loadxml.m
| 4,985 |
utf_8
|
9429ec4334b8abc0ff9910e7c9019fdc
|
function varargout = loadxml(filename,varargin)
%LOADXML Load workspace variables from disk (XML file).
% LOADXML FILENAME retrieves all variables from a file given a full
% pathname or a MATLABPATH relative partial pathname (see PARTIALPATH).
% If FILENAME has no extension LOAD looks for FILENAME and FILENAME.xml
% and treats it as an XML file.
%
% LOAD, by itself, uses the XML file named 'matlab.xml'. It is an error
% if 'matlab.xml' is not found.
%
% LOAD FILENAME X loads only X.
% LOAD FILENAME X Y Z ... loads just the specified variables. The
% wildcard '*' loads variables that match a pattern.
% Requested variables from FILENAME are created in the workspace.
%
% S = LOAD(...) returns the contents of FILENAME in variable S. S is
% a struct containing fields matching the variables retrieved.
%
% Use the functional form of LOAD, such as LOAD('filename'), when the
% file name is stored in a string, when an output argument is requested,
% or if FILENAME contains spaces.
%
% See also LOAD, XML2MAT, XMLTREE.
% Copyright 2003 Guillaume Flandin.
% $Revision: 4393 $ $Date: 2003/07/10 13:50 $
% $Id: loadxml.m 4393 2011-07-18 14:52:32Z guillaume $
if nargin == 0
filename = 'matlab.xml';
fprintf('\nLoading from: %s\n\n',filename);
end
if ~ischar(filename)
error('[LOADXML] Argument must contain a string.');
end
if ~exist(filename,'file')
filename = [filename '.xml'];
if ~exist(filename,'file')
error(sprintf(...
'[LOADXML] Unable to read file %s: file does not exist',filename));
end
end
if nargout > 1,
error('[LOADXML] Too many output arguments.');
end
t = xmltree(filename);
uid = children(t,root(t));
if nargout == 1
% varargout{1} = struct([]); % Matlab 6.0 and above
end
flagfirstvar = 1;
for i=1:length(uid)
if strcmp(get(t,uid(i),'type'),'element')
vname = get(t,uid(i),'name');
% TODO % No need to parse the whole tree
if isempty(varargin) | ismember(varargin,vname)
v = xml_create_var(t,uid(i));
if nargout == 1
if flagfirstvar
varargout{1} = struct(vname,v);
flagfirstvar = 0;
else
varargout{1} = setfield(varargout{1},vname,v);
end
else
assignin('caller',vname,v);
end
end
end
end
%=======================================================================
function v = xml_create_var(t,uid)
type = attributes(t,'get',uid,'type');
sz = str2num(attributes(t,'get',uid,'size'));
switch type
case 'double'
v = str2num(get(t,children(t,uid),'value'));
if ~isempty(sz)
v = reshape(v,sz);
end
case 'sparse'
u = children(t,uid);
for k=1:length(u)
if strcmp(get(t,u(k),'name'),'row')
i = str2num(get(t,children(t,u(k)),'value'));
elseif strcmp(get(t,u(k),'name'),'col')
j = str2num(get(t,children(t,u(k)),'value'));
elseif strcmp(get(t,u(k),'name'),'val')
s = str2num(get(t,children(t,u(k)),'value'));
end
end
v = sparse(i,j,s,sz(1),sz(2));
case 'struct'
u = children(t,uid);
v = []; % works with Matlab < 6.0
for i=1:length(u)
s(1).type = '()';
s(1).subs = {str2num(attributes(t,'get',u(i),'index'))};
s(2).type = '.';
s(2).subs = get(t,u(i),'name');
v = subsasgn(v,s,xml_create_var(t,u(i)));
end
if isempty(u),
v = struct([]); % Need Matlab 6.0 and above
end
case 'cell'
v = cell(sz);
u = children(t,uid);
for i=1:length(u)
v{str2num(attributes(t,'get',u(i),'index'))} = ...
xml_create_var(t,u(i));
end
case 'char'
if isempty(children(t,uid))
v = '';
else
v = get(t,children(t,uid),'value');
end
try % this can fail if blank spaces are lost or entity escaping
if ~isempty(sz)
if sz(1) > 1
v = reshape(v,fliplr(sz))'; % row-wise order
else
v = reshape(v,sz);
end
end
end
case {'int8','uint8','int16','uint16','int32','uint32'}
% TODO % Handle integer formats
warning(sprintf('%s matrices not handled.',type));
v = 0;
otherwise
try,
v = feval(class(v),get(t,uid,'value'));
catch,
warning(sprintf(...
'[LOADXML] Cannot convert from XML to %s.',type));
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_robust_average.m
|
.m
|
antx-master/xspm8/spm_robust_average.m
| 3,381 |
utf_8
|
8a8769e0ba80b51f950c5472f6f79613
|
function [Y,W] = spm_robust_average(X, dim, ks)
% Apply robust averaging routine to X sets
% FORMAT [Y,W] = spm_robust_averaget(X, dim, ks)
% X - data matrix to be averaged
% dim - the dimension along which the function will work
% ks - offset of the weighting function (default: 3)
%
% W - estimated weights
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% James Kilner
% $Id: spm_robust_average.m 5204 2013-01-24 11:27:30Z vladimir $
if nargin < 3 || isempty(ks)
ks = 3;
end
if nargin < 2 || isempty(dim)
dim = 1;
end
%-Remember the original data size and size of the mean
%--------------------------------------------------------------------------
origsize = size(X);
morigsize = origsize;
morigsize(dim) = 1;
if length(origsize)<dim || origsize(dim) == 1
warning('There is only one replication in the data. Robust averaging cannot be done.');
Y = X;
W = ones(size(X));
return;
end
%-Convert the data to repetitions x points matrix
%--------------------------------------------------------------------------
if dim > 1
X = shiftdim(X, dim-1);
end
if length(origsize) > 2
X = reshape(X, size(X, 1), []);
end
%-Rescale the data
%--------------------------------------------------------------------------
[X, scalefactor] = spm_cond_units(X);
%-Actual robust averaging
%--------------------------------------------------------------------------
ores=1;
nres=10;
n=0;
W = zeros(size(X));
while max(abs(ores-nres))>sqrt(1E-8)
ores=nres;
n=n+1;
if n==1
Y = nanmedian(X);
else
XX = X;
XX(isnan(XX)) = 0;
Y = sum(W.*XX)./sum(W);
end
if n > 200
warning('Robust averaging could not converge. Maximal number of iterations exceeded.');
break;
end
res = X-repmat(Y, size(X, 1), 1);
mad = nanmedian(abs(res-repmat(nanmedian(res), size(res, 1), 1)));
ind1 = find(mad==0);
ind2 = find(mad~=0);
W(:, ind1) = ~res(:, ind1);
if ~isempty(ind2)
res = res(:, ind2);
mad = mad(ind2);
res = res./repmat(mad, size(res, 1), 1);
res = abs(res)-ks;
res(res<0) = 0;
nres = (sum(res(~isnan(res)).^2));
W(:, ind2) = (abs(res)<1) .* ((1 - res.^2).^2);
W(W == 0) = eps; % This is to prevent appearance of NaNs when normalizing
W(isnan(X)) = 0;
W(X == 0 & ~repmat(all(X==0), size(X, 1), 1)) = 0; %Assuming X is a real measurement
end
end
disp(['Robust averaging finished after ' num2str(n) ' iterations.']);
%-Restore the average and weights to the original data dimensions
%--------------------------------------------------------------------------
Y = Y./scalefactor;
if length(origsize) > 2
Y = reshape(Y, circshift(morigsize, [1 -(dim-1)]));
W = reshape(W, circshift(origsize, [1 -(dim-1)]));
end
if dim > 1
Y = shiftdim(Y, length(origsize)-dim+1);
W = shiftdim(W, length(origsize)-dim+1);
end
%-Helper function
%--------------------------------------------------------------------------
function Y = nanmedian(X)
if ~any(any(isnan(X)))
Y = median(X);
else
Y = zeros(1, size(X,2));
for i = 1:size(X, 2)
Y(i) = median(X(~isnan(X(:, i)), i));
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_BMS_F_smpl.m
|
.m
|
antx-master/xspm8/spm_BMS_F_smpl.m
| 1,628 |
utf_8
|
ee07ac8baecef03c27abc7bbde7c2ebe
|
function [s_samp,s_bound] = spm_BMS_F_smpl (alpha,lme,alpha0)
% Get sample and lower bound approx. for model evidence p(y|r)
% in group BMS; see spm_BMS_F.
%
% FORMAT [s_samp,s_bound] = spm_BMS_F_smpl (alpha,lme,alpha0)
%
% REFERENCE: See appendix in
% Stephan KE, Penny WD, Daunizeau J, Moran RJ, Friston KJ
% Bayesian Model Selection for Group Studies. NeuroImage (under review)
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Will Penny
% $Id: spm_BMS_F_smpl.m 2626 2009-01-20 16:30:08Z maria $
% prevent numerical problems
max_val = log(realmax('double'));
for i=1:size(lme,1),
lme(i,:) = lme(i,:) - mean(lme(i,:));
for k = 1:size(lme,2),
lme(i,k) = sign(lme(i,k)) * min(max_val,abs(lme(i,k)));
end
end
% Number of samples per alpha bin (0.1)
Nsamp = 1e3;
% Sample from univariate gamma densities then normalise
% (see Dirichlet entry in Wikipedia or Ferguson (1973) Ann. Stat. 1,
% 209-230)
Nk = length(alpha);
for k = 1:Nk,
alpha_samp(:,k) = spm_gamrnd(alpha(k),1,Nsamp,1);
end
Ni = size(lme,1);
for i = 1:Ni,
s_approx(i) = sum((alpha./sum(alpha)).*lme(i,:));
s(i) = 0;
for n = 1:Nsamp,
s(i) = s(i) + si_fun(alpha_samp(n,:),lme(i,:));
end
s(i) = s(i)/Nsamp;
end
s_bound = sum(s_approx);
s_samp = sum(s);
return
%=========================================================================
function [si] = si_fun (alpha,lme)
% Check a lower bound
% FORMAT [si] = si_fun (alpha,lme)
esi = sum((exp(lme).*alpha)/sum(alpha));
si = log(esi);
return
|
github
|
philippboehmsturm/antx-master
|
spm_normalise.m
|
.m
|
antx-master/xspm8/spm_normalise.m
| 12,919 |
utf_8
|
716d6de42742658332dc1d1712f9738f
|
function params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% Spatial (stereotactic) normalisation
%
% FORMAT params = spm_normalise(VG,VF,matname,VWG,VWF,flags)
% VG - template handle(s)
% VF - handle of image to estimate params from
% matname - name of file to store deformation definitions
% VWG - template weighting image
% VWF - source weighting image
% flags - flags. If any field is not passed, then defaults are assumed.
% (defaults values are defined in spm_defaults.m)
% smosrc - smoothing of source image (FWHM of Gaussian in mm).
% smoref - smoothing of template image (defaults to 0).
% regtype - regularisation type for affine registration
% See spm_affreg.m
% cutoff - Cutoff of the DCT bases. Lower values mean more
% basis functions are used
% nits - number of nonlinear iterations
% reg - amount of regularisation
% _________________________________________________________________________
%
% This module spatially (stereotactically) normalises MRI, PET or SPECT
% images into a standard space defined by some ideal model or template
% image[s]. The template images supplied with SPM conform to the space
% defined by the ICBM, NIH P-20 project, and approximate that of the
% the space described in the atlas of Talairach and Tournoux (1988).
% The transformation can also be applied to any other image that has
% been coregistered with these scans.
%
%
% Mechanism
% Generally, the algorithms work by minimising the sum of squares
% difference between the image which is to be normalised, and a linear
% combination of one or more template images. For the least squares
% registration to produce an unbiased estimate of the spatial
% transformation, the image contrast in the templates (or linear
% combination of templates) should be similar to that of the image from
% which the spatial normalization is derived. The registration simply
% searches for an optimum solution. If the starting estimates are not
% good, then the optimum it finds may not find the global optimum.
%
% The first step of the normalization is to determine the optimum
% 12-parameter affine transformation. Initially, the registration is
% performed by matching the whole of the head (including the scalp) to
% the template. Following this, the registration proceeded by only
% matching the brains together, by appropriate weighting of the template
% voxels. This is a completely automated procedure (that does not
% require ``scalp editing'') that discounts the confounding effects of
% skull and scalp differences. A Bayesian framework is used, such that
% the registration searches for the solution that maximizes the a
% posteriori probability of it being correct. i.e., it maximizes the
% product of the likelihood function (derived from the residual squared
% difference) and the prior function (which is based on the probability
% of obtaining a particular set of zooms and shears).
%
% The affine registration is followed by estimating nonlinear deformations,
% whereby the deformations are defined by a linear combination of three
% dimensional discrete cosine transform (DCT) basis functions.
% The parameters represent coefficients of the deformations in
% three orthogonal directions. The matching involved simultaneously
% minimizing the bending energies of the deformation fields and the
% residual squared difference between the images and template(s).
%
% An option is provided for allowing weighting images (consisting of pixel
% values between the range of zero to one) to be used for registering
% abnormal or lesioned brains. These images should match the dimensions
% of the image from which the parameters are estimated, and should contain
% zeros corresponding to regions of abnormal tissue.
%
%
% Uses
% Primarily for stereotactic normalization to facilitate inter-subject
% averaging and precise characterization of functional anatomy. It is
% not necessary to spatially normalise the data (this is only a
% pre-requisite for intersubject averaging or reporting in the
% Talairach space).
%
% Inputs
% The first input is the image which is to be normalised. This image
% should be of the same modality (and MRI sequence etc) as the template
% which is specified. The same spatial transformation can then be
% applied to any other images of the same subject. These files should
% conform to the SPM data format (See 'Data Format'). Many subjects can
% be entered at once, and there is no restriction on image dimensions
% or voxel size.
%
% Providing that the images have a correct voxel-to-world mapping,
% which describes the spatial relationship between them, it is
% possible to spatially normalise the images without having first
% resliced them all into the same space.
%
% Default values of parameters pertaining to the extent and sampling of
% the standard space can be changed, including the model or template
% image[s].
%
%
% Outputs
% The details of the transformations are displayed in the results window,
% and the parameters are saved in the "*_sn.mat" file.
%
%__________________________________________________________________________
% Refs:
% K.J. Friston, J. Ashburner, C.D. Frith, J.-B. Poline,
% J.D. Heather, and R.S.J. Frackowiak
% Spatial Registration and Normalization of Images.
% Human Brain Mapping 2:165-189(1995)
%
% J. Ashburner, P. Neelin, D.L. Collins, A.C. Evans and K. J. Friston
% Incorporating Prior Knowledge into Image Registration.
% NeuroImage 6:344-352 (1997)
%
% J. Ashburner and K. J. Friston
% Nonlinear Spatial Normalization using Basis Functions.
% Human Brain Mapping 7(4):in press (1999)
%__________________________________________________________________________
% Copyright (C) 2002-2011 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_normalise.m 4621 2012-01-13 11:12:40Z guillaume $
if nargin<2, error('Incorrect usage.'); end;
if ischar(VF), VF = spm_vol(VF); end;
if ischar(VG), VG = spm_vol(VG); end;
if nargin<3,
if nargout==0,
[pth,nm,xt,vr] = spm_fileparts(deblank(VF(1).fname));
matname = fullfile(pth,[nm '_sn.mat']);
else
matname = '';
end;
end;
if nargin<4, VWG = ''; end;
if nargin<5, VWF = ''; end;
if ischar(VWG), VWG=spm_vol(VWG); end;
if ischar(VWF), VWF=spm_vol(VWF); end;
def_flags = spm_get_defaults('normalise.estimate');
def_flags.graphics = 1;
if nargin < 6,
flags = def_flags;
else
fnms = fieldnames(def_flags);
for i=1:length(fnms),
if ~isfield(flags,fnms{i}),
flags.(fnms{i}) = def_flags.(fnms{i});
end;
end;
end;
fprintf('Smoothing by %g & %gmm..\n', flags.smoref, flags.smosrc);
VF1 = spm_smoothto8bit(VF,flags.smosrc);
% Rescale images so that globals are better conditioned
VF1.pinfo(1:2,:) = VF1.pinfo(1:2,:)/spm_global(VF1);
for i=1:numel(VG),
VG1(i) = spm_smoothto8bit(VG(i),flags.smoref);
VG1(i).pinfo(1:2,:) = VG1(i).pinfo(1:2,:)/spm_global(VG(i));
end;
% Affine Normalisation
%--------------------------------------------------------------------------
fprintf('Coarse Affine Registration..\n');
aflags = struct('sep',max(flags.smoref,flags.smosrc), 'regtype',flags.regtype,...
'WG',[],'WF',[],'globnorm',0);
aflags.sep = max(aflags.sep,max(sqrt(sum(VG(1).mat(1:3,1:3).^2))));
aflags.sep = max(aflags.sep,max(sqrt(sum(VF(1).mat(1:3,1:3).^2))));
M = eye(4); %spm_matrix(prms');
spm_plot_convergence('Init','Affine Registration','Mean squared difference','Iteration');
[M,scal] = spm_affreg(VG1, VF1, aflags, M);
fprintf('Fine Affine Registration..\n');
aflags.WG = VWG;
aflags.WF = VWF;
aflags.sep = aflags.sep/2;
[M,scal] = spm_affreg(VG1, VF1, aflags, M,scal);
Affine = inv(VG(1).mat\M*VF1(1).mat);
spm_plot_convergence('Clear');
% Basis function Normalisation
%--------------------------------------------------------------------------
fov = VF1(1).dim(1:3).*sqrt(sum(VF1(1).mat(1:3,1:3).^2));
if any(fov<15*flags.smosrc/2 & VF1(1).dim(1:3)<15),
fprintf('Field of view too small for nonlinear registration\n');
Tr = [];
elseif isfinite(flags.cutoff) && flags.nits && ~isinf(flags.reg),
fprintf('3D CT Norm...\n');
Tr = snbasis(VG1,VF1,VWG,VWF,Affine,...
max(flags.smoref,flags.smosrc),flags.cutoff,flags.nits,flags.reg);
else
Tr = [];
end;
clear VF1 VG1
flags.version = 'spm_normalise.m 2.12 04/11/26';
flags.date = date;
params = struct('Affine',Affine, 'Tr',Tr, 'VF',VF, 'VG',VG, 'flags',flags);
if flags.graphics, spm_normalise_disp(params,VF); end;
% Remove dat fields before saving
%--------------------------------------------------------------------------
if isfield(VF,'dat'), VF = rmfield(VF,'dat'); end;
if isfield(VG,'dat'), VG = rmfield(VG,'dat'); end;
if ~isempty(matname),
fprintf('Saving Parameters..\n');
if spm_check_version('matlab','7') >= 0,
save(matname,'-V6','Affine','Tr','VF','VG','flags');
else
save(matname,'Affine','Tr','VF','VG','flags');
end;
end;
return;
%__________________________________________________________________________
%__________________________________________________________________________
function Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)
% 3D Basis Function Normalization
% FORMAT Tr = snbasis(VG,VF,VWG,VWF,Affine,fwhm,cutoff,nits,reg)
% VG - Template volumes (see spm_vol).
% VF - Volume to normalise.
% VWG - weighting Volume - for template.
% VWF - weighting Volume - for object.
% Affine - A 4x4 transformation (in voxel space).
% fwhm - smoothness of images.
% cutoff - frequency cutoff of basis functions.
% nits - number of iterations.
% reg - regularisation.
% Tr - Discrete cosine transform of the warps in X, Y & Z.
%
% snbasis performs a spatial normalization based upon a 3D
% discrete cosine transform.
%
%__________________________________________________________________________
fwhm = [fwhm 30];
% Number of basis functions for x, y & z
%--------------------------------------------------------------------------
tmp = sqrt(sum(VG(1).mat(1:3,1:3).^2));
k = max(round((VG(1).dim(1:3).*tmp)/cutoff),[1 1 1]);
% Scaling is to improve stability.
%--------------------------------------------------------------------------
stabilise = 8;
basX = spm_dctmtx(VG(1).dim(1),k(1))*stabilise;
basY = spm_dctmtx(VG(1).dim(2),k(2))*stabilise;
basZ = spm_dctmtx(VG(1).dim(3),k(3))*stabilise;
dbasX = spm_dctmtx(VG(1).dim(1),k(1),'diff')*stabilise;
dbasY = spm_dctmtx(VG(1).dim(2),k(2),'diff')*stabilise;
dbasZ = spm_dctmtx(VG(1).dim(3),k(3),'diff')*stabilise;
vx1 = sqrt(sum(VG(1).mat(1:3,1:3).^2));
vx2 = vx1;
kx = (pi*((1:k(1))'-1)/VG(1).dim(1)/vx1(1)).^2; ox=ones(k(1),1);
ky = (pi*((1:k(2))'-1)/VG(1).dim(2)/vx1(2)).^2; oy=ones(k(2),1);
kz = (pi*((1:k(3))'-1)/VG(1).dim(3)/vx1(3)).^2; oz=ones(k(3),1);
if 1,
% BENDING ENERGY REGULARIZATION
% Estimate a suitable sparse diagonal inverse covariance matrix for
% the parameters (IC0).
%------------------------------------------------------------------
IC0 = (1*kron(kz.^2,kron(ky.^0,kx.^0)) +...
1*kron(kz.^0,kron(ky.^2,kx.^0)) +...
1*kron(kz.^0,kron(ky.^0,kx.^2)) +...
2*kron(kz.^1,kron(ky.^1,kx.^0)) +...
2*kron(kz.^1,kron(ky.^0,kx.^1)) +...
2*kron(kz.^0,kron(ky.^1,kx.^1)) );
IC0 = reg*IC0*stabilise^6;
IC0 = [IC0*vx2(1)^4 ; IC0*vx2(2)^4 ; IC0*vx2(3)^4 ; zeros(prod(size(VG))*4,1)];
IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));
else
% MEMBRANE ENERGY (LAPLACIAN) REGULARIZATION
%------------------------------------------------------------------
IC0 = kron(kron(oz,oy),kx) + kron(kron(oz,ky),ox) + kron(kron(kz,oy),ox);
IC0 = reg*IC0*stabilise^6;
IC0 = [IC0*vx2(1)^2 ; IC0*vx2(2)^2 ; IC0*vx2(3)^2 ; zeros(prod(size(VG))*4,1)];
IC0 = sparse(1:length(IC0),1:length(IC0),IC0,length(IC0),length(IC0));
end;
% Generate starting estimates.
%--------------------------------------------------------------------------
s1 = 3*prod(k);
s2 = s1 + numel(VG)*4;
T = zeros(s2,1);
T(s1+(1:4:numel(VG)*4)) = 1;
pVar = Inf;
for iter=1:nits,
fprintf(' iteration %2d: ', iter);
[Alpha,Beta,Var,fw] = spm_brainwarp(VG,VF,Affine,basX,basY,basZ,dbasX,dbasY,dbasZ,T,fwhm,VWG, VWF);
if Var>pVar, scal = pVar/Var ; Var = pVar; else scal = 1; end;
pVar = Var;
T = (Alpha + IC0*scal)\(Alpha*T + Beta);
fwhm(2) = min([fw fwhm(2)]);
fprintf(' FWHM = %6.4g Var = %g\n', fw,Var);
end;
% Values of the 3D-DCT
%--------------------------------------------------------------------------
Tr = reshape(T(1:s1),[k 3]) * stabilise.^3;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_eeg_ft2spm.m
|
.m
|
antx-master/xspm8/spm_eeg_ft2spm.m
| 6,129 |
utf_8
|
a5369fdb03fab87d6f33d7a88c8bbac1
|
function D = spm_eeg_ft2spm(ftdata, filename)
% Converter from Fieldtrip (http://www.ru.nl/fcdonders/fieldtrip/)
% data structures to SPM8 file format
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Vladimir Litvak
% $Id: spm_eeg_ft2spm.m 4038 2010-08-10 10:39:00Z vladimir $
isTF = 0;
% If raw format
if iscell(ftdata.time)
if length(ftdata.time)>1
% Initial checks
if any(diff(cellfun('length', ftdata.time))~=0)
error('SPM can only handle data with equal trial lengths.');
else
times=cell2mat(ftdata.time(:));
if any(diff(times(:, 1))~=0) || any(diff(times(:, end))~=0)
error('SPM can only handle data the same trial borders.');
end
end
end
Ntrials=length(ftdata.trial);
Nchannels = size(ftdata.trial{1},1);
Nsamples = size(ftdata.trial{1},2);
data = zeros(Nchannels, Nsamples, Ntrials);
for n=1:Ntrials
data(:,:,n) = ftdata.trial{n};
end
ftdata.time = ftdata.time{1};
else
Nchannels = numel(ftdata.label);
Nsamples = length(ftdata.time);
rptind=strmatch('rpt', tokenize(ftdata.dimord, '_'));
if isempty(rptind)
rptind=strmatch('subj', tokenize(ftdata.dimord, '_'));
end
timeind=strmatch('time', tokenize(ftdata.dimord, '_'));
chanind=strmatch('chan', tokenize(ftdata.dimord, '_'));
if any(ismember({'trial', 'individual', 'avg'}, fieldnames(ftdata) )) % timelockanalysis
if ~isempty(rptind)
if isfield(ftdata, 'trial')
Ntrials = size(ftdata.trial, rptind);
data =permute(ftdata.trial, [chanind, timeind, rptind]);
else
Ntrials = size(ftdata.individual, rptind);
data =permute(ftdata.individual, [chanind, timeind, rptind]);
end
else
Ntrials = 1;
data =permute(ftdata.avg, [chanind, timeind]);
end
elseif isfield(ftdata, 'powspctrm')
isTF = 1;
Nfrequencies = numel(ftdata.freq);
freqind = strmatch('freq', tokenize(ftdata.dimord, '_'));
if ~isempty(rptind)
Ntrials = size(ftdata.powspctrm, rptind);
data = permute(ftdata.powspctrm, [chanind, freqind, timeind, rptind]);
else
Ntrials = 1;
data = permute(ftdata.powspctrm, [chanind, freqind, timeind]);
end
end
end
%--------- Start making the header
D = [];
% sampling rate in Hz
if isfield(ftdata, 'fsample')
D.Fsample = ftdata.fsample;
else
D.Fsample = 1./mean(diff(ftdata.time));
end
D.timeOnset = ftdata.time(1);
% Number of time bins in peri-stimulus time
D.Nsamples = Nsamples;
% Names of channels in order of the data
D.channels = struct('label', ftdata.label);
D.trials = repmat(struct('label', {'Undefined'}), 1, Ntrials);
[pathname, fname] = fileparts(filename);
D.path = pathname;
D.fname = [fname '.mat'];
D.data.fnamedat = [fname '.dat'];
D.data.datatype = 'float32-le';
if ~isTF
if Ntrials == 1
datafile = file_array(fullfile(D.path, D.data.fnamedat), [Nchannels Nsamples], D.data.datatype);
% physically initialise file
datafile(end,end) = 0;
datafile(:, :) = data;
else
datafile = file_array(fullfile(D.path, D.data.fnamedat), [Nchannels Nsamples Ntrials], D.data.datatype);
% physically initialise file
datafile(end,end) = 0;
datafile(:, :, :) = data;
end
else
if Ntrials == 1
datafile = file_array(fullfile(D.path, D.data.fnamedat), [Nchannels Nfrequencies Nsamples], D.data.datatype);
% physically initialise file
datafile(end,end) = 0;
datafile(:, :, :) = data;
else
datafile = file_array(fullfile(D.path, D.data.fnamedat), [Nchannels Nfrequencies Nsamples Ntrials], D.data.datatype);
% physically initialise file
datafile(end,end) = 0;
datafile(:, :, :, :) = data;
end
D.transform.ID = 'TF';
D.transform.frequencies = ftdata.freq;
end
D.data.y = datafile;
D = meeg(D);
if isfield(ftdata, 'hdr')
% Uses fileio function to get the information about channel types stored in
% the original header. This is now mainly useful for Neuromag support but might
% have other functions in the future.
origchantypes = ft_chantype(ftdata.hdr);
[sel1, sel2] = spm_match_str(D.chanlabels, ftdata.hdr.label);
origchantypes = origchantypes(sel2);
if length(strmatch('unknown', origchantypes, 'exact')) ~= numel(origchantypes)
D.origchantypes = struct([]);
D.origchantypes(1).label = ftdata.hdr.label(sel2);
D.origchantypes(1).type = origchantypes;
end
end
% Set channel types to default
S1 = [];
S1.task = 'defaulttype';
S1.D = D;
S1.updatehistory = 0;
D = spm_eeg_prep(S1);
if Ntrials == 1
D = type(D, 'continuous');
else
D = type(D, 'single');
end
if isfield(ftdata, 'hdr') && isfield(ftdata.hdr, 'grad')
D = sensors(D, 'MEG', ft_convert_units(ftdata.hdr.grad, 'mm'));
S = [];
S.task = 'project3D';
S.modality = 'MEG';
S.updatehistory = 0;
S.D = D;
D = spm_eeg_prep(S);
end
[ok D] = check(D);
save(D);
function [tok] = tokenize(str, sep, rep)
% TOKENIZE cuts a string into pieces, returning a cell array
%
% Use as
% t = tokenize(str, sep)
% t = tokenize(str, sep, rep)
% where str is a string and sep is the separator at which you want
% to cut it into pieces.
%
% Using the optional boolean flag rep you can specify whether repeated
% seperator characters should be squeezed together (e.g. multiple
% spaces between two words). The default is rep=1, i.e. repeated
% seperators are treated as one.
% Copyright (C) 2003-2006, Robert Oostenveld
tok = {};
f = find(str==sep);
f = [0, f, length(str)+1];
for i=1:(length(f)-1)
tok{i} = str((f(i)+1):(f(i+1)-1));
end
if nargin<3 || rep
% remove empty cells, which occur if the separator is repeated (e.g. multiple spaces)
tok(find(cellfun('isempty', tok)))=[];
end
|
github
|
philippboehmsturm/antx-master
|
spm_pf.m
|
.m
|
antx-master/xspm8/spm_pf.m
| 6,768 |
utf_8
|
7a122bb3a5c25e63f4470b6ba52cdb54
|
function [qx,qP,qD,xhist] = spm_pf(M,y,U)
% Particle Filtering for dynamic models
% FORMAT [qx,qP,qD,xhist] = spm_pf(M,y)
% M - model specification structure
% y - output or data (N x T)
% U - exogenous input
%
% M(1).x % initial states
% M(1).f = inline(f,'x','v','P') % state equation
% M(1).g = inline(g,'x','v','P') % observer equation
% M(1).pE % parameters
% M(1).V % observation noise precision
%
% M(2).v % initial process noise
% M(2).V % process noise precision
%
% qx - conditional expectation of states
% qP - {1 x T} conditional covariance of states
% qD - full sample
%__________________________________________________________________________
% See notes at the end of this script for details and a demo. This routine
% is based on:
%
% var der Merwe R, Doucet A, de Freitas N and Wan E (2000). The
% unscented particle filter. Technical Report CUED/F-INFENG/TR 380
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Karl Friston
% $Id: spm_pf.m 1143 2008-02-07 19:33:33Z spm $
% check model specification
%--------------------------------------------------------------------------
M = spm_DEM_M_set(M);
dt = M(1).E.dt;
if length(M) ~=2
errordlg('spm_pf requires a two-level model')
return
end
% INITIALISATION:
%==========================================================================
T = length(y); % number of time points
n = M(2).l; % number of innovations
N = 200; % number of particles.
% precision of measurement noise
%--------------------------------------------------------------------------
R = M(1).V;
for i = 1:length(M(1).Q)
R = R + M(1).Q{i}*exp(M(1).h(i));
end
P = M(1).pE; % parameters
Q = M(2).V.^-.5; % root covariance of innovations
v = kron(ones(1,N),M(2).v); % innovations
x = kron(ones(1,N),M(1).x); % hidden states
v = v + 128*Q*randn(size(v));
% inputs
%--------------------------------------------------------------------------
if nargin < 3
U = sparse(n,T);
end
for t = 1:T
% PREDICTION STEP: with the (8x) transition prior as proposal
%----------------------------------------------------------------------
for i = 1:N
v(:,i) = 8*Q*randn(n,1) + U(:,t);
f = M(1).f(x(:,i),v(:,i),P);
dfdx = spm_diff(M(1).f,x(:,i),v(:,i),P,1);
xPred(:,i) = x(:,i) + spm_dx(dfdx,f,dt);
end
% EVALUATE IMPORTANCE WEIGHTS: and normalise
%----------------------------------------------------------------------
for i = 1:N
yPred = M(1).g(xPred(:,i),v(:,i),P);
ePred = yPred - y(:,t);
w(i) = ePred'*R*ePred;
end
w = w - min(w);
w = exp(-w/2);
w = w/sum(w);
% SELECTION STEP: multinomial resampling.
%----------------------------------------------------------------------
x = xPred(:,multinomial(1:N,w));
% report and record moments
%----------------------------------------------------------------------
qx(:,t) = mean(x,2);
qP{t} = cov(x');
qX(:,t) = x(:);
fprintf('PF: time-step = %i : %i\n',t,T);
end
% sample density
%==========================================================================
if nargout > 3
xhist = linspace(min(qX(:)),max(qX(:)),32);
for i = 1:T
q = hist(qX(:,i),xhist);
qD(:,i) = q(:);
end
end
return
function I = multinomial(inIndex,q);
%==========================================================================
% PURPOSE : Performs the resampling stage of the SIR
% in order(number of samples) steps.
% INPUTS : - inIndex = Input particle indices.
% - q = Normalised importance ratios.
% OUTPUTS : - I = Resampled indices.
% AUTHORS : Arnaud Doucet and Nando de Freitas
% MULTINOMIAL SAMPLING:
% generate S ordered random variables uniformly distributed in [0,1]
% high speed Niclas Bergman Procedure
%--------------------------------------------------------------------------
q = q(:);
S = length(q); % S = Number of particles.
N_babies = zeros(1,S);
cumDist = cumsum(q');
u = fliplr(cumprod(rand(1,S).^(1./(S:-1:1))));
j = 1;
for i = 1:S
while (u(1,i) > cumDist(1,j))
j = j + 1;
end
N_babies(1,j) = N_babies(1,j) + 1;
end;
% COPY RESAMPLED TRAJECTORIES:
%--------------------------------------------------------------------------
index = 1;
for i = 1:S
if (N_babies(1,i)>0)
for j=index:index+N_babies(1,i)-1
I(j) = inIndex(i);
end;
end;
index = index + N_babies(1,i);
end
return
%==========================================================================
% notes and demo:
%==========================================================================
% The code below generates a nonlinear, non-Gaussian problem (S) comprising
% a model S.M and data S.Y (c.f. van der Merwe et al 2000))
%
% The model is f(x) = dxdt
% = 1 + sin(0.04*pi*t) - log(2)*x + n
% y = g(x)
% = (x.^2)/5 : if t < 30
% -2 + x/2 : otherwise
% i.e. the output nonlinearity becomes linear after 30 time steps. In this
% implementation time is modelled as an auxiliary state variable. n is
% the process noise, which is modelled as a log-normal variate. e is
% Gaussian observation noise.
% model specification
%--------------------------------------------------------------------------
f = '[1; (1 + sin(P(2)*pi*x(1)) - P(1)*x(2) + exp(v))]';
g = '(x(1) > 30)*(-2 + x(2)/2) + ~(x(1) > 30)*(x(2).^2)/5';
M(1).x = [1; 1]; % initial states
M(1).f = inline(f,'x','v','P'); % state equation
M(1).g = inline(g,'x','v','P'); % observer equation
M(1).pE = [log(2) 0.04]; % parameters
M(1).V = exp(4); % observation noise precision
M(2).v = 0; % initial process log(noise)
M(2).V = 2.4; % process log(noise) precision
% generate data (output)
%--------------------------------------------------------------------------
T = 60; % number of time points
S = spm_DEM_generate(M,T);
% Particle filtering
%--------------------------------------------------------------------------
pf_x = spm_pf(M,S.Y);
% plot results
%--------------------------------------------------------------------------
x = S.pU.x{1};
plot([1:T],x(2,:),[1:T],pf_x(2,:))
legend({'true','PF'})
|
github
|
philippboehmsturm/antx-master
|
spm_SpUtil.m
|
.m
|
antx-master/xspm8/spm_SpUtil.m
| 27,031 |
utf_8
|
52ecc1ec2086a8b82b6e6192fd8f435a
|
function varargout = spm_SpUtil(varargin)
% Space matrix utilities
% FORMAT varargout = spm_SpUtil(action,varargin)
%
%_______________________________________________________________________
%
% spm_SpUtil is a multi-function function containing various utilities
% for Design matrix and contrast construction and manipulation. In
% general, it accepts design matrices as plain matrices or as space
% structures setup by spm_sp.
%
% Many of the space utilities are computed using an SVD of the design
% matrix. The advantage of using space structures is that the svd of
% the design matrix is stored in the space structure, thereby saving
% unnecessary repeated computation of the SVD. This presents a
% considerable efficiency gain for large design matrices.
%
% Note that when space structures are passed as arguments is is
% assummed that their basic fields are filled in. See spm_sp for
% details of (design) space structures and their manipulation.
%
% Quick Reference :
%---------------------
% ('isCon',x,c) :
% ('allCon',x,c) :
% ('ConR',x,c) :
% ('ConO',x,c) :
% ('size',x,dim) :
% ('iX0check',i0,sL) :
%---------------------
% ('i0->c',x,i0) : Out : c
% ('c->Tsp',x,c) : Out : [X1o [X0]]
% ('+c->Tsp',x,c) : Out : [ukX1o [ukX0]]
% ('i0->x1o',x,i0) : Use ('i0->c',x,i0) and ('c->Tsp',X,c)
% ('+i0->x1o',x,i0) : Use ('i0->c',x,i0) and ('+c->Tsp',X,c)
% ('X0->c',x,X0) :~
% ('+X0->c',x,cukX0) :~
%---------------------
% ('trRV',x[,V]) :
% ('trMV',x[,V]) :
% ('i0->edf',x,i0,V) :
%
%---------------------
%
% Improvement compared to the spm99 beta version :
%
% Improvements in df computation using spm_SpUtil('trRV',x[,V]) and
% spm_SpUtil('trMV',sX [,V]). The degrees of freedom computation requires
% in general that the trace of RV and of RVRV be computed, where R is a
% projector onto either a sub space of the design space or the residual
% space, namely the space that is orthogonal to the design space. V is
% the (estimated or assumed) variance covariance matrix and is a number
% of scans by number of scans matrix which can be huge in some cases. We
% have (thanks to S Rouquette and JB) speed up this computation
% by using matlab built in functions of the frobenius norm and some theorems
% on trace computations.
%
% ======================================================================
%
% FORMAT i = spm_SpUtil('isCon',x,c)
% Tests whether weight vectors specify contrasts
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% [defaults to eye(size(X,2)) to test uniqueness of parameter estimates]
% i - logical row vector indiciating estimability of contrasts in c
%
% A linear combination of the parameter estimates is a contrast if and
% only if the weight vector is in the space spanned by the rows of X.
%
% The algorithm works by regressing the contrast weight vectors using
% design matrix X' (X transposed). Any contrast weight vectors will be
% fitted exactly by this procedure, leaving zero residual. Parameter
% tol is the tolerance applied when searching for zero residuals.
%
% Christensen R (1996)
% "Plane Answers to Complex Questions"
% 2nd Ed. Springer-Verlag, New York
%
% Andrade A, Paradis AL, Rouquette S and Poline JB, NeuroImage 9, 1999
% ----------------
%
% FORMAT i = spm_SpUtil('allCon',x,c)
% Tests whether all weight vectors specify contrasts:
% Same as all(spm_SpUtil('isCon',x,c)).
%
% ----------------
%
% FORMAT r = spm_SpUtil('ConR',x,c)
% Assess orthogonality of contrasts (wirit the data)
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% defaults to eye(size(X,2)) to test independence of parameter estimates
% r - Contrast correlation matrix, of dimension the number of contrasts.
%
% For the general linear model Y = X*B + E, a contrast weight vector c
% defines a contrast c*B. This is estimated by c*b, where b are the
% least squares estimates of B given by b=pinv(X)*Y. Thus, c*b = w*Y,
% where weight vector w is given by w=c*pinv(X); Since the data are
% assummed independent, two contrasts are indpendent if the
% corresponding weight vectors are orthogonal.
%
% r is the matrix of normalised inner products between the weight
% vectors corresponding to the contrasts. For iid E, r is the
% correlation matrix of the contrasts.
%
% The logical matrix ~r will be true for orthogonal pairs of contrasts.
%
% ----------------
%
% FORMAT r = spm_SpUtil('ConO',x,c)
% Assess orthogonality of contrasts (wirit the data)
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% [defaults to eye(size(X,2)) to test uniqueness of parameter estimates]
% r - Contrast orthogonality matrix, of dimension the number of contrasts.
%
% This is the same as ~spm_SpUtil('ConR',X,c), but uses a quicker
% algorithm by looking at the orthogonality of the subspaces of the
% design space which are implied by the contrasts:
% r = abs(c*X'*X*c')<tol
%
% ----------------
%
% FORMAT c = spm_SpUtil('i0->c',x,i0)
% Return F-contrast for specified design matrix partition
% x - Design matrix X, or space structure of X
% i0 - column indices of null hypothesis design matrix
%
% This functionality returns a rank n mxp matrix of contrasts suitable
% for an extra-sum-of-squares F-test comparing the design X, with a
% reduced design. The design matrix for the reduced design is X0 =
% X(:,i0), a reduction of n degrees of freedom.
%
% The algorithm, due to J-B, and derived from Christensen, computes the
% contrasts as an orthonormal basis set for the rows of the
% hypothesised redundant columns of the design matrix, after
% orthogonalisation with respect to X0. For non-unique designs, there
% are a variety of ways to produce equivalent F-contrasts. This method
% produces contrasts with non-zero weights only for the hypothesised
% redundant columns.
%
% ----------------
%
% case {'x0->c'} %-
% FORMAT c = spm_SpUtil('X0->c',sX,X0)
% ----------------
%
% FORMAT [X1,X0] = spm_SpUtil('c->TSp',X,c)
% Orthogonalised partitioning of design space implied by F-contrast
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% X1o - contrast space - design matrix corresponding according to contrast
% (orthogonalised wirit X0)
% X0 - matrix reduced according to null hypothesis
% (of same size as X but rank deficient)
% FORMAT [uX1,uX0] = spm_SpUtil('c->TSp+',X,c)
% + version to deal with the X1o and X0 partitions in the "uk basis"
%
% ( Note that unless X0 is reduced to a set of linearely independant )
% ( vectors, c will only be contained in the null space of X0. If X0 )
% ( is "reduced", then the "parent" space of c must be reduced as well )
% ( for c to be the actual null space of X0. )
%
% This functionality returns a design matrix subpartition whose columns
% span the hypothesised null design space of a given contrast. Note
% that X1 is orthogonal(ised) to X0, reflecting the situation when an
% F-contrast is tested using the extra sum-of-squares principle (when
% the extra distance in the hypothesised null space is measured
% orthogonal to the space of X0).
%
% Note that the null space design matrix will probably not be a simple
% sub-partition of the full design matrix, although the space spanned
% will be the same.
%
% ----------------
%
% FORMAT X1 = spm_SpUtil('i0->x1o',X,i0)
% x - Design matrix X, or space structure of X
% i0 - Columns of X that make up X0 - the reduced model (Ho:B1=0)
% X1 - Hypothesised null design space, i.e. that part of X orthogonal to X0
% This offers the same functionality as the 'c->TSp' option, but for
% simple reduced models formed from the columns of X.
%
% FORMAT X1 = spm_SpUtil('i0->x1o+',X,i0)
% + version to deal with the X1o and X0 partitions in the "uk basis"
%
% ----------------
%
% FORMAT [trRV,trRVRV] = spm_SpUtil('trRV',x[,V])
% trace(RV) & trace(RVRV) - used in df calculation
% x - Design matrix X, or space structure of X
% V - V matrix [defult eye] (trRV == trRVRV if V==eye, since R idempotent)
% trRV - trace(R*V), computed efficiently
% trRVRV - trace(R*V*R*V), computed efficiently
% This uses the Karl's cunning understanding of the trace:
% (tr(A*B) = sum(sum(A'*B)).
% If the space of X is set, then algorithm uses x.u to avoid extra computation.
%
% ----------------
%
% FORMAT [trMV, trMVMV]] = spm_SpUtil('trMV',x[,V])
% trace(MV) & trace(MVMV) if two ouput arguments.
% x - Design matrix X, or space structure of X
% V - V matrix [defult eye] (trMV == trMVMV if V==eye, since M idempotent)
% trMV - trace(M*V), computed efficiently
% trMVMV - trace(M*V*M*V), computed efficiently
% Again, this uses the Karl's cunning understanding of the trace:
% (tr(A*B) = sum(sum(A'.*B)).
% If the space of X is set, then algorithm uses x.u to avoid extra computation.
%
% ----------------
%
% OBSOLETE use FcUtil('H') for spm_SpUtil('c->H',x,c)
% Extra sum of squares matrix O for beta's from contrast
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% O - Matrix such that b'*O*b = extra sum of squares for F-test of contrast c
%
% ----------------
%
% OBSOLETE use spm_sp('=='...) for spm_SpUtil('c==X1o',x,c) {or 'cxpequi'}
% x - Design matrix X, or space structure of X
% c - contrast matrix (I.e. matrix of contrast weights, contrasts in columns)
% Must have column dimension matching that of X
% b - True is c is a spanning set for space of X
% (I.e. if contrast and space test the same thing)
%
% ----------------
%
% FORMAT [df1,df2] = spm_SpUtil('i0->edf',x,i0,V) {or 'edf'}
% (effective) df1 and df2 the residual df for the projector onto the
% null space of x' (residual forming projector) and the numerator of
% the F-test where i0 are the columns for the null hypothesis model.
% x - Design matrix X, or space structure of X
% i0 - Columns of X corresponding to X0 partition X = [X1,X0] & with
% parameters B = [B1;B0]. Ho:B1=0
% V - V matrix
%
% ----------------
%
% FORMAT sz = spm_SpUtil('size',x,dim)
% FORMAT [sz1,sz2,...] = spm_SpUtil('size',x)
% Returns size of design matrix
% (Like MatLab's `size`, but copes with design matrices inside structures.)
% x - Design matrix X, or structure containing design matrix in field X
% (Structure needn't be a space structure.)
% dim - dimension which to size
% sz - size
%
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes Jean-Baptiste Poline
% $Id: spm_SpUtil.m 4137 2010-12-15 17:18:32Z guillaume $
% (frobenius norm trick by S. Rouquette)
%-Format arguments
%-----------------------------------------------------------------------
if nargin==0, error('do what? no arguments given...')
else action = varargin{1}; end
switch lower(action),
case {'iscon','allcon','conr','cono'}
%=======================================================================
% i = spm_SpUtil('isCon',x,c)
if nargin==0, varargout={[]}; error('isCon : no argument specified'), end;
if nargin==1,
varargout={[]}; warning('isCon : no contrast specified'); return;
end;
if ~spm_sp('isspc',varargin{2})
sX = spm_sp('Set',varargin{2});
else sX = varargin{2}; end
if nargin==2, c=eye(spm_sp('size',sX,2)); else c=varargin{3}; end;
if isempty(c), varargout={[]}; return, end
switch lower(action)
case 'iscon'
varargout = { spm_sp('eachinspp',sX,c) };
case 'allcon'
varargout = {spm_sp('isinspp',sX,c)};
case 'conr'
if size(c,1) ~= spm_sp('size',sX,2)
error('Contrast not of the right size'), end
%-Compute inner products of data weight vectors
% (c'b = c'*pinv(X)*Y = w'*Y
% (=> w*w' = c'*pinv(X)*pinv(X)'*c == c'*pinv(X'*X)*c
r = c'*spm_sp('XpX-',sX)*c;
%-normalize by "cov(r)" to get correlations
r = r./(sqrt(diag(r))*sqrt(diag(r))');
r(abs(r) < sX.tol)=0; %-set near-zeros to zero
varargout = {r}; %-return r
case 'cono'
%-This is the same as ~spm_SpUtil('ConR',x,c), and so returns
% the contrast orthogonality (though not their corelations).
varargout = { abs(c'* spm_sp('XpX',sX) *c) < sX.tol};
end
case {'+c->tsp','c->tsp'} %- Ortho. partitioning implied by F-contrast
%=======================================================================
% spm_SpUtil('c->Tsp',sX,c)
% + version of 'c->tsp'.
% The + version returns the same in the base u(:,1:r).
%--------- begin argument check ------------------------------
if nargin ~= 3, error(['Wrong number of arguments in ' action])
else sX = varargin{2}; c = varargin{3}; end;
if nargout > 2, error(['Too many output arguments in ' action]), end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end;
if sX.rk == 0, error('c->Tsp null rank sX == 0'); end;
if ~isempty(c) && spm_sp('size',sX,2) ~= size(c,1),
error(' c->TSp matrix & contrast dimensions don''t match');
end
%--------- end argument check ---------------------------------
%- project c onto the space of X' if needed
%-------------------------------------------
if ~isempty(c) && ~spm_sp('isinspp',sX,c),
warning([sprintf('\n') 'c is not a proper contrast in ' action ...
' in ' mfilename sprintf('\n') '!!! projecting...' ]);
disp('from'), c, disp('to'), c = spm_sp('oPp:',sX,c)
end
cukFlag = strcmp(lower(action),'+c->tsp');
switch nargout
% case 0
% warning(['no output demanded in ' mfilename ' ' action])
case {0,1}
if ~isempty(c) && any(any(c)) %- c not empty & not null
if cukFlag, varargout = { spm_sp('cukxp-:',sX,c) };
else varargout = { spm_sp('xp-:',sX,c) };
end
else if isempty(c), varargout = { [] }; %- c empty
else %- c null
if cukFlag, varargout = { spm_sp('cukx',sX,c) };
else varargout = { spm_sp('x',sX)*c };
end
end
end
case 2
if ~isempty(c) && any(any(c)) %- not empty and not null
if cukFlag,
varargout = {
spm_sp('cukxp-:',sX,c), ... %- X1o
spm_sp('cukx',sX,spm_sp('r',spm_sp('set',c))) }; %- X0
else
varargout = {
spm_sp(':',sX, spm_sp('xp-:',sX,c)), ... %- X1o
spm_sp(':',sX, ...
spm_sp('x',sX)*spm_sp('r',spm_sp('set',c))) }; %- X0
end
else
if isempty(c), %- empty
if cukFlag, varargout = { [], spm_sp('cukx',sX) };
else varargout = { [], spm_sp('x',sX) };
end
else %- null
if cukFlag,
varargout = { spm_sp(':',sX,spm_sp('cukx',sX,c)), ...
spm_sp(':',sX,spm_sp('cukx',sX)) };
else
varargout = { spm_sp('x',sX)*c, spm_sp('x',sX)};
end
end;
end
otherwise
error(['wrong number of output argument in ' action]);
end
case {'i0->x1o','+i0->x1o'} %- Space tested whilst keeping size of X(i0)
%=======================================================================
% X1o = spm_SpUtil('i0->X1o',sX,i0)
% arguments are checked in calls to spm_Util
%--------------------------------------------
if nargin<3, error('Insufficient arguments'),
else sX = varargin{2}; i0 = varargin{3}; end;
cukFlag = strcmp(lower(action),'+i0->x1o');
c = spm_SpUtil('i0->c',sX,i0);
if cukFlag,
varargout = { spm_SpUtil('+c->TSp',sX,c) };
else
varargout = { spm_SpUtil('c->TSp',sX,c) };
end
case {'i0->c'} %-
%=======================================================================
% c = spm_SpUtil('i0->c',sX,i0)
%
% if i0 == [] : returns a proper contrast
% if i0 == [1:size(sX.X,2)] : returns [];
%
%- Algorithm : avoids the pinv(X0) and insure consistency
%- Get the estimable parts of c0 and c1
%- remove from c1_estimable the estimable part of c0.
%- Use the rotation making X1o orthog. to X0.
%- i0 is checked when Fc is created
%- If i0 defines a space that is the space of X but with
%- fewer vectors, c is null.
%--------- begin argument check --------------------------------
if nargin<3, error('Insufficient arguments'),
else sX = varargin{2}; i0 = varargin{3}; end;
if ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end;
if spm_sp('rk',sX) == 0, error('i0->c null rank sX == 0'); end;
sL = spm_sp('size',sX,2);
i0 = sf_check_i0(i0,sL);
%--------- end argument check ----------------------------------
c0 = eye(sL); c0 = c0(:,i0);
c1 = eye(sL); c1 = c1(:,setdiff(1:sL,i0));
%- try to avoid the matlab error when doing svd of matrices with
%- high multiplicities. (svd convergence pb)
if ~ spm_sp('isinspp',sX,c0), c0 = spm_sp('oPp:',sX,c0); end;
if ~ spm_sp('isinspp',sX,c1), c1 = spm_sp('oPp:',sX,c1); end;
if ~isempty(c1)
if ~isempty(c0)
%- varargout = { spm_sp('res',spm_sp('set',opp*c0),opp*c1) };
%- varargout = { c1 - c0*pinv(c0)*c1 }; NB: matlab pinv uses
%- svd: will fail if spm_sp('set') fails.
varargout = { spm_sp('r:',spm_sp('set',c0),c1) };
else varargout = { spm_sp('xpx',sX) }; end;
else
varargout = { [] }; %- not zeros(sL,1) : this is return when
%- appropriate
end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case {'+x0->c','x0->c'} %-
%=======================================================================
% c = spm_SpUtil('X0->c',sX,X0)
% c = spm_SpUtil('+X0->c',sX,cukX0)
% + version of 'x0->c'.
% The + version returns the same in the base u(:,1:r).
warning('Not tested for release - provided for completeness');
cukFlag = strcmp(lower(action),'+x0->c');
%--------- begin argument check ---------
if nargin<3, error('Insufficient arguments'),
else
sX = varargin{2};
if cukFlag, cukX0 = varargin{3}; else X0 = varargin{3}; end
end
if ~spm_sp('isspc',sX), sX = spm_sp('set',varargin{2}); end
if spm_sp('rk',sX) == 0, error(['null rank sX == 0 in ' action]); end
if cukFlag
if ~isempty(cukX0) && spm_sp('rk',sX) ~= size(cukX0,1),
cukX0, spm_sp('rk',sX),
error(['cukX0 of wrong size ' mfilename ' ' action]), end
else
if ~isempty(X0) && spm_sp('size',sX,1) ~= size(X0,1),
X0, spm_sp('size',sX,1),
error(['X0 of wrong size ' mfilename ' ' action]),X0, end
end
%--------- end argument check ---------
if cukFlag
if isempty(cukX0), X0 = []; else X0 = spm_sp('ox',sX)*cukX0; end
end
varargout = { sf_X0_2_c(X0,sX) };
case {'c->h','betarc'} %-Extra sum of squares matrix for beta's from
%- contrast : use F-contrast if possible
%=======================================================================
% H = spm_SpUtil('c->H',sX,c)
error(' Obsolete : Use F-contrast utilities ''H'' or ''Hsqr''... ');
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%=======================================================================
%=======================================================================
% trace part
%=======================================================================
%=======================================================================
%
case 'trrv' %-Traces for (effective) df calculation
%=======================================================================
% [trRV,trRVRV]= spm_SpUtil('trRV',x[,V])
if nargin == 1, error('insufficient arguments');
else sX = varargin{2}; end;
if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;
rk = spm_sp('rk',sX);
sL = spm_sp('size',sX,1);
if sL == 0,
warning('space with no dimension ');
if nargout==1, varargout = {[]};
else varargout = {[], []}; end
else
if nargin > 2 && ~isempty(varargin{3})
V = varargin{3};
u = sX.u(:,1:rk);
clear sX;
if nargout==1
%-only trRV needed
if rk==0 || isempty(rk), trMV = 0;
else trMV = sum(sum( u .* (V*u) ));
end
varargout = { trace(V) - trMV};
else
%-trRVRV is needed as well
if rk==0 || isempty(rk),
trMV = 0;
trRVRV = (norm(V,'fro'))^2;
trV = trace(V);
clear V u
else
Vu = V*u;
trV = trace(V);
trRVRV = (norm(V,'fro'))^2;
clear V;
trRVRV = trRVRV - 2*(norm(Vu,'fro'))^2;
trRVRV = trRVRV + (norm(u'*Vu,'fro'))^2;
trMV = sum(sum( u .* Vu ));
clear u Vu
end
varargout = {(trV - trMV), trRVRV};
end
else %- nargin == 2 | isempty(varargin{3})
if nargout==1
if rk==0 || isempty(rk), varargout = {sL};
else varargout = {sL - rk};
end
else
if rk==0 || isempty(rk), varargout = {sL,sL};
else varargout = {sL - rk, sL - rk};
end
end
end
end
case 'trmv' %-Traces for (effective) Fdf calculation
%=======================================================================
% [trMV, trMVMV]] = spm_SpUtil('trMV',sX [,V])
%
% NB : When V is given empty, the routine asssumes it's identity
% This is used in spm_FcUtil.
if nargin == 1, error('insufficient arguments');
else sX = varargin{2}; end;
if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;
rk = spm_sp('rk',sX);
if isempty(rk)
warning('Rank is empty');
if nargout==1, varargout = {[]};
else varargout = {[], []}; end
return;
elseif rk==0, warning('Rank is null in spm_SpUtil trMV ');
if nargout==1, varargout = {0};
else varargout = {0, 0}; end
return;
end;
if nargin > 2 && ~isempty(varargin{3}) %- V provided, and assumed correct !
V = varargin{3};
u = sX.u(:,1:rk);
clear sX;
if nargout==1
%-only trMV needed
trMV = sum(sum(u' .* (u'*V) ));
varargout = {trMV};
else
%-trMVMV is needed as well
Vu = V*u;
clear V
trMV = sum(sum( u .* Vu ));
trMVMV = (norm(u'*Vu,'fro'))^2;
clear u Vu
varargout = {trMV, trMVMV};
end
else % nargin == 2 | isempty(varargin{3}) %-no V specified: trMV == trMVMV
if nargout==1
varargout = {rk};
else
varargout = {rk, rk};
end
end
case {'i0->edf','edf'} %-Effective F degrees of freedom
%=======================================================================
% [df1,df2] = spm_SpUtil('i0->edf',sX,i0,V)
%-----------------------------------------------------------------------
%--------- begin argument check ----------------------------------------
if nargin<3, error('insufficient arguments'),
else i0 = varargin{3}; sX = varargin{2}; end
if ~spm_sp('isspc',sX), sX = spm_sp('Set',sX); end;
i0 = sf_check_i0(i0,spm_sp('size',sX,2));
if nargin == 4, V=varargin{4}; else V = eye(spm_sp('size',sX,1)); end;
if nargin>4, error('Too many input arguments'), end;
%--------- end argument check ------------------------------------------
warning(' Use F-contrast utilities if possible ... ');
[trRV,trRVRV] = spm_SpUtil('trRV', sX, V);
[trMpV,trMpVMpV] = spm_SpUtil('trMV',spm_SpUtil('i0->x1o',sX, i0),V);
varargout = {trMpV^2/trMpVMpV, trRV^2/trRVRV};
%=======================================================================
%=======================================================================
% Utilities
%=======================================================================
%=======================================================================
case 'size' %-Size of design matrix
%=======================================================================
% sz = spm_SpUtil('size',x,dim)
if nargin<3, dim=[]; else dim = varargin{3}; end
if nargin<2, error('insufficient arguments'), end
if isstruct(varargin{2})
if isfield(varargin{2},'X')
sz = size(varargin{2}.X);
else error('no X field'); end;
else
sz = size(varargin{2});
end
if ~isempty(dim)
if dim>length(sz), sz = 1; else sz = sz(dim); end
varargout = {sz};
elseif nargout>1
varargout = cell(1,min(nargout,length(sz)));
for i=1:min(nargout,length(sz)), varargout{i} = sz(i); end
else
varargout = {sz};
end
case 'ix0check' %-
%=======================================================================
% i0c = spm_SpUtil('iX0check',i0,sL)
if nargin<3, error('insufficient arguments'),
else i0 = varargin{2}; sL = varargin{3}; end;
varargout = {sf_check_i0(i0,sL)};
otherwise
%=======================================================================
error('Unknown action string in spm_SpUtil')
%=======================================================================
end
%=======================================================================
function i0c = sf_check_i0(i0,sL)
% NB : [] = sf_check_i0([],SL);
%
if all(ismember(i0,[0,1])) && length(i0(:))==sL, i0c=find(i0);
elseif ~isempty(i0) && any(floor(i0)~=i0) || any(i0<1) || any(i0>sL)
error('logical mask or vector of column indices required')
else i0c = i0; end
%=======================================================================
function c = sf_X0_2_c(X0,sX)
%
%- Algorithm to avoids the pinv(X0) and insure consistency
%- Get a contrast that span the space of X0 and is estimable
%- Get the orthogonal complement and project onto the estimable space
%- Strip zeros columns and use the rotation making X1o orthog. to X0
% !!! tolerance dealing ?
if ~isempty(X0)
sc0 = spm_sp('set',spm_sp('x-',sX,X0));
if sc0.rk
c = spm_sp('oPp:',sX,spm_sp('r',sc0));
else
c = spm_sp('oPp',sX);
end;
c = c(:,any(c));
sL = spm_sp('size',sX,2);
%- why the "& size(X0,2) ~= sL" !!!?
if isempty(c) && size(X0,2) ~= sL
c = zeros(sL,1);
end
else
c = spm_sp('xpx',sX);
end
%- c = spm_sp('r',sc0,spm_sp('oxp',sX)); would also works.
|
github
|
philippboehmsturm/antx-master
|
spm_dicom_convert.m
|
.m
|
antx-master/xspm8/spm_dicom_convert.m
| 45,741 |
utf_8
|
3053cf7d299fcdf734d63ad35fd14602
|
function out = spm_dicom_convert(hdr,opts,root_dir,format)
% Convert DICOM images into something that SPM can use
% FORMAT spm_dicom_convert(hdr,opts,root_dir,format)
% Inputs:
% hdr - a cell array of DICOM headers from spm_dicom_headers
% opts - options
% 'all' - all DICOM files [default]
% 'mosaic' - the mosaic images
% 'standard' - standard DICOM files
% 'spect' - SIEMENS Spectroscopy DICOMs (some formats only)
% This will write out a 5D NIFTI containing real and
% imaginary part of the spectroscopy time points at the
% position of spectroscopy voxel(s).
% 'raw' - convert raw FIDs (not implemented)
% root_dir - 'flat' - do not produce file tree [default]
% With all other options, files will be sorted into
% directories according to their sequence/protocol names
% 'date_time' - Place files under ./<StudyDate-StudyTime>
% 'patid' - Place files under ./<PatID>
% 'patid_date' - Place files under ./<PatID-StudyDate>
% 'patname' - Place files under ./<PatName>
% 'series' - Place files in series folders, without
% creating patient folders
% format - output format
% 'img' Two file (hdr+img) NIfTI format [default]
% 'nii' Single file NIfTI format
% All images will contain a single 3D dataset, 4D images
% will not be created.
% Output:
% out - a struct with a single field .files. out.files contains a
% cellstring with filenames of created files. If no files are
% created, a cell with an empty string {''} is returned.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner & Jesper Andersson
% $Id: spm_dicom_convert.m 4368 2011-06-20 11:59:54Z john $
if nargin<2, opts = 'all'; end
if nargin<3, root_dir = 'flat';end
if nargin<4, format = 'img'; end
[images,other] = select_tomographic_images(hdr);
[spect,guff] = select_spectroscopy_images(other);
[mosaic,standard] = select_mosaic_images(images);
fmos = {};
fstd = {};
fspe = {};
if (strcmp(opts,'all') || strcmp(opts,'mosaic')) && ~isempty(mosaic),
fmos = convert_mosaic(mosaic,root_dir,format);
end;
if (strcmp(opts,'all') || strcmp(opts,'standard')) && ~isempty(standard),
fstd = convert_standard(standard,root_dir,format);
end;
if (strcmp(opts,'all') || strcmp(opts,'spect')) && ~isempty(spect),
fspe = convert_spectroscopy(spect,root_dir,format);
end;
out.files = [fmos(:); fstd(:); fspe(:)];
if isempty(out.files)
out.files = {''};
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fnames = convert_mosaic(hdr,root_dir,format)
spm_progress_bar('Init',length(hdr),'Writing Mosaic', 'Files written');
fnames = cell(length(hdr),1);
for i=1:length(hdr),
% Output filename
%-------------------------------------------------------------------
fnames{i} = getfilelocation(hdr{i},root_dir,'f',format);
% Image dimensions and data
%-------------------------------------------------------------------
nc = hdr{i}.Columns;
nr = hdr{i}.Rows;
dim = [0 0 0];
dim(3) = read_NumberOfImagesInMosaic(hdr{i});
np = [nc nr]/ceil(sqrt(dim(3)));
dim(1:2) = np;
if ~all(np==floor(np)),
warning('%s: dimension problem [Num Images=%d, Num Cols=%d, Num Rows=%d].',...
hdr{i}.Filename,dim(3), nc,nr);
continue;
end;
% Apparently, this is not the right way of doing it.
%np = read_AcquisitionMatrixText(hdr{i});
%if rem(nc, np(1)) || rem(nr, np(2)),
% warning('%s: %dx%d wont fit into %dx%d.',hdr{i}.Filename,...
% np(1), np(2), nc,nr);
% return;
%end;
%dim = [np read_NumberOfImagesInMosaic(hdr{i})];
mosaic = read_image_data(hdr{i});
volume = zeros(dim);
for j=1:dim(3),
img = mosaic((1:np(1))+np(1)*rem(j-1,nc/np(1)), (np(2):-1:1)+np(2)*floor((j-1)/(nc/np(1))));
if ~any(img(:)),
volume = volume(:,:,1:(j-1));
break;
end;
volume(:,:,j) = img;
end;
dim = size(volume);
dt = determine_datatype(hdr{1});
% Orientation information
%-------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
analyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)-1) 0]'; 0 0 0 1]*[eye(4,3) [-1 -1 -1 1]'];
vox = [hdr{i}.PixelSpacing(:); hdr{i}.SpacingBetweenSlices];
pos = hdr{i}.ImagePositionPatient(:);
orient = reshape(hdr{i}.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
% The image position vector is not correct. In dicom this vector points to
% the upper left corner of the image. Perhaps it is unlucky that this is
% calculated in the syngo software from the vector pointing to the center of
% the slice (keep in mind: upper left slice) with the enlarged FoV.
dicom_to_patient = [orient*diag(vox) pos ; 0 0 0 1];
truepos = dicom_to_patient *[(size(mosaic)-dim(1:2))/2 0 1]';
dicom_to_patient = [orient*diag(vox) truepos(1:3) ; 0 0 0 1];
patient_to_tal = diag([-1 -1 1 1]);
mat = patient_to_tal*dicom_to_patient*analyze_to_dicom;
% Maybe flip the image depending on SliceNormalVector from 0029,1010
%-------------------------------------------------------------------
SliceNormalVector = read_SliceNormalVector(hdr{i});
if det([reshape(hdr{i}.ImageOrientationPatient,[3 2]) SliceNormalVector(:)])<0;
volume = volume(:,:,end:-1:1);
mat = mat*[eye(3) [0 0 -(dim(3)-1)]'; 0 0 0 1];
end;
% Possibly useful information
%-------------------------------------------------------------------
tim = datevec(hdr{i}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g Mosaic',...
hdr{i}.MagneticFieldStrength, hdr{i}.MRAcquisitionType,...
deblank(hdr{i}.ScanningSequence),...
hdr{i}.RepetitionTime,hdr{i}.EchoTime,hdr{i}.FlipAngle,...
datestr(hdr{i}.AcquisitionDate),tim(4),tim(5),tim(6));
% descrip = [deblank(descrip) ' ' hdr{i}.PatientsName];
if ~true, % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
volume = flipdim(volume,1);
end;
%if isfield(hdr{i},'RescaleSlope') && hdr{i}.RescaleSlope ~= 1,
% volume = volume*hdr{i}.RescaleSlope;
%end;
%if isfield(hdr{i},'RescaleIntercept') && hdr{i}.RescaleIntercept ~= 0,
% volume = volume + hdr{i}.RescaleIntercept;
%end;
%V = struct('fname',fname, 'dim',dim, 'dt',dt, 'mat',mat, 'descrip',descrip);
%spm_write_vol(V,volume);
% Note that data are no longer scaled by the maximum amount.
% This may lead to rounding errors in smoothed data, but it
% will get around other problems.
RescaleSlope = 1;
RescaleIntercept = 0;
if isfield(hdr{i},'RescaleSlope') && hdr{i}.RescaleSlope ~= 1,
RescaleSlope = hdr{i}.RescaleSlope;
end;
if isfield(hdr{i},'RescaleIntercept') && hdr{i}.RescaleIntercept ~= 0,
RescaleIntercept = hdr{i}.RescaleIntercept;
end;
N = nifti;
N.dat = file_array(fnames{i},dim,dt,0,RescaleSlope,RescaleIntercept);
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Scanner';
N.mat0_intent = 'Scanner';
N.descrip = descrip;
create(N);
% Write the data unscaled
dat = N.dat;
dat.scl_slope = [];
dat.scl_inter = [];
% write out volume at once - see spm_write_plane.m for performance comments
dat(:,:,:) = volume;
spm_progress_bar('Set',i);
end;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fnames = convert_standard(hdr,root_dir,format)
hdr = sort_into_volumes(hdr);
fnames = cell(length(hdr),1);
for i=1:length(hdr),
fnames{i} = write_volume(hdr{i},root_dir,format);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vol = sort_into_volumes(hdr)
%
% First of all, sort into volumes based on relevant
% fields in the header.
%
vol{1}{1} = hdr{1};
for i=2:length(hdr),
%orient = reshape(hdr{i}.ImageOrientationPatient,[3 2]);
%xy1 = hdr{i}.ImagePositionPatient(:)*orient;
match = 0;
if isfield(hdr{i},'CSAImageHeaderInfo') && isfield(hdr{i}.CSAImageHeaderInfo,'name')
ice1 = sscanf( ...
strrep(get_numaris4_val(hdr{i}.CSAImageHeaderInfo,'ICE_Dims'), ...
'X', '-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';
dimsel = logical([1 1 1 1 1 1 0 0 1]);
else
ice1 = [];
end;
for j=1:length(vol),
%orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);
%xy2 = vol{j}{1}.ImagePositionPatient(:)*orient;
% This line is a fudge because of some problematic data that Bogdan,
% Cynthia and Stefan were trying to convert. I hope it won't cause
% problems for others -JA
% dist2 = sum((xy1-xy2).^2);
dist2 = 0;
if strcmp(hdr{i}.Modality,'CT') && ...
strcmp(vol{j}{1}.Modality,'CT') % Our CT seems to have shears in slice positions
dist2 = 0;
end;
if ~isempty(ice1) && isfield(vol{j}{1},'CSAImageHeaderInfo') && isfield(vol{j}{1}.CSAImageHeaderInfo(1),'name')
% Replace 'X' in ICE_Dims by '-1'
ice2 = sscanf( ...
strrep(get_numaris4_val(vol{j}{1}.CSAImageHeaderInfo,'ICE_Dims'), ...
'X', '-1'), '%i_%i_%i_%i_%i_%i_%i_%i_%i')';
if ~isempty(ice2)
identical_ice_dims=all(ice1(dimsel)==ice2(dimsel));
else
identical_ice_dims = 0; % have ice1 but not ice2, ->
% something must be different
end,
else
identical_ice_dims = 1; % No way of knowing if there is no CSAImageHeaderInfo
end;
try
match = hdr{i}.SeriesNumber == vol{j}{1}.SeriesNumber &&...
hdr{i}.Rows == vol{j}{1}.Rows &&...
hdr{i}.Columns == vol{j}{1}.Columns &&...
sum((hdr{i}.ImageOrientationPatient - vol{j}{1}.ImageOrientationPatient).^2)<1e-4 &&...
sum((hdr{i}.PixelSpacing - vol{j}{1}.PixelSpacing).^2)<1e-4 && ...
identical_ice_dims && dist2<1e-3;
%if (hdr{i}.AcquisitionNumber ~= hdr{i}.InstanceNumber) || ...
% (vol{j}{1}.AcquisitionNumber ~= vol{j}{1}.InstanceNumber)
% match = match && (hdr{i}.AcquisitionNumber == vol{j}{1}.AcquisitionNumber)
%end;
% For raw image data, tell apart real/complex or phase/magnitude
if isfield(hdr{i},'ImageType') && isfield(vol{j}{1}, 'ImageType')
match = match && strcmp(hdr{i}.ImageType, vol{j}{1}.ImageType);
end;
if isfield(hdr{i},'SequenceName') && isfield(vol{j}{1}, 'SequenceName')
match = match && strcmp(hdr{i}.SequenceName,vol{j}{1}.SequenceName);
end;
if isfield(hdr{i},'SeriesInstanceUID') && isfield(vol{j}{1}, 'SeriesInstanceUID')
match = match && strcmp(hdr{i}.SeriesInstanceUID,vol{j}{1}.SeriesInstanceUID);
end;
if isfield(hdr{i},'EchoNumbers') && isfield(vol{j}{1}, 'EchoNumbers')
match = match && hdr{i}.EchoNumbers == vol{j}{1}.EchoNumbers;
end;
catch
match = 0;
end
if match
vol{j}{end+1} = hdr{i};
break;
end;
end;
if ~match,
vol{end+1}{1} = hdr{i};
end;
end;
%dcm = vol;
%save('dicom_headers.mat','dcm');
%
% Secondly, sort volumes into ascending/descending
% slices depending on .ImageOrientationPatient field.
%
vol2 = {};
for j=1:length(vol),
orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end;
z = zeros(length(vol{j}),1);
for i=1:length(vol{j}),
z(i) = vol{j}{i}.ImagePositionPatient(:)'*proj;
end;
[z,index] = sort(z);
vol{j} = vol{j}(index);
if length(vol{j})>1,
% dist = diff(z);
if any(diff(z)==0)
tmp = sort_into_vols_again(vol{j});
vol{j} = tmp{1};
vol2 = {vol2{:} tmp{2:end}};
end;
end;
end;
vol = {vol{:} vol2{:}};
for j=1:length(vol),
if length(vol{j})>1,
orient = reshape(vol{j}{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end;
z = zeros(length(vol{j}),1);
for i=1:length(vol{j}),
z(i) = vol{j}{i}.ImagePositionPatient(:)'*proj;
end;
dist = diff(sort(z));
if sum((dist-mean(dist)).^2)/length(dist)>1e-4,
fprintf('***************************************************\n');
fprintf('* VARIABLE SLICE SPACING *\n');
fprintf('* This may be due to missing DICOM files. *\n');
if checkfields(vol{j}{1},'PatientID','SeriesNumber','AcquisitionNumber','InstanceNumber'),
fprintf('* %s / %d / %d / %d \n',...
deblank(vol{j}{1}.PatientID), vol{j}{1}.SeriesNumber, ...
vol{j}{1}.AcquisitionNumber, vol{j}{1}.InstanceNumber);
fprintf('* *\n');
end;
fprintf('* %20.4g *\n', dist);
fprintf('***************************************************\n');
end;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function vol2 = sort_into_vols_again(volj)
if ~isfield(volj{1},'InstanceNumber'),
fprintf('***************************************************\n');
fprintf('* The slices may be all mixed up and the data *\n');
fprintf('* not really usable. Talk to your physicists *\n');
fprintf('* about this. *\n');
fprintf('***************************************************\n');
vol2 = {volj};
return;
end;
fprintf('***************************************************\n');
fprintf('* The AcquisitionNumber counter does not appear *\n');
fprintf('* to be changing from one volume to another. *\n');
fprintf('* Another possible explanation is that the same *\n');
fprintf('* DICOM slices are used multiple times. *\n');
%fprintf('* Talk to your MR sequence developers or scanner *\n');
%fprintf('* supplier to have this fixed. *\n');
fprintf('* The conversion is having to guess how slices *\n');
fprintf('* should be arranged into volumes. *\n');
if checkfields(volj{1},'PatientID','SeriesNumber','AcquisitionNumber'),
fprintf('* %s / %d / %d\n',...
deblank(volj{1}.PatientID), volj{1}.SeriesNumber, ...
volj{1}.AcquisitionNumber);
end;
fprintf('***************************************************\n');
z = zeros(length(volj),1);
t = zeros(length(volj),1);
d = zeros(length(volj),1);
orient = reshape(volj{1}.ImageOrientationPatient,[3 2]);
proj = null(orient');
if det([orient proj])<0, proj = -proj; end;
for i=1:length(volj),
z(i) = volj{i}.ImagePositionPatient(:)'*proj;
t(i) = volj{i}.InstanceNumber;
end;
% msg = 0;
[t,index] = sort(t);
volj = volj(index);
z = z(index);
msk = find(diff(t)==0);
if any(msk),
% fprintf('***************************************************\n');
% fprintf('* These files have the same InstanceNumber: *\n');
% for i=1:length(msk),
% [tmp,nam1,ext1] = fileparts(volj{msk(i)}.Filename);
% [tmp,nam2,ext2] = fileparts(volj{msk(i)+1}.Filename);
% fprintf('* %s%s = %s%s (%d)\n', nam1,ext1,nam2,ext2, volj{msk(i)}.InstanceNumber);
% end;
% fprintf('***************************************************\n');
index = [true ; diff(t)~=0];
t = t(index);
z = z(index);
d = d(index);
volj = volj(index);
end;
%if any(diff(sort(t))~=1), msg = 1; end;
[z,index] = sort(z);
volj = volj(index);
t = t(index);
vol2 = {};
while ~all(d),
i = find(~d);
i = i(1);
i = find(z==z(i));
[t(i),si] = sort(t(i));
volj(i) = volj(i(si));
for i1=1:length(i),
if length(vol2)<i1, vol2{i1} = {}; end;
vol2{i1} = {vol2{i1}{:} volj{i(i1)}};
end;
d(i) = 1;
end;
msg = 0;
if any(diff(sort(t))~=1), msg = 1; end;
if ~msg,
len = length(vol2{1});
for i=2:length(vol2),
if length(vol2{i}) ~= len,
msg = 1;
break;
end;
end;
end;
if msg,
fprintf('***************************************************\n');
fprintf('* There are missing DICOM files, so the the *\n');
fprintf('* resulting volumes may be messed up. *\n');
if checkfields(volj{1},'PatientID','SeriesNumber','AcquisitionNumber'),
fprintf('* %s / %d / %d\n',...
deblank(volj{1}.PatientID), volj{1}.SeriesNumber, ...
volj{1}.AcquisitionNumber);
end;
fprintf('***************************************************\n');
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fname = write_volume(hdr,root_dir,format)
% Output filename
%-------------------------------------------------------------------
fname = getfilelocation(hdr{1}, root_dir,'s',format);
% Image dimensions
%-------------------------------------------------------------------
nc = hdr{1}.Columns;
nr = hdr{1}.Rows;
dim = [nc nr length(hdr)];
dt = determine_datatype(hdr{1});
% Orientation information
%-------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
analyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]; % Flip voxels in y
patient_to_tal = diag([-1 -1 1 1]); % Flip mm coords in x and y directions
R = [reshape(hdr{1}.ImageOrientationPatient,3,2)*diag(hdr{1}.PixelSpacing); 0 0];
x1 = [1;1;1;1];
y1 = [hdr{1}.ImagePositionPatient(:); 1];
if length(hdr)>1,
x2 = [1;1;dim(3); 1];
y2 = [hdr{end}.ImagePositionPatient(:); 1];
else
orient = reshape(hdr{1}.ImageOrientationPatient,[3 2]);
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
if checkfields(hdr{1},'SliceThickness'),
z = hdr{1}.SliceThickness;
else
z = 1;
end
x2 = [0;0;1;0];
y2 = [orient*[0;0;z];0];
end
dicom_to_patient = [y1 y2 R]/[x1 x2 eye(4,2)];
mat = patient_to_tal*dicom_to_patient*analyze_to_dicom;
% Possibly useful information
%-------------------------------------------------------------------
if checkfields(hdr{1},'AcquisitionTime','MagneticFieldStrength','MRAcquisitionType',...
'ScanningSequence','RepetitionTime','EchoTime','FlipAngle',...
'AcquisitionDate'),
if isfield(hdr{1},'ScanOptions'),
ScanOptions = hdr{1}.ScanOptions;
else
ScanOptions = 'no';
end
tim = datevec(hdr{1}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg/SO=%s %s %d:%d:%.5g',...
hdr{1}.MagneticFieldStrength, hdr{1}.MRAcquisitionType,...
deblank(hdr{1}.ScanningSequence),...
hdr{1}.RepetitionTime,hdr{1}.EchoTime,hdr{1}.FlipAngle,...
ScanOptions,...
datestr(hdr{1}.AcquisitionDate),tim(4),tim(5),tim(6));
else
descrip = hdr{1}.Modality;
end;
if ~true, % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
end;
% Write the image volume
%-------------------------------------------------------------------
spm_progress_bar('Init',length(hdr),['Writing ' fname], 'Planes written');
N = nifti;
pinfos = [ones(length(hdr),1) zeros(length(hdr),1)];
for i=1:length(hdr)
if isfield(hdr{i},'RescaleSlope'), pinfos(i,1) = hdr{i}.RescaleSlope; end
if isfield(hdr{i},'RescaleIntercept'), pinfos(i,2) = hdr{i}.RescaleIntercept; end
end
if any(any(diff(pinfos,1))),
% Ensure random numbers are reproducible (see later)
% when intensities are dithered to prevent aliasing effects.
rand('state',0);
end
volume = zeros(dim);
for i=1:length(hdr),
plane = read_image_data(hdr{i});
if any(any(diff(pinfos,1))),
% This is to prevent aliasing effects in any subsequent histograms
% of the data (eg for mutual information coregistration).
% It's a bit inelegant, but probably necessary for when slices are
% individually rescaled.
plane = double(plane) + rand(size(plane)) - 0.5;
end
if pinfos(i,1)~=1, plane = plane*pinfos(i,1); end;
if pinfos(i,2)~=0, plane = plane+pinfos(i,2); end;
plane = fliplr(plane);
if ~true, plane = flipud(plane); end; % LEFT-HANDED STORAGE
volume(:,:,i) = plane;
spm_progress_bar('Set',i);
end;
if ~any(any(diff(pinfos,1))),
% Same slopes and intercepts for all slices
pinfo = pinfos(1,:);
else
% Variable slopes and intercept (maybe PET/SPECT)
mx = max(volume(:));
mn = min(volume(:));
%% Slope and Intercept
%% 32767*pinfo(1) + pinfo(2) = mx
%% -32768*pinfo(1) + pinfo(2) = mn
% pinfo = ([32767 1; -32768 1]\[mx; mn])';
% Slope only
dt = 'int16-be';
pinfo = [max(mx/32767,-mn/32768) 0];
end
N.dat = file_array(fname,dim,dt,0,pinfo(1),pinfo(2));
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Scanner';
N.mat0_intent = 'Scanner';
N.descrip = descrip;
create(N);
N.dat(:,:,:) = volume;
spm_progress_bar('Clear');
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fnames = convert_spectroscopy(hdr,root_dir,format)
fnames = cell(length(hdr),1);
for i=1:length(hdr),
fnames{i} = write_spectroscopy_volume(hdr(i),root_dir,format);
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fname = write_spectroscopy_volume(hdr,root_dir,format)
% Output filename
%-------------------------------------------------------------------
fname = getfilelocation(hdr{1}, root_dir,'S',format);
% guess private field to use
if isfield(hdr{1}, 'Private_0029_1210')
privdat = hdr{1}.Private_0029_1210;
elseif isfield(hdr{1}, 'Private_0029_1110')
privdat = hdr{1}.Private_0029_1110;
else
disp('Don''t know how to handle these spectroscopy data');
fname = '';
return;
end
% Image dimensions
%-------------------------------------------------------------------
nc = get_numaris4_numval(privdat,'Columns');
nr = get_numaris4_numval(privdat,'Rows');
% Guess number of timepoints in file - don't know whether this should be
% 'DataPointRows'-by-'DataPointColumns' or 'SpectroscopyAcquisitionDataColumns'
ntp = get_numaris4_numval(privdat,'DataPointRows')*get_numaris4_numval(privdat,'DataPointColumns');
dim = [nc nr numel(hdr) 2 ntp];
dt = spm_type('float32'); % Fixed datatype
% Orientation information
%-------------------------------------------------------------------
% Axial Analyze voxel co-ordinate system:
% x increases right to left
% y increases posterior to anterior
% z increases inferior to superior
% DICOM patient co-ordinate system:
% x increases right to left
% y increases anterior to posterior
% z increases inferior to superior
% T&T co-ordinate system:
% x increases left to right
% y increases posterior to anterior
% z increases inferior to superior
analyze_to_dicom = [diag([1 -1 1]) [0 (dim(2)+1) 0]'; 0 0 0 1]; % Flip voxels in y
patient_to_tal = diag([-1 -1 1 1]); % Flip mm coords in x and y directions
shift_vx = [eye(4,3) [.5; .5; 0; 1]];
orient = reshape(get_numaris4_numval(privdat,...
'ImageOrientationPatient'),[3 2]);
ps = get_numaris4_numval(privdat,'PixelSpacing');
if nc*nr == 1
% Single Voxel Spectroscopy (based on the following information from SIEMENS)
%---------------------------------------------------------------
% NOTE: Internally the position vector of the CSI matrix shows to the outer border
% of the first voxel. Therefore the position vector has to be corrected.
% (Note: The convention of Siemens spectroscopy raw data is in contrast to the
% DICOM standard where the position vector points to the center of the first voxel.)
%---------------------------------------------------------------
% SIEMENS decides which definition to use based on the contents of the
% 'PixelSpacing' internal header field. If it has non-zero values,
% assume DICOM convention. If any value is zero, assume SIEMENS
% internal convention for this direction.
% Note that in SIEMENS code, there is a shift when PixelSpacing is
% zero. Here, the shift seems to be necessary when PixelSpacing is
% non-zero. This may indicate more fundamental problems with
% orientation decoding.
if ps(1) == 0 % row
ps(1) = get_numaris4_numval(privdat,...
'VoiPhaseFoV');
shift_vx(1,4) = 0;
end
if ps(2) == 0 % col
ps(2) = get_numaris4_numval(privdat,...
'VoiReadoutFoV');
shift_vx(2,4) = 0;
end
end
pos = get_numaris4_numval(privdat,'ImagePositionPatient');
% for some reason, pixel spacing needs to be swapped
R = [orient*diag(ps([2 1])); 0 0];
x1 = [1;1;1;1];
y1 = [pos; 1];
if length(hdr)>1,
error('spm_dicom_convert:spectroscopy',...
'Don''t know how to handle multislice spectroscopy data.');
else
orient(:,3) = null(orient');
if det(orient)<0, orient(:,3) = -orient(:,3); end;
try
z = get_numaris4_numval(privdat,...
'VoiThickness');
catch
try
z = get_numaris4_numval(privdat,...
'SliceThickness');
catch
z = 1;
end
end;
x2 = [0;0;1;0];
y2 = [orient*[0;0;z];0];
end
dicom_to_patient = [y1 y2 R]/[x1 x2 eye(4,2)];
mat = patient_to_tal*dicom_to_patient*shift_vx*analyze_to_dicom;
% Possibly useful information
%-------------------------------------------------------------------
if checkfields(hdr{1},'AcquisitionTime','MagneticFieldStrength','MRAcquisitionType',...
'ScanningSequence','RepetitionTime','EchoTime','FlipAngle',...
'AcquisitionDate'),
tim = datevec(hdr{1}.AcquisitionTime/(24*60*60));
descrip = sprintf('%gT %s %s TR=%gms/TE=%gms/FA=%gdeg %s %d:%d:%.5g',...
hdr{1}.MagneticFieldStrength, hdr{1}.MRAcquisitionType,...
deblank(hdr{1}.ScanningSequence),...
hdr{1}.RepetitionTime,hdr{1}.EchoTime,hdr{1}.FlipAngle,...
datestr(hdr{1}.AcquisitionDate),tim(4),tim(5),tim(6));
else
descrip = hdr{1}.Modality;
end;
if ~true, % LEFT-HANDED STORAGE
mat = mat*[-1 0 0 (dim(1)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1];
end;
% Write the image volume
%-------------------------------------------------------------------
N = nifti;
pinfo = [1 0];
if isfield(hdr{1},'RescaleSlope'), pinfo(1) = hdr{1}.RescaleSlope; end;
if isfield(hdr{1},'RescaleIntercept'), pinfo(2) = hdr{1}.RescaleIntercept; end;
N.dat = file_array(fname,dim,dt,0,pinfo(1),pinfo(2));
N.mat = mat;
N.mat0 = mat;
N.mat_intent = 'Scanner';
N.mat0_intent = 'Scanner';
N.descrip = descrip;
N.extras = struct('MagneticFieldStrength',...
get_numaris4_numval(privdat,'MagneticFieldStrength'),...
'TransmitterReferenceAmplitude',...
get_numaris4_numval(privdat,'TransmitterReferenceAmplitude'));
create(N);
% Read data, swap dimensions
data = permute(reshape(read_spect_data(hdr{1},privdat),dim([4 5 1 2 3])), ...
[3 4 5 1 2]);
% plane = fliplr(plane);
N.dat(:,:,:,:,:) = data;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [images,guff] = select_tomographic_images(hdr)
images = {};
guff = {};
for i=1:length(hdr),
if ~checkfields(hdr{i},'Modality') || ~(strcmp(hdr{i}.Modality,'MR') ||...
strcmp(hdr{i}.Modality,'PT') || strcmp(hdr{i}.Modality,'CT'))
if checkfields(hdr{i},'Modality'),
fprintf('File "%s" can not be converted because it is of type "%s", which is not MRI, CT or PET.\n', hdr{i}.Filename, hdr{i}.Modality);
else
fprintf('File "%s" can not be converted because it does not encode an image.\n', hdr{i}.Filename);
end
guff = [guff(:)',hdr(i)];
elseif ~checkfields(hdr{i},'StartOfPixelData','SamplesperPixel',...
'Rows','Columns','BitsAllocated','BitsStored','HighBit','PixelRepresentation'),
disp(['Cant find "Image Pixel" information for "' hdr{i}.Filename '".']);
guff = [guff(:)',hdr(i)];
%elseif isfield(hdr{i},'Private_2001_105f'),
% % This field corresponds to: > Stack Sequence 2001,105F SQ VNAP, COPY
% % http://www.medical.philips.com/main/company/connectivity/mri/index.html
% % No documentation about this private field is yet available.
% disp('Cant yet convert Phillips Intera DICOM.');
% guff = {guff{:},hdr{i}};
elseif ~(checkfields(hdr{i},'PixelSpacing','ImagePositionPatient','ImageOrientationPatient')||isfield(hdr{i},'Private_0029_1110')||isfield(hdr{i},'Private_0029_1210')),
disp(['Cant find "Image Plane" information for "' hdr{i}.Filename '".']);
guff = [guff(:)',hdr(i)];
elseif ~checkfields(hdr{i},'PatientID','SeriesNumber','AcquisitionNumber','InstanceNumber'),
%disp(['Cant find suitable filename info for "' hdr{i}.Filename '".']);
if ~isfield(hdr{i},'SeriesNumber')
disp('Setting SeriesNumber to 1');
hdr{i}.SeriesNumber=1;
images = [images(:)',hdr(i)];
end;
if ~isfield(hdr{i},'AcquisitionNumber')
if isfield(hdr{i},'Manufacturer') && ~isempty(strfind(upper(hdr{1}.Manufacturer), 'PHILIPS'))
% WHY DO PHILIPS DO THINGS LIKE THIS????
if isfield(hdr{i},'InstanceNumber')
hdr{i}.AcquisitionNumber = hdr{i}.InstanceNumber;
else
disp('Setting AcquisitionNumber to 1');
hdr{i}.AcquisitionNumber=1;
end
else
disp('Setting AcquisitionNumber to 1');
hdr{i}.AcquisitionNumber=1;
end
images = [images(:)',hdr(i)];
end;
if ~isfield(hdr{i},'InstanceNumber')
disp('Setting InstanceNumber to 1');
hdr{i}.InstanceNumber=1;
images = [images(:)',hdr(i)];
end;
else
images = [images(:)',hdr(i)];
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [mosaic,standard] = select_mosaic_images(hdr)
mosaic = {};
standard = {};
for i=1:length(hdr),
if ~checkfields(hdr{i},'ImageType','CSAImageHeaderInfo') ||...
isfield(hdr{i}.CSAImageHeaderInfo,'junk') ||...
isempty(read_AcquisitionMatrixText(hdr{i})) ||...
isempty(read_NumberOfImagesInMosaic(hdr{i})) ||...
read_NumberOfImagesInMosaic(hdr{i}) == 0
% NumberOfImagesInMosaic seems to be set to zero for pseudo images
% containing e.g. online-fMRI design matrices, don't treat them as
% mosaics
standard = {standard{:}, hdr{i}};
else
mosaic = {mosaic{:},hdr{i}};
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [spect,images] = select_spectroscopy_images(hdr)
spectsel = zeros(1,numel(hdr));
for i=1:length(hdr),
if isfield(hdr{i},'SOPClassUID')
spectsel(i) = strcmp(hdr{i}.SOPClassUID,'1.3.12.2.1107.5.9.1');
end;
end;
spect = hdr(logical(spectsel));
images = hdr(~logical(spectsel));
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ok = checkfields(hdr,varargin)
ok = 1;
for i=1:(nargin-1),
if ~isfield(hdr,varargin{i}),
ok = 0;
break;
end;
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function clean = strip_unwanted(dirty)
msk = (dirty>='a'&dirty<='z') | (dirty>='A'&dirty<='Z') |...
(dirty>='0'&dirty<='9') | dirty=='_';
clean = dirty(msk);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function img = read_image_data(hdr)
img = [];
if hdr.SamplesperPixel ~= 1,
warning([hdr.Filename ': SamplesperPixel = ' num2str(hdr.SamplesperPixel) ' - cant be an MRI']);
return;
end;
prec = ['ubit' num2str(hdr.BitsAllocated) '=>' 'uint32'];
if isfield(hdr,'TransferSyntaxUID') && strcmp(hdr.TransferSyntaxUID,'1.2.840.10008.1.2.2') && strcmp(hdr.VROfPixelData,'OW'),
fp = fopen(hdr.Filename,'r','ieee-be');
else
fp = fopen(hdr.Filename,'r','ieee-le');
end;
if fp==-1,
warning([hdr.Filename ': cant open file']);
return;
end;
if isfield(hdr,'TransferSyntaxUID')
switch(hdr.TransferSyntaxUID)
case {'1.2.840.10008.1.2.4.50','1.2.840.10008.1.2.4.51','1.2.840.10008.1.2.4.70',...
'1.2.840.10008.1.2.4.80','1.2.840.10008.1.2.4.90','1.2.840.10008.1.2.4.91'},
% try to read PixelData as JPEG image - offset is just a guess
offset = 16;
fseek(fp,hdr.StartOfPixelData+offset,'bof');
img = fread(fp,Inf,'*uint8');
% save PixelData into temp file - imread and its subroutines can only
% read from file, not from memory
tfile = tempname;
tfp = fopen(tfile,'w+');
fwrite(tfp,img,'uint8');
fclose(tfp);
% read decompressed data, transpose to match DICOM row/column order
img = imread(tfile)';
delete(tfile);
otherwise
fseek(fp,hdr.StartOfPixelData,'bof');
img = fread(fp,hdr.Rows*hdr.Columns,prec);
end
else
fseek(fp,hdr.StartOfPixelData,'bof');
img = fread(fp,hdr.Rows*hdr.Columns,prec);
end
fclose(fp);
if numel(img)~=hdr.Rows*hdr.Columns,
error([hdr.Filename ': cant read whole image']);
end;
img = bitshift(img,hdr.BitsStored-hdr.HighBit-1);
if hdr.PixelRepresentation,
% Signed data - done this way because bitshift only
% works with signed data. Negative values are stored
% as 2s complement.
neg = logical(bitshift(bitand(img,uint32(2^hdr.HighBit)),-hdr.HighBit));
msk = (2^hdr.HighBit - 1);
img = double(bitand(img,msk));
img(neg) = img(neg)-2^(hdr.HighBit);
else
% Unsigned data
msk = (2^(hdr.HighBit+1) - 1);
img = double(bitand(img,msk));
end;
img = reshape(img,hdr.Columns,hdr.Rows);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function img = read_spect_data(hdr,privdat)
% Guess number of timepoints in file - don't know whether this should be
% 'DataPointRows'-by-'DataPointColumns' or 'SpectroscopyAcquisitionDataColumns'
ntp = get_numaris4_numval(privdat,'DataPointRows')*get_numaris4_numval(privdat,'DataPointColumns');
% Data is stored as complex float32 values, timepoint by timepoint, voxel
% by voxel. Reshaping is done in write_spectroscopy_volume.
if ntp*2*4 ~= hdr.SizeOfCSAData
warning([hdr.Filename,': Data size mismatch.']);
end
fp = fopen(hdr.Filename,'r','ieee-le');
fseek(fp,hdr.StartOfCSAData,'bof');
img = fread(fp,2*ntp,'float32');
fclose(fp);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function nrm = read_SliceNormalVector(hdr)
str = hdr.CSAImageHeaderInfo;
val = get_numaris4_val(str,'SliceNormalVector');
for i=1:3,
nrm(i,1) = sscanf(val(i,:),'%g');
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function n = read_NumberOfImagesInMosaic(hdr)
str = hdr.CSAImageHeaderInfo;
val = get_numaris4_val(str,'NumberOfImagesInMosaic');
n = sscanf(val','%d');
if isempty(n), n=[]; end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function dim = read_AcquisitionMatrixText(hdr)
str = hdr.CSAImageHeaderInfo;
val = get_numaris4_val(str,'AcquisitionMatrixText');
dim = sscanf(val','%d*%d')';
if length(dim)==1,
dim = sscanf(val','%dp*%d')';
end;
if isempty(dim), dim=[]; end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function val = get_numaris4_val(str,name)
name = deblank(name);
val = {};
for i=1:length(str),
if strcmp(deblank(str(i).name),name),
for j=1:str(i).nitems,
if str(i).item(j).xx(1),
val = {val{:} str(i).item(j).val};
end;
end;
break;
end;
end;
val = strvcat(val{:});
return;
%_______________________________________________________________________
%_______________________________________________________________________
function val = get_numaris4_numval(str,name)
val1 = get_numaris4_val(str,name);
val = zeros(size(val1,1),1);
for k = 1:size(val1,1)
val(k)=str2num(val1(k,:));
end;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function fname = getfilelocation(hdr,root_dir,prefix,format)
if nargin < 3
prefix = 'f';
end;
if strncmp(root_dir,'ice',3)
root_dir = root_dir(4:end);
imtype = textscan(hdr.ImageType,'%s','delimiter','\\');
try
imtype = imtype{1}{3};
catch
imtype = '';
end;
prefix = [prefix imtype get_numaris4_val(hdr.CSAImageHeaderInfo,'ICE_Dims')];
end;
if strcmp(root_dir, 'flat')
% Standard SPM file conversion
%-------------------------------------------------------------------
if checkfields(hdr,'SeriesNumber','AcquisitionNumber')
if checkfields(hdr,'EchoNumbers')
fname = sprintf('%s%s-%.4d-%.5d-%.6d-%.2d.%s', prefix, strip_unwanted(hdr.PatientID),...
hdr.SeriesNumber, hdr.AcquisitionNumber, hdr.InstanceNumber,...
hdr.EchoNumbers, format);
else
fname = sprintf('%s%s-%.4d-%.5d-%.6d.%s', prefix, strip_unwanted(hdr.PatientID),...
hdr.SeriesNumber, hdr.AcquisitionNumber, ...
hdr.InstanceNumber, format);
end;
else
fname = sprintf('%s%s-%.6d.%s',prefix, ...
strip_unwanted(hdr.PatientID),hdr.InstanceNumber, format);
end;
fname = fullfile(pwd,fname);
return;
end;
% more fancy stuff - sort images into subdirectories
if ~isfield(hdr,'ProtocolName')
if isfield(hdr,'SequenceName')
hdr.ProtocolName = hdr.SequenceName;
else
hdr.ProtocolName='unknown';
end;
end;
if ~isfield(hdr,'SeriesDescription')
hdr.SeriesDescription = 'unknown';
end;
if ~isfield(hdr,'EchoNumbers')
hdr.EchoNumbers = 0;
end;
m = sprintf('%02d', floor(rem(hdr.StudyTime/60,60)));
h = sprintf('%02d', floor(hdr.StudyTime/3600));
studydate = sprintf('%s_%s-%s', datestr(hdr.StudyDate,'yyyy-mm-dd'), ...
h,m);
switch root_dir
case {'date_time','series'}
id = studydate;
case {'patid', 'patid_date', 'patname'},
id = strip_unwanted(hdr.PatientID);
end;
serdes = strrep(strip_unwanted(hdr.SeriesDescription),...
strip_unwanted(hdr.ProtocolName),'');
protname = sprintf('%s%s_%.4d',strip_unwanted(hdr.ProtocolName), ...
serdes, hdr.SeriesNumber);
switch root_dir
case 'date_time',
dname = fullfile(pwd, id, protname);
case 'patid',
dname = fullfile(pwd, id, protname);
case 'patid_date',
dname = fullfile(pwd, id, studydate, protname);
case 'patname',
dname = fullfile(pwd, strip_unwanted(hdr.PatientsName), ...
id, protname);
case 'series',
dname = fullfile(pwd, protname);
otherwise
error('unknown file root specification');
end;
if ~exist(dname,'dir'),
mkdir_rec(dname);
end;
% some non-product sequences on SIEMENS scanners seem to have problems
% with image numbering in MOSAICs - doublettes, unreliable ordering
% etc. To distinguish, always include Acquisition time in image name
sa = sprintf('%02d', floor(rem(hdr.AcquisitionTime,60)));
ma = sprintf('%02d', floor(rem(hdr.AcquisitionTime/60,60)));
ha = sprintf('%02d', floor(hdr.AcquisitionTime/3600));
fname = sprintf('%s%s-%s%s%s-%.5d-%.5d-%d.%s', prefix, id, ha, ma, sa, ...
hdr.AcquisitionNumber,hdr.InstanceNumber, ...
hdr.EchoNumbers,format);
fname = fullfile(dname, fname);
%_______________________________________________________________________
%_______________________________________________________________________
function suc = mkdir_rec(str)
% works on full pathnames only
opwd=pwd;
if str(end) ~= filesep, str = [str filesep];end;
pos = strfind(str,filesep);
suc = zeros(1,length(pos));
for g=2:length(pos)
if ~exist(str(1:pos(g)-1),'dir'),
cd(str(1:pos(g-1)-1));
suc(g) = mkdir(str(pos(g-1)+1:pos(g)-1));
end;
end;
cd(opwd);
return;
%_______________________________________________________________________
%_______________________________________________________________________
function ret = read_ascconv(hdr)
% In SIEMENS data, there is an ASCII text section with
% additional information items. This section starts with a code
% ### ASCCONV BEGIN ###
% and ends with
% ### ASCCONV END ###
% It is read by spm_dicom_headers into an entry 'MrProtocol' in
% CSASeriesHeaderInfo or into an entry 'MrPhoenixProtocol' in
% Private_0029_1110 or Private_0029_1120.
% The additional items are assignments in C syntax, here they are just
% translated according to
% [] -> ()
% " -> '
% 0xX -> hex2dec('X')
% and collected in a struct.
ret=struct;
% get ascconv data
if isfield(hdr, 'Private_0029_1110')
X = get_numaris4_val(hdr.Private_0029_1110,'MrPhoenixProtocol');
elseif isfield(hdr, 'Private_0029_1120')
X = get_numaris4_val(hdr.Private_0029_1120,'MrPhoenixProtocol');
else
X=get_numaris4_val(hdr.CSASeriesHeaderInfo,'MrProtocol');
end
ascstart = strfind(X,'### ASCCONV BEGIN ###');
ascend = strfind(X,'### ASCCONV END ###');
if ~isempty(ascstart) && ~isempty(ascend)
tokens = textscan(char(X((ascstart+22):(ascend-1))),'%s', ...
'delimiter',char(10));
tokens{1}=regexprep(tokens{1},{'\[([0-9]*)\]','"(.*)"','0x([0-9a-fA-F]*)'},{'($1+1)','''$1''','hex2dec(''$1'')'});
% If everything would evaluate correctly, we could use
% eval(sprintf('ret.%s;\n',tokens{1}{:}));
for k = 1:numel(tokens{1})
try
eval(['ret.' tokens{1}{k} ';']);
catch
disp(['AscConv: Error evaluating ''ret.' tokens{1}{k} ''';']);
end;
end;
end;
%_______________________________________________________________________
%_______________________________________________________________________
function dt = determine_datatype(hdr)
% Determine what datatype to use for NIfTI images
be = spm_platform('bigend');
if hdr.HighBit>16
if hdr.PixelRepresentation
dt = [spm_type( 'int32') be];
else
dt = [spm_type('uint32') be];
end
else
if hdr.PixelRepresentation || hdr.HighBit<=15
dt = [spm_type( 'int16') be];
else
dt = [spm_type('uint16') be];
end
end
|
github
|
philippboehmsturm/antx-master
|
spm_spm_ui.m
|
.m
|
antx-master/xspm8/spm_spm_ui.m
| 98,074 |
utf_8
|
dfdd679af4a4b15272726dcb46e888fe
|
function varargout = spm_spm_ui(varargin)
% Setting up the general linear model for independent data
% FORMATs (given in Programmers Help)
%_______________________________________________________________________
%
% spm_spm_ui.m configures the design matrix (describing the general
% linear model), data specification, and other parameters necessary for
% the statistical analysis. These parameters are saved in a
% configuration file (SPM.mat) in the current directory, and are
% passed on to spm_spm.m which estimates the design. Inference on these
% estimated parameters is then handled by the SPM results section.
%
% A separate program (spm_spm_fmri_ui.m) handles design configuration
% for fMRI time series, though this program can be used for fMRI data
% when observations can be regarded as independent.
%
% ----------------------------------------------------------------------
%
% Various data and parameters need to be supplied to specify the design:
% * the image files
% * indicators of the corresponding condition/subject/group
% * any covariates, nuisance variables, or design matrix partitions
% * the type of global normalisation (if any)
% * grand mean scaling options
% * thresholds and masks defining the image volume to analyse
%
% The interface supports a comprehensive range of options for all these
% parameters, which are described below in the order in which the
% information is requested. Rather than ask for all these parameters,
% spm_spm_ui.m uses a "Design Definition", a structure describing the
% options and defaults appropriate for a particular analysis. Thus,
% once the user has chosen a design, a subset of the following prompts
% will be presented.
%
% If the pre-specified design definitions don't quite have the combination
% of options you want, you can pass a custom design structure D to be used
% as parameter: spm_spm_ui('cfg',D). The format of the design structure
% and option definitions are given in the programmers help, at the top of
% the main body of the code.
%
% ----------------
%
% Design class & Design type
% ==========================
%
% Unless a design definition is passed to spm_spm_ui.m as a parameter,
% the user is prompted first to select a design class, and then to
% select a design type from that class.
%
% The designs are split into three classes:
% i) Basic stats: basic models for simple statistics
% These specify designs suitable for simple voxel-by-voxel analyses.
% - one-sample t-test
% - two-sample t-test
% - paired t-test
% - one way Anova
% - one way Anova (with constant)
% - one way Anova (within subject)
% - simple regression (equivalent to correlation)
% - multiple regression
% - multiple regression (with constant)
% - basic AnCova (ANalysis of COVAriance)
% (essentially a two-sample t-test with a nuisance covariate)
%
% ii) PET models: models suitable for analysis of PET/SPECT experiments
% - Single-subject: conditions & covariates
% - Single-subject: covariates only
%
% - Multi-subj: conditions & covariates
% - Multi-subj: cond x subj interaction & covariates
% - Multi-subj: covariates only
% - Multi-group: conditions & covariates
% - Multi-group: covariates only
%
% - Population main effect: 2 cond's, 1 scan/cond (paired t-test)
% - Dodgy population main effect: >2 cond's, 1 scan/cond
% - Compare-populations: 1 scan/subject (two sample t-test)
% - Compare-populations: 1 scan/subject (AnCova)
%
% - The Full Monty... (asks you everything!)
%
% iii) SPM96 PET models: models used in SPM96 for PET/SPECT
% These models are provided for backward compatibility, but as they
% don't include some of the advanced modelling features, we recommend
% you switch to the new (SPM99) models at the earliest opportunity.
% - SPM96:Single-subject: replicated conditions
% - SPM96:Single-subject: replicated conditions & covariates
% - SPM96:Single-subject: covariates only
% - SPM96:Multi-subject: different conditions
% - SPM96:Multi-subject: replicated conditions
% - SPM96:Multi-subject: different conditions & covariates
% - SPM96:Multi-subject: replicated conditions & covariates
% - SPM96:Multi-subject: covariates only
% - SPM96:Multi-group: different conditions
% - SPM96:Multi-group: replicated conditions
% - SPM96:Multi-group: different conditions & covariates
% - SPM96:Multi-group: replicated conditions & covariates
% - SPM96:Multi-group: covariates only
% - SPM96:Compare-groups: 1 scan per subject
%
%
% Random effects, generalisability, population inference...
% =========================================================
%
% Note that SPM only considers a single component of variance, the
% residual error variance. When there are repeated measures, all
% analyses with SPM are fixed effects analyses, and inference only
% extends to the particular subjects under consideration (at the times
% they were imaged).
%
% In particular, the multi-subject and multi-group designs ignore the
% variability in response from subject to subject. Since the
% scan-to-scan (within-condition, within-subject variability is much
% smaller than the between subject variance which is ignored), this can
% lead to detection of group effects that are not representative of the
% population(s) from which the subjects are drawn. This is particularly
% serious for multi-group designs comparing two groups. If inference
% regarding the population is required, a random effects analysis is
% required.
%
% However, random effects analyses can be effected by appropriately
% summarising the data, thereby collapsing the model such that the
% residual variance for the new model contains precisely the variance
% components needed for a random effects analysis. In many cases, the
% fixed effects models here can be used as the first stage in such a
% two-stage procedure to produce appropriate summary data, which can
% then be used as raw data for a second-level analysis. For instance,
% the "Multi-subj: cond x subj interaction & covariates" design can be
% used to write out an image of the activation for each subject. A
% simple t-test on these activation images then turns out to be
% equivalent to a mixed-effects analysis with random subject and
% subject by condition interaction effects, inferring for the
% population based on this sample of subjects (strictly speaking the
% design would have to be balanced, with equal numbers of scans per
% condition per subject, and also only two conditions per subject). For
% additional details, see spm_RandFX.man.
%
% ----------------
%
% Selecting image files & indicating conditions
% =============================================
%
% You may now be prompted to specify how many studies, subjects and
% conditions you have, and then will be promted to select the scans.
%
% The data should all have the same orientation and image and voxel size.
%
% File selection is handled by spm_select.m - the help for which describes
% efficient use of the interface.
%
% You may be asked to indicate the conditions for a set of scans, with
% a prompt like "[12] Enter conditions? (2)". For this particular
% example you need to indicate for 12 scans the corresponding
% condition, in this case from 2 conditions. Enter a vector of
% indicators, like '0 1 0 1...', or a string of indicators, like
% '010101010101' or '121212121212', or 'rararararara'. (This
% "conditions" input is handled by spm_input.m, where comprehensive
% help can be found.)
%
% ----------------
%
% Covariate & nuisance variable entry
% ===================================
%
% * If applicable, you'll be asked to specify covariates and nuisance
% variables. Unlike SPM94/5/6, where the design was partitioned into
% effects of interest and nuisance effects for the computation of
% adjusted data and the F-statistic (which was used to thresh out
% voxels where there appeared to be no effects of interest), SPM99 does
% not partition the design in this way. The only remaining distinction
% between effects of interest (including covariates) and nuisance
% effects is their location in the design matrix, which we have
% retained for continuity. Pre-specified design matrix partitions can
% be entered. (The number of covariates / nuisance variables specified,
% is actually the number of times you are prompted for entry, not the
% number of resulting design matrix columns.) You will be given the
% opportunity to name the covariate.
%
% * Factor by covariate interactions: For covariate vectors, you may be
% offered a choice of interaction options. (This was called "covariate
% specific fits" in SPM95/6.) The full list of possible options is:
% - <none>
% - with replication
% - with condition (across group)
% - with subject (across group)
% - with group
% - with condition (within group)
% - with subject (within group)
%
% * Covariate centering: At this stage may also be offered "covariate
% centering" options. The default is usually that appropriate for the
% interaction chosen, and ensures that main effects of the interacting
% factor aren't affected by the covariate. You are advised to choose
% the default, unless you have other modelling considerations. The full
% list of possible options is:
% - around overall mean
% - around replication means
% - around condition means (across group)
% - around subject means (across group)
% - around group means
% - around condition means (within group)
% - around subject means (within group)
% - <no centering>
%
% ----------------
%
% Global options
% ==============
%
% Depending on the design configuration, you may be offered a selection
% of global normalisation and scaling options:
%
% * Method of global flow calculation
% - SPM96:Compare-groups: 1 scan per subject
% - None (assumming no other options requiring the global value chosen)
% - User defined (enter your own vector of global values)
% - SPM standard: mean voxel value (within per image fullmean/8 mask)
%
% * Grand mean scaling : Scaling of the overall grand mean simply
% scales all the data by a common factor such that the mean of all the
% global values is the value specified. For qualitative data, this puts
% the data into an intuitively accessible scale without altering the
% statistics. When proportional scaling global normalisation is used
% (see below), each image is seperately scaled such that it's global
% value is that specified (in which case the grand mean is also
% implicitly scaled to that value). When using AnCova or no global
% normalisation, with data from different subjects or sessions, an
% intermediate situation may be appropriate, and you may be given the
% option to scale group, session or subject grand means seperately. The
% full list of possible options is:
% - scaling of overall grand mean
% - caling of replication grand means
% - caling of condition grand means (across group)
% - caling of subject grand means (across group)
% - caling of group grand means
% - caling of condition (within group) grand means
% - caling of subject (within group) grand means
% - implicit in PropSca global normalisation)
% - no grand Mean scaling>'
%
% * Global normalisation option : Global nuisance effects are usually
% accounted for either by scaling the images so that they all have the
% same global value (proportional scaling), or by including the global
% covariate as a nuisance effect in the general linear model (AnCova).
% Much has been written on which to use, and when. Basically, since
% proportional scaling also scales the variance term, it is appropriate
% for situations where the global measurement predominantly reflects
% gain or sensitivity. Where variance is constant across the range of
% global values, linear modelling in an AnCova approach has more
% flexibility, since the model is not restricted to a simple
% proportional regression.
%
% Considering AnCova global normalisation, since subjects are unlikely
% to have the same relationship between global and local measurements,
% a subject-specific AnCova ("AnCova by subject"), fitting a different
% slope and intercept for each subject, would be preferred to the
% single common slope of a straight AnCova. (Assumming there's enough
% scans per subject to estimate such an effect.) This is basically an
% interaction of the global covariate with the subject factor. You may
% be offered various AnCova options, corresponding to interactions with
% various factors according to the design definition: The full list of
% possible options is:
% - AnCova
% - AnCova by replication
% - AnCova by condition (across group)
% - AnCova by subject (across group)
% - AnCova by group
% - AnCova by condition (within group)
% - AnCova by subject (within group)
% - Proportional scaling
% - <no global normalisation>
%
% Since differences between subjects may be due to gain and sensitivity
% effects, AnCova by subject could be combined with "grand mean scaling
% by subject" to obtain a combination of between subject proportional
% scaling and within subject AnCova.
%
% * Global centering: Lastly, for some designs using AnCova, you will
% be offered a choice of centering options for the global covariate. As
% with covariate centering, this is only relevant if you have a
% particular interest in the parameter estimates. Usually, the default
% of a centering corresponding to the AnCova used is chosen. The full
% list of possible options is:
% - around overall mean
% - around replication means
% - around condition means (across group)
% - around subject means (across group)
% - around group means
% - around condition means (within group)
% - around subject means (within group)
% - <no centering>
% - around user specified value
% - (as implied by AnCova)
% - GM (The grand mean scaled value)
% - (redundant: not doing AnCova)
%
%
%
% Note that this is a logical ordering for the global options, which is
% not the order used by the interface due to algorithm constraints. The
% interface asks for the options in this order:
% - Global normalisation
% - Grand mean scaling options
% (if not using proportional scaling global normalisation)
% - Value for grand mean scaling proportional scaling GloNorm
% (if appropriate)
% - Global centering options
% - Value for global centering (if "user-defined" chosen)
% - Method of calculation
%
% ----------------
%
% Masking options
% ===============
%
% The mask specifies the voxels within the image volume which are to be
% assessed. SPM supports three methods of masking. The volume analysed
% is the intersection of all masks:
%
% i) Threshold masking : "Analysis threshold"
% - images are thresholded at a given value and only voxels at
% which all images exceed the threshold are included in the
% analysis.
% - The threshold can be absolute, or a proportion of the global
% value (after scaling), or "-Inf" for no threshold masking.
% - (This was called "Grey matter threshold" in SPM94/5/6)
%
% ii) Implicit masking
% - An "implicit mask" is a mask implied by a particular voxel
% value. Voxels with this mask value are excluded from the
% analysis.
% - For image data-types with a representation of NaN
% (see spm_type.m), NaN's is the implicit mask value, (and
% NaN's are always masked out).
% - For image data-types without a representation of NaN, zero is
% the mask value, and the user can choose whether zero voxels
% should be masked out or not.
%
% iii) Explicit masking
% - Explicit masks are other images containing (implicit) masks
% that are to be applied to the current analysis.
% - All voxels with value NaN (for image data-types with a
% representation of NaN), or zero (for other data types) are
% excluded from the analysis.
% - Explicit mask images can have any orientation and voxel/image
% size. Nearest neighbour interpolation of a mask image is used if
% the voxel centers of the input images do not coincide with that
% of the mask image.
%
%
% ----------------
%
% Non-sphericity correction
% =========================
%
% In some instances the i.i.d. assumptions about the errors do not hold:
%
% Identity assumption:
% The identity assumption, of equal error variance (homoscedasticity), can
% be violated if the levels of a factor do not have the same error variance.
% For example, in a 2nd-level analysis of variance, one contrast may be scaled
% differently from another. Another example would be the comparison of
% qualitatively different dependant variables (e.g. normals vs. patients). If
% You say no to identity assumptions, you will be asked whether the error
% variance is the same over levels of each factor. Different variances
% (heteroscedasticy) induce different error covariance components that
% are estimated using restricted maximum likelihood (see below).
%
% Independence assumption.
% In some situations, certain factors may contain random effects. These induce
% dependencies or covariance components in the error terms. If you say no
% to independence assumptions, you will be asked whether random effects
% should be modelled for each factor. A simple example of this would be
% modelling the random effects of subject. These cause correlations among the
% error terms of observation from the same subject. For simplicity, it is
% assumed that the random effects of each factor are i.i.d. One can always
% re-specify the covariance components by hand in SPM.xVi.Vi for more
% complicated models
%
% ReML
% The ensuing covariance components will be estimated using ReML in spm_spm
% (assuming the same for all responsive voxels) and used to adjust the
% statistics and degrees of freedom during inference. By default spm_spm
% will use weighted least squares to produce Gauss-Markov or Maximum
% likelihood estimators using the non-sphericity structure specified at this
% stage. The components will be found in xX.xVi and enter the estimation
% procedure exactly as the serial correlations in fMRI models.
%
% see also: spm_reml.m and spm_non_sphericity.m
%
% ----------------
%
% Multivariate analyses
% =====================
%
% Mulitvariate analyses with n-variate response variables are supported
% and automatically invoke a ManCova and CVA in spm_spm. Multivariate
% designs are, at the moment limited to Basic and PET designs.
%
% ----------------------------------------------------------------------
%
% Variables saved in the SPM stucture
%
% xY.VY - nScan x 1 struct array of memory mapped images
% (see spm_vol for definition of the map structure)
% xX - structure describing design matrix
% xX.D - design definition structure
% (See definition in main body of spm_spm_ui.m)
% xX.I - nScan x 4 matrix of factor level indicators
% I(n,i) is the level of factor i corresponding to image n
% xX.sF - 1x4 cellstr containing the names of the four factors
% xX.sF{i} is the name of factor i
% xX.X - design matrix
% xX.xVi - correlation constraints for non-spericity correction
% xX.iH - vector of H partition (condition effects) indices,
% identifying columns of X correspoding to H
% xX.iC - vector of C partition (covariates of interest) indices
% xX.iB - vector of B partition (block effects) indices
% xX.iG - vector of G partition (nuisance variables) indices
% xX.name - p x 1 cellstr of effect names corresponding to columns
% of the design matrix
%
% xC - structure array of covariate details
% xC(i).rc - raw (as entered) i-th covariate
% xC(i).rcname - name of this covariate (string)
% xC(i).c - covariate as appears in design matrix (after any scaling,
% centering of interactions)
% xC(i).cname - cellstr containing names for effects corresponding to
% columns of xC(i).c
% xC(i).iCC - covariate centering option
% xC(i).iCFI - covariate by factor interaction option
% xC(i).type - covariate type: 1=interest, 2=nuisance, 3=global
% xC(i).cols - columns of design matrix corresponding to xC(i).c
% xC(i).descrip - cellstr containing a description of the covariate
%
% xGX - structure describing global options and values
% xGX.iGXcalc - global calculation option used
% xGX.sGXcalc - string describing global calculation used
% xGX.rg - raw globals (before scaling and such like)
% xGX.iGMsca - grand mean scaling option
% xGX.sGMsca - string describing grand mean scaling
% xGX.GM - value for grand mean (/proportional) scaling
% xGX.gSF - global scaling factor (applied to xGX.rg)
% xGX.iGC - global covariate centering option
% xGX.sGC - string describing global covariate centering option
% xGX.gc - center for global covariate
% xGX.iGloNorm - Global normalisation option
% xGX.sGloNorm - string describing global normalisation option
%
% xM - structure describing masking options
% xM.T - Threshold masking value (-Inf=>None,
% real=>absolute, complex=>proportional (i.e. times global) )
% xM.TH - nScan x 1 vector of analysis thresholds, one per image
% xM.I - Implicit masking (0=>none, 1=>implicit zero/NaN mask)
% xM.VM - struct array of explicit mask images
% (empty if no explicit masks)
% xM.xs - structure describing masking options
% (format is same as for xsDes described below)
%
% xsDes - structure of strings describing the design:
% Fieldnames are essentially topic strings (use "_"'s for
% spaces), and the field values should be strings or cellstr's
% of information regarding that topic. spm_DesRep.m
% uses this structure to produce a printed description
% of the design, displaying the fieldnames (with "_"'s
% converted to spaces) in bold as topics, with
% the corresponding text to the right
%
% SPMid - String identifying SPM and program versions
%
% ----------------
%
% NB: The SPM.mat file is not very portable: It contains
% memory-mapped handles for the images, which hardcodes the full file
% pathname and datatype. Therefore, subsequent to creating the
% SPM.mat, you cannot move the image files, and cannot move the
% entire analysis to a system with a different byte-order (even if the
% full file pathnames are retained. Further, the image scalefactors
% will have been pre-scaled to effect any grand mean or global
% scaling.
%_______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% Andrew Holmes
% $Id: spm_spm_ui.m 4185 2011-02-01 18:46:18Z guillaume $
SCCSid = '$Rev: 4185 $';
%=======================================================================
% - FORMAT specifications for programers
%=======================================================================
%( This is a multi function function, the first argument is an action )
%( string, specifying the particular action function to take. )
%
% FORMAT spm_spm_ui('CFG',D)
% Configure design
% D - design definition structure - see format definition below
% (If D is a struct array, then the user is asked to choose from the
% design definitions in the array. If D is not specified as an
% argument, then user is asked to choose from the standard internal
% definitions)
%
% FORMAT [P,I] = spm_spm_ui('Files&Indices',DsF,Dn,DbaTime)
% PET/SPECT file & factor level input
% DsF - 1x4 cellstr of factor names (ie D.sF)
% Dn - 1x4 vector indicating the number of levels (ie D.n)
% DbaTime - ask for F3 images in time order, with F2 levels input by user?
% P - nScan x 1 cellsrt of image filenames
% I - nScan x 4 matrix of factor level indices
%
% FORMAT D = spm_spm_ui('DesDefs_Stats')
% Design definitions for simple statistics
% D - struct array of design definitions (see definition below)
%
% FORMAT D = spm_spm_ui('DesDefs_PET')
% Design definitions for PET/SPECT models
% D - struct array of design definitions (see definition below)
%
% FORMAT D = spm_spm_ui('DesDefs_PET96')
% Design definitions for SPM96 PET/SPECT models
% D - struct array of design definitions (see definition below)
%=======================================================================
% Design definitions specification for programers & power users
%=======================================================================
% Within spm_spm_ui.m, a definition structure, D, determines the
% various options, defaults and specifications appropriate for a
% particular design. Usually one uses one of the pre-specified
% definitions chosen from the menu, which are specified in the function
% actions at the end of the program (spm_spm_ui('DesDefs_Stats'),
% spm_spm_ui('DesDefs_PET'), spm_spm_ui('DesDefs_PET96')). For
% customised use of spm_spm_ui.m, the design definition structure is
% shown by the following example:
%
% D = struct(...
% 'DesName','The Full Monty...',...
% 'n',[Inf Inf Inf Inf], 'sF',{{'repl','cond','subj','group'}},...
% 'Hform', 'I(:,[4,2]),''-'',{''stud'',''cond''}',...
% 'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...
% 'nC',[Inf,Inf],'iCC',{{[1:8],[1:8]}},'iCFI',{{[1:7],[1:7]}},...
% 'iGXcalc',[1,2,3],'iGMsca',[1:7],'GM',50,...
% 'iGloNorm',[1:9],'iGC',[1:11],...
% 'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
% 'b',struct('aTime',1));
%
% ( Note that the struct command expands cell arrays to give multiple )
% ( records, so if you want a cell array as a field value, you have to )
% ( embed it within another cell, hence the double "{{"'s. )
%
% ----------------
%
% Design structure fields and option definitions
% ==============================================
%
% D.Desname - a string naming the design
%
% In general, spm_spm_ui.m accomodates four factors. Usually these are
% 'group', 'subject', 'condition' & 'replication', but to allow for a
% flexible interface these are dynamically named for different designs,
% and are referred to as Factor4, Factor3, Factor2, and Factor1
% respectively. The first part of the D definition dictates the names
% and number of factor levels (i.e. number of subjects etc.) relevant
% for this design, and also how the H (condition) and B (block)
% partitions of the design matrix should be constructed.
%
% D.n - a 1x4 vector, indicating the number of levels. D.n(i)
% for i in [1:4] is the number of levels for factor i.
% Specify D.n(i) as 1 to ignore this factor level,
% otherwise the number of levels can be pre-specified as a
% given number, or given as Inf to allow the user to
% choose the number of levels.
%
% D.sF - a 1x4 cellstr containing the names of the four
% factors. D.sF{i} is the name of factor i.
%
% D.b.aTime - a binary indicator specifying whether images within F3
% level (subject) are selected in time order. For time
% order (D.b.aTime=1), F2 levels are indicated by a user
% input "condition" string (input handled by spm_input's
% 'c' type). When (D.b.aTime=0), images for each F3 are
% selected by F2 (condition). The latter was the mode of
% SPM95 and SPM96. (SPM94 and SPMclassic didn't do
% replications of conditions.)
%
% Once the user has entered the images and indicated the factor levels,
% a nScan x 4 matrix, I, of indicator variables is constructed
% specifying for each scan the relevant level of each of the four
% factors. I(n,i) is the level of factor i corresponding to image n.
% This I matrix of factor indicators is then used to construct the H
% and B forms of the design matrix according to the prescripton in the
% design definition D:
%
% D.Hform - a string specifying the form of the H partition of the
% design matrix. The string is evaluated as an argument
% string for spm_DesMtx, which builds design matrix
% partitions from indicator vectors.
% (eval(['[H,Hnames] = spm_DesMtx(',D.Hform,');']))
%
% D.BForm - a string specifying the form of the G partition.
%
% ( Note that a constant H partition is dropped if the B partition can )
% ( model the constant effect. )
%
% The next part of the design definition defines covariate options.
% Covariates are split into covariates (of interest) and nuisance
% variables. The covariates of interest and nuisance variables are put
% into the C & G partitions of the design matrox (the final design
% matrix is [H,C,B,G], where global nuisance covariates are appended to
% G). In SPM94/5/6 the design matrix was partitioned into effects of
% interest [H,C] and effects of no interest [B,G], with an F-test for
% no effects of interest and adjusted data (for effects of no interest)
% following from these partitions. SPM99 is more freestyle, with
% adjustments and F-tests specified by contrasts. However, the concept
% of effects of interest and of no interest has been maintained for
% continuity, and spm_spm_ui.m computes an F-contrast to test for "no
% effects of interest".
%
% D.nC - a 1x2 vector: D.nC(1) is the number of covariates,
% D.nC(2) the number of nuisance variables. Specify zero
% to skip covariate entry, the actual number of
% covariates, or Inf to let the user specify the number of
% covariates. As with earlier versions, blocks of design
% matrix can be entered. However, these are now treated as
% a single covariate entity, so the number of
% covariates.nuisance variables is now the number of items
% you are prompted for, regardless of their dimension. (In
% SPM95-6 this number was the number of covariate vectors
% that could be entered.)
%
% D.iCC - a 1x2 cell array containing two vectors indicating the
% allowable covariate centering options for this design.
% These options are defined in the body of spm_spm_ui.m,
% in variables sCC & CFIforms. Use negative indices to
% indicate the default, if any - the largest negative
% wins.
%
% D.iCFI - a 1x2 cell array containing two vectors indicating the
% allowable covariate by factor interactions for this
% design. Interactions are only offered with a factor if
% it has multiple levels. The options are defined in the
% body of spm_spm_ui.m, in variables sCFI & CFIforms. Use
% negative indicies to indicate a default.
%
% The next part defines global options:
%
% D.iGXcalc - a vector of possible global calculation options for
% this design, as listed in the body of spm_spm_ui.m in
% variable sGXcalc. (If other global options are chosen,
% then the "omit" option is not offered.) Again, negative
% values indicate a default.
%
% D.iGloNorm - a vector of possible global normalisation options for
% this design, as described in the body of spm_spm_ui.m in
% variable sGloNorm.
%
% D.iGMsca - a vector of possible grand mean scaling options, as
% described in the body of spm_spm_ui.m in variable
% sGMsca. (Note that grand mean scaling is redundent when
% using proportional scaling global flow normalisation.)
%
% D.iGC - a vector of possible global covariate centering
% options, corresponding to the descriptions in variable
% iCC given in the body of spm_spm_ui.m. This is only
% relevant for AnCova type global normalisation, and even
% then only if you're actually interested in constraining
% the values of the parameters in some useful way.
% Usually, one chooses option 10, "as implied by AnCova".
%
% The next component specifies masking options:
%
% D.M_.T - a vector defining the analysis threshold: Specify
% "-Inf" as an element to offer "None" as an option. If a
% real element is found, then absolute thresholding is
% offered, with the first real value proffered as default
% threshold. If an imaginary element is found, then
% proportional thresholding if offered (i.e. the threshold
% is a proportion of the image global), with the (abs of)
% the first imaginary element proffered as default.
%
% D.M_.I - Implicit masking? 0-no, 1-yes, Inf-ask. (This is
% irrelevant for image types with a representation of NaN,
% since NaN is then the mask value, and NaN's are always
% masked.)
%
% D.M.X - Explicit masking? 0-no, 1-yes, Inf-ask.
%
% ----------------
%
% To use a customised design structure D, type spm_spm_ui('cfg',D) in the
% Matlab command window.
%
% The easiest way to generate a customised design definition structure
% is to tweak one of the pre-defined definitions. The following code
% will prompt you to select one of the pre-defined designs, and return
% the design definition structure for you to work on:
%
% D = spm_spm_ui(char(spm_input('Select design class...','+1','m',...
% {'Basic stats','Standard PET designs','SPM96 PET designs'},...
% {'DesDefs_Stats','DesDefs_PET','DesDefs_PET96'},2)));
% D = D(spm_input('Select design type...','+1','m',{D.DesName}'))
%
%_______________________________________________________________________
% @(#)spm_spm_ui.m 2.54 Andrew Holmes 04/12/09
%-Condition arguments
%-----------------------------------------------------------------------
if (nargin==0), Action = 'CFG'; else, Action = varargin{1}; end
switch lower(Action)
case 'cfg'
%===================================================================
% - C O N F I G U R E D E S I G N
%===================================================================
% spm_spm_ui('CFG',D)
if nargin<2, D = []; else, D = varargin{2}; end
%-GUI setup
%-------------------------------------------------------------------
SPMid = spm('FnBanner',mfilename,SCCSid);
[Finter,Fgraph,CmdLine] = spm('FnUIsetup','Stats: Setup analysis',0);
spm_help('!ContextHelp',mfilename)
%-Ask about overwriting files from previous analyses...
%-------------------------------------------------------------------
if exist(fullfile('.','SPM.mat'))
str = { 'Current directory contains existing SPM file:',...
'Continuing will overwrite existing file!'};
if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename);
fprintf('%-40s: %30s\n\n',...
'Abort... (existing SPM file)',spm('time'))
spm_clf(Finter)
return
end
end
%-Option definitions
%-------------------------------------------------------------------
%-Generic factor names
sF = {'sF1','sF2','sF3','sF4'};
%-Covariate by factor interaction options
sCFI = {'<none>';... %-1
'with sF1';'with sF2';'with sF3';'with sF4';... %-2:5
'with sF2 (within sF4)';'with sF3 (within sF4)'}; %-6,7
%-DesMtx argument components for covariate by factor interaction options
% (Used for CFI's Covariate Centering (CC), GMscale & Global normalisation)
CFIforms = { '[]', 'C', '{}';... %-1
'I(:,1)', 'FxC', '{D.sF{1}}';... %-2
'I(:,2)', 'FxC', '{D.sF{2}}';... %-3
'I(:,3)', 'FxC', '{D.sF{3}}';... %-4
'I(:,4)', 'FxC', '{D.sF{4}}';... %-5
'I(:,[4,2])', 'FxC', '{D.sF{4},D.sF{2}}';... %-6
'I(:,[4,3])', 'FxC', '{D.sF{4},D.sF{3}}' }; %-7
%-Centre (mean correction) options for covariates & globals (CC)
% (options 9-12 are for centering of global when using AnCova GloNorm) (GC)
sCC = { 'around overall mean';... %-1
'around sF1 means';... %-2
'around sF2 means';... %-3
'around sF3 means';... %-4
'around sF4 means';... %-5
'around sF2 (within sF4) means';... %-6
'around sF3 (within sF4) means';... %-7
'<no centering>';... %-8
'around user specified value';... %-9
'(as implied by AnCova)';... %-10
'GM';... %-11
'(redundant: not doing AnCova)'}'; %-12
%-DesMtx I forms for covariate centering options
CCforms = {'ones(nScan,1)',CFIforms{2:end,1},''}';
%-Global normalization options (options 1-7 match CFIforms) (GloNorm)
sGloNorm = { 'AnCova';... %-1
'AnCova by sF1';... %-2
'AnCova by sF2';... %-3
'AnCova by sF3';... %-4
'AnCova by sF4';... %-5
'AnCova by sF2 (within sF4)';... %-6
'AnCova by sF3 (within sF4)';... %-7
'proportional scaling';... %-8
'<no global normalisation>'}; %-9
%-Grand mean scaling options (GMsca)
sGMsca = { 'scaling of overall grand mean';... %-1
'scaling of sF1 grand means';... %-2
'scaling of sF2 grand means';... %-3
'scaling of sF3 grand means';... %-4
'scaling of sF4 grand means';... %-5
'scaling of sF2 (within sF4) grand means';... %-6
'scaling of sF3 (within sF4) grand means';... %-7
'(implicit in PropSca global normalisation)';... %-8
'<no grand Mean scaling>' }; %-9
%-NB: Grand mean scaling by subject is redundent for proportional scaling
%-Global calculation options (GXcalc)
sGXcalc = { 'omit';... %-1
'user specified';... %-2
'mean voxel value (within per image fullmean/8 mask)'}; %-3
%===================================================================
%-D E S I G N P A R A M E T E R S
%===================================================================
%-Get design type
%-------------------------------------------------------------------
if isempty(D)
D = spm_spm_ui( ...
char(spm_input('Select design class...','+1','m',...
{'Basic stats','Standard PET designs','SPM96 PET designs'},...
{'DesDefs_Stats','DesDefs_PET','DesDefs_PET96'},2)));
end
D = D(spm_input('Select design type...','+1','m',{D.DesName}'));
%-Set factor names for this design
%-------------------------------------------------------------------
sCC = sf_estrrep(sCC,[sF',D.sF']);
sCFI = sf_estrrep(sCFI,[sF',D.sF']);
sGloNorm = sf_estrrep(sGloNorm,[sF',D.sF']);
sGMsca = sf_estrrep(sGMsca,[sF',D.sF']);
%-Get filenames & factor indicies
%-------------------------------------------------------------------
[P,I] = spm_spm_ui('Files&Indices',D.sF,D.n,D.b.aTime);
nScan = size(I,1); %-#obs
%-Additional design parameters
%-------------------------------------------------------------------
bL = any(diff(I,1),1); %-Multiple factor levels?
% NB: bL(2) might be thrown by user specified f1 levels
% (D.b.aTime & D.n(2)>1) - assumme user is consistent?
bFI = [bL(1),bL(2:3)&~bL(4),bL(4),bL([2,3])&bL(4)];
%-Allowable interactions for covariates
%-Only offer interactions with multi-level factors, and
% don't offer by F2|F3 if bL(4)!
%-Build Condition (H) and Block (B) partitions
%===================================================================
H=[];Hnames=[];
B=[];Bnames=[];
eval(['[H,Hnames] = spm_DesMtx(',D.Hform,');'])
if rank(H)==nScan, error('unestimable condition effects'), end
eval(['[B,Bnames] = spm_DesMtx(',D.Bform,');'])
if rank(B)==nScan, error('unestimable block effects'), end
%-Drop a constant H partition if B partition can model constant
if size(H,2)>0 & all(H(:)==1) & (rank([H B])==rank(B))
H = []; Hnames = {};
warning('Dropping redundant constant H partition')
end
%-Covariate partition(s): interest (C) & nuisance (G) excluding global
%===================================================================
nC = D.nC; %-Default #covariates
C = {[],[]}; Cnames = {{},{}}; %-Covariate DesMtx partitions & names
xC = []; %-Struct array to hold raw covariates
dcname = {'CovInt','NusCov'}; %-Default root names for covariates
dstr = {'covariate','nuisance variable'};
GUIpos = spm_input('!NextPos');
nc = [0,0];
for i = 1:2 % 1:covariates of interest, 2:nuisance variables
if isinf(nC(i)), nC(i)=spm_input(['# ',dstr{i},'s'],GUIpos,'w1'); end
while nc(i) < nC(i)
%-Create prompt, get covariate, get covariate name
%-----------------------------------------------------------
if nC(i)==1
str=dstr{i};
else
str=sprintf('%s %d',dstr{i},nc(i)+1);
end
c = spm_input(str,GUIpos,'r',[],[nScan,Inf]);
if any(isnan(c(:))), break, end %-NaN is dummy value to exit
nc(i) = nc(i)+1; %-#Covariates (so far)
if nC(i)>1, tstr = sprintf('%s^{%d}',dcname{i},nc(i));
else, tstr = dcname{i}; end
cname = spm_input([str,' name?'],'+1','s',tstr);
rc = c; %-Save covariate value
rcname = cname; %-Save covariate name
%-Interaction option? (if single covariate vector entered)?
%-----------------------------------------------------------
if size(c,2) == 1
%-User choice of interaction options, default is negative
%-Only offer interactions for appropriate factor combinations
if length(D.iCFI{i})>1
iCFI = intersect(abs(D.iCFI{i}),find([1,bFI]));
dCFI = max([1,intersect(iCFI,-D.iCFI{i}(D.iCFI{i}<0))]);
iCFI = spm_input([str,': interaction?'],'+1','m',...
sCFI(iCFI),iCFI,find(iCFI==dCFI));
else
iCFI = abs(D.iCFI{i}); %-AutoSelect default option
end
else
iCFI = 1;
end
%-Centre covariate(s)? (Default centring to correspond to CFI)
% Always offer "no centering" as default for design matrix blocks
%-----------------------------------------------------------
DiCC = D.iCC{i};
if size(c,2)>1, DiCC = union(DiCC,-8); end
if length(DiCC)>1
%-User has a choice of centering options
%-Only offer factor specific for appropriate factor combinations
iCC = intersect(abs(DiCC),find([1,bFI,1]) );
%-Default is max -ve option in D, overridden by iCFI if CFI
if iCFI == 1, dCC = -DiCC(DiCC<0); else, dCC = iCFI; end
dCC = max([1,intersect(iCC,dCC)]);
iCC = spm_input([str,': centre?'],'+1','m',...
sCC(iCC),iCC,find(iCC==dCC));
else
iCC = abs(DiCC); %-AutoSelect default option
end
%-Centre within factor levels as appropriate
if any(iCC == [1:7]), c = c - spm_meanby(c,eval(CCforms{iCC})); end
%-Do any interaction (only for single covariate vectors)
%-----------------------------------------------------------
if iCFI > 1 %-(NB:iCFI=1 if size(c,2)>1)
tI = [eval(CFIforms{iCFI,1}),c];
tConst = CFIforms{iCFI,2};
tFnames = [eval(CFIforms{iCFI,3}),{cname}];
[c,cname] = spm_DesMtx(tI,tConst,tFnames);
elseif size(c,2)>1 %-Design matrix block
[null,cname] = spm_DesMtx(c,'X',cname);
else
cname = {cname};
end
%-Store raw covariate details in xC struct for reference
%-Pack c into appropriate DesMtx partition
%-----------------------------------------------------------
%-Construct description string for covariate
str = {sprintf('%s: %s',str,rcname)};
if size(rc,2)>1, str = {sprintf('%s (block of %d covariates)',...
str{:},size(rc,2))}; end
if iCC < 8, str=[str;{['used centered ',sCC{iCC}]}]; end
if iCFI> 1, str=[str;{['fitted as interaction ',sCFI{iCFI}]}]; end
tmp = struct( 'rc',rc, 'rcname',rcname,...
'c',c, 'cname',{cname},...
'iCC',iCC, 'iCFI',iCFI,...
'type',i,...
'cols',[1:size(c,2)] + ...
size([H,C{1}],2) + ...
size([B,C{2}],2)*(i-1),...
'descrip',{str} );
if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end
C{i} = [C{i},c];
Cnames{i} = [Cnames{i}; cname];
end % (while)
end % (for)
clear c tI tConst tFnames
spm_input('!SetNextPos',GUIpos);
%-Unpack into C & G design matrix sub-partitions
G = C{2}; Gnames = Cnames{2};
C = C{1}; Cnames = Cnames{1};
%-Options...
%===================================================================
%-Global normalization options (GloNorm)
%-------------------------------------------------------------------
if length(D.iGloNorm)>1
%-User choice of global normalisation options, default is negative
%-Only offer factor specific for appropriate factor combinations
iGloNorm = intersect(abs(D.iGloNorm),find([1,bFI,1,1]));
dGloNorm = max([0,intersect(iGloNorm,-D.iGloNorm(D.iGloNorm<0))]);
iGloNorm = spm_input('GloNorm: Select global normalisation','+1','m',...
sGloNorm(iGloNorm),iGloNorm,find(iGloNorm==dGloNorm));
else
iGloNorm = abs(D.iGloNorm);
end
%-Grand mean scaling options (GMsca)
%-------------------------------------------------------------------
if iGloNorm==8
iGMsca=8; %-grand mean scaling implicit in PropSca GloNorm
elseif length(D.iGMsca)==1
iGMsca = abs(D.iGMsca);
else
%-User choice of grand mean scaling options
%-Only offer factor specific for appropriate factor combinations
iGMsca = intersect(abs(D.iGMsca),find([1,bFI,0,1]));
%-Default is max -ve option in D, overridden by iGloNorm if AnCova
if iGloNorm==9, dGMsca=-D.iGMsca(D.iGMsca<0); else, dGMsca=iGloNorm; end
dGMsca = max([0,intersect(iGMsca,dGMsca)]);
iGMsca = spm_input('GMsca: grand mean scaling','+1','m',...
sGMsca(iGMsca),iGMsca,find(iGMsca==dGMsca));
end
%-Value for PropSca / GMsca (GM)
%-------------------------------------------------------------------
if iGMsca == 9 %-Not scaling (GMsca or PropSca)
GM = 0; %-Set GM to zero when not scaling
else %-Ask user value of GM
if iGloNorm==8
str = 'PropSca global mean to';
else
str = [strrep(sGMsca{iGMsca},'scaling of','scale'),' to'];
end
GM = spm_input(str,'+1','r',D.GM,1);
%-If GM is zero then don't GMsca! or PropSca GloNorm
if GM==0, iGMsca=9; if iGloNorm==8, iGloNorm=9; end, end
end
%-Sort out description strings for GloNorm and GMsca
%-------------------------------------------------------------------
sGloNorm = sGloNorm{iGloNorm};
sGMsca = sGMsca{iGMsca};
if iGloNorm==8
sGloNorm = sprintf('%s to %-4g',sGloNorm,GM);
elseif iGMsca<8
sGMsca = sprintf('%s to %-4g',sGMsca,GM);
end
%-Global centering (for AnCova GloNorm) (GC)
%-------------------------------------------------------------------
%-Specify the centering option for the global covariate for AnCova
%-Basically, if 'GMsca'ling then should centre to GM (iGC=11). Otherwise,
% should centre in similar fashion to AnCova (i.e. by the same factor(s)),
% such that models are seperable (iGC=10). This is particularly important
% for subject specific condition effects if then passed on to a second-level
% model. (See also spm_adjmean_ui.m) SPM96 (& earlier) used to just centre
% GX around its (overall) mean (iGC=1).
%-This code allows more general options to be specified (but is complex)
%-Setting D.iGC=[-10,-11] gives the standard choices above
%-If not doing AnCova then GC is irrelevant
if ~any(iGloNorm == [1:7])
iGC = 12;
gc = [];
else
%-Annotate options 10 & 11 with specific details
%---------------------------------------------------------------
%-Tag '(as implied by AnCova)' with actual AnCova situation
sCC{10} = [sCC{iGloNorm},' (<= ',sGloNorm,')'];
%-Tag 'GM' case with actual GM & GMsca case
sCC{11} = sprintf('around GM=%g (i.e. %s after grand mean scaling)',...
GM,strrep(sCC{iGMsca},'around ',''));
%-Constuct vector of allowable iGC
%---------------------------------------------------------------
%-Weed out redundent factor combinations from pre-set allowable options
iGC = intersect(abs(D.iGC),find([1,bFI,1,1,1,1]));
%-Omit 'GM' option if didn't GMsca (iGMsca~=8 'cos doing AnCova)
if any(iGMsca==[8,9]), iGC = setdiff(iGC,11); end
%-Omit 'GM' option if same as '(as implied by AnCova)'
if iGloNorm==iGMsca, iGC = setdiff(iGC,11); end
%-If there's a choice, set defaults (if any), & get answer
%---------------------------------------------------------------
if length(iGC)>1
dGC = max([0,intersect(iGC,-D.iGC(D.iGC<0))]);
str = 'Centre global covariate';
if iGMsca<8, str = [str,' (after grand mean scaling)']; end
iGC = spm_input(str,'+1','m',sCC(iGC),iGC,find(iGC==dGC));
elseif isempty(iGC)
error('Configuration error: empty iGC')
end
%-If 'user specified' then get value
%---------------------------------------------------------------
if iGC==9
gc = spm_input('Centre globals around','+0','r',D.GM,1);
sCC{9} = sprintf('%s of %g',sCC{iGC},gc);
else
gc = 0;
end
end
%-Thresholds & masks defining voxels to analyse (MASK)
%===================================================================
GUIpos = spm_input('!NextPos');
%-Analysis threshold mask
%-------------------------------------------------------------------
%-Work out available options:
% -Inf=>None, real=>absolute, complex=>proportional, (i.e. times global)
M_T = D.M_.T; if isempty(M_T), M_T = [-Inf, 100, 0.8*sqrt(-1)]; end
M_T = { 'none', M_T(min(find(isinf(M_T))));...
'absolute', M_T(min(find(isfinite(M_T)&(M_T==real(M_T)))));...
'relative', M_T(min(find(isfinite(M_T)&(M_T~=real(M_T))))) };
%-Work out available options
%-If there's a choice between proportional and absolute then ask
%-------------------------------------------------------------------
q = ~[isempty(M_T{1,2}), isempty(M_T{2,2}), isempty(M_T{3,2})];
if all(q(2:3))
tmp = spm_input('Threshold masking',GUIpos,'b',M_T(q,1),find(q));
q(setdiff([1:3],tmp))=0;
end
%-Get mask value - note that at most one of q(2:3) is true
%-------------------------------------------------------------------
if ~any(q) %-Oops - nothing specified!
M_T = -Inf;
elseif all(q==[1,0,0]) %-no threshold masking
M_T = -Inf;
else %-get mask value
if q(1), args = {'br1','None',-Inf,abs(M_T{1+find(q(2:3)),2})};
else, args = {'r',abs(M_T{1+find(q(2:3)),2})}; end
if q(2)
M_T = spm_input('threshold',GUIpos,args{:});
elseif q(3)
M_T = spm_input('threshold (relative to global)',GUIpos,...
args{:});
if isfinite(M_T) & isreal(M_T), M_T=M_T*sqrt(-1); end
else
error('Shouldn''t get here!')
end
end
%-Make a description string
%-------------------------------------------------------------------
if isinf(M_T)
xsM.Analysis_threshold = 'None (-Inf)';
elseif isreal(M_T)
xsM.Analysis_threshold = sprintf('images thresholded at %6g',M_T);
else
xsM.Analysis_threshold = sprintf(['images thresholded at %6g ',...
'times global'],imag(M_T));
end
%-Implicit masking: Ignore zero voxels in low data-types?
%-------------------------------------------------------------------
% (Implicit mask is NaN in higher data-types.)
type = getfield(spm_vol(P{1,1}),'dt')*[1,0]';
if ~spm_type(type,'nanrep')
switch D.M_.I
case Inf, M_I = spm_input('Implicit mask (ignore zero''s)?',...
'+1','y/n',[1,0],1); %-Ask
case {0,1}, M_I = D.M_.I; %-Pre-specified
otherwise, error('unrecognised D.M_.I type')
end
if M_I, xsM.Implicit_masking = 'Yes: zero''s treated as missing';
else, xsm.Implicit_masking = 'No'; end
else
M_I = 1;
xsM.Implicit_masking = 'Yes: NaN''s treated as missing';
end
%-Explicit mask images (map them later...)
%-------------------------------------------------------------------
switch(D.M_.X)
case Inf, M_X = spm_input('explicitly mask images?','+1','y/n',[1,0],2);
case {0,1}, M_X = D.M_.X;
otherwise, error('unrecognised D.M_.X type')
end
if M_X, M_P = spm_select(Inf,'image','select mask images'); else, M_P = {}; end
%-Global calculation (GXcalc)
%===================================================================
iGXcalc = abs(D.iGXcalc);
%-Only offer "omit" option if not doing any GloNorm, GMsca or PropTHRESH
if ~(iGloNorm==9 & iGMsca==9 & (isinf(M_T)|isreal(M_T)))
iGXcalc = intersect(iGXcalc,[2:size(sGXcalc,1)]);
end
if isempty(iGXcalc)
error('no GXcalc options')
elseif length(iGXcalc)>1
%-User choice of global calculation options, default is negative
dGXcalc = max([1,intersect(iGXcalc,-D.iGXcalc(D.iGXcalc<0))]);
iGXcalc = spm_input('Global calculation','+1','m',...
sGXcalc(iGXcalc),iGXcalc,find(iGXcalc==dGXcalc));
else
iGXcalc = abs(D.iGXcalc);
end
if iGXcalc==2 %-Get user specified globals
g = spm_input('globals','+0','r',[],[nScan,1]);
end
sGXcalc = sGXcalc{iGXcalc};
% Non-sphericity correction (set xVi.var and .dep)
%===================================================================
xVi.I = I;
nL = max(I); % number of levels
mL = find(nL > 1); % multilevel factors
xVi.var = sparse(1,4); % unequal variances
xVi.dep = sparse(1,4); % dependencies
if length(mL) > 1
% repeated measures design
%---------------------------------------------------------------
if spm_input('non-sphericity correction?','+1','y/n',[1,0],0)
% make menu strings
%-----------------------------------------------------------
for i = 1:4
mstr{i} = sprintf('%s (%i levels)',D.sF{i},nL(i));
end
mstr = mstr(mL);
% are errors identical
%-----------------------------------------------------------
if spm_input('are errors identical','+1','y/n',[0,1],0)
str = 'unequal variances are between';
[i j] = min(nL(mL));
i = spm_input(str,'+0','m',mstr,[],j);
% set in xVi and eliminate from dependency option
%-------------------------------------------------------
xVi.var(mL(i)) = 1;
mL(i) = [];
mstr(i) = [];
end
% are errors independent
%-----------------------------------------------------------
if spm_input('are errors independent','+1','y/n',[0,1],0)
str = ' dependencies are within';
[i j] = max(nL(mL));
i = spm_input(str,'+0','m',mstr,[],j);
% set in xVi
%-------------------------------------------------------
xVi.dep(mL(i)) = 1;
end
end
end
%-Place covariance components Q{:} in xVi.Vi
%-------------------------------------------------------------------
xVi = spm_non_sphericity(xVi);
%===================================================================
% - C O N F I G U R E D E S I G N
%===================================================================
spm('FigName','Stats: configuring',Finter,CmdLine);
spm('Pointer','Watch');
%-Images & image info: Map Y image files and check consistency of
% dimensions and orientation / voxel size
%===================================================================
fprintf('%-40s: ','Mapping files') %-#
VY = spm_vol(char(P));
%-Check compatability of images (Bombs for single image)
%-------------------------------------------------------------------
spm_check_orientations(VY);
fprintf('%30s\n','...done') %-#
%-Global values, scaling and global normalisation
%===================================================================
%-Compute global values
%-------------------------------------------------------------------
switch iGXcalc, case 1
%-Don't compute => no GMsca (iGMsca==9) or GloNorm (iGloNorm==9)
g = [];
case 2
%-User specified globals
case 3
%-Compute as mean voxel value (within per image fullmean/8 mask)
g = zeros(nScan,1 );
fprintf('%-40s: %30s','Calculating globals',' ') %-#
for i = 1:nScan
str = sprintf('%3d/%-3d',i,nScan);
fprintf('%s%30s',repmat(sprintf('\b'),1,30),str)%-#
g(i) = spm_global(VY(i));
end
fprintf('%s%30s\n',repmat(sprintf('\b'),1,30),'...done') %-#
otherwise
error('illegal iGXcalc')
end
rg = g;
fprintf('%-40s: ','Design configuration') %-#
%-Scaling: compute global scaling factors gSF required to implement
% proportional scaling global normalisation (PropSca) or grand mean
% scaling (GMsca), as specified by iGMsca (& iGloNorm)
%-------------------------------------------------------------------
switch iGMsca, case 8
%-Proportional scaling global normalisation
if iGloNorm~=8, error('iGloNorm-iGMsca(8) mismatch for PropSca'), end
gSF = GM./g;
g = GM*ones(nScan,1);
case {1,2,3,4,5,6,7}
%-Grand mean scaling according to iGMsca
gSF = GM./spm_meanby(g,eval(CCforms{iGMsca}));
g = g.*gSF;
case 9
%-No grand mean scaling
gSF = ones(nScan,1);
otherwise
error('illegal iGMsca')
end
%-Apply gSF to memory-mapped scalefactors to implement scaling
%-------------------------------------------------------------------
for i = 1:nScan
VY(i).pinfo(1:2,:) = VY(i).pinfo(1:2,:)*gSF(i);
end
%-AnCova: Construct global nuisance covariates partition (if AnCova)
%-------------------------------------------------------------------
if any(iGloNorm == [1:7])
%-Centre global covariate as requested
%---------------------------------------------------------------
switch iGC, case {1,2,3,4,5,6,7} %-Standard sCC options
gc = spm_meanby(g,eval(CCforms{iGC}));
case 8 %-No centering
gc = 0;
case 9 %-User specified centre
%-gc set above
case 10 %-As implied by AnCova option
gc = spm_meanby(g,eval(CCforms{iGloNorm}));
case 11 %-Around GM
gc = GM;
otherwise %-unknown iGC
error('unexpected iGC value')
end
%-AnCova - add scaled centred global to DesMtx `G' partition
%---------------------------------------------------------------
rcname = 'global';
tI = [eval(CFIforms{iGloNorm,1}),g - gc];
tConst = CFIforms{iGloNorm,2};
tFnames = [eval(CFIforms{iGloNorm,3}),{rcname}];
[f,gnames] = spm_DesMtx(tI,tConst,tFnames);
clear tI tConst tFnames
%-Save GX info in xC struct for reference
%---------------------------------------------------------------
str = {sprintf('%s: %s',dstr{2},rcname)};
if any(iGMsca==[1:7]), str=[str;{['(after ',sGMsca,')']}]; end
if iGC ~= 8, str=[str;{['used centered ',sCC{iGC}]}]; end
if iGloNorm > 1
str=[str;{['fitted as interaction ',sCFI{iGloNorm}]}];
end
tmp = struct( 'rc',rg.*gSF, 'rcname',rcname,...
'c',f, 'cname' ,{gnames},...
'iCC',iGC, 'iCFI' ,iGloNorm,...
'type', 3,...
'cols',[1:size(f,2)] + size([H C B G],2),...
'descrip', {str} );
G = [G,f]; Gnames = [Gnames; gnames];
if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end
elseif iGloNorm==8 | iGXcalc>1
%-Globals calculated, but not AnCova: Make a note of globals
%---------------------------------------------------------------
if iGloNorm==8
str = { 'global values: (used for proportional scaling)';...
'("raw" unscaled globals shown)'};
elseif isfinite(M_T) & ~isreal(M_T)
str = { 'global values: (used to compute analysis threshold)'};
else
str = { 'global values: (computed but not used)'};
end
rcname ='global';
tmp = struct( 'rc',rg, 'rcname',rcname,...
'c',{[]}, 'cname' ,{{}},...
'iCC',0, 'iCFI' ,0,...
'type', 3,...
'cols', {[]},...
'descrip', {str} );
if isempty(xC), xC = tmp; else, xC = [xC,tmp]; end
end
%-Save info on global calculation in xGX structure
%-------------------------------------------------------------------
xGX = struct(...
'iGXcalc',iGXcalc, 'sGXcalc',sGXcalc, 'rg',rg,...
'iGMsca',iGMsca, 'sGMsca',sGMsca, 'GM',GM,'gSF',gSF,...
'iGC', iGC, 'sGC', sCC{iGC}, 'gc', gc,...
'iGloNorm',iGloNorm, 'sGloNorm',sGloNorm);
%-Construct masking information structure and compute actual analysis
% threshold using scaled globals (rg.*gSF)
%-------------------------------------------------------------------
if isreal(M_T), M_TH = M_T * ones(nScan,1); %-NB: -Inf is real
else, M_TH = imag(M_T) * (rg.*gSF); end
if ~isempty(M_P)
VM = spm_vol(char(M_P));
xsM.Explicit_masking = [{'Yes: mask images :'};{VM.fname}'];
else
VM = [];
xsM.Explicit_masking = 'No';
end
xM = struct('T',M_T, 'TH',M_TH, 'I',M_I, 'VM',{VM}, 'xs',xsM);
%-Construct full design matrix (X), parameter names and structure (xX)
%===================================================================
X = [H C B G];
tmp = cumsum([size(H,2), size(C,2), size(B,2), size(G,2)]);
xX = struct( 'X', X,...
'iH', [1:size(H,2)],...
'iC', [1:size(C,2)] + tmp(1),...
'iB', [1:size(B,2)] + tmp(2),...
'iG', [1:size(G,2)] + tmp(3),...
'name', {[Hnames; Cnames; Bnames; Gnames]},...
'I', I,...
'sF', {D.sF});
%-Design description (an nx2 cellstr) - for saving and display
%===================================================================
tmp = { sprintf('%d condition, +%d covariate, +%d block, +%d nuisance',...
size(H,2),size(C,2),size(B,2),size(G,2));...
sprintf('%d total, having %d degrees of freedom',...
size(X,2),rank(X));...
sprintf('leaving %d degrees of freedom from %d images',...
size(X,1)-rank(X),size(X,1)) };
xsDes = struct( 'Design', {D.DesName},...
'Global_calculation', {sGXcalc},...
'Grand_mean_scaling', {sGMsca},...
'Global_normalisation', {sGloNorm},...
'Parameters', {tmp} );
fprintf('%30s\n','...done') %-#
%-Assemble SPM structure
%===================================================================
SPM.xY.P = P; % filenames
SPM.xY.VY = VY; % mapped data
SPM.nscan = size(xX.X,1); % scan number
SPM.xX = xX; % design structure
SPM.xC = xC; % covariate structure
SPM.xGX = xGX; % global structure
SPM.xVi = xVi; % non-sphericity structure
SPM.xM = xM; % mask structure
SPM.xsDes = xsDes; % description
SPM.SPMid = SPMid; % version
%-Save SPM.mat and set output argument
%-------------------------------------------------------------------
fprintf('%-40s: ','Saving SPM configuration') %-#
if spm_check_version('matlab','7') >=0
save('SPM.mat', 'SPM', '-V6');
else
save('SPM.mat', 'SPM');
end;
fprintf('%30s\n','...SPM.mat saved') %-#
varargout = {SPM};
%-Display Design report
%===================================================================
fprintf('%-40s: ','Design reporting') %-#
fname = cat(1,{SPM.xY.VY.fname}');
spm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes)
fprintf('%30s\n','...done')
%-End: Cleanup GUI
%===================================================================
spm_clf(Finter)
spm('Pointer','Arrow')
fprintf('%-40s: %30s\n','Completed',spm('time')) %-#
spm('FigName','Stats: configured',Finter,CmdLine);
spm('Pointer','Arrow')
fprintf('\n\n')
case 'files&indices'
%===================================================================
% - Get files and factor indices
%===================================================================
% [P,I] = spm_spm_ui('Files&Indices',DsF,Dn,DbaTime,nV)
% DbaTime=D.b.aTime; Dn=D.n; DsF=D.sF;
if nargin<5, nV = 1; else, nV = varargin{5}; end
if nargin<4, DbaTime = 1; else, DbaTime = varargin{4}; end
if nargin<3, Dn = [Inf,Inf,Inf,Inf]; else, Dn=varargin{3}; end
if nargin<2, DsF = {'Fac1','Fac2','Fac3','Fac4'}; else, DsF=varargin{2}; end
%-Initialise variables
%-------------------------------------------------------------------
i4 = []; % factor 4 index (usually group)
i3 = []; % factor 3 index (usually subject), per f4
i2 = []; % factor 2 index (usually condition), per f3/f4
i1 = []; % factor 1 index (usually replication), per f2/f3/f4
P = {}; % cell array of string filenames
%-Accrue filenames and factor level indicator vectors
%-------------------------------------------------------------------
bMV = nV>1;
if isinf(Dn(4)), n4 = spm_input(['#',DsF{4},'''s'],'+1','n1');
else, n4 = Dn(4); end
bL4 = n4>1;
ti2 = '';
GUIpos = spm_input('!NextPos');
for j4 = 1:n4
spm_input('!SetNextPos',GUIpos);
sF4P=''; if bL4, sF4P=[DsF{4},' ',int2str(j4),': ']; end
if isinf(Dn(3)), n3=spm_input([sF4P,'#',DsF{3},'''s'],'+1','n1');
else, n3 = Dn(3); end
bL3 = n3>1;
if DbaTime & Dn(2)>1
%disp('NB:selecting in time order - manually specify conditions')
%-NB: This means f2 levels might not be 1:n2
GUIpos2 = spm_input('!NextPos');
for j3 = 1:n3
sF3P=''; if bL3, sF3P=[DsF{3},' ',int2str(j3),': ']; end
str = [sF4P,sF3P];
tP = {};
n21 = Dn(2)*Dn(1);
for v=1:nV
vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end
ttP = cellstr(spm_select(n21,'image',[str,'select images',vstr]));
n21 = length(ttP);
tP = [tP,ttP];
end
ti2 = spm_input([str,' ',DsF{2},'?'],GUIpos2,'c',ti2',n21,Dn(2));
%-Work out i1 & check
[tl2,null,j] = unique(ti2);
tn1 = zeros(size(tl2)); ti1 = zeros(size(ti2));
for i=1:length(tl2)
tn1(i)=sum(j==i); ti1(ti2==tl2(i))=1:tn1(i); end
if isfinite(Dn(1)) & any(tn1~=Dn(1))
%-#i1 levels mismatches specification in Dn(1)
error(sprintf('#%s not %d as pre-specified',DsF{1},Dn(1)))
end
P = [P;tP];
i4 = [i4; j4*ones(n21,1)];
i3 = [i3; j3*ones(n21,1)];
i2 = [i2; ti2];
i1 = [i1; ti1];
end
else
if isinf(Dn(2))
n2 = spm_input([sF4P,'#',DsF{2},'''s'],'+1','n1');
else
n2 = Dn(2);
end
bL2 = n2>1;
if n2==1 & Dn(1)==1 %-single scan per f3 (subj)
%disp('NB:single scan per f3')
str = [sF4P,'select images, ',DsF{3},' 1-',int2str(n3)];
tP = {};
for v=1:nV
vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end
ttP = cellstr(spm_select(n3,'image',[str,vstr]));
tP = [tP,ttP];
end
P = [P;tP];
i4 = [i4; j4*ones(n3,1)];
i3 = [i3; [1:n3]'];
i2 = [i2; ones(n3,1)];
i1 = [i1; ones(n3,1)];
else
%-multi scan per f3 (subj) case
%disp('NB:multi scan per f3')
for j3 = 1:n3
sF3P=''; if bL3, sF3P=[DsF{3},' ',int2str(j3),': ']; end
if Dn(1)==1
%-No f1 (repl) within f2 (cond)
%disp('NB:no f1 within f2')
str = [sF4P,sF3P,'select images: ',DsF{2},...
' 1-',int2str(n2)];
tP = {};
for v=1:nV
vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end
ttP = cellstr(spm_select(n2,'image',[str,vstr]));
tP = [tP,ttP];
end
P = [P;tP];
i4 = [i4; j4*ones(n2,1)];
i3 = [i3; j3*ones(n2,1)];
i2 = [i2; [1:n2]'];
i1 = [i1; ones(n2,1)];
else
%-multi f1 (repl) within f2 (cond)
%disp('NB:f1 within f2')
for j2 = 1:n2
sF2P='';
if bL2, sF2P=[DsF{2},' ',int2str(j2),': ']; end
str = [sF4P,sF3P,sF2P,' select images...'];
tP = {};
n1 = Dn(1);
for v=1:nV
vstr=''; if bMV, vstr=sprintf(' (var-%d)',v); end
ttP = cellstr(spm_select(n1,'image',[str,vstr]));
n1 = length(ttP);
tP = [tP,ttP];
end
P = [P;tP];
i4 = [i4; j4*ones(n1,1)];
i3 = [i3; j3*ones(n1,1)];
i2 = [i2; j2*ones(n1,1)];
i1 = [i1; [1:n1]'];
end % (for j2)
end % (if Dn(1)==1)
end % (for j3)
end % (if n2==1 &...)
end % (if DbaTime & Dn(2)>1)
end % (for j4)
varargout = {P,[i1,i2,i3,i4]};
case 'desdefs_stats'
%===================================================================
% - Basic Stats Design definitions...
%===================================================================
% D = spm_spm_ui('DesDefs_Stats');
% These are the basic Stats design definitions...
%-Note: struct expands cell array values to give multiple records:
% => must embed cell arrays within another cell array!
%-Negative indices indicate defaults (first used)
D = struct(...
'DesName','One sample t-test',...
'n', [Inf 1 1 1], 'sF',{{'obs','','',''}},...
'Hform', 'I(:,2),''-'',''mean''',...
'Bform', '[]',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',-Inf,'I',Inf,'X',Inf),...
'b',struct('aTime',0));
D = [D, struct(...
'DesName','Two sample t-test',...
'n', [Inf 2 1 1], 'sF',{{'obs','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',1))];
D = [D, struct(...
'DesName','Paired t-test',...
'n', [1 2 Inf 1], 'sF',{{'','cond','pair',''}},...
'Hform', 'I(:,2),''-'',''condition''',...
'Bform', 'I(:,3),''-'',''\gamma''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','One way Anova',...
'n', [Inf Inf 1 1], 'sF',{{'repl','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', '[]',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','One way Anova (with constant)',...
'n', [Inf Inf 1 1], 'sF',{{'repl','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','One way Anova (Within-subjects)',...
'n', [1 Inf Inf 1],'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Simple regression (correlation)',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', 'I(:,2),''-'',''\mu''',...
'nC',[1,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Multiple regression',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', '[]',...
'nC',[Inf,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Multiple regression (with constant)',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', 'I(:,2),''-'',''\mu''',...
'nC',[Inf,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','AnCova',...
'n', [Inf Inf 1 1], 'sF',{{'repl','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,1],'iCC',{{8,1}},'iCFI',{{1,1}},...
'iGXcalc',[-1,2,3],'iGMsca',[1,-9],'GM',[],...
'iGloNorm',9,'iGC',12,...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',0))];
varargout = {D};
case 'desdefs_pet'
%===================================================================
% - Standard (SPM99) PET/SPECT Design definitions...
%===================================================================
% D = spm_spm_ui('DesDefs_PET');
% These are the standard PET design definitions...
%-Single subject
%-------------------------------------------------------------------
D = struct(...
'DesName','Single-subject: conditions & covariates',...
'n', [Inf Inf 1 1], 'sF',{{'repl','condition','',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[Inf,Inf],'iCC',{{[-1,3,8],[-1,8]}},'iCFI',{{[1,3],1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1));
D = [D, struct(...
'DesName','Single-subject: covariates only',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[Inf,Inf],'iCC',{{[-1,8],[-1,8]}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1))];
%-Multi-subject
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','Multi-subj: conditions & covariates',...
'n',[Inf Inf Inf 1], 'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{[1,3,4,8],[1,4,8]}},'iCFI',{{[1,3,-4],[1,-4]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...
'iGloNorm',[4,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1))];
D = [D, struct(...
'DesName','Multi-subj: cond x subj interaction & covariates',...
'n',[Inf Inf Inf 1], 'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,[3,2]),''-'',{''subj'',''cond''}',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{[1,3,4,8],[1,4,8]}},'iCFI',{{[1,3,-4],[1,-4]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...
'iGloNorm',[4,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1))];
D = [D, struct(...
'DesName','Multi-subj: covariates only',...
'n',[Inf 1 Inf 1], 'sF',{{'repl','','subject',''}},...
'Hform', '[]',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{[1,4,8],[1,4,8]}},'iCFI',{{[1,-4],[1,-4]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-4,9],'GM',50,...
'iGloNorm',[4,8:9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Multi-group
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','Multi-group: conditions & covariates',...
'n',[Inf Inf Inf Inf], 'sF',{{'repl','condition','subject','group'}},...
'Hform', 'I(:,[4,2]),''-'',{''stud'',''cond''}',...
'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{[5:8],[5,7,8]}},'iCFI',{{[1,5,6,-7],[1,5,-7]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-7,9],'GM',50,...
'iGloNorm',[7,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',1))];
D = [D, struct(...
'DesName','Multi-group: covariates only',...
'n',[Inf 1 Inf Inf], 'sF',{{'repl','','subject','group'}},...
'Hform', '[]',...
'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{[5,7,8],[5,7,8]}},'iCFI',{{[1,5,-7],[1,5,-7]}},...
'iGXcalc',[1,2,-3],'iGMsca',[-7,9],'GM',50,...
'iGloNorm',[7,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Population comparisons
%-------------------------------------------------------------------
D = [D, struct(...
'DesName',...
'Population main effect: 2 cond''s, 1 scan/cond (paired t-test)',...
'n',[1 2 Inf 1], 'sF',{{'','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName',...
'Dodgy population main effect: >2 cond''s, 1 scan/cond',...
'n',[1 Inf Inf 1], 'sF',{{'','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Compare-populations: 1 scan/subject (two sample t-test)',...
'n',[Inf 2 1 1], 'sF',{{'subject','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','Compare-populations: 1 scan/subject (AnCova)',...
'n',[Inf 2 1 1], 'sF',{{'subject','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,Inf],'iCC',{{8,1}},'iCFI',{{1,1}},...
'iGXcalc',[1,2,-3],'iGMsca',[-1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0,0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-The Full Monty!
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','The Full Monty...',...
'n',[Inf Inf Inf Inf], 'sF',{{'repl','cond','subj','group'}},...
'Hform', 'I(:,[4,2]),''-'',{''stud'',''cond''}',...
'Bform', 'I(:,[4,3]),''-'',{''stud'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{[1:8],[1:8]}},'iCFI',{{[1:7],[1:7]}},...
'iGXcalc',[1,2,3],'iGMsca',[1:7],'GM',50,...
'iGloNorm',[1:9],'iGC',[1:11],...
'M_',struct('T',[-Inf,0,0.8*sqrt(-1)],'I',Inf,'X',Inf),...
'b',struct('aTime',1))];
varargout = {D};
case 'desdefs_pet96'
%===================================================================
% - SPM96 PET/SPECT Design definitions...
%===================================================================
% D = spm_spm_ui('DesDefs_PET96');
%-Single subject
%-------------------------------------------------------------------
D = struct(...
'DesName','SPM96:Single-subject: replicated conditions',...
'n', [Inf Inf 1 1], 'sF',{{'repl','condition','',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0));
D = [D, struct(...
'DesName','SPM96:Single-subject: replicated conditions & covariates',...
'n', [Inf Inf 1 1], 'sF',{{'repl','condition','',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Single-subject: covariates only',...
'n', [Inf 1 1 1], 'sF',{{'repl','','',''}},...
'Hform', '[]',...
'Bform', 'I(:,3),''-'',''\mu''',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Multi-subject
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','SPM96:Multi-subject: different conditions',...
'n', [1 Inf Inf 1], 'sF',{{'','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''scancond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-subject: replicated conditions',...
'n',[Inf Inf Inf 1], 'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-subject: different conditions & covariates',...
'n', [1 Inf Inf 1], 'sF',{{'','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''cond''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,4],[1,4]}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-subject: replicated conditions & covariates',...
'n',[Inf Inf Inf 1], 'sF',{{'repl','condition','subject',''}},...
'Hform', 'I(:,2),''-'',''condition''',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,3,4],[1,4]}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-subject: covariates only',...
'n',[Inf 1 Inf 1], 'sF',{{'repl','','subject',''}},...
'Hform', '[]',...
'Bform', 'I(:,3),''-'',''subj''',...
'nC',[Inf,Inf],'iCC',{{[1,4,8],[1,4,8]}},'iCFI',{{[1,4],[1,4]}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,4,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Multi-study
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','SPM96:Multi-study: different conditions',...
'n',[1 Inf Inf Inf], 'sF',{{'','cond','subj','study'}},...
'Hform', 'I(:,[4,2]),''-'',{''study'',''cond''}',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-study: replicated conditions',...
'n',[Inf Inf Inf Inf], 'sF',{{'repl','cond','subj','study'}},...
'Hform', 'I(:,[4,2]),''-'',{''study'',''condition''}',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-study: different conditions & covariates',...
'n',[1 Inf Inf Inf], 'sF',{{'','cond','subj','study'}},...
'Hform', 'I(:,[4,2]),''-'',{''study'',''cond''}',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,6,7],[1,5,7]}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-study: replicated conditions & covariates',...
'n',[Inf Inf Inf Inf], 'sF',{{'','cond','subj','study'}},...
'Hform', 'I(:,[4,2]),''-'',{''study'',''condition''}',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,6,7],[1,5,7]}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
D = [D, struct(...
'DesName','SPM96:Multi-study: covariates only',...
'n',[Inf 1 Inf Inf], 'sF',{{'repl','','subj','study'}},...
'Hform', '[]',...
'Bform', 'I(:,[4,3]),''-'',{''study'',''subj''}',...
'nC',[Inf,Inf],'iCC',{{1,1}},'iCFI',{{[1,5,7],[1,5,7]}},...
'iGXcalc',3,'iGMsca',[1,5,9],'GM',50,...
'iGloNorm',[1,5,7,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
%-Group comparisons
%-------------------------------------------------------------------
D = [D, struct(...
'DesName','SPM96:Compare-groups: 1 scan per subject',...
'n',[Inf Inf 1 1], 'sF',{{'subject','group','',''}},...
'Hform', 'I(:,2),''-'',''group''',...
'Bform', '[]',...
'nC',[0,0],'iCC',{{8,8}},'iCFI',{{1,1}},...
'iGXcalc',3,'iGMsca',[1,9],'GM',50,...
'iGloNorm',[1,8,9],'iGC',10,...
'M_',struct('T',[0.8*sqrt(-1)],'I',0,'X',0),...
'b',struct('aTime',0))];
varargout = {D};
otherwise
%===================================================================
% - U N K N O W N A C T I O N
%===================================================================
warning(['Illegal Action string: ',Action])
%===================================================================
% - E N D
%===================================================================
end
%=======================================================================
%- S U B - F U N C T I O N S
%=======================================================================
function str = sf_estrrep(str,srstr)
%=======================================================================
for i = 1:size(srstr,1)
str = strrep(str,srstr{i,1},srstr{i,2});
end
|
github
|
philippboehmsturm/antx-master
|
spm_minmax.m
|
.m
|
antx-master/xspm8/spm_minmax.m
| 3,751 |
utf_8
|
1a7267151fb6239e66dbd59584c49bea
|
function [mnv,mxv] = spm_minmax(g)
% Compute a suitable range of intensities for VBM preprocessing stuff
% FORMAT [mnv,mxv] = spm_minmax(g)
% g - array of data
% mnv - minimum value
% mxv - maximum value
%
% A MOG with two Gaussians is fitted to the intensities. The lower
% Gaussian is assumed to represent background. The lower value is
% where there is a 50% probability of being above background. The
% upper value is one that encompases 99.5% of the values.
%____________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_minmax.m 2774 2009-02-23 14:40:17Z john $
d = [size(g) 1];
mxv = double(max(g(:)));
mnv = double(min(g(:)));
h = zeros(256,1);
spm_progress_bar('Init',d(3),'Initial histogram','Planes loaded');
sw = warning('off','all');
for i=1:d(3)
h = h + spm_hist(uint8(round(g(:,:,i)*(255/mxv))),ones(d(1)*d(2),1));
spm_progress_bar('Set',i);
end;
warning(sw);
spm_progress_bar('Clear');
% Occasional problems with partially masked data because the first Gaussian
% just fits the big peak at zero. This will fix that one, but cause problems
% for skull-stripped data.
h(1) = 0;
h(end) = 0;
% Very crude heuristic to find a suitable lower limit. The large amount
% of background really messes up mutual information registration.
% Begin by modelling the intensity histogram with two Gaussians. One
% for background, and the other for tissue.
[mn,v,mg] = fithisto((0:255)',h,1000,[1 128],[32 128].^2,[1 1]);
pr = distribution(mn,v,mg,(0:255)');
%fg = spm_figure('FindWin','Interactive');
%if ~isempty(fg)
% figure(fg);
% plot((0:255)',h/sum(h),'b', (0:255)',pr,'r');
% drawnow;
%end;
% Find the lowest intensity above the mean of the first Gaussian
% where there is more than 50% probability of not being background
mnd = find((pr(:,1)./(sum(pr,2)+eps) < 0.5) & (0:255)' >mn(1));
if isempty(mnd) || mnd(1)==1 || mn(1)>mn(2),
mnd = 1;
else
mnd = mnd(1)-1;
end
mnv = mnd*mxv/255;
% Upper limit should get 99.5% of the intensities of the
% non-background region
ch = cumsum(h(mnd:end))/sum(h(mnd:end));
ch = find(ch>0.995)+mnd;
mxv = ch(1)/255*mxv;
return;
%_______________________________________________________________________
%_______________________________________________________________________
function [mn,v,mg,ll]=fithisto(x,h,maxit,n,v,mg)
% Fit a mixture of Gaussians to a histogram
h = h(:);
x = x(:);
sml = mean(diff(x))/1000;
if nargin==4
mg = sum(h);
mn = sum(x.*h)/mg;
v = (x - mn); v = sum(v.*v.*h)/mg*ones(1,n);
mn = (1:n)'/n*(max(x)-min(x))+min(x);
mg = mg*ones(1,n)/n;
elseif nargin==6
mn = n;
n = length(mn);
else
error('Incorrect usage');
end;
ll = Inf;
for it=1:maxit
prb = distribution(mn,v,mg,x);
scal = sum(prb,2)+eps;
oll = ll;
ll = -sum(h.*log(scal));
if it>2 && oll-ll < length(x)/n*1e-9
break;
end;
for j=1:n
p = h.*prb(:,j)./scal;
mg(j) = sum(p);
mn(j) = sum(x.*p)/mg(j);
vr = x-mn(j);
v(j) = sum(vr.*vr.*p)/mg(j)+sml;
end;
mg = mg + 1e-3;
mg = mg/sum(mg);
end;
%_______________________________________________________________________
%_______________________________________________________________________
function y=distribution(m,v,g,x)
% Gaussian probability density
if nargin ~= 4
error('not enough input arguments');
end;
x = x(:);
m = m(:);
v = v(:);
g = g(:);
if ~all(size(m) == size(v) & size(m) == size(g))
error('incompatible dimensions');
end;
for i=1:size(m,1)
d = x-m(i);
amp = g(i)/sqrt(2*pi*v(i));
y(:,i) = amp*exp(-0.5 * (d.*d)/v(i));
end;
return;
|
github
|
philippboehmsturm/antx-master
|
spm_create_vol.m
|
.m
|
antx-master/xspm8/spm_create_vol.m
| 4,967 |
utf_8
|
7a051f745805c44e02ffd7b190e4a2c8
|
function V = spm_create_vol(V,varargin)
% Create a volume
% FORMAT V = spm_create_vol(V)
% V - image volume information (see spm_vol.m)
%____________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
% John Ashburner
% $Id: spm_create_vol.m 1169 2008-02-26 14:53:43Z volkmar $
for i=1:numel(V),
if nargin>1,
v = create_vol(V(i),varargin{:});
else
v = create_vol(V(i));
end;
f = fieldnames(v);
for j=1:size(f,1),
V(i).(f{j}) = v.(f{j});
end;
end;
function V = create_vol(V,varargin)
if ~isstruct(V), error('Not a structure.'); end;
if ~isfield(V,'fname'), error('No "fname" field'); end;
if ~isfield(V,'dim'), error('No "dim" field'); end;
if ~all(size(V.dim)==[1 3]),
error(['"dim" field is the wrong size (' num2str(size(V.dim)) ').']);
end;
if ~isfield(V,'n'),
V.n = [1 1];
else
V.n = [V.n(:)' 1 1];
V.n = V.n(1:2);
end;
if V.n(1)>1 && V.n(2)>1,
error('Can only do up to 4D data (%s).',V.fname);
end;
if ~isfield(V,'dt'),
V.dt = [spm_type('float64') spm_platform('bigend')];
end;
dt{1} = spm_type(V.dt(1));
if strcmp(dt{1},'unknown'),
error(['"' dt{1} '" is an unrecognised datatype (' num2str(V.dt(1)) ').']);
end;
if V.dt(2), dt{2} = 'BE'; else dt{2} = 'LE'; end;
if ~isfield(V,'pinfo'), V.pinfo = [Inf Inf 0]'; end;
if size(V.pinfo,1)==2, V.pinfo(3,:) = 0; end;
V.fname = deblank(V.fname);
[pth,nam,ext] = fileparts(V.fname);
switch ext,
case {'.img'}
minoff = 0;
case {'.nii'}
minoff = 352;
otherwise
error(['"' ext '" is not a recognised extension.']);
end;
bits = spm_type(V.dt(1),'bits');
minoff = minoff + ceil(prod(V.dim(1:2))*bits/8)*V.dim(3)*(V.n(1)-1+V.n(2)-1);
V.pinfo(3,1) = max(V.pinfo(3,:),minoff);
if ~isfield(V,'descrip'), V.descrip = ''; end;
if ~isfield(V,'private'), V.private = struct; end;
dim = [V.dim(1:3) V.n];
dat = file_array(V.fname,dim,[dt{1} '-' dt{2}],0,V.pinfo(1),V.pinfo(2));
N = nifti;
N.dat = dat;
N.mat = V.mat;
N.mat0 = V.mat;
N.mat_intent = 'Aligned';
N.mat0_intent = 'Aligned';
N.descrip = V.descrip;
try
N0 = nifti(V.fname);
% Just overwrite if both are single volume files.
tmp = [N0.dat.dim ones(1,5)];
if prod(tmp(4:end))==1 && prod(dim(4:end))==1
N0 = [];
end;
catch
N0 = [];
end;
if ~isempty(N0),
% If the dimensions differ, then there is the potential for things to go badly wrong.
tmp = [N0.dat.dim ones(1,5)];
if any(tmp(1:3) ~= dim(1:3))
warning(['Incompatible x,y,z dimensions in file "' V.fname '" [' num2str(tmp(1:3)) ']~=[' num2str(dim(1:3)) '].']);
end;
if dim(5) > tmp(5) && tmp(4) > 1,
warning(['Incompatible 4th and 5th dimensions in file "' V.fname '" (' num2str([tmp(4:5) dim(4:5)]) ').']);
end;
N.dat.dim = [dim(1:3) max(dim(4:5),tmp(4:5))];
if ~strcmp(dat.dtype,N0.dat.dtype),
warning(['Incompatible datatype in file "' V.fname '" ' N0.dat.dtype ' ~= ' dat.dtype '.']);
end;
if single(N.dat.scl_slope) ~= single(N0.dat.scl_slope) && (size(N0.dat,4)>1 || V.n(1)>1),
warning(['Incompatible scalefactor in "' V.fname '" ' num2str(N0.dat.scl_slope) '~=' num2str(N.dat.scl_slope) '.']);
end;
if single(N.dat.scl_inter) ~= single(N0.dat.scl_inter),
warning(['Incompatible intercept in "' V.fname '" ' num2str(N0.dat.scl_inter) '~=' num2str(N.dat.scl_inter) '.']);
end;
if single(N.dat.offset) ~= single(N0.dat.offset),
warning(['Incompatible intercept in "' V.fname '" ' num2str(N0.dat.offset) '~=' num2str(N.dat.offset) '.']);
end;
if V.n(1)==1,
% Ensure volumes 2..N have the original matrix
nt = size(N.dat,4);
if nt>1 && sum(sum((N0.mat-V.mat).^2))>1e-8,
M0 = N0.mat;
if ~isfield(N0.extras,'mat'),
N0.extras.mat = zeros([4 4 nt]);
else
if size(N0.extras.mat,4)<nt,
N0.extras.mat(:,:,nt) = zeros(4);
end;
end;
for i=2:nt,
if sum(sum(N0.extras.mat(:,:,i).^2))==0,
N0.extras.mat(:,:,i) = M0;
end;
end;
N.extras.mat = N0.extras.mat;
end;
N0.mat = V.mat;
if strcmp(N0.mat0_intent,'Aligned'), N.mat0 = V.mat; end;
if ~isempty(N.extras) && isstruct(N.extras) && isfield(N.extras,'mat') &&...
size(N.extras.mat,3)>=1,
N.extras.mat(:,:,V.n(1)) = V.mat;
end;
else
N.extras.mat(:,:,V.n(1)) = V.mat;
end;
if ~isempty(N0.extras) && isstruct(N0.extras) && isfield(N0.extras,'mat'),
N0.extras.mat(:,:,V.n(1)) = N.mat;
N.extras = N0.extras;
end;
if sum((V.mat(:)-N0.mat(:)).^2) > 1e-4,
N.extras.mat(:,:,V.n(1)) = V.mat;
end;
end;
create(N);
V.private = N;
|
github
|
philippboehmsturm/antx-master
|
spm_check_results.m
|
.m
|
antx-master/xspm8/spm_check_results.m
| 2,501 |
utf_8
|
a9b2a3fb54c8c128a16928e69bb03bb4
|
function spm_check_results(SPMs,xSPM)
% Display several MIPs in the same figure
% FORMAT spm_check_results(SPMs,xSPM)
% SPMs - char or cell array of paths to SPM.mat[s]
% xSPM - structure containing thresholding details, see spm_getSPM.m
%
% Beware: syntax and features of this function are likely to change.
%__________________________________________________________________________
% Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_check_results.m 4661 2012-02-20 17:48:16Z guillaume $
cwd = pwd;
%-Get input parameter SPMs
%--------------------------------------------------------------------------
if ~nargin || isempty(SPMs)
[SPMs, sts] = spm_select(Inf,'^SPM\.mat$','Select SPM.mat[s]');
if ~sts, return; end
end
SPMs = cellstr(SPMs);
%-Get input parameter xSPM
%--------------------------------------------------------------------------
xSPM.swd = spm_file(SPMs{1},'fpath');
try, [xSPM.thresDesc, xSPM.u] = convert_desc(xSPM.thresDesc); end
[tmp, xSPM] = spm_getSPM(xSPM);
if ~isfield(xSPM,'units'), xSPM.units = {'mm' 'mm' 'mm'}; end
[xSPM.thresDesc, xSPM.u] = convert_desc(xSPM.thresDesc);
%-
%--------------------------------------------------------------------------
Fgraph = spm_figure('GetWin','Graphics');
spm_figure('Clear','Graphics');
mn = numel(SPMs);
n = round(mn^0.4);
m = ceil(mn/n);
w = 1/n;
h = 1/m;
ds = (w+h)*0.02;
for ij=1:numel(SPMs)
i = 1-h*(floor((ij-1)/n)+1);
j = w*rem(ij-1,n);
xSPM.swd = spm_file(SPMs{ij},'fpath');
[tmp, myxSPM] = spm_getSPM(xSPM);
hMIPax(ij) = axes('Parent',Fgraph,'Position',[j+ds/2 i+ds/2 w-ds h-ds],'Visible','off');
hMIPax(ij) = spm_mip_ui(myxSPM.Z,myxSPM.XYZmm,myxSPM.M,myxSPM.DIM,hMIPax(ij),myxSPM.units);
axis(hMIPax(ij),'image');
set(findobj(hMIPax(ij),'type','image'),'UIContextMenu',[]);
hReg = get(hMIPax(ij),'UserData');
set(hReg.hXr,'visible','off');
set(hReg.hMIPxyz,'visible','off');
end
linkaxes(hMIPax);
cd(cwd);
%==========================================================================
% function [str, u] = convert_desc(str)
%==========================================================================
function [str, u] = convert_desc(str)
td = regexp(str,'p\D?(?<u>[\.\d]+) \((?<thresDesc>\S+)\)','names');
if isempty(td)
td = regexp(str,'\w=(?<u>[\.\d]+)','names');
td.thresDesc = 'none';
end
if strcmp(td.thresDesc,'unc.'), td.thresDesc = 'none'; end
u = str2double(td.u);
str = td.thresDesc;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.