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
|
uoguelph-mlrg/vlr-master
|
reslice_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/reslice_nii.m
| 9,817 |
utf_8
|
05783cd4f127a22486db67a9cc89ad2a
|
% 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
|
uoguelph-mlrg/vlr-master
|
save_untouch_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/save_untouch_nii.m
| 6,494 |
utf_8
|
50fa95cbb847654356241a853328f912
|
% 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
|
uoguelph-mlrg/vlr-master
|
view_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/view_nii.m
| 139,608 |
utf_8
|
74f9dea7539a45a7993beb22becf2fa2
|
% 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
|
uoguelph-mlrg/vlr-master
|
mat_into_hdr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/mat_into_hdr.m
| 2,608 |
utf_8
|
d53006b93ff90a4a5561d16ff2f4e9a6
|
%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
|
uoguelph-mlrg/vlr-master
|
xform_nii.m
|
.m
|
vlr-master/utils/nii/nifti_DL/xform_nii.m
| 18,107 |
utf_8
|
29a1cff91c944d6a93e5101946a5da4d
|
% 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
|
uoguelph-mlrg/vlr-master
|
make_ana.m
|
.m
|
vlr-master/utils/nii/nifti_DL/make_ana.m
| 5,455 |
utf_8
|
2f62999cbcad72129c892135ff492a1e
|
% 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
|
uoguelph-mlrg/vlr-master
|
extra_nii_hdr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/extra_nii_hdr.m
| 7,830 |
utf_8
|
853f39f00cbf133e90d0f2cf08d79488
|
% 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
|
uoguelph-mlrg/vlr-master
|
rri_xhair.m
|
.m
|
vlr-master/utils/nii/nifti_DL/rri_xhair.m
| 2,208 |
utf_8
|
b3ae9df90d43e5d9538b6b135fa8af20
|
% 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
|
uoguelph-mlrg/vlr-master
|
save_untouch_nii_hdr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/save_untouch_nii_hdr.m
| 8,514 |
utf_8
|
582f82c471a9a8826eda59354f61dd1a
|
% 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
|
uoguelph-mlrg/vlr-master
|
expand_nii_scan.m
|
.m
|
vlr-master/utils/nii/nifti_DL/expand_nii_scan.m
| 1,333 |
utf_8
|
748da05d09c1a005401c67270c4b94ab
|
% 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
|
uoguelph-mlrg/vlr-master
|
load_untouch_header_only.m
|
.m
|
vlr-master/utils/nii/nifti_DL/load_untouch_header_only.m
| 7,068 |
utf_8
|
8996c72db42b01029c92a4ecd88f4b21
|
% 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
|
uoguelph-mlrg/vlr-master
|
bipolar.m
|
.m
|
vlr-master/utils/nii/nifti_DL/bipolar.m
| 2,145 |
utf_8
|
295f87ece96ca4c5dff8dce4cd912a34
|
%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
|
uoguelph-mlrg/vlr-master
|
save_nii_hdr.m
|
.m
|
vlr-master/utils/nii/nifti_DL/save_nii_hdr.m
| 9,270 |
utf_8
|
f97c194f5bfc667eb4f96edf12be02a7
|
% 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
|
uoguelph-mlrg/vlr-master
|
makediffeos.m
|
.m
|
vlr-master/spm/deform/makediffeos.m
| 1,338 |
utf_8
|
8bde1c01636201ff1d3eba506055a424
|
% MAKEDIFFEOS
% Calling the functions mni2ptx_old and ptx2mni_old re-computes a transformation
% matrix which is expensive to compute and can easily be saved as a mat file.
% The purpose of this function is to pre-compute those transforms (T) for use by
% the new mni2ptx and ptx2mni to transform between mni and ptx quickly. You must
% run makealldiffeos first.
function [] = makediffeos(N,nvec)
for n = nvec
for t = 1:2
switch t
case 1
xform = imglutname('xform', N,n,1);
templatei = imgname('mni:FLAIR', n,1);
templateo = imglutname('FLAIR', N,n,1);
savename = imglutname('mni2ptx',N,n,0);
case 2
xform = imglutname('ixform', N,n,1);
templatei = imglutname('FLAIR', N,n,1);
templateo = imgname('mni:FLAIR', n,1);
savename = imglutname('ptx2mni',N,n,0);
end
ni = nifti(templatei);
no = nifti(templateo);
nx = nifti(xform);
si = size(ni.dat);
so = size(no.dat);
M = nx.mat\ni.mat;
X = spm_affine(squeeze(single(nx.dat(:,:,:,1,:))),inv(no.mat));
T = zeros([si,3],'single');
for d = 1:3
for z = 1:si(3)
Mz = M*spm_matrix([0,0,z]);
Tzd = spm_slice_vol(X(:,:,:,d),Mz,si(1:2),[1,nan]);
T(:,:,z,d) = single(Tzd);
end
end
save(savename,'T','so');
end
end
|
github
|
uoguelph-mlrg/vlr-master
|
spmdeform_old.m
|
.m
|
vlr-master/spm/deform/spmdeform_old.m
| 2,052 |
utf_8
|
d3c51e0733a8e7cddb779f509aba4d00
|
% SPMDEFORM
% This function calls SPM's deform tool to warp 3D image arrays (varargin)
% according to the transformation file xform
% (this is given as a filename: the xform estimated by SPM previously).
% This requires saving the images as nii temporarily.
% The xform filename is used as a temporary directory.
% All input images for warping are saved using the format spmdef_#.
% All output images after warping are saved using the format ospmdef_#.
% On completion, the temporary images are read in as MATLAB 3D arrays,
% and the nii files deleted (but not the temporary directory).
function [varargout] = spmdeform_old(xform,templatei,templateo,varargin)
[~,tmp,~] = fileparts(xform);
tdir = tmpname(tmp);
if ~exist(tdir,'dir'), mkdir(tdir); end
fname = fullfile(tdir,'@spmdef_#.nii');
for i = 1:numel(varargin)
% generate file name
namei{i,1} = strrep(strrep(fname,'@', ''),'#',num2str(i));
nameo{i,1} = strrep(strrep(fname,'@','o'),'#',num2str(i));
% write the input image to file using templatei
writenii(imrotate(varargin{i},180), namei{i}, templatei);
end
while ~all(cellfun(@(f)exist(f,'file'),namei)), pause(0.05); end
% run the SPM deformation module
matlabbatch = makebatch(xform,namei,templateo);
spm_jobman('run',matlabbatch);
% read the outputs from file and delete the temporary nii files
while ~all(cellfun(@(f)exist(f,'file'),nameo)), pause(0.05); end
for i = 1:numel(varargin)
varargout{i} = imrotate(readnii(nameo{i}),180);
end
pause(0.5);
for i = 1:numel(varargin)
delete(namei{i},nameo{i});
end
function [matlabbatch] = makebatch(xform,namei,templateo)
matlabbatch{1}.spm.util.defs.comp{1}.def = {xform};
matlabbatch{1}.spm.util.defs.out{1}.push.fnames = namei;
matlabbatch{1}.spm.util.defs.out{1}.push.weight = {''};
matlabbatch{1}.spm.util.defs.out{1}.push.savedir.savesrc = 1;
matlabbatch{1}.spm.util.defs.out{1}.push.fov.file = {templateo};
matlabbatch{1}.spm.util.defs.out{1}.push.preserve = 0;
matlabbatch{1}.spm.util.defs.out{1}.push.fwhm = [0 0 0];
matlabbatch{1}.spm.util.defs.out{1}.push.prefix = 'o';
|
github
|
uoguelph-mlrg/vlr-master
|
spmdeform.m
|
.m
|
vlr-master/spm/deform/spmdeform.m
| 423 |
utf_8
|
3eebf56e73afeae5fd1c65139b9ec6d5
|
% SPMDEFORM
% This function is a wrapper for spm_diffeo('push',...)
% as implemented in 'push_def(Def,mat,job)' line 514 of spm_deformations.m
%
% Outputs will match the ordering of varargin.
function [varargout] = spmdeform(T,so,varargin)
for v = 1:numel(varargin)
Vi = single(varargin{v});
[Vo,c] = spm_diffeo('push',Vi,T,so);
spm_smooth(Vo,Vo,0.25);
spm_smooth(c,c,0.25);
varargout{v} = Vo./(c+0.001);
end
|
github
|
uoguelph-mlrg/vlr-master
|
ptx2mni_old.m
|
.m
|
vlr-master/spm/deform/ptx2mni_old.m
| 619 |
utf_8
|
e6c7c39fde2c210383721dde6decea7e
|
% MNI2PTX
% This function uses spmdeform to warp MNI space inputs (varargin) to pt space,
% using the deformation specified by imglutname('ixform',N,n) -- i.e. for pt 'n'
function [varargout] = ptx2mni_old(N,n,varargin)
xform = imglutname('ixform', N,n,1); % xform
templatei = imglutname('FLAIR', N,n,1); % pt space template
templateo = imgname ('mni:FLAIR',n,1); % mni space template
varargout = cell(size(varargin));
[varargout{:}] = imprep(+90,varargin{:});
[varargout{:}] = spmdeform_old(xform,templatei,templateo,varargin{:});
[varargout{:}] = imprep(-90,varargout{:});
|
github
|
uoguelph-mlrg/vlr-master
|
ptx2mni.m
|
.m
|
vlr-master/spm/deform/ptx2mni.m
| 452 |
utf_8
|
23f5f8dabeb2d1e65ca92e57f5f024a1
|
% MNI2PTX
% This function uses spmdeform to warp MNI space inputs (varargin) to pt space,
% using the deformation specified by imglutname('ixform',N,n) -- i.e. for pt 'n'
function [varargout] = ptx2mni(N,n,varargin)
xform = load(imglutname('ptx2mni',N,n,1)); % xform
varargout = cell(size(varargin));
[varargout{:}] = imprep(-90,varargin{:});
[varargout{:}] = spmdeform(xform.T,xform.so,varargout{:});
[varargout{:}] = imprep(+90,varargout{:});
|
github
|
uoguelph-mlrg/vlr-master
|
mni2ptx_old.m
|
.m
|
vlr-master/spm/deform/mni2ptx_old.m
| 621 |
utf_8
|
742c3e27fbd491cf0bd197258a15bbf4
|
% MNI2PTX
% This function uses spmdeform to warp pt space inputs (varargin) to MNI space,
% using the deformation specified by imglutname('xform',N,n) -- i.e. for pt 'n'
function [varargout] = mni2ptx_old(N,n,varargin)
xform = imglutname('xform', N,n,1); % xform
templatei = imgname ('mni:FLAIR',n,1); % mni space template
templateo = imglutname('FLAIR', N,n,1); % pt space template
varargout = cell([1,numel(varargin)]);
[varargout{:}] = imprep(+90,varargin{:});
[varargout{:}] = spmdeform_old(xform,templatei,templateo,varargin{:});
[varargout{:}] = imprep(-90,varargout{:});
|
github
|
uoguelph-mlrg/vlr-master
|
makealldiffeos.m
|
.m
|
vlr-master/spm/deform/makealldiffeos.m
| 1,308 |
utf_8
|
5e4adae5fe7bf236717ea96909cff8c2
|
% MAKEALLDIFFEOS
% This function pre-computes transformation matrices used by SPM to transform
% between native (ptx) and MNI space. The matrices are expensive to compute, so
% a hack-ish parallelization is used which spawns background matlab instances to
% complete more quickly.
function [] = makealldiffeos()
Ni = 129;
cpu = 5;
% the bat file
file.bat = 'tmp.bat';
% the code for execution
code = 'makediffeos(%d,[#]);';
% group the indices
bat = {[10]};
% create the file contents
for n = 1:cpu % cpu
i = num2cell(n:cpu:Ni);
nib = numel(i);
numstr = sprintf(repmat('%02.f,',[1,nib]),i{:});
codi = sprintf(strrep(code,'#',numstr),Ni);
bat{end+1} = ['@echo COMPUTING DIFFEOS ',numstr,'...',10];
bat{end+1} = ['@',matx(codi),10];
bat{end+1} = ['@timeout 0.5 > nul',10];
end
bat{end+1} = 'exit';
% write the file
fid = fopen(file.bat,'w');
fwrite(fid,cat(2,bat{:}));
fclose(fid);
while ~fileready(file.bat,1000), pause(0.1); end
eval(['!call ',file.bat,' &']); % execute the bat file
% xform is a filename specifying the SPM transform to be applied
% templatei is a filename specifying an input image template (affine xform)
% templateo is a filename specifying the output image template (size, fov, etc)
% varargin are image arrays to be transformed, whose size matches xform
|
github
|
uoguelph-mlrg/vlr-master
|
mni2ptx.m
|
.m
|
vlr-master/spm/deform/mni2ptx.m
| 454 |
utf_8
|
1045489efa2143f0fd053b4114acd6bc
|
% MNI2PTX
% This function uses spmdeform to warp pt space inputs (varargin) to MNI space,
% using the deformation specified by imglutname('xform',N,n) -- i.e. for pt 'n'
function [varargout] = mni2ptx(N,n,varargin)
xform = load(imglutname('mni2ptx',N,n,1)); % xform
varargout = cell([1,numel(varargin)]);
[varargout{:}] = imprep(-90,varargin{:});
[varargout{:}] = spmdeform(xform.T,xform.so,varargout{:});
[varargout{:}] = imprep(+90,varargout{:});
|
github
|
uoguelph-mlrg/vlr-master
|
plot_synthetic_histmatch.m
|
.m
|
vlr-master/figs/plot_synthetic_histmatch.m
| 2,817 |
utf_8
|
05c6dd57705544c06fafe4df3068a4c4
|
function [] = plot_synthetic_histmatch()
V = 100^3;
src = {'uniform','unimodal','bimodal','trimodal'};
clr = rainbow6; clr = clr([1,2,3,4],:);
tar = {'uniform','unimodal','bimodal','trimodal'};
for s = 1:numel(src), X{s} = data(V,src{s}); end
for t = 1:numel(tar), [T{t},pt{t}] = data(V,tar{t}); end
% plot original
figure; hold on;
for i = 1:numel(src)
Q(i,:) = plot_quantiles(X{i},clr(i,:),0);
end
saveplot('histmatch-q-original','y','f_{\textsc{y}}(y)',[0,1],[0,5]);
D0 = meanquantilediff(Q);
% plot after different matching
for t = 1:numel(T)
figure; hold on;
for i = 1:numel(src)
Y = histeq(X{i},pt{t});
Y = Y+0.01*randn(size(Y));
Q(i,:) = plot_quantiles(Y,clr(i,:),i/15);
end
fprintf(['%5.03f\n'],100*meanquantilediff(Q)/D0);
saveplot(['histmatch-q-',tar{t}],'\tilde{y}','f_{\tilde{\textsc{y}}}(\tilde{y})',[0,1],[0,5]);
end
% legend
figure;
for s = 1:numel(src), plot(nan(2,1),'color',clr(s,:)); hold on; end
plot(nan(2,1),'s','markersize',2,'color',lighten([0,0,0],0.5),'linewidth',2);
figresize(gcf,[300,200]);
leg = {'Uniform source','Unimodal source','Bimodal source','Trimodal source','Quantiles'};
legend(leg);
legend(gca,'boxoff');
set(gca,'xcolor','w','ycolor','w');
print(gcf,thesisname('fig','histmatch-q-legend'),'-depsc');
close(gcf);
function [p,u] = histogram(x)
du = 0.002;
u = 0:du:1;
x(x<0|x>1) = nan;
p = ksdensity(x,u,'support',[0-2*du,1+2*du],'width',5*du);
function [T,pt] = data(V,type)
[~,u] = histogram([0,1]); % dummy call
switch type
case 'uniform'
T = rand ([V,1]);
pt = ones(size(u));
case 'unimodal'
T = randn([V,1])*0.08 + 0.5;
pt = normpdf(u,0.5,0.08);
case 'bimodal'
T = [randn([0.5*V,1])*0.05+0.3; ...
randn([0.5*V,1])*0.05+0.7];
pt = 0.5*normpdf(u,0.3,0.05) ...
+ 0.5*normpdf(u,0.7,0.05);
case 'trimodal'
T = [randn([0.3*V,1])*0.05+0.25; ...
randn([0.4*V,1])*0.05+0.5; ...
randn([0.3*V,1])*0.05+0.75;];
pt = 0.3*normpdf(u,0.25,0.05) ...
+ 0.4*normpdf(u,0.50,0.05) ...
+ 0.3*normpdf(u,0.75,0.05);
end
function [Q] = plot_quantiles(X,clr,dy)
Q = quantile(X,linspace(0,1,15));
C = monomap(clr,numel(Q),[-1,+1]);
d = 1/4;
[p,u] = histogram(X);
hold on;
for q = 1:numel(Q)
[~,i] = min(abs(u-Q(q)));
y = clip([0:d:p(i)]+dy,[0,p(i)]);
x = Q(q)*ones(size(y));
plot(x,y,'s','markersize',2,'color',lighten(clr,0.5),'linewidth',2);
end
plot(u,p,'color',darken(clr,0));
function [D] = meanquantilediff(Q)
p = nchoosek(1:size(Q,1),2);
for i = 1:size(p,1)
D(i) = mean(abs(Q(p(i,1),:)-Q(p(i,2),:)));
end
D = mean(D);
function [] = saveplot(name,x,y,xmm,ymm)
xlim(xmm); xlabel(['$',x,'$'],'interpreter','latex');
ylim(ymm); ylabel(['$',y,'$'],'interpreter','latex');
drawnow;
figresize(gcf,[600,400]);
print(gcf,thesisname('fig',name),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
plot_y_sep_objectives.m
|
.m
|
vlr-master/figs/plot_y_sep_objectives.m
| 1,807 |
utf_8
|
f14d5c607b2797686db85c29af628b50
|
function [] = plot_y_sep_objectives()
for t = 1:3
switch t
case 1
Y = {[0.1,0.15,0.18,0.25,0.29,0.36,0.48,0.72],...
[0.43,0.52,0.62,0.67,0.75,0.78,0.85]};
case 2
Y = {[0.1,0.15,0.18,0.25,0.29,0.36,0.41,0.49],...
[0.51,0.54,0.61,0.75,0.78,0.85]};
case 3
Y = {[0.1,0.15,0.18,0.25,0.29,0.36,0.40,0.43],...
[0.61,0.64,0.69,0.75,0.78,0.85]};
end
C = [zeros(size(Y{1})),ones(size(Y{2}))];
Y = cat(2,Y{:});
plotsave(['jsep-diff-',num2str(t)],@Jdiff,Y,C);
plotsave(['jsep-conv-',num2str(t)],@Jconv,Y,C);
end
function [] = Jdiff(Y,C)
[J,YS,CS] = jsepdiff(Y,C);
plot(YS,CS,'-','color',lighten(red(1),0.5));
j = 0;
for i = 1:numel(YS)-1
if CS(i) ~= CS(i+1)
j = j + 1;
text(mean([YS(i),YS(i+1)]),0.5,num2str(j),'backgroundcolor','w',...
'horizontalalignment','center','verticalalignment','middle');
end
end
text(0.05,1,['$\mathcal{Z} = ',num2str(J),'$'],'interpreter','latex');
function [] = Jconv(Y,C)
[J,P,Po] = jsepconv(Y,C);
N = numel(Po);
scale = 0.04;
clr = {lighten(blu(1),0.2),lighten(blu(1),0.5)};
area(linspace(0,1,N),scale*P{2},'facecolor',lighten(clr{2},0.5),'edgecolor',clr{2});
area(linspace(0,1,N),scale*P{1},'facecolor',lighten(clr{1},0.5),'edgecolor',clr{1});
area(linspace(0,1,N),scale*Po, 'facecolor',lighten(red(1),0.3),'edgecolor',red(1));
text(0.05,1,['$\mathcal{Z} = ',num2str(J,'%.02f'),'$'],'interpreter','latex');
function [] = plotsave(name,fun,Y,C)
figure; hold on;
plot(Y,C,'ko','markersize',10);
fun(Y,C);
plot(Y,C,'ko','markersize',10);
xlim([0,1]); xlabel('Transformed Graylevels $(\tilde{y})$','interpreter','latex')
ylim([-0.1,+1.1]); ylabel('Lesion Class $(c)$','interpreter','latex');
tightsubs(1,1,gca,[0.2,0.2,0.05,0.05]);
print(gcf,thesisname('fig',name),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
plot_converge.m
|
.m
|
vlr-master/figs/plot_converge.m
| 1,017 |
utf_8
|
0406c0d850fce9df00497c72c958846d
|
function [] = plot_converge()
% define the hyperparameters
h = hypdef_final;
h.name.cv = 'nocv';
h.sam.fresh = 0;
h = hypfill(h);
% load the training data
[h,Y,C] = gettrainingdata(h);
ivec = true([1,size(Y,2)]);
idx.i.train = ivec;
idx.s.train = ivec;
idx.i.valid = ivec;
idx.s.valid = ivec;
[Y,C,idx] = dataregfun(h.lr.reg.py,h.lr.reg.pc,Y,C,idx);
[b,db] = vlrmap(h, Y(:,idx.s.train), C(:,idx.s.train));
% plot the quantiles of dB vs iterations
for b = 1:2
plotone(squeeze(db(:,b,:)),b);
end
function [] = plotone(db,b)
qvec = 0.00:0.05:1.00;
clr = flipud(monomap(red(1),numel(qvec),[-0.8,+0.8]));
qdb = quantile(abs(db),qvec)';
figure;
hold on;
for q = 1:numel(qvec)
plot(qdb(:,q),'color',clr(q,:));
end
ylabel(['Upate magnitude $\left|\Delta\beta^',num2str(b-1),'\right|$'],'interpreter','latex');
xlabel('Iteration $(t)$','interpreter','latex');
set(gca,'xtick',[0:5:size(db,2)]);
tightsubs(1,1,gca,0.05*[3,3,1,1]);
print(thesisname('fig','seg',['converge-b',num2str(b-1),'.eps']),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
plot_mri_spin_echo.m
|
.m
|
vlr-master/figs/plot_mri_spin_echo.m
| 2,679 |
utf_8
|
82104048b23837d3f74016d6488f1c8e
|
function [] = plot_mri_spin_echo()
figure;
N = 100;
clr.RF = darken(red(1),0.5);
clr.psi = blu(1);
clr.T2 = lighten(blu(1),0.5);
clr.T1 = lighten([1.0,0.5,0.0],0.5);
t2 = linspace(0,2,3*N);
t1 = linspace(-1,+1,N);
curv = 0.02*linspace(1,0,1.5*N);
tz = zeros(1,N);
p090 = 1*sinc(3*t1);
p180 = 2*sinc(3*t1);
RF = [tz,p090,tz,tz,p180,tz,tz,tz,tz,tz,tz,tz];
t = linspace(0,1,numel(RF));
T2 = [zeros(1,N*1.5), exp(-2*t(1:end-N*1.5))];
T1 = [zeros(1,N*1.5),1-exp(-0.5*t(1:end-N*1.5))];
T2x = [zeros(1,N*1.5), exp(-3*t2),exp(3*t2-6),exp(-3*t2)];
T2x = [T2x,zeros(1,size(T2,2)-size(T2x,2))];
psi = cos(400*t).*T2.*T2x;
T2(1:N*1.5) = nan;
T1(1:N*1.5) = nan;
psi = 10*[psi,nan*t1,psi(1:4*N)];
RF = 1*[RF, nan*t1, RF(1:4*N)];
T2 = 10*[T2, nan*t1, curv, T2(N*1.5+1:4*N)*1];
T1 = 10*[T1, nan*t1, 1-curv, T1(N*1.5+1:4*N)*1];
ax(1) = subplot(2,1,1); hold on;
plot(14+3*RF,'color',clr.RF);
plot(psi,'color',clr.psi);
plot(T2,'color',clr.T2);
plot(T1,'color',clr.T1);
plot(psi,'color',clr.psi);
doublearrow([N*1.5,N*04.5],-10,20,0.5,'$TE/2$','k');
doublearrow([N*1.5,N*07.5],-14,20,0.5,'$TE$','k');
doublearrow([N*1.5,N*14.5],-18,20,0.5,'$TR$','k');
set(gca,'xtick',[],'ytick',[],'xlim',[1,numel(RF)],'xcolor','w','ycolor','w');
ylim(10*[-2.5,+2.5]);
xlim([1,numel(psi)])
text(12.5*N,14,'$\cdots$','interpreter','latex','color','k',...
'horizontalalignment','center','verticalalignment','middle');
text(12.5*N, 0,'$\cdots$','interpreter','latex','color','k',...
'horizontalalignment','center','verticalalignment','middle');
text( 1.5*N,22,'$90^{\circ}$','interpreter','latex','color',clr.RF,...
'horizontalalignment','center','verticalalignment','middle');
text( 4.5*N,22,'$180^{\circ}$','interpreter','latex','color',clr.RF,...
'horizontalalignment','center','verticalalignment','middle');
text(14.5*N,22,'$90^{\circ}$','interpreter','latex','color',clr.RF,...
'horizontalalignment','center','verticalalignment','middle');
text( 7.5*N, 6,'$SE$','interpreter','latex','color',clr.psi,...
'horizontalalignment','center','verticalalignment','middle');
legend({'$RF$','$\Psi$','$\Psi_{T2}$','$\Psi_{T1}$'},'interpreter','latex','location','eastoutside');
tightsubs(1,1,ax,0.05*[1,1,3,1]);
figresize(gcf,[1000,700]);
print(gcf,thesisname('fig','mrispinecho.eps'),'-depsc');
close(gcf);
function [] = doublearrow(t,x,dt,dx,label,color)
plot(t+[+dt,-dt],[x,x],'color',color);
fill([t(1),t(1)+dt,t(1)+dt,t(1)],[x,x+dx,x-dx,x],color,'edgecolor','none');
fill([t(2),t(2)-dt,t(2)-dt,t(2)],[x,x+dx,x-dx,x],color,'edgecolor','none');
text(mean(t),x-dx,label,'interpreter','latex','color',color,...
'horizontalalignment','center','verticalalignment','top');
|
github
|
uoguelph-mlrg/vlr-master
|
show_registration.m
|
.m
|
vlr-master/figs/show_registration.m
| 692 |
utf_8
|
18bac7c912cfcd4f18ac18431b2bcebd
|
function [] = show_registration()
x = {[200,135,23],[130,69,52]};
[I] = getimg([5,9,19]);
for i = 1:2
compareslice(I(i,:),x{i},i);
end
function [I] = getimg(idx)
for i = 1:numel(idx)
I{1,i} = flip(imrotate(readnicenii(imgname('h17:FLAIR',idx(i),1)),180));
I{2,i} = readnicenii(imgname('mni:FLAIR',idx(i),1));
end
function [] = compareslice(I,x,k)
figure;
for i = 1:numel(I)
I{i} = padarray(I{i}(:,:,x(3)),[15,0],0,'post');
IX{i} = im2rgb(I{i},gray,[0,1600]);
IX{i}(:,x(2),1) = 1;
IX{i}(x(1),:,1) = 1;
end
timshow(IX{:});
set(gcf,'color','w');
print(thesisname('fig',['pre-registration-',num2str(k),'.png']),'-dpng');
close(gcf);
function [If] = flip(I)
If = I(:,end:-1:1,:);
|
github
|
uoguelph-mlrg/vlr-master
|
show_m08_revise_manuals.m
|
.m
|
vlr-master/figs/show_m08_revise_manuals.m
| 1,090 |
utf_8
|
0beaf6df06394b4c0d6a2bd94643bbe5
|
function [] = show_m08_revise_manuals()
% n.b. THIS IS VERY EXPENSIVE FUNCTION
% Thanks Harvard for interpolating to 0.5mm in all dimensions
% 1GB for each image, you tryna prove something?
[I,GO,GR] = getimg(1);
%compareslice(I,GO,GR,[500,900],128,0,'m08rev-01-d0-z128');
compareslice(I,GO,GR,[500,900],146,2,'m08rev-01-d2-z146');
[I,GO,GR] = getimg(5);
compareslice(I,GO,GR,[120,230],107,2,'m08rev-05-d2-z107');
[I,GO,GR] = getimg(6);
compareslice(I,GO,GR,[250,500],101,2,'m08rev-06-d2-z101');
function [I,GO,GR] = getimg(i)
I = ndresize(readnii(imgname('m08:FLAIR',i,1)),0.5);
GO = ndresize(readnii(imgname('m08:mano',i,1)),0.5);
GR = ndresize(readnii(imgname('m08:mans',i,1)),0.5);
function [] = compareslice(I,GO,GR,mm,z,ds,key)
I = getslice(I, z,ds);
GR = getslice(GR,z,ds);
GO = getslice(GO,z,ds);
timshow(redoverlay(I,GR,mm),0);
print(thesisname('fig',[key,'-r.png']),'-dpng');
timshow(redoverlay(I,GO,mm),0);
print(thesisname('fig',[key,'-o.png']),'-dpng');
function [I] = getslice(I,z,ds)
xc = 25;
I = shiftdim(I,ds);
I = I(xc+1:end-xc,xc+1:end-xc,z);
I = imrotate(I,ds*90);
|
github
|
uoguelph-mlrg/vlr-master
|
plot_mle_challenges.m
|
.m
|
vlr-master/figs/plot_mle_challenges.m
| 699 |
utf_8
|
c205d0f67ec567e31d8e430bf1aa2f1a
|
function [] = plot_mle_challenges()
% challenge 1: separable classes
Y = [clip(0.25+0.05*randn(32,1),[0.0,0.5]);
clip(0.75+0.05*randn(32,1),[0.5,1.0])];
C = [0*ones(32,1),1*ones(32,1)];
B{1} = 1e6*[-0.5,1];
B{2} = 50*[-0.5,1];
plotone(Y,C,B,'chmle-sep.eps');
% challenge 2: no lesions
Y = [0.5+0.1*randn(64,1)];
C = [0*ones(64,1)];
B{1} = 1e6*[-100,1];
B{2} = 50*[-0.9,1];
plotone(Y,C,B,'chmle-noles.eps');
function [] = plotone(Y,C,B,name)
figure;
orange = [1.0,0.5,0.0];
plot(0,nan,'color',orange);
lrplot([],[],B{2},'color',blu(1));
lrplot( Y, C,B{1},'color',orange);
legend({'MLE','Desired'},'location','nw','interpreter','latex');
print(gcf,thesisname('fig',name),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
plot_B_reparam.m
|
.m
|
vlr-master/figs/plot_B_reparam.m
| 961 |
utf_8
|
84c36c6c335bb603bfeed44643e110ea
|
function [] = plot_B_reparam()
% vary threshold (t)
B{1} = 16*[-0.4,1.0];
B{2} = 16*[-0.5,1.0];
B{3} = 16*[-0.6,1.0];
leg = {'$\tau=0.4$','$\tau=0.5$','$\tau=0.6$'};
plotone(B,leg,'reparam-t.eps');
% vary sensitivity (s)
B{1} = 8*[-0.5,1];
B{2} = 16*[-0.5,1];
B{3} = 32*[-0.5,1];
leg = {'$s=8$','$s=16$','$s=32$'};
plotone(B,leg,'reparam-s.eps');
% vary b0
B{1} = 16*[-0.4,1.0];
B{2} = 16*[-0.5,1.0];
B{3} = 16*[-0.6,1.0];
leg = {'$\beta^0=12$','$\beta^0=16$','$\beta^0=20$'};
plotone(B,leg,'reparam-b0.eps');
% vary b1
B{1} = [-6,9];
B{2} = [-6,12];
B{3} = [-6,16];
leg = {'$\beta^1=9$','$\beta^1=12$','$\beta^1=16$'};
plotone(B,leg,'reparam-b1.eps');
function [] = plotone(B,leg,name)
figure;
cmap = monomap(blu(1),3,[-0.5,0.5]);
lrplot([],[],B{1},'color',cmap(1,:));
lrplot([],[],B{2},'color',cmap(2,:));
lrplot([],[],B{3},'color',cmap(3,:));
legend(leg,'location','nw','interpreter','latex');
print(gcf,thesisname('fig',name),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
show_plot_simflair.m
|
.m
|
vlr-master/figs/show_plot_simflair.m
| 2,193 |
utf_8
|
09bd8ad8592c94531857a09a1c290cef
|
function [] = show_plot_simflair()
% get the TE/TR/TI data
si = [1,2,3,4,5,6, 8,9,10,11,12]; % no TERI data from Harvard
[names,~,~,~,TERI,~] = arrayfun(@scanparams,si,'un',0);
TERI = cat(1,TERI{:});
mri = cat(1,repmat({'ir'},[9,1]),'se','se');
S = size(TERI,1);
z = 90;
%yrng = [0,3.5];
yrng = [0.5,2];
noise = 0.03;
cmap = inferno;
% printing the table to file
str = '';
str = [str,textable('top',...
{'Scanner','\\gm{}','\\wm{}','\\csf{}','\\wmh{}',...
'$\\frac{\\wmh}{\\gm}$','$\\frac{\\wmh}{\\wm}$','$\\frac{\\wmh}{\\csf}$'},...
'rccccccc')];
for s = 1:S
[F,y(:,s),TPM] = simflair(TERI(s,:),'wm',mri{s});
F = F + noise.*randn(size(F));
% the business:
showflair(F(:,:,z),si(s),yrng,cmap);
plotpmf(F,TPM,si(s),yrng);
line = cat(1,names{s},num2cell(y(:,s)),num2cell(abs(y(4,s)./y(1:3,s))))';
str = [str,textable('line',line,'%.02f')];
end
str = [str,textable('bottom')];
fid = fopen(thesisname('dir','simflair.tex'),'w');
fprintf(fid,str);
fclose(fid);
showcolorbar(yrng,cmap);
function [] = showcolorbar(yrng,cmap)
hcolorbar(yrng(1):yrng(2),cmap);
print(gcf,thesisname('fig','hcbar-simflair.eps'),'-depsc');
close(gcf);
function [] = showflair(F,i,yrng,cmap)
cy = 20;
cx = 20;
timshow(F(1+cy:end-cy,1+cx:end-cx),yrng,cmap,'w500');
print(thesisname('fig',['simflair-s=',num2str(i,'%02.f'),'.png']),'-dpng');
%print(['simflair-s=',num2str(i,'%02.f'),'.png'],'-dpng');
close(gcf);
function [] = plotpmf(F,TPM,i,yrng)
clr = rainbow6;
M = ~isnan(F);
W = sum(TPM(M));
TPM = nd2cell(TPM,4);
N = 512;
u = linspace(yrng(1),yrng(2),N);
for t = 1:4
PMF(:,t) = (sum(TPM{t}(M))/W)*pofwy(F(M),TPM{t}(M),yrng,yrng,N);
PMF(1,t) = 0;
PMF(end,t) = 0;
end
figure; hold on;
plot(u,sum(PMF,2),'k','linewidth',1);
PMF(:,t) = 25*PMF(:,t);
for t = 1:4
h = fill(u,PMF(:,t),lighten(clr(t,:),0.7),'edgecolor',clr(t,:));
end
leg = {'Full Image','GM','WM','CSF','WMH$\times25$'};
legend(leg,'location','ne','interpreter','latex');
xlim(yrng); xlabel('$y$','interpreter','latex');
ylim([0,0.1]); ylabel('$p_{_{\textsc{y}}}(y)$','interpreter','latex');
figresize(gcf,[1200,450]);
print(thesisname('fig',['simflairplot-s=',num2str(i,'%02.f'),'.eps']),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
show_bias.m
|
.m
|
vlr-master/figs/show_bias.m
| 574 |
utf_8
|
45beaa0401ea9d4417ef4f30eeaa535d
|
function [] = show_bias()
cmap = inferno;
idx = 11;
z = 20;
mm = [300,800];
I{1} = niceimg(readnii(imgname('h17:FLAIR' ,idx,1)),z,mm,cmap);
I{2} = niceimg(readnii(imgname('h17:FLAIRm',idx,1)),z,mm,cmap);
I{3} = niceimg(readnii(imgname('h17:bias', idx,1)),z,[0,3],cmap);
for i = 1:numel(I)
timshow(I{i},0);
print(thesisname('fig',['pre-bias-',num2str(i),'.png']),'-dpng');
close(gcf);
end
vcolorbar(0:1:3,cmap);
print(thesisname('fig',['cmap-pre-bias.eps']),'-depsc');
close(gcf);
function [I] = niceimg(I,z,mm,cmap)
I = momi(clip(I(:,:,z),mm));
I = im2rgb(I,cmap);
|
github
|
uoguelph-mlrg/vlr-master
|
show_tpfpfn_raw_thropt.m
|
.m
|
vlr-master/figs/show_tpfpfn_raw_thropt.m
| 1,803 |
utf_8
|
00ebc2e216b774c3f7dcb3870793f78d
|
function [varargout] = show_tpfpfn_raw_thropt(I,G,thr)
cmap = inferno;
key = 'mni96-mni';
N = 96;
savename = ['data/misc/',key,'-thr.mat'];
if nargin < 2 % load images
load(['data/misc/',key,'-I.mat']);
load(['data/misc/',key,'-G.mat']);
M = brainfun;
for i = 1:numel(I)
I{i} = I{i}.*double(M);
end
end
if nargin < 3
if exist(savename,'file') % load thresholds
load(savename)
else % calculate thresholds (expensive)
for i = 1:numel(I)
thr(i) = runthropt(I{i},G{i});
statusbar(numel(I),i,numel(I)/3,1);
end
save(savename,'thr'); % save thresholds
end
end
% create TP FP FN images
[TP,FP,FN] = tpfpfn(I,G,thr);
sliceshow(TP,zfun,cmap,[0,0.25]);
print(gcf,thesisname('fig','rawthropt-tp.png'),'-dpng'); close(gcf);
sliceshow(FP,zfun,cmap,[0,0.25]);
print(gcf,thesisname('fig','rawthropt-fp.png'),'-dpng'); close(gcf);
sliceshow(FN,zfun,cmap,[0,0.25]);
print(gcf,thesisname('fig','rawthropt-fn.png'),'-dpng'); close(gcf);
vcolorbar(0:0.05:0.25,cmap);
print(gcf,thesisname('fig','cmap-rawthropt.eps'),'-depsc'); close(gcf);
if nargout == 3
varargout = {TP,FP,FN};
else
varargout = {};
end
function [thr] = runthropt(I,G)
to = double(quantile(I(:),0.95));
optfun = @(t)objective(double(I(:)),double(G(:)),t);
fminopt = optimset('maxiter',100,'display','off');
thr = fminsearch(optfun,to,fminopt);
function [J] = objective(I,G,t)
C = I>t;
dsc = double(2*sum(C.*G)) ./ double(sum(C+G));
J = -gather(dsc);
function [TP,FP,FN] = tpfpfn(I,G,thr)
N = numel(I);
TP = zeros(size(I{1}));
FP = zeros(size(I{1}));
FN = zeros(size(I{1}));
for i = 1:N
Ci = I{i} > thr(i);
Gi = G{i} > 0.5;
TP = TP + (1/N)*double( Ci & Gi);
FP = FP + (1/N)*double( Ci & ~Gi);
FN = FN + (1/N)*double(~Ci & Gi);
end
|
github
|
uoguelph-mlrg/vlr-master
|
show_tikzfigs.m
|
.m
|
vlr-master/figs/show_tikzfigs.m
| 5,105 |
utf_8
|
a5bef0d8a20858662445e8250999d862
|
function [] = show_tikzfigs(x,todo)
if nargin < 1, h = hypdef_final; x = load(h.save.name,'h','o'); end
if nargin < 2, todo = {'slice','lr','hist'}; end
for t = 1:numel(todo)
switch todo{t}
case 'slice', tikzslice(x);
case 'lr', tikzsigmoids;
case 'hist', tikzhists;
end
end
close all;
function [] = tikzslice(x)
n = 2; n2 = 80; nt = 3; c = 3;
z = 61;
cmap = inferno;
% load some raw images
M = logical(getslice('mni:brain',1,z));
I1 = getslice('mni:FLAIRm',n, z,M);
G1 = getslice('mni:mans', n, z,M);
I2 = getslice('mni:FLAIRm',n2,z,M);
G2 = getslice('mni:mans', n2,z,M);
It = getslice('mni:FLAIRm',nt,z,M);
% load some sample model data
T = clip(-x.o.B{c}{1}(:,:,z)./x.o.B{c}{2}(:,:,z),[0.5, 1]).*M;
S = clip( x.o.B{c}{2}(:,:,z), [0 ,50]).*M;
%T = T(:,:,z); T(T<=0) = 1; T = gaussfilter(medfilt2(T,[5,5]),[.5,.5]); T = T.*M;
%S = T(:,:,z); T(S<=1) = 100; S = gaussfilter(medfilt2(S,[5,5]),[.5,.5]); S = S.*M;
% crop for better resolution
I1(I1<1/100) = 0;
[I1,G1,M,I2,G2,T,S,It] = specialcrop(I1,G1,M,I2,G2,T,S,It);
% generate the images of interest
G1 = G1 > 0.5;
G2 = G2 > 0.5;
I1 = momi(max(0,I1)); % raw
I2 = momi(max(0,I2)); % raw
IR = momi(max(0,I1.*M)); % after registration
It = momi(max(0,It.*M));
JR = biny((IR-mean(IR(M)))./std(IR(M)),[-1,+2],[0,1],256); % IR post-standardize
Jt = biny((It-mean(It(M)))./std(It(M)),[-1,+2],[0,1],256); % It post-standardize
Qt = 1./(1+exp(-(S.*(Jt-T)))).*M; % compute the predicted lesions
Lt = postpro(x.h,x.o.thr(x.h.cv.i(nt)),dumthree(Qt));
Lt = Lt(:,:,2); % do the post-process
% convert stuff to RGB
Qt = im2rgb(Qt/1.1,cmap,[0,1]);
T = im2rgb(T,cmap,[0.5,1.0]);
S = im2rgb(S,cmap,[0,50]);
imgs = { I1 , I2 , IR , G1 , G2 , JR , T , It , Jt , Qt , Lt };
names = {'i1','i2','ir','c1','c2','jr','bb','it','jt','qt','lt'};
% debug: show all
%timshow(imgs{:},[0,1],'5x2');
for i = 1:numel(imgs)
timshow(imgs{i},[0,1],0,'w200');
print(gcf,thesisname('fig','tikz',[names{i},'.png']),'-dpng');
close(gcf);
end
function [I] = getslice(key,n,z,M)
I = imrotate(readnii(imgname(key,n,1)),180);
I = max(0,I(:,:,z));
if nargin == 3, M = ones(size(I)); end
[~,mm] = alphatrim(I,[0,0.995],M);
I = momi(clip(I,mm));
function [I3] = dumthree(I)
I3 = cat(3,I,I,I);
function [C] = postpro(h,thr,C0)
C = C0 > thr;
C = bwareaopen(C,ceil(h.pp.minmm3*1.5^3));
function [varargout] = specialcrop(varargin)
for i = 1:numel(varargin)
varargout{i} = varargin{i}(5:end-6,4+1:end-4);
end
function [] = tikzsigmoids()
mu = [0.3,0.8]; sd = [0.2,0.1]; N = [35,9];
yo = 0.6;
s = 12;
y = cat(1,mu(1)+sd(1)*randn([N(1),1]),mu(2)+sd(2)*randn([N(2),1]));
c = cat(1,0*ones([N(1),1]),1*ones([N(2),1]));
yt = 0.72;
ct = 1./(1+exp(-s*(yt-yo)));
% plot the training sigmoid
plotlogit(yo,s);
plot(y,c,'k.','markersize',15);
cs = 0.5+[-1,+1]; ys = yo + 4*(cs-0.5)/s;
yy = [yo,yo]; cy = ylim;
plot(yy,cy,':', 'color',lighten(red(1),0.5));
plot(ys,cs,'--','color',lighten(red(1),0.5));
print(gcf,thesisname('paper','tikz','lr-fit'),'-depsc');
% plot the testing sigmoid
plotlogit(yo,s);
plot([yt,yt],[0,ct],':','color',lighten(red(1),0.5));
plot([0,yt],[ct,ct],':','color',lighten(red(1),0.5));
plot(yt,ct,'k.','markersize',15);
plot(yt,ct,'o','markersize',15,'color',red(1));
print(gcf,thesisname('paper','tikz','lr-test'),'-depsc');
function [] = plotlogit(yo,s)
y = 0:0.01:1;
c = 1./(1+exp(-(s.*(y-yo))));
figure;
hold on;
plot(y,c,'-','color',lighten(red(1),0.1));
ylim([-0.1,1.1]);
xlim([0,1]);
ylabel('$$\hat{c} = p(c=1\mid y;\beta)$$','interpreter','latex','fontsize',24);
xlabel('$$y$$','interpreter','latex','fontsize',24);
set(gca,'xtick',[0:0.25:1],'ytick',[0,1]);
figresize(gcf,[400,400]);
tightsubs(1,1,gca,[0.15,0.2,0.15,0.2]);
function [] = tikzhists()
savename = fullfile('data','misc','eg-hist.mat');
if exist(savename,'file')
load(savename,'y','HI','HJ');
else
[y,HI,HJ] = makehistdata(savename);
end
yname = {'y','\tilde{y}'};
plothist(y,HI,yname{1}); print(gcf,thesisname('paper','tikz','hist-pre' ),'-depsc');
plothist(y,HJ,yname{2}); print(gcf,thesisname('paper','tikz','hist-post'),'-depsc');
function [] = plothist(y,H,yname)
nscan = [5,5,5,13,5,5];
clr = get(0,'defaultaxescolororder');
figure; hold on;
for s = numel(nscan):-1:1
for i = 1:nscan(s)
clri = lighten(clr(s,:),i/(nscan(s)+5));
plot(y,H(:,sum(nscan(1:s-1))+i),'color',clri);
end
end
ylim([0,5]);
xlim([min(y),max(y)]);
xlabel(['$$',yname,'$$'], 'interpreter','latex','fontsize',40);
ylabel(['$$p(',yname,')$$'],'interpreter','latex','fontsize',40);
figresize(gcf,[400,400]);
tightsubs(1,1,gca,[0.2,0.2,0.1,0.1]);
function [y,HI,HJ] = makehistdata(savename)
h = hypdef_final;
h.M = readnicenii(imgname('mni:brain','')) > 0.5;
N = 256;
y = linspace(0,1,N);
for i = 1:h.Ni
I = readnicenii(imglutname('mni:FLAIRm',109,i)).*h.M;
I = momi(alphaclip(I,[0.001,0.999],h.M)) + 0.01*randn(size(I));
J = standardize(I, h.M > 0.5, h.std.type, h.std.args{:});
HI(:,i) = ksdensity(I(h.M),y,'width',0.02);
HJ(:,i) = ksdensity(J(h.M),y,'width',0.02);
statusbar(h.Ni,i,h.Ni/3,1);
end
save(savename,'y','HI','HJ');
|
github
|
uoguelph-mlrg/vlr-master
|
plotypmf.m
|
.m
|
vlr-master/figs/utils/plotypmf.m
| 584 |
utf_8
|
8353f266614455f0139ef8eca2420a88
|
% PLOTYPMF
% This function plots he histogram of the data in Y
% stratified by image (dim 2), and coloured by scanner.
function [] = plotypmf(Y,h,leg)
if nargin < 3, leg = 0; end % dont pring legend by default
if max(Y(:)) > 1
Y = bsxfun(@rdivide,Y,max(Y));
end
n = 1:size(Y,2)/h.Ni:size(Y,2);
N = 128;
u = linspace(0,1,N);
P = arrayfun(@(i)ksdensity(Y(:,i),u,'width',0.02),n,'un',0);
scannerplot(h,cat(1,P{:}),u,leg);
xlim([0,1]); xlabel('Graylevel $y$','interpreter','latex');
ylim([0,6]); ylabel('PMF $f_y(y)$','interpreter','latex');
tightsubs(1,1,gca,0.5*[0.2,0.3,0.12,0.12]);
|
github
|
uoguelph-mlrg/vlr-master
|
textableres.m
|
.m
|
vlr-master/figs/utils/textableres.m
| 1,327 |
utf_8
|
9814f3665631e44d9b5e61ddc390fd28
|
function [] = textableres(h,o,fname,names)
if nargin < 3
fname = fullfile(h.save.figdir,resultsname('tab'));
end
if ~iscell(o)
N = 1;
o = {o};
fmt = 'rcccc';
toprows = {'Scanner','LL','SI','Pr','Re'};
else
N = numel(o);
fmt = sprintf('rc%s',repmat('ccc',[1,N]));
R1 = cellfun(@(s)sprintf('\\\\multicolumn{3}{c}{%s}',s),names,'un',0);
R2 = arrayfun(@(i)(' SI & Pr & Re '),1:N,'un',0);
RL = arrayfun(@(i)(sprintf('\\\\cmidrule(lr){%d-%d}',3*i+1,3*i+3)),1:N,'un',0);
toprows = {'','',R1{:};[cell2mat(RL),'Scanner'],'LL',R2{:}};
end
str = '';
str = [str,textable('top',toprows,fmt)];
for i = 1:numel(h.scan.N)
str = [str,makeline(o,h.scan.i==i,h.scan.names{i},h.scan.clr(i,:))];
end
str = [str,'\\midrule\n'];
str = [str,makeline(o,true(size(h.scan.i)),'ALL',[1,1,1])];
str = [str,textable('bottom')];
f = fopen(fname,'w');
fprintf(f,str);
fclose(f);
function [str] = makeline(o,idx,name,clr)
mop = @median;
N = numel(o);
data = num2cell(cell2mat(arrayfun(@(i)([...
mop(o{i}.si(idx)),...
mop(o{i}.pr(idx)),...
mop(o{i}.re(idx))]...
),1:N,'un',0)));
sclr = sprintf(' %0.02f',clr);
sname = sprintf('%s {\\\\color[rgb]{%s}$\\\\blacksquare$}',name,sclr);
fmt = arrayfun(@(i)('%.02f'),1:3*N,'un',0);
line = {sname,mop(o{1}.ll(idx)),data{:}};
str = textable('line',line,{'','%.0f',fmt{:}});
|
github
|
uoguelph-mlrg/vlr-master
|
copythesisresults.m
|
.m
|
vlr-master/figs/utils/copythesisresults.m
| 3,355 |
utf_8
|
6290dbad00e0cf51f1fcc6372fd08fe7
|
% COPYTHESISRESULTS
% Since by default, cross validation batches print results to a unique folder,
% this function collects a few used directly in the thesis and copies them into
% the thesis figure directory. Since MATLAB copying is slow, the (windows)
% command line copy is used
function [] = copythesisresults()
todo = deftodo();
for k = 1:numel(todo)
for i = 1:numel(todo{k}.figs)
todo{k}.copy(todo{k}.figs{i});
end
end
function [todo] = deftodo()
tabnames = {};
h = hypdef_final;
i = 0;
i = i + 1;
todo{i} = onekey(key2hyp(h,'e[P--L--A--F--]'),'base','seg',...
resultsname('tab'),...
resultsname('box','si'),...
resultsname('box','pr'),...
resultsname('box','re'),...
resultsname('ba',1),...
resultsname('ba',2),...
resultsname('img','T'),...
resultsname('img','S'),...
resultsname('cmap','T'),...
resultsname('cmap','S'));
i = i + 1;
todo{i} = onekey(hypdef_final,'final','seg',...
resultsname('tab'),...
resultsname('box','si'),...
resultsname('box','pr'),...
resultsname('box','re'),...
resultsname('scat','si'),...
resultsname('scat','pr'),...
resultsname('scat','re'),...
resultsname('ba',1),...
resultsname('ba',2),...
resultsname('img','T'),...
resultsname('img','S'),...
resultsname('img','TP'),...
resultsname('img','FP'),...
resultsname('img','FN'),...
resultsname('cmap','T'),...
resultsname('cmap','S'),...
resultsname('cmap','tri'));
i = i + 1;
tabnames{end+1} = ['Baseline/base-',resultsname('tab')];
todo{i} = onekey(key2hyp(h,'e[P--L--A--F--]'),'base','tab',resultsname('tab'));
i = i + 1;
tabnames{end+1} = ['Final/final-',resultsname('tab')];
todo{i} = onekey(hypdef_final,'final','tab',resultsname('tab'));
%todo{i} = onekey(key2hyp(h,'e[P1-L3-Ab-Fg2]'),'final','tab',resultsname('tab'));
sets = { 'ovb', 'cv', 'ystd', 'lam', 'beta'};
keyfun = {@key2hyp, @cv2hyp, @ystd2hyp, @key2hyp, @key2hyp};
for s = 1:numel(sets)
[h,names,params] = defhypset(sets{s});
for k = 1:numel(h)
i = i + 1;
hk = keyfun{s}(h{k},params{k,1:end-1});
todo{i} = onekey(hk,params{k,1},'tab',resultsname('tab'));
tabnames{end+1} = [names{k},'/',params{k,1},'-',resultsname('tab')];
end
end
fid = fopen(thesisname('fig','tab','table-index.tex'),'w+');
fprintf(fid,maketabnames(tabnames));
fclose(fid);
function [key] = onekey(h,okey,dir,varargin)
for v = 1:numel(varargin)
key.figs{v} = varargin{v};
end
key.copy = @(name)fcopy(h,okey,dir,name);
function [] = fcopy(h,outkey,dir,name)
load(h.save.name,'h');
iname = fullfile(h.save.figdir,name);
oname = thesisname('fig',dir,[outkey,'-',name]);
evalstr = ['!copy "',iname,'" "',oname,'"'];
fprintf(['> copying to: ',outkey,'-',name,'\n']);
eval(evalstr);
function [tabnamestr] = maketabnames(tabnames)
tabnamestr = '';
for i = 1:numel(tabnames)
tabnamei = strrep(strrep(tabnames{i},'\','\\'),'.tex','');
tabnamestr = [tabnamestr,tabnamei,','];
end
tabnamestr = tabnamestr(1:end-1);
|
github
|
uoguelph-mlrg/vlr-master
|
boxplotcompare.m
|
.m
|
vlr-master/figs/utils/boxplotcompare.m
| 2,272 |
utf_8
|
ba6b99358ef30a59f867d14fd663a401
|
function [] = boxplotcompare(h,metrics,mlabs,llthr,savename,leg,pfun,tn)
% clean up inputs
if nargin < 3, mlabs = metrics; end
if nargin < 4, llthr = []; end
if nargin < 5, savename = ''; end
if nargin < 6, leg = {}; end
if nargin < 7, pfun = []; end
if nargin < 8, tn = {'fig','seg'}; end
if isa(metrics,'char'), metrics = {metrics}; end
if isa(mlabs,'char'), mlabs = {mlabs}; end
% initializations
N.m = length(metrics);
N.h = numel(h);
N.t = length(llthr)+1;
X = cell(N.t,N.h,N.m);
% collect the data in a sincle cell for boxplotn
for n = 1:N.h
o = load(h{n}.save.name,'o');
[idx,labs] = ll2idx(o.o.ll,llthr);
for i = 1:size(idx,2)
for m = 1:N.m
X{i,n,m} = o.o.(metrics{m})(idx(:,i));
end
end
end
% make the box plots
cmap = rainbow7;
for m = 1:N.m
preplot();
boxplotn(X(:,:,m),cmap,labs);
postplot(N,mlabs{m});
if ~isempty(savename)
print(thesisname(tn{:},[savename,'-',metrics{m},'.eps']),'-depsc');
close(gcf);
end
if ~isempty(pfun)
statscompare(pfun,X(:,:,m),mlabs{m},labs);
end
end
if ~isempty(leg)
extralegend(leg,cmap,[1,numel(leg)]);
if ~isempty(savename)
print(thesisname(tn{:},[savename,'-leg.eps']),'-depsc');
close(gcf);
end
end
function [idx,labs] = ll2idx(ll,llthr)
% make binary group selector by lesion load,
% using thresholds llthr
if isempty(llthr)
idx = true(size(ll(:)));
labs = {''};
else
idx = false(length(ll),length(llthr)+1);
llthr = [0;llthr(:);inf];
Nt = numel(llthr)-1;
for t = 1:Nt
idx(:,t) = (ll>llthr(t)) & (ll<llthr(t+1));
switch t
case 1
labs{t} = sprintf('<%0.0f',llthr(t+1));
case Nt
labs{t} = sprintf('>%0.0f',llthr(t));
otherwise
labs{t} = sprintf('%0.0f-%0.0f',llthr(t),llthr(t+1));
end
end
end
function [] = preplot()
figure;
hold on;
for l = 0.2:0.2:0.8
plot([0,1/eps],[l,l],'-','linewidth',1,'color',lighten([0,0,0],0.8));
end
function [wid] = postplot(N,mlab)
wid = [150 + 50*N.t*N.h + 100*N.t];
figresize(gcf,[wid,550]);
set(gca,'ylim',[0,1]);
ylabel(mlab,'interpreter','latex');
if N.t > 1
xlabel(['$LL$ (mL)'],'interpreter','latex');
end
tightsubs(1,1,gca,0.03*[5, 4, 1, 1]);
|
github
|
uoguelph-mlrg/vlr-master
|
textable.m
|
.m
|
vlr-master/figs/utils/textable.m
| 856 |
utf_8
|
9b0bd7f2063ffe6f5f47623cfa55776a
|
function [str] = textable(part, varargin)
switch part
case 'top'
titles = varargin{1};
cols = varargin{2};
str = ['\\begin{tabular}{',cols,'}\n\\toprule\n',...
linestr(titles),'\\midrule\n'];
case 'line'
data = varargin{1};
fmt = varargin{2};
str = linestr(data,fmt);
case 'bottom'
str = '\\bottomrule\n\\end{tabular}';
end
str = strrep(str,'NaN','---');
str = strrep(str,'Inf','$\\infty$');
function [str] = linestr(X,fmt)
if nargin < 2
fmt = '%.02f';
end
if isa(fmt,'char')
fmt = repmat({fmt},size(X));
end
if isa(X,'cell')
fun = @(j,i)([num2str(X{j,i},fmt{j,i}),' & ']);
end
if isa(X,'numeric')
fun = @(j,i)([num2str(X(j,i),fmt{j,i}),' & ']);
end
% inject ' & '
str = '';
for j = 1:size(X,1)
str = [str,cell2mat(arrayfun(@(i)fun(j,i),1:size(X,2),'un',0))];
str(end-1:end+4) = '\\\\\n';
end
|
github
|
uoguelph-mlrg/vlr-master
|
roianalysis.m
|
.m
|
vlr-master/paper/roianalysis.m
| 1,270 |
utf_8
|
8b6bbe8da991e2698ea15920d628ae14
|
function [] = roianalysis(M)
if nargin < 1
h = hypdef_final;
load(h.save.name,'h');
M = makecvmasks(h);
end
printvolumes(M,'t1');
printvolumes(M,'t0');
printvolumes(M,'t0v1');
roi = 't0';
[hs.lam,name.lam] = defhypset('lam');
[hs.psu,name.psu] = defhypset('psu');
performanceroi(hs.lam,M,roi);
performanceroi(hs.psu,M,roi);
function [] = performanceroi(hs,M,roi)
for s = 1:numel(hs)
statusupdate(s,numel(hs));
load(hs{s}.save.name,'h','t','o');
h = hroi(h,roi);
for i = 1:h.Ni
[o.si(i),o.pr(i),o.re(i)] = ...
performanceiroi(M.(roi){h.cv.i(i)},t.TP{i},t.FP{i},t.FN{i});
o.lle(i) = nan;
statusbar(h.Ni,i,h.Ni/3,1);
end
save(h.save.name,'h','o');
end
function [si,pr,re] = performanceiroi(ROI,TP,FP,FN)
ROI = single(ROI);
TP = sum(TP(:).*ROI(:));
FP = sum(FP(:).*ROI(:));
FN = sum(FN(:).*ROI(:));
si = 2*TP/(2*FP+FP+FN);
pr = TP/(TP+FP);
re = TP/(TP+FN);
si(isnan(si)) = 0;
pr(isnan(pr)) = 0;
re(isnan(re)) = 0;
function [] = printvolumes(M,field)
x = (1.5^3)/1000;
Mf = M.(field);
v = x*cell2mat(arrayfun(@(i)sum(Mf{i}(:)),1:numel(Mf),'un',0));
fprintf([field,': \t']);
printiqr(v,'%.0f');
function [] = printiqr(x,fmt)
fprintf(['$',fmt,'\\thinspace[',fmt,'-',fmt,']$\n'],...
quantile(x,0.5),quantile(x,0.25),quantile(x,0.75));
|
github
|
uoguelph-mlrg/vlr-master
|
paperresults.m
|
.m
|
vlr-master/paper/paperresults.m
| 2,738 |
utf_8
|
44f0ce18dbaec28a4ae91453e8d1d348
|
function [] = paperresults()
% ------------------------------------------------------------------------------
% statusupdate(50); statusupdate('stats results'); statusupdate();
% paperstats;
% ------------------------------------------------------------------------------
% statusupdate(50); statusupdate('param results'); statusupdate();
% [h,names] = defhypset('lam');
% roicompare (h,names,'lam');
% [h,names] = defhypset('psu');
% roicompare (h,names,'psu');
% ------------------------------------------------------------------------------
statusupdate(50); statusupdate('copying results'); statusupdate();
h.final = hypdef_final;
d.final = fullfile(h.final.save.figdir);
d.thesis = thesisname('fig');
tocopy = deftocopy(d);
for k = 1:numel(tocopy)
for i = 1:numel(tocopy{k}.item)
tocopy{k}.copy(tocopy{k}.item{i});
end
end
statusupdate('done'); statusupdate(); statusupdate(50); statusupdate();
function [tocopy] = deftocopy(d)
tocopy{1} = copyitem(d.final,'','final',{...
resultsname('tab'),...
resultsname('scat','si'),...
resultsname('scat','pr'),...
resultsname('scat','re'),...
resultsname('ba',1),...
resultsname('ba',2),...
resultsname('img','T'),...
resultsname('img','S'),...
resultsname('img','Y'),...
resultsname('cmap','T'),...
resultsname('cmap','S'),...
resultsname('cmap','Y'),...
resultsname('tab'),...
});
tocopy{2} = copyitem(fullfile(d.thesis,'seg'),'exseg','exseg',{...
'I.png',...
'J.png',...
'T.png',...
'S.png',...
'Q.png',...
'C.png',...
'G.png',...
'P.png',...
});
tocopy{3} = copyitem(fullfile(d.thesis,'seg'),'lpa','lpa',{...
resultsname('box','si'),...
resultsname('box','pr'),...
resultsname('box','re'),...
resultsname('box','leg'),...
});
tocopy{4} = copyitem(fullfile(d.thesis,'seg'),'cv','cv',{
resultsname('box','si'),...
resultsname('box','pr'),...
resultsname('box','re'),...
resultsname('box','leg'),...
});
function [C] = copyitem(idir,ipref,opref,inames)
for v = 1:numel(inames)
C.item{v} = inames{v};
end
C.copy = @(name)fcopy(idir,ipref,opref,name);
function [] = fcopy(idir,ipref,opref,name)
statusupdate(sprintf('%s [%s -> %s]',name,ipref,opref));
statusupdate();
if ~isempty(ipref)
ipref = [ipref,'-'];
end
if ~isempty(opref)
opref = [opref,'-'];
end
iname = fullfile(idir,[ipref,name]);
oname = thesisname('paper',[opref,name]);
evalstr = ['!copy "',iname,'" "',oname,'" > nul'];
%evalstr = ['!copy "',iname,'" "',oname,'"'];
eval(evalstr);
function [] = roicompare(h,names,lab)
test = @(x1,x2)signrank([x1(:)-x2(:)]);
metrics = {{'si','pr','re'},{'$SI$','$Pr$','$Re$'}};
for i = 1:numel(h)
h{i} = hroi(h{i},'t0');
end
boxplotcompare(h,metrics{:},[],['roi-',lab,'-box'],names,test,{'paper'});
|
github
|
uoguelph-mlrg/vlr-master
|
hypdef_final.m
|
.m
|
vlr-master/exp/hyp/hypdef_final.m
| 1,284 |
utf_8
|
59ca4e247bc6c5abf898ff0a666a8d6d
|
% HYPDEF_FINAL(h)
% This function defines all model hyperparameters for the segmentation pipeline.
% Default values shown.
% Some shorthands used here are expanded by hypfill.
% DO NOT EDIT!
function [h] = hypdef_final(h)
% flag-like names
h.name.key = 'e-default'; % h.name.key = 'LPA';
h.name.data = 'mni96'; % h.name.data = 'mni109';
h.name.cv = 'loso'; % h.name.cv = 'nocv';
% scanner parameters
h.cmap = inferno;
h.Ni = [];
h.scan.idx = [1,2,3,4,5,6,9]; % h.scan.idx = [1,2,3,4,5,6,9,7,8,10];
h.scan.clr = rainbow7; % h.scan.clr = rainbow10;
% sampling parameters
h.sam.fresh = 0;
h.sam.resize = 0.5;
h.sam.dx = kernelshifts(binsphere(1));
h.sam.flip = 1;
% grey standardization parameters
h.std.type = 'm3';
h.std.args = {pmfdef('lskew')};
% logistic regression parameters
h.lr.Nit = 30;
h.lr.B = [0,0];
h.lr.alpha = 1;
h.lr.reg.la = 1e-3;
h.lr.reg.py = [1];
h.lr.reg.pc = [1];
h.lr.pad = [-20,20];%[-1.5;1];
h.lr.pp.filter= @(B)(gaussfilter(B,[2,2,2]));
%h.lr.pp.filter= @(B)(op23(B,@(B)medfilt2(B,[3,3])));
% post processing parameters
h.pp.saveles = 'les';
h.pp.thr.def = 0.5;
h.pp.thr.Nit = 30;
h.pp.minmm3 = 5;
% cross validation and scanner
h = hypfill(h);
|
github
|
uoguelph-mlrg/vlr-master
|
fig_exseg.m
|
.m
|
vlr-master/exp/hyp/fig_exseg.m
| 1,822 |
utf_8
|
2e7e70111e6a83addaaceadfcb70b35b
|
function [] = fig_exseg(h,o,tn)
if nargin < 2, load(h.save.name,'h','o'); end
if nargin < 3, tn = {'fig','seg'}; end
i = 45; z = 50;
[Z,names] = getdata(h,o,i,z);
for n = 1:numel(Z)
figure;
timshow(Z{n},0,'w500');
if strcmp(names{n},'P')
hold on;
area([0,0,0],[0,0,0],'facecolor',grn(1));
area([0,0,0],[0,0,0],'facecolor',red(1));
area([0,0,0],[0,0,0],'facecolor',blu(1));
l = legend({'TP','FP','FN'},'location','ne',...
'fontsize',32,'TextColor','w','Color','k','fontname','CMU Serif');
set(l,'position',[0.7,0.75,0.3,0.25]);
end
set(gcf,'InvertHardcopy','off');
print(thesisname(tn{:},['exseg-',names{n},'.png']),'-dpng');
%close(gcf);
end
function [varargout] = zslice(z,varargin)
dx = 0;
dy = 40;
for i = 1:numel(varargin)
varargout{i} = varargin{i}(end-dy:-1:dy+1,dx+1:end-dx,z);
end
function [Z,names] = getdata(h,o,i,z)
I = imrotate(readnicenii(imglutname('FLAIRm',96,i)),0);
G = imrotate(readnicenii(imglutname('mans', 96,i)),0) > 0.5;
x = readniivsize(imglutname('FLAIRm',96,i));
[B{1},B{2},M] = mni2ptx(h.Ni,i,o.B{h.cv.i(i)}{:},single(h.M));
M = M > 0.5;
B{1}(~M) = -1.5;
B{2}(~M) = 1;
cmap = inferno;
J = standardize(I,M>0.5,h.std.type,h.std.args{:});
I = momi(alphaclip(I,[0.001,0.999],M));
Q = M./(1+exp(-(B{1}+B{2}.*J)));
T = -B{1}./B{2}.*M;
S = B{2}.*M;
C = logical(postpro(h,Q,x,o.thr(h.cv.i(i))));
P = zeros(size(G)); P( C& G) = 2; P( C&~G) = 1; P(~C& G) = 3;
G = single(G); C = single(C);
[I,J,T,S,Q,C,G,P] = zslice(z,I,J,T,S,Q,C,G,P);
Z= {...
im2rgb(I,gray,[0,1]);
im2rgb(J,cmap,[0.2,1]);
im2rgb(T,cmap,[0.2,1]);
im2rgb(S,cmap,[0,60]);
im2rgb(Q,cmap,[0,1]);
im2rgb(C,gray,[0,1]);
im2rgb(G,gray,[0,1]);
im2rgb(P,krgb,[0,3])};
names = {'I','J','T','S','Q','C','G','P'};
function [cmap] = krgb()
cmap = [0,0,0; red(1); grn(1); blu(1)];
|
github
|
uoguelph-mlrg/vlr-master
|
hypdef_baseline.m
|
.m
|
vlr-master/exp/hyp/hypdef_baseline.m
| 1,191 |
utf_8
|
64fe8979e01ebaaad5a0daa969d168ca
|
% HYPDEF_BASELINE(h)
% This function defines all model hyperparameters for the segmentation pipeline.
% Default values shown.
% Some shorthands used here are expanded by hypfill.
% EXP: baseline
% DO NOT EDIT!
function [h] = hypdef_baseline(h)
% flag-like names
h.name.key = 'e-base'; % h.name.key = 'LPA';
h.name.data = 'mni96'; % h.name.data = 'mni109';
h.name.cv = 'loso'; % h.name.cv = 'nocv';
% scanner parameters
h.cmap = inferno;
h.Ni = [];
h.scan.idx = [1,2,3,4,5,6,9]; % h.scan.idx = [1,2,3,4,5,6,9,7,8,10];
h.scan.clr = rainbow7; % h.scan.clr = rainbow10;
% sampling parameters
h.sam.fresh = 1;
h.sam.resize = 0.5;
h.sam.dx = [0,0,0];
h.sam.flip = 0;
% grey standardization parameters
h.std.type = 'm3';
h.std.args = {pmfdef('lskew')};
% logistic regression parameters
h.lr.Nit = 30;
h.lr.B = [0,0];
h.lr.alpha = 1;
h.lr.reg.la = 0;
h.lr.reg.py = [];
h.lr.reg.pc = [];
h.lr.pad = [-1.5;1];
h.lr.pp.filter= @(B)(B);
% post processing parameters
h.pp.saveles = 'les';
h.pp.thr.def = 0.5;
h.pp.thr.Nit = 30;
h.pp.minmm3 = 5;
% cross validation and scanner
h = hypfill(h);
|
github
|
uoguelph-mlrg/vlr-master
|
fig_final.m
|
.m
|
vlr-master/exp/hyp/fig_final.m
| 974 |
utf_8
|
881ce3321cdb99e411f80b8aa914fcdf
|
function [] = fig_final(todo)
if nargin < 1, todo = {'sum','lpa','man','exseg','thr'}; end
h = hypdef_final;
load(h.save.name,'h','o');
for i = 1:numel(todo)
switch todo{i}
case 'sum'
load(h.save.name,'t');
summarizeresults(h,o,t);
copythesisresults;
case 'lpa'
fig_lpa({'beta','compare'},h);
case 'man'
stats_man(o);
case 'exseg'
fig_exseg(h,o);
case 'thr'
fig_thropt(h);
end
end
function [] = stats_man(o)
names = {'i15','m16'};
fprintf('MANUAL COMPARISONS =====================\n');
for n = 1:numel(names)
man = load(['data/misc/',names{n},'-mantoman.mat']);
docomparison({man.si(:),o.si(:)},{names{n},'LPA'});
end
fprintf('LL COMPARISON ==========================\n');
icc = ICC([o.ll(:),o.lle(:)],'A-1');
fprintf('ICC = %.03f\n', icc);
function [] = docomparison(x,names)
p = ranksum(x{:});
pre = sprintf('[%s : %s] [%.03f : %.03f] -',...
names{:},median(x{1}),median(x{2}));
printpval(pre,p);
|
github
|
uoguelph-mlrg/vlr-master
|
fig_lpa.m
|
.m
|
vlr-master/exp/hyp/fig_lpa.m
| 1,725 |
utf_8
|
dbe07fc926bb248a8d1d8284f590fa46
|
function [] = fig_lpa(todo,hvlr)
if nargin < 1, todo = {'beta','compare'}; end
if nargin < 2
h{1} = hypdef_final;
else
h{1} = hvlr;
end
h{2} = getfield(load(fullfile('data','misc','mni96-LPA-loso.mat'),'h'),'h');
names = {'VLR','LPA'};
metrics = {{'si','pr','re'},{'$SI$','$Pr$','$Re$'}};
test = @(x1,x2)signrank([x1(:)-x2(:)]);
for i = 1:numel(todo)
switch todo{i}
case 'beta'
showbeta;
case 'compare'
boxplotcompare(h,metrics{:},[4,22],'lpa-box',names,test);
end
end
function [varargout] = lpaimg(varargin)
lpamatfile = 'C:\program files\matlab\spm12\toolbox\LST\LST_lpa_stuff.mat';
data = load(lpamatfile,'bp_mni',varargin{:});
Z = zeros([121,145,121]);
for v = 1:numel(varargin)
varargout{v} = Z;
varargout{v}(data.bp_mni) = data.(varargin{v});
varargout{v} = imrotate(varargout{v},90);
end
function [B] = vlrbeta(BX)
M = brainfun;
s = std(BX(M));
%[h,names] = defhypset('ystd');
%i = find(strcmp(arrayfun(@(i)names{i}(9:end-1),1:numel(names),'un',0),'SS'));
%load(h{i}.save.name,'o');
h = hypdef_final;
load(h.save.name,'o');
BC = arrayfun(@(i)(o.B{i}{1}),1:numel(o.B),'un',0);
B = mean(cat(4,BC{:}),4);
B = s*(B - median(B(M)))./std(B(M));
function [] = showbeta()
cmap = inferno;
bmm = [-2,+3];
btick = [-2:+3];
M = brainfun;
% LPA beta_0
B.LPA = lpaimg('sp_mni2_Bf2');
% VLR beta_0
B.VLR = vlrbeta(B.LPA);
% black oob
B.LPA(~M) = -inf;
B.VLR(~M) = -inf;
% show the results
sliceshow(B.LPA,zfun,cmap,bmm);
print(gcf,thesisname('fig','seg','b0-LPA.png'),'-dpng');
close(gcf);
sliceshow(B.VLR,zfun,cmap,bmm);
print(gcf,thesisname('fig','seg','b0-VLR.png'),'-dpng');
close(gcf);
vcolorbar(btick,cmap);
print(gcf,thesisname('fig','seg','cmap-LPA.eps'),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
defhypset.m
|
.m
|
vlr-master/exp/hyp/defhypset.m
| 3,814 |
utf_8
|
f498d6cca92ced1a2f4fcd9254a4f18d
|
% DEFHYPSET(HYPSET)
% This function defines various sets of hyperparameter combinations for
% comparison.
function [h,names,params] = defhypset(hypset)
switch hypset
case 'ovb' % add regularizations 'one at a time' vs baseline
params = {'e[P--L--A--F--]','\texttt{base}';
'e[P1-L--A--F--]','$V = 1$';
'e[P--L3-A--F--]','$\lambda = {10}^{-3}$';
'e[P--L--Af-F--]','$\mathrm{a}_{R} = 1$';
'e[P--L--As-F--]','$\mathrm{a}_{S} = \mathbf{N}_6$';};
ho = hypdef_baseline;
for i = 1:size(params,1)
h{i} = key2hyp(ho,params{i,1});
names{i} = params{i,2};
end
case 'cv' % compare different cross validation methods (expensive)
cvs = {'loso', '\texttt{loso}' ;
'kfcv', '\texttt{kfcv}' ;
'loo', '\texttt{loo}' ;
'osaat','\texttt{osaat}';
'nocv', '\texttt{nocv}' ;};
ho = hypdef_final;
for i = 1:size(cvs,1)
h{i} = cv2hyp(ho,cvs{i,1});
names{i} = cvs{i,2};
end
params = cvs;
case 'ystd-full' % compare all different ystd methods (toy only)
ystds = {'na', {},'\textbf{Raw}';
'rm', {[0.0001,0.9999]},'\textbf{RM1}';
'rm', {[0.001, 0.999 ]},'\textbf{RM2}';
'rm', {[0.01, 0.99 ]},'\textbf{RM3}';
'ss', {},'\textbf{SS}';
'he',{pmfdef('uniform')},'\textbf{HE}';
'm1',{pmfdef('normal')} ,'\textbf{HM1}';
'm2',{pmfdef('rskew')} ,'\textbf{HM2}';
'm3',{pmfdef('lskew')} ,'\textbf{HM3}';
'ny',{linspace(0,1,16)} ,'\textbf{NY}';};
ho = hypdef_final;
for i = 1:size(ystds,1)
h{i} = ystd2hyp(ho,ystds{i,1:2});
names{i} = ystds{i,3};
end
params = ystds;
case 'ystd' % compare different ystd methods
ystds = {'ss',{}, '\textbf{SS}';
'he',{pmfdef('uniform')},'\textbf{HE}';
'm1',{pmfdef('normal')}, '\textbf{HM1}';
'm2',{pmfdef('rskew')}, '\textbf{HM2}';
'm3',{pmfdef('lskew')}, '\textbf{HM3}';};
ho = hypdef_final;
for i = 1:size(ystds,1)
h{i} = ystd2hyp(ho,ystds{i,1:2});
names{i} = ystds{i,3};
end
params = ystds;
case 'lam' % compare different lambdas
params = {'e[P1-L--Ab-Fg2]','$\lambda = 0$';
'e[P1-L5-Ab-Fg2]','$\lambda = {10}^{-5}$';
'e[P1-L4-Ab-Fg2]','$\lambda = {10}^{-4}$';
'e[P1-L3-Ab-Fg2]','$\lambda = {10}^{-3}$';
'e[P1-L2-Ab-Fg2]','$\lambda = {10}^{-2}$';
'e[P1-L1-Ab-Fg2]','$\lambda = {10}^{-1}$';};
ho = hypdef_final;
for i = 1:size(params,1)
h{i} = key2hyp(ho,params{i,1});
names{i} = params{i,2};
end
case 'psu' % compare different V
params = {'e[P--L3-Ab-Fg2]','$V = 0$';
'e[P1-L3-Ab-Fg2]','$V = 1$';
'e[P3-L3-Ab-Fg2]','$V = 3$';
'e[P9-L3-Ab-Fg2]','$V = 9$';
'e[P27L3-Ab-Fg2]','$V = 27$';};
ho = hypdef_final;
for i = 1:size(params,1)
h{i} = key2hyp(ho,params{i,1});
names{i} = params{i,2};
end
case 'beta' % compare different beta smoothing
params = {'e[P1-L3-Ab-F--]','$(\cdot)$';
'e[P1-L3-Ab-Fm3]','$\mathrm{Med}_{3\times3}$';
'e[P1-L3-Ab-Fm5]','$\mathrm{Med}_{5\times5}$';
'e[P1-L3-Ab-Fg1]','$\mathrm{G}_{\sigma=1}$';
'e[P1-L3-Ab-Fg2]','$\mathrm{G}_{\sigma=2}$';
'e[P1-L3-Ab-Fg3]','$\mathrm{G}_{\sigma=3}$';};
ho = hypdef_final;
for i = 1:size(params,1)
h{i} = key2hyp(ho,params{i,1});
h{i}.sam.resize = 1;
h{i} = hypfill(h{i});
names{i} = params{i,2};
end
otherwise
error('Unrecognized hypset name: %s', hypset);
end
|
github
|
uoguelph-mlrg/vlr-master
|
fig_thropt.m
|
.m
|
vlr-master/exp/hyp/fig_thropt.m
| 1,643 |
utf_8
|
6c6c50f80f95a26187fcb04219169eb8
|
function [] = fig_thropt(h,fresh)
if nargin < 1, h = hypdef_final; end
if nargin < 2, fresh = 0; end
thr = 0:0.01:1;
Qx = getsampledles(h,fresh);
load(h.save.train,'Cx');
for t = 1:numel(thr)
for i = 1:h.Ni
[si(i,t),pr(i,t),re(i,t)] = performance(Qx{i} > thr(t), Cx{i} > 0.5);
end
statusbar(numel(thr),t,h.Ni/3,1);
end
pr = fixpr(pr);
plot_prcurve(h,pr,re);
plot_sicurve(h,thr,si);
function [Qx] = getsampledles(h,fresh)
savename = fullfile('data','misc',[h.name.data,'-ptx-Q.mat']);
h.M = brainfun;
if fresh || ~exist(savename,'file')
for i = 1:h.Ni
M = mni2ptx(h.Ni,i,h.M);
Q = readnicenii(imglutname('les',h.Ni,i));
Qx{i} = Q(M > 0.5);
statusbar(h.Ni,i,h.Ni/3,1);
end
save(savename,'Qx');
else
load(savename,'Qx');
end
function [pr] = fixpr(pr)
for i = 1:size(pr,1)
idx = find(pr(i,:)==0,1,'first');
pr(i,idx:end) = 1;
end
function [] = plot_prcurve(h,pr,re)
fprintf('AUC = %.03f\n',abs(trapz(median(re),median(pr))));
plot(0,nan,'k','linewidth',2);
scannerplot(h,pr,re,'sw');
plot(median(pr),median(re),'k','linewidth',2);
leg = findobj(gcf,'type','legend');
legend(['Median',leg.String(1:end-1)]);
xlabel('Recall (Re)','interpreter','latex');
ylabel('Precision (Pr)','interpreter','latex');
tightsubs(1,1,gca,0.04*[4,4,1,1]);
print(gcf,thesisname('fig','curve-pr-re'),'-depsc');
close(gcf);
function [] = plot_sicurve(h,thr,si)
scannerplot(h,si,thr);
plot(thr,median(si),'k','linewidth',2);
xlabel('Threshold ($\pi$)','interpreter','latex');
ylabel('Similarity Index (SI)','interpreter','latex');
tightsubs(1,1,gca,0.04*[4,4,1,1]);
print(gcf,thesisname('fig','curve-si'),'-depsc');
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
fig_hypcompare.m
|
.m
|
vlr-master/exp/hyp/fig_hypcompare.m
| 1,072 |
utf_8
|
015b990716a749bcb33130c900e56eac
|
function [] = fig_hypcompare(todo)
if nargin < 1, todo = {'ovb','cv','ystd','lam'}; end
metrics = {{'si','pr','re'},{'$SI$','$Pr$','$Re$'}};
tests = deftests();
for i = 1:numel(todo)
switch todo{i}
case {'cv','ovb','lam'}
[h,names] = defhypset(todo{i});
boxplotcompare(h,metrics{:},[],[todo{i},'-box'],names,tests.rank.pair);
case {'beta'}
[h,names] = defhypset(todo{i});
boxplotcompare(h,metrics{:},[],[todo{i},'-box'],names,tests.rank.pair);
show_betas(defhypset(todo{i}),56);
case {'ystd'}
[h,names] = defhypset(todo{i});
boxplotcompare(h,metrics{:},[4,22],[todo{i},'-box'],names,tests.rank.pair);
show_ystd(defhypset(todo{i}));
otherwise
warning('Unrecognized todo: %s',todo{i});
end
end
function [tests] = deftests()
tests.rank.pair = @(x1,x2)signrank([x1(:)-x2(:)]);
tests.rank.unpr = @(x1,x2)ranksum(x1(:),x2(:));
tests.norm.pair = @(x1,x2)outwo(@ttest,[x1(:)-x2(:)]);
tests.norm.unpr = @(x1,x2)outwo(@ttest2,x1(:),x2(:));
function [out] = outwo(fun,varargin)
[~,out] = fun(varargin{:});
|
github
|
uoguelph-mlrg/vlr-master
|
fig_ystd.m
|
.m
|
vlr-master/exp/ystd/fig_ystd.m
| 2,726 |
utf_8
|
1436bffa348c8b423d76324c930b2272
|
function [] = fig_ystd(todo)
if nargin < 1, todo = {'ypmf','tpmf','Z1','Z2'}; end %
matfile = 'D:/DATA/WML/thesis/mni96-ystd.mat';
[h,names] = defhypset('ystd-full');
for i = 1:numel(todo)
switch todo{i}
case 'ypmf'
load(matfile,'Y','h');
doplotypmf(Y,h,names);
case 'tpmf'
load(matfile,'h');
doplottpmf(h,names);
case 'Z1'
load(matfile,'J','h');
doshowzx(J,h,1,names);
case 'Z2'
load(matfile,'J','h');
doshowzx(J,h,2,names);
otherwise
warning('Unrecognized todo: %s',todo{i});
end
end
function [idx] = hlabelfind(names,lab)
idx = find(strcmp(arrayfun(@(i)names{i}(9:end-1),1:numel(names),'un',0),lab));
function [] = doplotypmf(Y,h,names)
i = hlabelfind(names,'Raw');
plotypmf(Y{i},h{i},'nw');
print(thesisname('fig','ystd','ystd-pmf-na.eps'),'-depsc'); close(gcf);
i = hlabelfind(names,'HE');
plotypmf(Y{i},h{i},'nw');
print(thesisname('fig','ystd','ystd-pmf-he.eps'),'-depsc'); close(gcf);
i = hlabelfind(names,'HM3');
plotypmf(Y{i},h{i},'nw');
print(thesisname('fig','ystd','ystd-pmf-m3.eps'),'-depsc'); close(gcf);
function [] = doplottpmf(h,names)
clr = rainbow6;
figure; hold on;
leg = {'HE','HM1','HM2','HM3'};
for i = 1:numel(leg)
plotpmf(h{hlabelfind(names,leg{i})}.std.args{1},clr(i,:));
end
legend(leg,'location','nw','interpreter','latex');
print(thesisname('fig','ystd','ystd-pmf-hm123.eps'),'-depsc'); close(gcf);
function [] = doshowzx(J,h,j,names)
cmap = inferno;
ii = hlabelfind(names,'RM1');
io = hlabelfind(names,'HM3');
for s = [ii,io];%[1,i]%1:size(J,2)
h{s}.M = brainfun;
h{s}.sam.Mr = ndresize(h{s}.M,h{s}.sam.resize);
Z{j,s} = reconparams(h{s},J{j,s}(:));
Z{j,s} = Z{j,s}{1};
end
mm{1} = {[0,300],[-80,+80]};
dd{1} = {100,40};
mm{2} = {[0,0.15],[-0.05,+0.05]};
dd{2} = {0.05,0.05};
fname = strrep(thesisname('fig','ystd',['ystd-zx-*-#.png']),'#',num2str(j));
cname = strrep(thesisname('fig','ystd',['cbar-zx-*-#.eps']),'#',num2str(j));
% slice plots
sliceshow(Z{j,ii},zfun,mm{j}{1},cmap);
print(strrep(fname,'*','na'),'-dpng'); close(gcf);
sliceshow(Z{j,io},zfun,mm{j}{1},cmap);
print(strrep(fname,'*','op'),'-dpng'); close(gcf);
sliceshow(Z{j,ii}-Z{j,io},zfun,mm{j}{2},spiderman);
print(strrep(fname,'*','naop'),'-dpng'); close(gcf);
% vcolorbars
vcolorbar(mm{j}{1}(1):dd{j}{1}:mm{j}{1}(2),cmap);
print(strrep(cname,'*','i'),'-depsc'); close(gcf);
vcolorbar(mm{j}{2}(1):dd{j}{2}:mm{j}{2}(2),spiderman);
print(strrep(cname,'*','d'),'-depsc'); close(gcf);
function [] = plotpmf(pmf,clr)
u = linspace(0,1,numel(pmf));
plot(u,pmf,'color',clr);
xlim([0,1]); xlabel('Graylevel $y$','interpreter','latex');
ylim([0,0.05]); ylabel('PMF $f_y(y)$','interpreter','latex');
tightsubs(1,1,gca,0.5*[0.3,0.3,0.12,0.12]);
|
github
|
uoguelph-mlrg/vlr-master
|
exp_ystd.m
|
.m
|
vlr-master/exp/ystd/exp_ystd.m
| 629 |
utf_8
|
f76231fb93b9d6c841465223687c7125
|
function [] = exp_ystd()
[Y0,C,h,names] = init;
for s = 1:numel(h)
Y{s} = standardize(Y0,[],h{s}.std.type,h{s}.std.args{:});
J{1,s} = jsepdiff(Y{s},C);
J{2,s} = jsepconv(Y{s},C); % long compute time
statusbar(numel(h),s,h{s}.Ni/3,1);
end
save('D:/DATA/WML/mat/mni96-ystd.mat','h','names','Y','C','J','-v7.3');
function [Y0,C,h,names] = init()
% load the raw data (should be pre-computed)
hraw = hypdef_final;
hraw.std.type = 'na';
hraw.std.agrs = {};
hraw.sam.fresh = 0;
hraw.lr.pad = 0;
hraw = hypfill(hraw);
[~,Y0,C] = gettrainingdata(hraw);
% define the conditions for testing
[h,names] = defhypset('ystd-full');
|
github
|
uoguelph-mlrg/vlr-master
|
mapupdate.m
|
.m
|
vlr-master/exp/toy/mapupdate.m
| 786 |
utf_8
|
741300df956139c5b4a4283457c5f8a8
|
% MAPUPDATE(Y,C)
% This function computes the map update for a given B, Y, C, lam combination
% for one voxel data (not in parallel).
function [B] = mapupdate(B,Y,C,lam,alpha)
Y = Y(:)';
C = C(:)';
% transform the features by the class
Y1 = [ones(size(Y));Y];
Y1(:,~C) = -Y1(:,~C);
% compute the update
s1 = 1./(1+exp(B'*Y1));
a = s1.*(1-s1);
g = Y1*s1' - (lam.*[0,1])*B; % lam
H = (Y1.*[a;a])*Y1' + lam*[0,0;0,1]; % lam
togglewarnings('off');
dB = H\g;
togglewarnings('on');
% apply the update
B = B + alpha*dB;
function [] = togglewarnings(onoff)
% supress annoying msg in known bad scenarios
warning(onoff,'MATLAB:illConditionedMatrix');
warning(onoff,'MATLAB:singularMatrix');
warning(onoff,'MATLAB:nearlySingularMatrix');
warning(onoff,'MATLAB:legend:IgnoringExtraEntries');
|
github
|
uoguelph-mlrg/vlr-master
|
exp_toyreg.m
|
.m
|
vlr-master/exp/toy/exp_toyreg.m
| 5,490 |
utf_8
|
f87f98b4f46be0feef67cc955bade8b8
|
function [] = exp_toyreg(todo)
if nargin < 1
todo = {'tab-pmf','plt-pmf','plt-lam','plt-psu','srf-lam'};%,'srf-psu'};
end
[D,R] = data;
if any(strcmp('tab-pmf',todo)), tab_distribs(R); end
if any(strcmp('plt-pmf',todo)), plt_distribs(D,R); end
if any(strcmp('plt-lam',todo)), plt_lambdas(D); end
if any(strcmp('plt-psu',todo)), plt_psuedos(D); end
if any(strcmp('srf-lam',todo)), srf_lambdas(D); end
%if any(strcmp('srf-psu',todo)), srf_psuedos; end
% sub-main functions
function [] = tab_distribs(R)
DM = cell2mat(R);
DM = num2cell(DM(:,[1,3,5,2,4,6]));
str = '';
title = {'','\\multicolumn{3}{c}{$c=0$}','\\multicolumn{3}{c}{$c=1$}';
'\\cmidrule(lr){2-4}\\cmidrule(lr){5-7}\n\\#',...
'$\\mu$ & $\\sigma$ & $N$','$\\mu$ & $\\sigma$ & $N$'};
str = [str,textable('top',title,'ccccccc')];
for r = 1:size(R,1)
for i = [3,6]
if DM{r,i} == 0
DM(r,i-2:i-1) = {'---','---'};
end
end
fmt = {'%c','%.01f','%.02f','%d','%.01f','%.02f','%d'};
str = [str,textable('line',{r+96,DM{r,:}},fmt)];
end
str = [str,textable('bottom')];
fid = fopen(thesisname('fig','toy','toy-pmf-tab.tex'),'w');
fprintf(fid,str);
fclose(fid);
function [] = plt_distribs(D,R)
for d = 1:size(R,1)
plotdistribs(D{d},R(d,:));
legend({'$c=0$','$c=1$'},'location','nw','interpreter','latex');
print(gcf,thesisname('fig','toy',num2str(d,'toy-pmf-%d.eps')),'-depsc');
close(gcf);
end
function [] = plt_lambdas(D)
T = time;
clr = rainbow6;
lam = lambdas();
for d = 1:6 % #notalldistributions
for l = 1:4
L(l) = LINE(lam(l),zeros(2,0),clr(l,:),D{d});
end
figure(d);
X = VOX(L,0.5,T);
X = initplot(X);
plotloop(X);
initplot(X);
leg = {'$\lambda = 0$',...
'$\lambda = 10^{-3}$',...
'$\lambda = 10^{-2}$',...
'$\lambda = 10^{-1}$'};
legend(leg,'location','nw','interpreter','latex');
print(gcf,thesisname('fig','toy',num2str(d,'toy-lam-%d.eps')),'-depsc');
close(gcf);
end
function [] = plt_psuedos(D)
T = time;
P = psuedos;
clr = rainbow6;
for d = 1:numel(D)
for l = numel(P):-1:1
L(l) = LINE(10.^(-3),P{l},clr(l,:),D{d});
end
figure(d);
X = VOX(L,0.5,T);
X = initplot(X);
plotloop(X);
initplot(X);
plotpsu(X);
leg = arrayfun(@(i)sprintf('$V = %d$',i),[0,1,3,9],'un',0);
legend(leg,'location','nw','interpreter','latex');
print(gcf,thesisname('fig','toy',num2str(d,'toy-psu-%d.eps')),'-depsc');
close(gcf);
end
function [] = srf_lambdas(D)
d = 5;
lam = lambdas();
NL = numel(lam);
for l = 1:NL
% lambda only
surfmapj([],[],lam(l),[0,1]);
print(gcf,thesisname('fig',num2str(5-l,'toy-srf-lamo-%d.eps')),'-depsc');
close(gcf);
% lambda and data
surfmapj(D{d}.Y,D{d}.C,lam(l));
print(gcf,thesisname('fig','toy',num2str(5-l,'toy-srf-lamy-%d.eps')),'-depsc');
close(gcf);
end
% dataset definitions
function [ts] = time()
ts = round(10.^[0:0.2:3]);
function [D,R] = data()
N = 100;
R = {...
[ 0.3, 0.7],[0.12,0.12],N*[1,1.0];
[ 0.3, 0.7],[0.12,0.12],N*[1,0.1];
[ 0.3, 0.7],[0.24,0.24],N*[1,0.1];
[ 0.3, 0.7],[0.06,0.06],N*[1,0.1];
[ 0.3, 0.7],[0.03,0.03],N*[1,0.1];
[ 0.6, 0.3],[0.08,0.08],N*[1,0.1];
[ 0.4, 0.0],[0.10,0.00],N*[1,0.0];
[ 0.6, 0.0],[0.08,0.00],N*[1,0.0];
[ 0.8, 0.0],[0.06,0.00],N*[1,0.0];
};
for x = 1:size(R,1)
[D{x}.Y,D{x}.C] = cytoy(R{x,:});
end
function [lam] = lambdas()
lam = [10*eps,1e-3,1e-2,1e-1];
function [psu] = psuedos()
N = 100;
psu = {...
[ones(1, 0);ones(1, 0)];
[ones(1, 1);ones(1, 1)];
[ones(1,0.03*N);ones(1,0.03*N)];
[ones(1,0.09*N);ones(1,0.09*N)];
};
% 'class' definition: one fitted line
function [L] = LINE(lam,psu,clr,data)
L.B = [0;0];
L.lam = lam;
L.Y = data.Y(:);
L.C = data.C(:);
L.clr = clr;
L.ls = '-';
L.psu = psu;
% 'class' definition: one voxel location
function [X] = VOX(L,alpha,ts)
X.alpha = alpha;
X.ts = ts;
X.L = L;
X.NL = numel(L);
% 'methods'
function [X] = initplot(X)
ax = gca; hold(ax,'on');
ylim([-0.1,+1.1]); ylabel('Class (c)' ,'interpreter','latex');
xlim([ 0 , 1 ]); xlabel('Graylevel (y)','interpreter','latex');
for l = 1:X.NL
plot(0,nan,'color',X.L(l).clr);
end
for l = 1:X.NL
plot(X.L(l).Y(:),X.L(l).C(:),'ko','linewidth',2);
end
tightsubs(1,1,ax,[0.2,0.2,0.12,0.12]);
function [X] = plotloop(X)
for l = 1:X.NL
L = X.L(l);
Y = [L.Y',L.psu(1,:)];
C = [L.C',L.psu(2,:)];
Yco = mean(Y(C<0.5));
C(Y<Yco) = 0;
[~,c{l},y] = plotlrfit(L.B,Y,C,L.lam,X.alpha,X.ts,L.clr);
end
for l = X.NL:-1:1
plot(y,c{l},L.ls,'color',X.L(l).clr);
end
function [] = plotpsu(X)
dy = 0.01;
for l = X.NL:-1:1
np = size(X.L(l).psu,2);
for i = 1:np
plot(X.L(l).psu(1,i),X.L(l).psu(2,i)-dy*(np-i),...
'd','linewidth',2,'markersize',6,'color',X.L(l).clr);
end
end
function [B] = update(L,alpha)
% kill dark lesions (vs mean of healthy)
Yco = mean(L.Y(L.C<0.5));
L.C(L.Y<Yco) = 0;
% add the psuedo-lesions
if ~isempty(L.psu)
L.Y = [L.Y;L.psu(1,:)'];
L.C = [L.C;L.psu(2,:)'];
end
B = mapupdate(L.B,L.Y,L.C,L.lam,alpha);
function [] = plotdistribs(D,DS)
ax = gca; hold(ax,'on');
ylim([-0.1,+1.1]); ylabel('PMF ($f_y(y)$)','interpreter','latex');
xlim([ 0 , 1 ]); xlabel('Graylevel (y)' ,'interpreter','latex');
clr = [lighten(blu(1),0.5);red(1)];
y = linspace(0,1,512);
for c = 1:2
P{c} = 0.01*DS{3}(c)*normpdf(y,DS{1}(c),DS{2}(c));
P{c}(1) = 0; P{c}(end) = 0;
fill(y,0.15*P{c},lighten(clr(c,:),0.5),'edgecolor',clr(c,:));
end
plot(D.Y(:),D.C(:),'ko','linewidth',2);
tightsubs(1,1,ax,[0.2,0.2,0.12,0.12]);
|
github
|
uoguelph-mlrg/vlr-master
|
standardize.m
|
.m
|
vlr-master/vlr/standardize.m
| 1,523 |
utf_8
|
8a6def5228954a8f30f929a71f83d8e7
|
% STANDARDIZE
% This function standardizes the data in Yn, selected by the mask M
% The standardization type is a string, and additional required
% parameters should be passed to to varargin
% If M is empty, then stdfun operates along the 1st dimension of Y only.
function [Ynt] = standardize(Yn,M,type,varargin)
% define the transformation
switch type
case 'na' % none!
stdfun = @(y)(y);
case 'rm' % range matching (quantiles specified)
qmm = varargin{1}; ymm = quantile(Yn,qmm,1);
stdfun = @(y)(bsxfun(@rdivide,bsxfun(@minus,y,ymm(1,:)),diff(ymm)));
case 'ss' % statistical standardization
stdfun = @(y)(bsxfun(@rdivide,bsxfun(@minus,y,mean(y,1)),4*std(y,[],1))+0.5);
case 'he' % histogram equalization
stdfun = @(y)(bsxfun(@(y,i)histeq(y./max(y)),y,1:size(y,2)));
%stdfun = @(y)(bsxfun(@(y,i)histeq(im2double(y)),y,1:size(y,2)));
case {'m1','m2','m3'} % histogram matching (target specified)
pdf = varargin{1};
stdfun = @(y)(bsxfun(@(y,i)histeq(y./max(y),pdf),y,1:size(y,2)));
%stdfun = @(y)(bsxfun(@(y,i)histeq(im2double(y),pdf),y,1:size(y,2)));
case 'ny' % nyul standardization
qout = varargin{1};
stdfun = @(y)(bsxfun(@(y,i)nyulstd(y,qout),y,1:size(y,2)));
otherwise
error('Unknown standardization type: %s.',type);
end
% apply the transformation
if ~isempty(M)
Ynt = zeros(size(Yn),class(Yn));
Ynt(logical(M)) = stdfun(Yn(logical(M)));
else
Ynt = stdfun(Yn);
end
% clip outliers
if ~strcmp(type,'na')
Ynt = clip(Ynt,[0,1]);
end
|
github
|
uoguelph-mlrg/vlr-master
|
maketrainingdata.m
|
.m
|
vlr-master/vlr/maketrainingdata.m
| 2,621 |
utf_8
|
fde7f464133f1e5f8761d90c9928ec78
|
% MAKETRAININGDATA(h)
% This function loads and preprocesses all training data specified by h.
% On completion, these data are saved to file to save time.
% If a save file already exists with the specified name, it is loaded.
function [h,Y,C] = maketrainingdata(h)
[h,N] = init(h);
Y = nan(N.v,h.Ni*N.a,'single'); % graylevel data
C = nan(N.v,h.Ni*N.a,'single'); % labels
% for all subjects...
for n = 1:h.Ni
[h,Yn,Cn] = loadone(h,n);
[Ynt] = prepone(h,Yn);
[h,Y,C] = sampleone(h,Y,C,Ynt,Cn,n,N);
statusbar(h.Ni,n,h.Ni/3,1);
end
% nan -> 0
Y(isnan(Y) | isnan(C)) = 0;
C(isnan(Y) | isnan(C)) = 0;
function [h,N] = init(h)
% load the MNI-space brain mask
h.M = brainfun;
% resize the mask by the VLR fitting factor
h.sam.Mr = ndresize(h.M,h.sam.resize);
N.s = size(h.sam.dx,1); % shift augmentation count
N.f = h.sam.flip+1; % flip augmentation count
N.a = N.s*N.f; % total augmentation count
N.v = sum(h.sam.Mr(:)); % number of fitted voxels
function [h,Yn,Cn] = loadone(h,n)
% load the MNI-space FLAIR and label image
h.name.img{n} = imglutname('mni:FLAIRm',h.Ni,n);
Yn = readnicenii(imglutname('mni:FLAIRm',h.Ni,n),h.M,[0,1]);
Cn = readnicenii(imglutname('mni:mans', h.Ni,n),h.M);
Cn = Cn./max(Cn(:)); % in case not \in [0,1]
function [Ynt] = prepone(h,Yn)
% graylevel standardization
Ynt = standardize(Yn,h.M,h.std.type,h.std.args{:});
function [h,Y,C] = sampleone(h,Y,C,Yn,Cn,n,N)
% Resize the image, perform data augmentation transformations
% then vectorize only the brain voxels for efficiency
r = h.sam.resize;
for f = 1:N.f
for s = 1:N.s
xs = h.sam.dx(s,:);
Yr = flipshiftresize(Yn,f,xs,r); % graylevels
Cr = flipshiftresize(Cn,f,xs,r); % label
ia = (n-1)*N.a + (f-1)*N.s + s;
Y(:,ia) = Yr(h.sam.Mr);
C(:,ia) = Cr(h.sam.Mr);
h.sam.i(ia) = n;
end
end
function [Irsf] = flipshiftresize(I,f,s,r)
if f==1, If = I(:,1:+1:end,:); % original
elseif f==2, If = I(:,end:-1:1,:); % flipped
end
Irsf = ndresize(imshift(If,s),r); % shift & resize
function [IS] = imshift(I,T) % easier to use than matlab imshift
if all(T==[0,0,0]), IS = I;
elseif all(T==[0,0,+1]), IS = cat(3, I(:,:,1+1:end), I(:,:, end));
elseif all(T==[0,0,-1]), IS = cat(3, I(:,:, 1), I(:,:,1:end-1));
elseif all(T==[0,+1,0]), IS = cat(2, I(:,1+1:end,:), I(:, end,:));
elseif all(T==[0,-1,0]), IS = cat(2, I(:, 1,:), I(:,1:end-1,:));
elseif all(T==[+1,0,0]), IS = cat(1, I(1+1:end,:,:), I( end,:,:));
elseif all(T==[-1,0,0]), IS = cat(1, I( 1,:,:), I(1:end-1,:,:));
else error('Not implemented: please use standard imshift instead.');
end
|
github
|
uoguelph-mlrg/vlr-master
|
arbiter.m
|
.m
|
vlr-master/vlr/arbiter.m
| 2,380 |
utf_8
|
d162d6e034a1db167ab37fffd16b831f
|
% ARBITER
% This function runs one entire cross validation
% of the segmentation model:
% 1. Load the experiment hyperparameters
% 2. Load training data
% 3. For all cross valiation folds:
% 3.1. Define the training-testing indices
% 3.2. Fit the VLR model
% 3.3. Inference & post processing on test images
% 3.4. Performance evaluation on test images
% 3.5. Save results to file
% 4. Summarize the results with automated plotting
% and PDF report generation.
% `h` can be defined as in hypdef_final, hypdef_base, etc.
function [] = arbiter(h)
% ==================================================
statusupdate(80);
statusupdate([h.name.full]); statusupdate();
statusupdate(80);
% --------------------------------------------------
statusupdate('loading training data...'); statusupdate();
[h,Y,C,Yx,Cx] = gettrainingdata(h); t = [];
% ==================================================
for c = 1:numel(h.cv.N)
statusupdate(80);
% ------------------------------------------------
statusupdate(c,numel(h.cv.N)); statusupdate();
[idx] = makeidx(h,c);
% ------------------------------------------------
statusupdate('computing regression...'); statusupdate();
[o.B{c}] = trainlogreg(h,idx,Y,C);
% ------------------------------------------------
statusupdate('optimizing threshold...'); statusupdate();
[o.thr(c)] = thropt(h,Yx,Cx,o.B{c},find(idx.i.train));
% ------------------------------------------------
statusupdate('measuring test performance...');
%[o,t] = performancebat(h,o,t,idx); % fast matlab spawns
[o,t] = performancebati(h,o,t,idx); % slow singleton
%[o,h] = performancetest(h,'loso'); % for LPA, etc.
% ------------------------------------------------
statusupdate('saving...'); statusupdate();
save(h.save.name,'h','o','t','-v7.3');
end
statusupdate(80);
% ==================================================
statusupdate('summarizing results...'); statusupdate();
summarizeresults(h, o, t);
% --------------------------------------------------
statusupdate('done');statusupdate();
statusupdate(80);
% ==================================================
function [B] = trainlogreg(h,idx,Y,C)
% append the pseudolesions
[Y,C,idx] = dataregfun(h.lr.reg.py,h.lr.reg.pc,Y,C,idx);
% compute the regression
[b] = vlrmap(h, Y(:,idx.s.train), C(:,idx.s.train));
% reconstruct the parameter images
B = reconparams(h, b);
|
github
|
uoguelph-mlrg/vlr-master
|
hypdef.m
|
.m
|
vlr-master/vlr/hypdef.m
| 1,254 |
utf_8
|
3dcbe6c806a1204b2a79a8ffa6030897
|
% HYPDEF(h)
% This function defines all model hyperparameters for the segmentation pipeline.
% This version (vs _final and _baseline) is for experimenting with parameters.
% Some shorthands used here are expanded by hypfill.
function [h] = hypdef(h)
% flag-like names
h.name.key = 'test'; % h.name.key = 'LPA';
h.name.data = 'mni96'; % h.name.data = 'mni109';
h.name.cv = 'loso'; % h.name.cv = 'nocv';
% scanner parameters
h.cmap = inferno;
h.Ni = [];
h.scan.idx = [1,2,3,4,5,6,9]; % h.scan.idx = [1,2,3,4,5,6,9,7,8,10];
h.scan.clr = rainbow7; % h.scan.clr = rainbow10;
% sampling parameters
h.sam.fresh = 0;
h.sam.resize = 0.5;
h.sam.dx = kernelshifts(binsphere(1));
h.sam.flip = 1;
% grey standardization parameters
h.std.type = 'm3';
h.std.args = {pmfdef('lskew')};
% logistic regression parameters
h.lr.Nit = 30;
h.lr.B = [0,0];
h.lr.alpha = 1;
h.lr.reg.la = 1e-3;
h.lr.reg.py = [1];
h.lr.reg.pc = [1];
h.lr.pad = [-20,20];%[-1.5;1];
h.lr.pp.filter= @(B)(gaussfilter(B,[2,2,2]));
% post processing parameters
h.pp.saveles = 'test';
h.pp.thr.def = 0.5;
h.pp.thr.Nit = 30;
h.pp.minmm3 = 5;
% cross validation and scanner
h = hypfill(h);
|
github
|
uoguelph-mlrg/vlr-master
|
performancebat.m
|
.m
|
vlr-master/vlr/performancebat.m
| 3,466 |
utf_8
|
d1db4ab8ae539f5c6d787eb4031b03be
|
% PERFORMANCEBAT
% This function analyzes the performance of the VLR model using the fitted
% parameter images in o.B{idx.c} -- i.e. one cross validation fold.
% To do this efficiently, several MATLAB instances are spawned to compute
% the anaysis in parallel. The function called by the spawns is performancei.
% Data for each each analysis (h,B,thr) are saved to a .mat file.
% Temporary images for each subject (for spmdeform) are saved in
% a subject-specific folder.
% The temporary folders are generated by tmpname.
function [o,t] = performancebat(h,o,t,idx)
[file] = filenames(idx); % create the filenames
cleanup(file); % cleanup tmp files & folders (pre)
writemat(file,h,o,idx); % write the common mat file for loading
writebat(file,h,idx); % write the bat file (and wait for it to be done)
while(~fileready(file.bat,1000) || ~fileready(file.mat.c,1000)), pause(0.1); end
eval(['!call ',file.bat,' &']); % execute the bat file
%eval(['!start cmd /c ',file.bat,' &']); % execute the bat file
[o,t] = getresults(file,h,o,t,idx); % collect the results as the become available
cleanup(file); % cleanup tmp files & folders (post)
function [file,cidx] = filenames(idx)
cidx = find(idx.i.valid);
file.tmp = tmpname('*');
file.bat = fullfile(pwd,'tmp.bat');
file.mat.c = tmpname('c',idx.c,'.mat');
for n = 1:numel(cidx)
file.mat.i{n} = tmpname('i',cidx(n),'.mat');
end
function [] = writemat(file,h,o,idx)
B = o.B{idx.c};
thr = o.thr(idx.c);
save(file.mat.c,'h','B','thr');
function [] = writebat(file,h,idx)
% the code for execution
code = 'performancei(%d,[#]);';
% group the indices
cidx = find(idx.i.valid);
Ni = numel(cidx);
Nib = ceil(Ni./h.cv.cpu);
bat = {[10]};
% create the file contents
for n = 1:min(h.cv.cpu,Ni)
i = num2cell(cidx(n:h.cv.cpu:Ni));
nib = numel(i);
numstr = sprintf(repmat('%02.f,',[1,nib]),i{:});
codi = sprintf(strrep(code,'#',numstr),idx.c);
bat{end+1} = ['@echo ANALYZING IMAGES ',numstr,'...',10];
bat{end+1} = ['@',matx(codi),10];
%bat{end+1} = ['@timeout 1 > nul',10];
end
bat{end+1} = 'exit';
% write the file
fid = fopen(file.bat,'w');
fwrite(fid,cat(2,bat{:}));
fclose(fid);
function [o,t] = getresults(file,h,o,t,idx)
cidx = find(idx.i.valid);
Ni = numel(cidx);
done = false(size(cidx));
% while waiting for some mat files to finish
while(~all(done))
% check all
for n = 1:Ni
i = cidx(n);
% if file exists and hasn't been modified in 2500 ms
if fileready(file.mat.i{n},2500)
load(file.mat.i{n},'p'); % load and distribute results
o.si(i) = p.si; o.pr(i) = p.pr; o.re(i) = p.re;
o.ll(i) = p.ll; o.lle(i) = p.lle;
t.TP{i} = p.TP; t.FP{i} = p.FP; t.FN{i} = p.FN;
delete(file.mat.i{n}); % then delete the mat file
done(n) = true; % check this one off
statusbar(Ni,sum(done),h.Ni/3,1);
end
end
pause(0.1);
end
% saving every B consumes too much memory in LOO-CV
if strcmp(h.name.cv,'loo');
o.B{idx.c} = {};
end
function [] = cleanup(file)
if exist(file.bat,'file')
delete(file.bat);
end
if exist(file.mat.c,'file')
delete(file.mat.c);
end
droot = fileparts(file.tmp);
F = dir(file.tmp);
F = F(arrayfun(@(x)(~any(strcmp(x.name,{'.','..'}))),F));
for f = 1:numel(F)
pathname = fullfile(droot,F(f).name);
if exist(pathname,'dir')
rmdir(pathname,'s');
elseif exist(pathname,'file')
delete(pathname);
end
end
|
github
|
uoguelph-mlrg/vlr-master
|
hypfill.m
|
.m
|
vlr-master/vlr/hypfill.m
| 2,415 |
utf_8
|
fb649bd4b03098223811ef61e8d2d42d
|
% hypdef(h)
% This function fills in the repetitive parameters and info related to one VLR
% cross validation run.
% hypdef must be called first.
function [h] = hypfill(h)
% load scanner parameters
[names,short,N,vsize,tERI,Y4] = arrayfun(@scanparams,h.scan.idx,'un',0);
h.scan.names = names;
h.scan.short = short;
h.scan.N = cell2mat(N);
n = 1;
for i = 1:numel(h.scan.N)
for ni = 1:h.scan.N(i)
h.scan.i (n) = i;
h.scan.vsize(n,:) = vsize{i};
h.scan.tERI (n,:) = tERI{i};
h.scan.Y4 (n,:) = Y4{i};
n = n + 1;
end
end
h.Ni = sum(h.scan.N);
% cross validation parameters
switch h.name.cv
case 'loso'
h.cv.N = h.scan.N;
h.cv.i = [];
for i = 1:numel(h.cv.N)
h.cv.i(end+1:end+h.cv.N(i)) = i;
end
h.cv.names = h.scan.names;
case 'kfcv'
h.cv.N = h.scan.N;
idx = kfcvidx(h);
for i = 1:numel(idx)
h.cv.i(idx{i}) = i;
end
h.cv.names = arrayfun(@(i)sprintf('Group %02.0f',i),1:max(h.cv.i),'un',0);
case 'loo'
h.cv.N = ones([1,h.Ni]);
h.cv.i = 1:h.Ni;
h.cv.names = arrayfun(@(i)num2str(i,'%02.0f'),1:96,'un',0);
case 'nocv'
h.cv.N = h.Ni;
h.cv.i = ones(1,h.cv.N);
h.cv.names = {'All'};
case 'osaat'
h.cv.N = ones([1,h.Ni]);
h.cv.i = 1:h.Ni;
h.cv.names = arrayfun(@(i)num2str(i,'%02.0f'),1:96,'un',0);
otherwise
error('Unrecognized CV option: %s',h.name.cv);
end
h.cv.cpu = 5;
% savenames
outroot = 'C:\Users\Jesse\Documents\Research\working-docs\results\';
h.name.resize = ['r=',num2str(h.sam.resize,'%1.1f')];
h.name.aug = ['a=',num2str([h.sam.flip,size(h.sam.dx,1)>1],'%0.0f')];
h.name.train = [h.name.data,'-train-',...
h.std.type, '-',...
h.name.resize, '-',...
h.name.aug];
if h.name.key(1) == 'e'
h.name.full = [h.name.data, '-',...
h.std.type, '-',...
h.name.resize,'-',...
h.name.key, '-',...
h.name.cv];
else
h.name.full = [h.name.data,'-',h.name.key];
end
h.save.train = fullfile('data','train',[h.name.train,'.mat']);
h.save.name = fullfile('data', [h.name.full,'.mat']);
h.save.ples = fullfile('data', [h.name.full,'-ples.mat']);
h.save.outdir = fullfile(outroot, h.name.full);
h.save.pdf = fullfile(h.save.outdir,h.name.full);
h.save.figdir = fullfile(h.save.outdir,'figs');
|
github
|
uoguelph-mlrg/vlr-master
|
performancetest.m
|
.m
|
vlr-master/vlr/performancetest.m
| 2,061 |
utf_8
|
de5a6bc62a657262ddfaf21306189f8b
|
% PERFORMANCETEST
% This function analyzes the performance of *any* segmentation model,
% provided the initial segmentations (can be probabilistic) are saved as nii.
% These segmentations are loaded using imglutname with the key specified.
% Segmentations are thresholded using either the default threshold specified
% in h.pp.thr.def, or loaded from the file:
% ['data/',h.name.data,'-thropt-',key,'.mat']
% (if the threshold has been optimized in cross validation, for instance).
function [o,h] = performancetest(h, key, o, flag)
if nargin < 3, flag = ''; end
% try to load optimal thresholds
[h] = loadthropt(h,key,flag);
for i = 1:h.Ni
% load nii images from file (no mrf)
[C,G,x] = loadkeyimg(h,key,i);
% analyze performance
[o.si(i),o.pr(i),o.re(i),o.ll(i),o.lle(i),TP,FP,FN] = performance(C,G,x/10);
% store the TP FP FN
[t.FP{i},t.TP{i},t.FN{i}] = ptx2mni(h.Ni, i, single(FP), single(TP), single(FN));
% update status bar
statusbar(h.Ni,i,h.Ni/3,1); fclose('all');
end
function [C,G,x] = loadkeyimg(h,key,i)
% read and threshold the images for comparison
[C,x] = readnicenii(imglutname(lower(key), h.Ni,i));
[G] = readnicenii(imglutname('mans', h.Ni,i));
G = G > 0.5;
C = C > h.pp.thr.opt(h.cv.i(i));
function [h] = loadthropt(h,key,flag)
% try to load the optimal threshold file, if it exists
% make sure it has the same data key as the current data
if isfield(h.pp.thr,'opt')
assert(strcmp(h.name.key,key) || strcmp(flag,'-h'),[...
'Keys do not match - h: ''%s'', given: ''%s''\n'...
'Are you sure you want to use these optimal thresholds?\n',...
'If so: use the flag ''-h''.'],...
h.name.key, key);
else
throptmat = ['data/',h.name.data,'-thropt-',key,'.mat'];
assert(exist(throptmat,'file') || strcmp(flag,'-d'),[...
'Can''t find optimal thresholds file: ''%s''\n',...
'To use h.pp.thr.def instead, use the flag ''-d''.'],...
throptmat);
if exist(throptmat,'file')
load(throptmat);
h.pp.thr.opt = thr;
else
h.pp.thr.opt = h.pp.thr.def * ones(size(h.cv.N));
end
end
|
github
|
uoguelph-mlrg/vlr-master
|
thropt.m
|
.m
|
vlr-master/vlr/thropt.m
| 1,430 |
utf_8
|
2cb09e1e33ebe69e6a070f0a6d030c18
|
% THROPT
% This function uses fminsearch to optimize the threshold (thr) applied to
% probabilistic predictions of the lesion class (all data vectorized).
% The objective is to maximize the mean similarity index on the training data.
function [thr] = thropt(h,Y,C,B,nidx)
% compute the probabilistic output
statusupdate(1,2);
for i = 1:numel(nidx)
[B0,B1,M] = mni2ptx(h.Ni,nidx(i),B{:},h.M);
Q{i} = 1./(1+exp(-bsxfun(@plus,B0(M>0.5),bsxfun(@times,Y{nidx(i)}(:),B1(M>0.5)))));
G{i} = C{nidx(i)}(:);
statusbar(numel(nidx),i,h.Ni/3,1);
end
% define the inputs of the optimization by fminsearch
optfun = @(t)objective(Q,G,t);
udfun = @(x,ovals,state)updatefun(h.pp.thr.Nit,h.Ni/3,x,ovals,state);
fminopt = optimset('maxiter',h.pp.thr.Nit,'OutputFcn',udfun,'Display','off');
% run the optimization
statusupdate(2,2);
[thr,~,flag] = fminsearch(optfun, h.pp.thr.def, fminopt);
% print complete statusbar if early convergence
statusbar(h.pp.thr.Nit,h.pp.thr.Nit,h.Ni/3,1);
function [J] = objective(Q,C,thr)
for i = 1:numel(Q)
Qi = Q{i} > thr;
Ci = C{i} > 0.5;
SI(i) = 2*sum(Qi.*Ci) ./ sum(Qi+Ci);
end
SI(isnan(SI)) = [];
J = -gather(mean(SI)); % gather mean from GPU
%fprintf('%.03f\n',J);
function [stop] = updatefun(Nit,wid,~,ovals,~,~)
% statusbar to show progress (might stop early if convergence)
stop = false;
if (ovals.iteration > 0) && (ovals.iteration < Nit)
statusbar(Nit,ovals.iteration,wid,1);
end
|
github
|
uoguelph-mlrg/vlr-master
|
performancebati.m
|
.m
|
vlr-master/vlr/performancebati.m
| 1,490 |
utf_8
|
dc10dc2d865b4ef8736f05a83956e80c
|
% PERFORMANCEBATI
% This function analyzes the performance of the VLR model using the fitted
% parameter images in o.B{idx.c} -- i.e. one cross validation fold.
% This function does not require additional matlab spawns, unlike
% performancebat, and rolls the functionality of performancebat and performancei
% together in one (slower) function.
function [o,t] = performancebati(h,o,t,idx)
cidx = find(idx.i.valid);
for k = 1:numel(cidx)
i = cidx(k);
% load all images into pt space
[I,x] = readnicenii(imglutname('FLAIRm',h.Ni,i));
[G] = readnicenii(imglutname('mans', h.Ni,i));
% warp the B images to pt space
[Bi{1},Bi{2},Mi] = mni2ptx(h.Ni,i,o.B{idx.c}{:},h.M);
% compute the prediction
G = G > 0.5;
Y = standardize(I,Mi,h.std.type,h.std.args{:});
eta = Bi{1} + Bi{2}.*Y;
C0 = Mi./(1+exp(-eta));
% save the prediction before post-processing
if h.pp.saveles
writenii(imrotate(C0,180),imglutname(h.pp.saveles,h.Ni,i,0),...
imglutname('mans', h.Ni,i,1),'double');
end
% post-processing
C = postpro(h,C0,x,o.thr(idx.c));
% analyze performance
[p.si,p.pr,p.re,p.ll,p.lle,TPi,FPi,FNi] = performance(C,G,x/10);
% warp the TP FP FN
[p.FP,p.TP,p.FN] = ptx2mni(h.Ni,i,FPi,TPi,FNi);
% gather the results into output data structure
o.si(i) = p.si; o.pr(i) = p.pr; o.re(i) = p.re;
o.ll(i) = p.ll; o.lle(i)= p.lle;
t.TP{i} = p.TP; t.FP{i} = p.FP; t.FN{i} = p.FN;
statusbar(numel(cidx),k,h.Ni/3,1);
end
|
github
|
uoguelph-mlrg/vlr-master
|
maketestingdata.m
|
.m
|
vlr-master/vlr/maketestingdata.m
| 996 |
utf_8
|
c34b3073ca9d12ed634fe2fccc77522e
|
% MAKETESTINGDATA(h)
% This function loads and preprocesses all testing data specified by h.
% On completion, these data are saved to file to save time.
% If a save file already exists with the specified name, it is loaded.
function [Y,C] = maketestingdata(h)
Y = {}; % graylevel data
C = {}; % labels
% for all subjects...
for n = 1:h.Ni
[Yn,Cn] = loadone(h,n);
[Ynt,M] = prepone(h,Yn,n);
[Y,C] = sampleone(Y,C,Ynt,Cn,M,n);
statusbar(h.Ni,n,h.Ni/3,1);
end
function [Yn,Cn] = loadone(h,n)
% load the MNI-space FLAIR and label image
Yn = readnicenii(imglutname('FLAIRm',h.Ni,n),h.M,[0,1]);
Cn = readnicenii(imglutname('mans', h.Ni,n));
Cn = Cn./max(Cn(:)); % in case not \in [0,1]
function [Ynt,M] = prepone(h,Yn,n)
% warp the brain mask to ptx
M = mni2ptx(h.Ni,n,h.M);
% graylevel standardization
Ynt = standardize(Yn,M,h.std.type,h.std.args{:});
function [Y,C] = sampleone(Y,C,Yn,Cn,M,n)
% Vectorize only the brain voxels for efficiency
Y{n} = Yn(M > 0.5);
C{n} = Cn(M > 0.5);
|
github
|
uoguelph-mlrg/vlr-master
|
performance.m
|
.m
|
vlr-master/vlr/performance.m
| 671 |
utf_8
|
24c84d58883a8b0981a234e047311af5
|
% PERFORMANCE
% This function computes the performance metrics, and TP/FP/FN images for one
% comparison of Ce (estimated) and Ct (true)
function [si,pr,re,ll,lle,TP,FP,FN] = performance(Ce,Ct,x)
% TP/FP/FN images
TP = Ce & Ct;
FP = Ce & ~Ct;
FN = ~Ce & Ct;
% TP/FP/FN voxel counts
nTP = sum(TP(:));
nFP = sum(FP(:));
nFN = sum(FN(:));
% metrics
si = (2*nTP) ./ ((2*nTP) + nFP + nFN + eps); % similarity index
pr = nTP ./ (nTP + nFP + eps); % precision
re = nTP ./ (nTP + nFN + eps); % recall
% lesion loads
if nargin == 2, x = 1; end % assume 1mm3 voxel volume
ll = sum(Ct(:))*prod(x); % true
lle = sum(Ce(:))*prod(x); % estimated
|
github
|
uoguelph-mlrg/vlr-master
|
gettrainingdata.m
|
.m
|
vlr-master/vlr/gettrainingdata.m
| 739 |
utf_8
|
06e258e3bcb061bf489b93f145eb055a
|
% GETTRAININGDATA
% This function either:
% - preps the training data from scratch (h.sam.fresj = 1)
% - loads the training data from file (h.sam.fresj = 0)
% and returns the results in
% h (some metadata changed) and
% Y and C both size: [V,N], for V voxels, and N subjects
function [h,Y,C,Yx,Cx] = gettrainingdata(h)
if ~exist(h.save.figdir), mkdir(h.save.figdir); end
if h.sam.fresh
statusupdate(1,2);
[h,Y,C] = maketrainingdata(h);
statusupdate(2,2);
[Yx,Cx] = maketestingdata(h);
ho.M = h.M;
ho.sam.Mr = h.sam.Mr;
ho.sam.i = h.sam.i;
save(h.save.train,'-v7.3','Y','C','Yx','Cx','ho');
else
load(h.save.train,'Y','C','Yx','Cx','ho');
h.M = ho.M;
h.sam.Mr = ho.sam.Mr;
h.sam.i = ho.sam.i;
end
|
github
|
uoguelph-mlrg/vlr-master
|
postpro.m
|
.m
|
vlr-master/vlr/postpro.m
| 418 |
utf_8
|
d6b9925cda1df5ec30733c99cbf56010
|
% POSTPRO
% This function computes the post-processing for a single image C:
% 1. thresholding
% 2. minimum lesion size (converted here from voxels to pixel count); 26 connect
function [C] = postpro(h,C,x,thr)
% defaults:
if nargin < 3, x = [1,1,1]; end % assumed voxel size = [1,1,1]
if nargin < 4, thr = h.pp.thr.def; end % non-optimized threshold
C = C > thr;
C = bwareaopen(C,ceil(h.pp.minmm3*prod(x)),26);
|
github
|
uoguelph-mlrg/vlr-master
|
vlrmap.m
|
.m
|
vlr-master/vlr/vlrmap.m
| 2,674 |
utf_8
|
91ca7fb933695293f8b4ed78452712b6
|
% VLRMAP
% This function estimates a [V,2] matrix of beta parameters (B) for V parallel
% logistic regression models.
% The training data are specified in Y (size: [V,N,K]) and C (size: [V,N,1])
% V is the number of voxels
% N is the number of training examples
% K is the number of features (must be K=1 here for efficient implementation)
% Uses gpuArray -- if you don't have GPU set up, just remove all calls of
% gpuArray, gather, and gpuDevice. You can set Nb = 1 and Nd = V.
function [B,dB] = vlrmap(h,Y,C)
[V,N,K] = size(Y);
dBout = (nargout == 2);
% expand the parameters to match size if not done already
B = h.lr.B; % size(B) needs to be [V, 1, 2] for multiply compatibility
if size(B,1) == 1
B = padarray(shiftdim(B,-1),[V-1,0,0],'post','replicate');
end
if dBout
dB = zeros([size(squeeze(B)),h.lr.Nit]);
end
% prepend a row of ones for multipl compatibility
Y = padarray(Y,[0,0,1],1,'pre');
% transform the features by the labels for efficient implementation
C(C>=0.5) = +1;
C(C< 0.5) = -1;
for k = 1:K+1
YS(:,:,k) = Y(:,:,k).*C;
end
clearvars('C','Y');
% computing max batch size for GPU
GPU = gpuDevice(1);
Nf = 9; % empirical memory scale factor
Nb = ceil(4*(V*N*Nf)/GPU.FreeMemory); % 4-bytes x [size] x Nf vars
Nd = ceil(V/Nb);
% for each batch (if cannot fit all data on GPU)
for b = 1:Nb
% select the batch indices for GPU
bi = ((b-1)*Nd)+1 : min(b*Nd,V);
% transfer to GPU
Yb = gpuArray(single(YS(bi,:,:))); % features
Bb = gpuArray(single( B(bi,:,:))); % beta
% run the optimization
statusupdate(b,Nb);
for t = 1:h.lr.Nit
if dBout
[Bb,dBbt] = update(Yb,Bb,h.lr.alpha,h.lr.reg.la);
dB(bi,:,t) = squeeze(gather(dBbt));
else
Bb = update(Yb,Bb,h.lr.alpha,h.lr.reg.la);
end
% statusbar
statusbar(h.lr.Nit,t,h.Ni/3,1);
end
% gather from GPU
B(bi,:,:) = gather(Bb);
reset(GPU);
end
B = squeeze(B); % [V,1,2] -> [V,2]
function [Bout,dB] = update(Y,B0,alpha,la)
% compute the activation
B = padarray(B0,[0,size(Y,2)-1,0],'replicate','post');
S = B.*Y; S = S(:,:,1) + S(:,:,2); % could be sum(B.*Y,3) but CUDA error win10
S = 1./(1+exp(S));
clear('B');
% compute the Hessian elements
A = S.*(1-S);
H11 = sum(A.*Y(:,:,1).*Y(:,:,1), 2);% + la;
H22 = sum(A.*Y(:,:,2).*Y(:,:,2), 2) + la;
H12 = sum(A.*Y(:,:,1).*Y(:,:,2), 2);
Hd = H11.*H22 - H12.*H12; % determinate for inversion
clear('A');
% compute the gradient elements
G1 = sum(Y(:,:,1).*S,2);% - la.*B0(:,:,1);
G2 = sum(Y(:,:,2).*S,2) - la.*B0(:,:,2);
clear('S');
% compute the update
dB = reshape([(H22.*G1 - H12.*G2)./Hd, (H11.*G2 - H12.*G1)./Hd],size(B0));
% apply the update
Bout = B0 + alpha*dB;
|
github
|
uoguelph-mlrg/vlr-master
|
performancei.m
|
.m
|
vlr-master/vlr/performancei.m
| 1,664 |
utf_8
|
25e09ad92ee8d56309df6d3f984a9ad0
|
% PERFORMANCEI
% This function computes the performance analysis for a number of images,
% selected by ivec (indices in 1:h.Ni).
% This function expects the file tpmname('c',c,'.mat') to exist, and contain the
% variables h, B, thr, where B is in MNI space.
% B is warped to patient space using mni2ptx, inference is computed, post-
% processing is applied, then performance is analyzed.
% TP, FP, and FN images are warped from pt space to MNI space for later use.
% Outputs are saved in the variable p to tmpname('i',i,'.mat').
function [] = performancei(c,ivec)
load(tmpname('c',c,'.mat'),'h','B','thr');
for i = ivec
% load all images into pt space
[I,x] = readnicenii(imglutname('FLAIRm',h.Ni,i));
[G] = readnicenii(imglutname('mans', h.Ni,i));
% warp the B images to pt space
[Bi{1},Bi{2},Mi] = mni2ptx(h.Ni,i,B{:},h.M);
% compute the prediction
G = G > 0.5;
Y = standardize(I,Mi,h.std.type,h.std.args{:});
eta = Bi{1} + Bi{2}.*Y;
C0 = Mi./(1+exp(-eta));
% save the prediction before post-processing
if h.pp.saveles
writenii(imrotate(C0,180),imglutname(h.pp.saveles,h.Ni,i,0),...
imglutname('mans', h.Ni,i,1),'double');
end
% post-processing
C = postpro(h,C0,x,thr);
% analyze performance
[p.si,p.pr,p.re,p.ll,p.lle,TPi,FPi,FNi] = performance(C,G,x/10);
% warp the TP FP FN
[p.FP,p.TP,p.FN] = ptx2mni(h.Ni,i,FPi,TPi,FNi);
% write to file if not captured output
save(tmpname('i',i,'.mat'),'p');
end
function [p] = pdef()
p.si = nan;
p.pr = nan;
p.re = nan;
p.ll = nan;
p.lle = nan;
p.FP = nan([145,121,121]);
p.TP = nan([145,121,121]);
p.FN = nan([145,121,121]);
|
github
|
uoguelph-mlrg/vlr-master
|
summarizeresults.m
|
.m
|
vlr-master/vlr/summarizeresults.m
| 4,432 |
utf_8
|
501834c662830166d93fe722b75d5345
|
% SUMMARIZERESULTS
% This function creates various figures, and a table which summarize
% the performance of a segmentation model.
% These can be compiled in a PDF report using the 'pdf' option,
% so long as the necessary template is available (specific to the CV type)
function [] = summarizeresults(h, o, t, todo)
doall = {'scatter','box','table','tpfpfn','betas','egy','baplot','pdf'};
if nargin == 3 || isempty(todo) % default: run all
todo = doall;
end
if any(strcmp('scatter',todo)), scannerscatter(h,o); end
if any(strcmp('box',todo)), llboxplot(h,o); end
if any(strcmp('table',todo)), textableres(h,o); end
if any(strcmp('baplot',todo)), blandaltmanplot(h,o); end
if any(strcmp('tpfpfn',todo)), tpfpfn(h,t); end
if any(strcmp('betas',todo)), betas(h,o,3); end
if any(strcmp('egy',todo)), egy(h,62); end % 0 | 62
if any(strcmp('pdf',todo)), makepdf(h); end
for i = 1:numel(todo)
if ~any(strcmp(todo{i},doall))
warning('Unrecognized todo: %s',todo{i});
end
end
function [] = makepdf(h)
tname = strrep(fullfile(['C:\Users\Jesse\Documents\Research\working-docs\',...
'results\templates\template-$.tex']),'$',h.name.cv);
fid = fopen([h.save.pdf,'.tex'],'w');
fprintf(fid,strrep(strrep(strrep(fileread(tname),'TITLE',h.name.key),'%','%%'),'\','\\'));
fclose(fid);
compiletex(h.save.pdf);
eval(['!foxitreader "',h.save.pdf,'.pdf" &']);
function [] = scannerscatter(h,o)
text(nan,nan,'','interpreter','latex');
titles = {'Similarity Index (SI)','Precision (Pr)','Recall (Re)'};
names = {'si','pr','re'};
y = {o.si, o.pr, o.re};
N = max(h.scan.i);
ymm = [0,1];
for i = 1:3
plot(zeros(1,N),nan(N),'-'); hold on;
polyfitplot(o.ll,y{i},3,linspace(0,max(o.ll),256),0.1);
for s = 1:N
plot(o.ll(:,h.scan.i==s),y{i}(:,h.scan.i==s),'o','color',h.scan.clr(s,:));
end
xlabel('Lesion Load (ml)','interpreter','latex');
ylabel(titles{i},'interpreter','latex');
ylim(ymm);
figresize(gcf,[800,550]);
printfig(h,resultsname('scat',names{i}));
end
function [] = llboxplot(h,o)
text(nan,nan,'','interpreter','latex');
titles = {'Similarity Index (SI)','Precision (P)','Recall (R)'};
names = {'si','pr','re'};
y = {o.si, o.pr, o.re};
ll3 = 4-sum(bsxfun(@lt,o.ll,[0,4,22,inf]'));
labels = {'<4','4-22','>22'};
ymm = [0,1];
for i = 1:3
boxplot(y{i},ll3,'labels',labels,'colors','k','symbol','k+');
xlabel('LL (ml)','interpreter','latex');
ylabel(titles{i},'interpreter','latex');
ylim(ymm);
figresize(gcf,[800,550]);
tightsubs(1,1,gca,[0.20,0.15,0.05,0.05]);
printfig(h,resultsname('box',names{i}));
end
function [] = betas(h,o,c)
c = min(c,numel(o.B));
if isempty(o.B{c})
warning('B is empty. Skipping...');
return;
end
M = brainfun;
I{1} = -o.B{c}{1}./o.B{c}{2}.*M;
I{2} = o.B{c}{2}.*M;
names = { 'T', 'S'};
cmaps = { h.cmap, h.cmap};
mm = { [0.2,1], [0,60]};
mmx = {[0.2:0.2:1], [0:20:60]};
for i = 1:2
sliceshow(I{i},zfun,mm{i},cmaps{i}); drawnow;
printfig(h,resultsname('img',names{i}));
vcolorbar(mmx{i},cmaps{i});
printfig(h,resultsname('cmap',names{i}));
end
function [] = egy(h,n)
M = brainfun;
J = readnicenii(imgname('mni:FLAIRm',n,1));
I = standardize(J,M,h.std.type,h.std.args{:});
cmap = gray;
mm = [0.2,1]; mmx = [0.2:0.2:1];
sliceshow(I,zfun,mm,cmap); drawnow;
printfig(h,resultsname('img','Y'));
vcolorbar(mmx,cmap);
printfig(h,resultsname('cmap','Y'));
function [] = tpfpfn(h,t)
N = numel(t.TP);
Z = zeros(size(t.TP{1}));
T{1} = Z; T{2} = Z; T{3} = Z;
for i = 1:N
T{1} = T{1} + single(t.FP{i})/N; % false positive (red)
T{2} = T{2} + single(t.TP{i})/N; % true positive (green)
T{3} = T{3} + single(t.FN{i})/N; % false negative (blue)
end
names = {'FP','TP','FN'};
mm = [0,0.2];
mmx = 0.00 : 0.05 : 0.2;
for t = 1:3
figure;
sliceshow(T{t},zfun,mm,h.cmap); drawnow;
printfig(h,resultsname('img',names{t}));
end
vcolorbar(mmx,h.cmap);
printfig(h,resultsname('cmap','tri'));
function [] = blandaltmanplot(h,o)
blandaltman(o.ll,o.lle,1,{'LL (mL)','Manual','Auto.'});
printfig(h,resultsname('ba',2));
printfig(h,resultsname('ba',1));
function [] = printfig(h,name)
[~,~,ext] = fileparts(name);
switch ext
case '.png'
flag = '-dpng';
case '.eps'
flag = '-depsc';
otherwise
error('Unrecognized figure format: %s',ext);
end
print(gcf,fullfile(h.save.figdir,name),flag);
close(gcf);
|
github
|
uoguelph-mlrg/vlr-master
|
uber.m
|
.m
|
vlr-master/vlr/uber.m
| 1,822 |
utf_8
|
812d50f4223eb9ed3338967b1b050ce6
|
% UBER
% This function literally runs all scripts necessary to generate the thesis.
% It would probably take days to run and will almost certainly crash somewhere.
% Please explore for the desired set of results to re-create.
% [ ] not re-run
% [x] checked and re-run
function [] = uber()
def; % adjust some figure defaults
% ---------------------------------------------------------
% cross validation batches for parameter comparison
exp_hyp(defhypset('ovb')) % [x]
exp_hyp(defhypset('cv')) % [ ]
exp_hyp(defhypset('ystd')) % [x]
exp_hyp(defhypset('lam')) % [x]
exp_hyp(defhypset('psu')) % [x]
exp_hyp(defhypset('beta')) % [x]
% other computation
exp_ystd(); % [ ]
exp_toyreg(); % [x]
% ---------------------------------------------------------
% summarizing the results
fig_hypcompare({'ovb'}) % [x]
fig_hypcompare({'cv'}) % [x]
fig_hypcompare({'ystd'}) % [x]
fig_hypcompare({'lam'}) % [x]
fig_hypcompare({'beta'}) % [x]
fig_final(); % [x]
fig_ystd(); % [x]
% ---------------------------------------------------------
% stand-alone figures (mostly don't need the above to run)
plot_B_reparam(); % [x]
plot_basic_lr(); % [x]
plot_converge(); % [x]
plot_mle_challenges(); % [x]
plot_mri_decay_3d(); % [x]
plot_mri_spin_echo(); % [x]
plot_synthetic_histmatch(); % [x]
plot_y_sep_objectives(); % [x]
show_beta_r(); % [x]
show_bias(); % [x]
show_brain_mask(); % [x]
show_m08_revise_manuals(); % [x]
show_plot_simflair(); % [x]
show_registration(); % [x]
show_tikzfigs(); % [x]
show_tpfpfn_raw_thropt(); % [x]
show_tpms(); % [x]
show_wmhdist(); % [x]
kfcvidx(hypdef_final,true); % [x]
|
github
|
uoguelph-mlrg/vlr-master
|
gausssep.m
|
.m
|
vlr-master/vlr/ops/gausssep.m
| 855 |
utf_8
|
1717f9ffcef50feed23b76944f34d396
|
% [G] = gausssep(sig)
%
% GAUSSSEP generates N 1D Gaussian probability density functions having the
% standard deviations specified in the vector sig. Each element in sig
% corresponds to a dimension. Can be used for separate 1D convolutions.
%
% Inputs:
% sig - N-vector corresponding to the standard deviations requested for each
% of N dimensions.
%
% wid - (optional) width of the kernel (in both directions) in units of
% standard deviations. Default: 3
%
% Outputs:
% G - N 1-D Gaussian kernels (cell).
%
% Jesse Knight 2016
function [G] = gausssep(sig,wid)
if nargin == 1
wid = 3; % how many std to include?
end
N = numel(sig); % num dims
for n = 1:N
R = floor(-wid*sig(n)):ceil(+wid*sig(n)); % sampling points in each dim
G{n} = shiftdim(normpdf(R,0,sig(n)),2-n);
G{n} = G{n}./sum(G{n}(:));
end
|
github
|
uoguelph-mlrg/vlr-master
|
gauss.m
|
.m
|
vlr-master/vlr/ops/gauss.m
| 1,197 |
utf_8
|
8aff4cbc002952e74befd8a0c6c12d5f
|
% [G] = gauss(sig)
%
% GAUSS generates an N-D Gaussian probability density function having the
% standard deviations specified in the vector sig. Each element in sig
% corresponds to a dimension. Guaranteed to have unit norm.
%
% Inputs:
% sig - N-vector corresponding to the standard deviations requested for each
% of N dimensions.
%
% wid - (optional) width of the kernel (in both directions) in units of
% standard deviations. Default: 3
%
% Outputs:
% G - N-D Gaussian kernel.
%
% Jesse Knight 2016
function [G] = gauss(sig,wid)
if nargin == 1
wid = 3; % how many std to include?
end
N = numel(sig); % num dims
X = cell(1,N); % N-D grid coordinates
W = cell(1,N); % store size of the kernel later
for n = 1:N
R{n} = floor(-wid*sig(n)):ceil(+wid*sig(n)); % sampling points in each dim
end
[X{:}] = ndgrid(R{:},1); % transform to grid N-D arrays
W(:) = cellfun(@numel,R,'uni',false); % track exact size
for n = 1:N
X{n} = X{n}(:); % vectorize the grids for mvnpdf below
end
G = mvnpdf(cat(2,X{:}),zeros(1,N),sig); % compute vectorized kernel values
G = reshape(G,cat(2,W{:},1)); % reshape to N-D array
G = G./sum(G(:)); % assert unit norm
|
github
|
uoguelph-mlrg/vlr-master
|
ICC.m
|
.m
|
vlr-master/vlr/ops/ICC.m
| 6,497 |
utf_8
|
8eeda47d684e52b93442490c92158ed0
|
function [r, LB, UB, F, df1, df2, p] = ICC(M, type, alpha, r0)
% Intraclass correlation
% [r, LB, UB, F, df1, df2, p] = ICC(M, type, alpha, r0)
%
% M is matrix of observations. Each row is an object of measurement and
% each column is a judge or measurement.
%
% 'type' is a string that can be one of the six possible codes for the desired
% type of ICC:
% '1-1': The degree of absolute agreement among measurements made on
% randomly seleted objects. It estimates the correlation of any two
% measurements.
% '1-k': The degree of absolute agreement of measurements that are
% averages of k independent measurements on randomly selected
% objects.
% 'C-1': case 2: The degree of consistency among measurements. Also known
% as norm-referenced reliability and as Winer's adjustment for
% anchor points. case 3: The degree of consistency among measurements maded under
% the fixed levels of the column factor. This ICC estimates the
% corrlation of any two measurements, but when interaction is
% present, it underestimates reliability.
% 'C-k': case 2: The degree of consistency for measurements that are
% averages of k independent measurements on randomly selected
% onbjectgs. Known as Cronbach's alpha in psychometrics. case 3:
% The degree of consistency for averages of k independent
% measures made under the fixed levels of column factor.
% 'A-1': case 2: The degree of absolute agreement among measurements. Also
% known as criterion-referenced reliability. case 3: The absolute
% agreement of measurements made under the fixed levels of the column factor.
% 'A-k': case 2: The degree of absolute agreement for measurements that are
% averages of k independent measurements on randomly selected objects.
% case 3: he degree of absolute agreement for measurements that are
% based on k independent measurements maded under the fixed levels
% of the column factor.
%
% ICC is the estimated intraclass correlation. LB and UB are upper
% and lower bounds of the ICC with alpha level of significance.
%
% In addition to estimation of ICC, a hypothesis test is performed
% with the null hypothesis that ICC = r0. The F value, degrees of
% freedom and the corresponding p-value of the this test are
% reported.
%
% (c) Arash Salarian, 2008
%
% Reference: McGraw, K. O., Wong, S. P., "Forming Inferences About
% Some Intraclass Correlation Coefficients", Psychological Methods,
% Vol. 1, No. 1, pp. 30-46, 1996
%
if nargin < 3
alpha = .05;
end
if nargin < 4
r0 = 0;
end
[n, k] = size(M);
SStotal = var(M(:)) *(n*k - 1);
MSR = var(mean(M, 2)) * k;
MSW = sum(var(M,0, 2)) / n;
MSC = var(mean(M, 1)) * n;
MSE = (SStotal - MSR *(n - 1) - MSC * (k -1))/ ((n - 1) * (k - 1));
switch type
case '1-1'
[r, LB, UB, F, df1, df2, p] = ICC_case_1_1(MSR, MSE, MSC, MSW, alpha, r0, n, k);
case '1-k'
[r, LB, UB, F, df1, df2, p] = ICC_case_1_k(MSR, MSE, MSC, MSW, alpha, r0, n, k);
case 'C-1'
[r, LB, UB, F, df1, df2, p] = ICC_case_C_1(MSR, MSE, MSC, MSW, alpha, r0, n, k);
case 'C-k'
[r, LB, UB, F, df1, df2, p] = ICC_case_C_k(MSR, MSE, MSC, MSW, alpha, r0, n, k);
case 'A-1'
[r, LB, UB, F, df1, df2, p] = ICC_case_A_1(MSR, MSE, MSC, MSW, alpha, r0, n, k);
case 'A-k'
[r, LB, UB, F, df1, df2, p] = ICC_case_A_k(MSR, MSE, MSC, MSW, alpha, r0, n, k);
end
%----------------------------------------
function [r, LB, UB, F, df1, df2, p] = ICC_case_1_1(MSR, MSE, MSC, MSW, alpha, r0, n, k)
r = (MSR - MSW) / (MSR + (k-1)*MSW);
F = (MSR/MSW) * (1-r0)/(1+(k-1)*r0);
df1 = n-1;
df2 = n*(k-1);
p = 1-fcdf(F, df1, df2);
FL = (MSR/MSW) / finv(1-alpha/2, n-1, n*(k-1));
FU = (MSR/MSW) * finv(1-alpha/2, n*(k-1), n-1);
LB = (FL - 1) / (FL + (k-1));
UB = (FU - 1) / (FU + (k-1));
%----------------------------------------
function [r, LB, UB, F, df1, df2, p] = ICC_case_1_k(MSR, MSE, MSC, MSW, alpha, r0, n, k)
r = (MSR - MSW) / MSR;
F = (MSR/MSW) * (1-r0);
df1 = n-1;
df2 = n*(k-1);
p = 1-fcdf(F, df1, df2);
FL = (MSR/MSW) / finv(1-alpha/2, n-1, n*(k-1));
FU = (MSR/MSW) * finv(1-alpha/2, n*(k-1), n-1);
LB = 1 - 1 / FL;
UB = 1 - 1 / FU;
%----------------------------------------
function [r, LB, UB, F, df1, df2, p] = ICC_case_C_1(MSR, MSE, MSC, MSW, alpha, r0, n, k)
r = (MSR - MSE) / (MSR + (k-1)*MSE);
F = (MSR/MSE) * (1-r0)/(1+(k-1)*r0);
df1 = n - 1;
df2 = (n-1)*(k-1);
p = 1-fcdf(F, df1, df2);
FL = (MSR/MSE) / finv(1-alpha/2, n-1, (n-1)*(k-1));
FU = (MSR/MSE) * finv(1-alpha/2, (n-1)*(k-1), n-1);
LB = (FL - 1) / (FL + (k-1));
UB = (FU - 1) / (FU + (k-1));
%----------------------------------------
function [r, LB, UB, F, df1, df2, p] = ICC_case_C_k(MSR, MSE, MSC, MSW, alpha, r0, n, k)
r = (MSR - MSE) / MSR;
F = (MSR/MSE) * (1-r0);
df1 = n - 1;
df2 = (n-1)*(k-1);
p = 1-fcdf(F, df1, df2);
FL = (MSR/MSE) / finv(1-alpha/2, n-1, (n-1)*(k-1));
FU = (MSR/MSE) * finv(1-alpha/2, (n-1)*(k-1), n-1);
LB = 1 - 1 / FL;
UB = 1 - 1 / FU;
%----------------------------------------
function [r, LB, UB, F, df1, df2, p] = ICC_case_A_1(MSR, MSE, MSC, MSW, alpha, r0, n, k)
r = (MSR - MSE) / (MSR + (k-1)*MSE + k*(MSC-MSE)/n);
a = (k*r0) / (n*(1-r0));
b = 1 + (k*r0*(n-1))/(n*(1-r0));
F = MSR / (a*MSC + b*MSE);
%df2 = (a*MSC + b*MSE)^2/((a*MSC)^2/(k-1) + (b*MSE)^2/((n-1)*(k-1)));
a = k*r/(n*(1-r));
b = 1+k*r*(n-1)/(n*(1-r));
v = (a*MSC + b*MSE)^2/((a*MSC)^2/(k-1) + (b*MSE)^2/((n-1)*(k-1)));
df1 = n - 1;
df2 = v;
p = 1-fcdf(F, df1, df2);
Fs = finv(1-alpha/2, n-1, v);
LB = n*(MSR - Fs*MSE)/(Fs*(k*MSC + (k*n - k - n)*MSE) + n*MSR);
Fs = finv(1-alpha/2, v, n-1);
UB = n*(Fs*MSR-MSE)/(k*MSC + (k*n - k - n)*MSE + n*Fs*MSR);
%----------------------------------------
function [r, LB, UB, F, df1, df2, p] = ICC_case_A_k(MSR, MSE, MSC, MSW, alpha, r0, n, k)
r = (MSR - MSE) / (MSR + (MSC-MSE)/n);
c = r0/(n*(1-r0));
d = 1 + (r0*(n-1))/(n*(1-r0));
F = MSR / (c*MSC + d*MSE);
%df2 = (c*MSC + d*MSE)^2/((c*MSC)^2/(k-1) + (d*MSE)^2/((n-1)*(k-1)));
a = k*r/(n*(1-r));
b = 1+k*r*(n-1)/(n*(1-r));
v = (a*MSC + b*MSE)^2/((a*MSC)^2/(k-1) + (b*MSE)^2/((n-1)*(k-1)));
df1 = n - 1;
df2 = v;
p = 1-fcdf(F, df1, df2);
Fs = finv(1-alpha/2, n-1, v);
LB = n*(MSR - Fs*MSE)/(Fs*(MSC-MSE) + n*MSR);
Fs = finv(1-alpha/2, v, n-1);
UB = n*(Fs*MSR - MSE)/(MSC - MSE + n*Fs*MSR);
|
github
|
uoguelph-mlrg/vlr-master
|
ksd.m
|
.m
|
vlr-master/vlr/ops/ksd.m
| 5,483 |
utf_8
|
22cbdf897669a121d77594881d415175
|
% This function is equivalent to ksdensity, except that repetitive overhead is
% removed (which otherwise accounts for ~0.5 the runtime).
% Some hard-coded parameters: [0,1] input data range and support
function [px] = ksd(X,xi,kfcn,wid)
% minimal function calls...
N = numel(X(:));
kcut = 3;
px = compute_pdf_cdf(xi, 1, 100, -Inf, +Inf, ones(1,N)./N, ...
kfcn, kcut, 0, wid, X(:), Inf);
% p = compute_pdf_cdf([0,1], 1, 100, -Inf, Inf, ones(1,N)./N, ...
% kfcn, kcut, 0, wid, X(:), Inf);
% everything else is stolen from "statkscompute"
% -----------------------------
function [fout,xout,u]=compute_pdf_cdf(xi,xispecified,m,L,U,weight,...
kernel,cutoff,iscdf,u,ty,foldpoint)
foldwidth = min(cutoff,3);
issubdist = isfinite(foldpoint);
if ~xispecified
xi = compute_default_xi(ty,foldwidth,issubdist,m,u,U,L);
elseif ~isvector(xi)
error('stats:ksdensity:VectorRequired','XI must be a vector');
end
% Compute transformed values of evaluation points that are in bounds
xisize = size(xi);
fout = zeros(xisize);
if iscdf && isfinite(U)
fout(xi>=U) = sum(weight);
end
xout = xi;
xi = xi(:);
if L==-Inf && U==Inf % unbounded support
inbounds = true(size(xi));
txi = xi;
elseif L==0 && U==Inf % positive support
inbounds = (xi>0);
xi = xi(inbounds);
txi = log(xi);
foldpoint = log(foldpoint);
else % finite support [L, U]
inbounds = (xi>L) & (xi<U);
xi = xi(inbounds);
txi = log(xi-L) - log(U-xi);
foldpoint = log(foldpoint-L) - log(U-foldpoint);
end
% If the density is censored at the end, add new points so that we can fold
% them back across the censoring point as a crude adjustment for bias.
if issubdist
needfold = (txi >= foldpoint - foldwidth*u);
txifold = (2*foldpoint) - txi(needfold);
nfold = sum(needfold);
else
nfold = 0;
end
% Compute kernel estimate at the requested points
f = dokernel(iscdf,txi,ty,u,weight,kernel,cutoff);
% If we need extra points for folding, do that now
if nfold>0
% Compute the kernel estimate at these extra points
ffold = dokernel(iscdf,txifold,ty,u,weight,kernel,cutoff);
if iscdf
% Need to use upper tail for cdf at folded points
ffold = sum(weight) - ffold;
end
% Fold back over the censoring point
f(needfold) = f(needfold) + ffold;
if iscdf
% For cdf, extend last value horizontally
maxf = max(f(txi<=foldpoint));
f(txi>foldpoint) = maxf;
else
% For density, define a crisp upper limit with vertical line
f(txi>foldpoint) = 0;
if ~xispecified
xi(end+1) = xi(end);
f(end+1) = 0;
inbounds(end+1) = true;
end
end
end
if iscdf
% Guard against roundoff. Lower boundary of 0 should be no problem.
f = min(1,f);
else
% Apply reverse transformation and create return value of proper size
f = f(:) ./ u;
if L==0 && U==Inf % positive support
f = f ./ xi;
elseif U<Inf % bounded support
f = f * (U-L) ./ ((xi-L) .* (U-xi));
end
end
fout(inbounds) = f;
xout(inbounds) = xi;
% -----------------------------
function xi = compute_default_xi(ty,foldwidth,issubdist,m,u,U,L)
% Get XI values at which to evaluate the density
% Compute untransformed values of lower and upper evaluation points
ximin = min(ty) - foldwidth*u;
if issubdist
ximax = max(ty);
else
ximax = max(ty) + foldwidth*u;
end
if L==0 && U==Inf % positive support
ximin = exp(ximin);
ximax = exp(ximax);
elseif U<Inf % bounded support
ximin = (U*exp(ximin)+L) / (exp(ximin)+1);
ximax = (U*exp(ximax)+L) / (exp(ximax)+1);
end
xi = linspace(ximin, ximax, m);
% -----------------------------
function f = dokernel(iscdf,txi,ty,u,weight,kernel,cutoff)
% Now compute density estimate at selected points
blocksize = 3e4;
m = length(txi);
n = length(ty);
if n*m<=blocksize && ~iscdf
% For small problems, compute kernel density estimate in one operation
z = (repmat(txi',n,1)-repmat(ty,1,m))/u;
f = weight * feval(kernel, z);
else
% For large problems, try more selective looping
% First sort y and carry along weights
[ty,idx] = sort(ty);
weight = weight(idx);
% Loop over evaluation points
f = zeros(1,m);
if isinf(cutoff)
for k=1:m
% Sum contributions from all
z = (txi(k)-ty)/u;
f(k) = weight * feval(kernel,z);
end
else
% Sort evaluation points and remember their indices
[stxi,idx] = sort(txi);
jstart = 1; % lowest nearby point
jend = 1; % highest nearby point
halfwidth = cutoff*u;
for k=1:m
% Find nearby data points for current evaluation point
lo = stxi(k) - halfwidth;
while(ty(jstart)<lo && jstart<n)
jstart = jstart+1;
end
hi = stxi(k) + halfwidth;
jend = max(jend,jstart);
while(ty(jend)<=hi && jend<n)
jend = jend+1;
end
nearby = jstart:jend;
% Sum contributions from these points
z = (stxi(k)-ty(nearby))/u;
fk = weight(nearby) * feval(kernel,z);
if iscdf
fk = fk + sum(weight(1:jstart-1));
end
f(k) = fk;
end
% Restore original x order
f(idx) = f;
end
end
|
github
|
uoguelph-mlrg/vlr-master
|
biny.m
|
.m
|
vlr-master/vlr/ops/biny.m
| 2,682 |
utf_8
|
e82b021467cd0a70f67cb2b0a2106653
|
% [YB,U] = biny(Y,varargin)
%
% BINY re-bins data to evenly spaced bins using user specified min-max
% specifications for both input and output data ranges, and the number of
% bins. Input data outside the input range is saturated (set to min or
% max value, before continuing).
%
% Args:
% Y - ND array of real-valued data
% N - number of bins - integer value; can appear before or after mi/mo
% mi - minmax (input) - [low,high] appears first; [] to use default
% mo - minmax (output) - [low,high] appears second; [] to use default
%
% This function was designed for look-up table transforms of ND-arrays:
% Y - ND-array of real valued data
% T - vector lookup table transform with N values
%
% e.g. to use default [min(Y(:)),max(Y(:))] as input range:
% Ybin = biny(Y,[],[1,N],N);
% e.g. saturating anything below 0.1 and above 1.5 in input range:
% Ybin = biny(Y,[0.1,1.5],[1,N],N);
% then, to perform the look-up (because Ybin has values 1,...,N):
% YT = T(Ybin);
%
% Jesse Knight 2016
function [YB,U] = biny(Y,varargin)
dtype = class(Y); % store original data type
Y = double(Y); % faster than single, and need non-int precision
minmax = [min(Y(:)),max(Y(:))]; % default if no user specification
% parse args - check if user has specified the {mi, mo, N} arguments
[mi,mo,N] = parseargs(minmax,varargin);
% bin data, re-cast
[YB] = cast(binit(Y,mi,mo,N),dtype);
% bin dummy data to give vector of levels
[U] = binit(linspace(mi(1),mi(2),N),mi,mo,N);
function [YB] = binit(Y,mi,mo,N)
% saturate with input minmax
YS = min(mi(2),max(mi(1),Y));
% bin to 0:1
YL = round(((YS - mi(1)) ./ diff(mi)) .* (N-1)) ./ (N-1);
% scale to output minmax
YB = (YL .* diff(mo)) + mo(1);
function [minmaxi,minmaxo,N] = parseargs(minmax,vargs)
% defaults
N = 256;
minmaxi = minmax;
minmaxo = [0,1];
% parsing user specs
nminmax = 0;
for v = 1:numel(vargs)
if (numel(size(vargs{v})) == 2) % arg must be "2D" (including [1,1])
if (all(size(vargs{v}) == [1,1])) % number of levels
N = vargs{v};
elseif (all(size(vargs{v}) == [1,2])) % minmax
if nminmax == 0 % input specified (appears first)
minmaxi = vargs{v};
nminmax = 1;
elseif nminmax == 1 % output too (appears second)
minmaxo = vargs{v};
nminmax = -1;
end
elseif isempty(vargs{v}) && isnumeric(vargs{v})
if nminmax == 0 % input specified (default)
minmaxi = minmax;
nminmax = 1;
elseif nminmax == 1 % output too (default)
minmaxo = minmax;
nminmax = -1;
end
end
else
warning('Binning specifications must be 1 or 2 element vectors.');
end
end
|
github
|
uoguelph-mlrg/vlr-master
|
nyulstd.m
|
.m
|
vlr-master/vlr/ops/nyulstd.m
| 485 |
utf_8
|
de3af2d9825e38d6f8071262867569d6
|
% NYULSTD
% Graylevel standardization proposed by Nyul et al (1999).
% Graylevels in y are piecewise linearly matched so that
% evenly spaced input quantiles match the output quantiles specified in 'qo'.
% The number of quantiles is taken from numel(qo).
function [yt] = nyulstd(y,qo)
N = numel(qo);
qi = quantile(y(:),linspace(0,1,N));
yt = zeros(size(y),class(y));
for i = 1:N-1
x = (y>=qi(i)) & (y<=qi(i+1));
yt(x) = qo(i) + (y(x)-qi(i)).*(qo(i+1)-qo(i))./(qi(i+1)-qi(i));
end
|
github
|
uoguelph-mlrg/vlr-master
|
binsphere.m
|
.m
|
vlr-master/vlr/ops/binsphere.m
| 193 |
utf_8
|
ecf9f2a1a63288adda757af89f91062c
|
% BINSPHERE
% make a binary sphere-ish 3D image of radius R (in pixels)
function [V] = binsphere(R)
[x,y,z] = ndgrid(-R:R);
SE = strel(sqrt(x.^2 + y.^2 + z.^2) <=R);
V = double(SE.getnhood());
|
github
|
uoguelph-mlrg/vlr-master
|
kernelshifts.m
|
.m
|
vlr-master/vlr/ops/kernelshifts.m
| 412 |
utf_8
|
684453bc04e03db9a74336ad51cf2910
|
% KERNELSHIFTS
% Returns the shift amounts (relative to center element)
% of all other nonzero kernel elements (i.e. binary to [x1,x2,x3] coordinates)
function [dx] = kernelshifts(K)
cx = round([size(K,1),size(K,2),size(K,3)]/2);
ksize = size(K);
x = cell([numel(ksize),1]);
dx = zeros([0,numel(ksize)]);
for i = 1:numel(K)
if K(i)
[x{:}] = ind2sub(ksize,i);
dx(end+1,:) = cx - cat(2,x{:});
end
end
|
github
|
uoguelph-mlrg/vlr-master
|
op23.m
|
.m
|
vlr-master/vlr/ops/op23.m
| 1,308 |
utf_8
|
cb939bcc0c2644e0edd425bfd07effea
|
% [IF] = op23(I,filtfun,W)
%
% OP23 filters a 3D image I using the 2D image filtering function filtfun in a
% single operation (using reshaping). This speeds up the application of
% nonlinear filters on 3D volumes by not processing slices in serial.
%
% Inputs:
% I - 3D image volume for filtering.
%
% filtfun - filter function which only accepts 2D inputs.
%
% wid - (optional) padding width to avoid mixing data from adjacent
% slices; only important if I contains information near the edges.
% Padding style: replicate. Default wid: 0 (no padding).
%
% Outputs:
% IF - filtered image.
%
% Examples:
%
% >> op23(randn(10,10,10),@(I)medfilt2(I,[5,5]),2);
% Show a random 10x10x10 volume of data with the default figure colourmap,
% automatic contrast scaling, with 0.5% of total figure size padded around.
%
% Jesse Knight 2016
function [IF] = op23(I,filtfun,wid)
if nargin == 2
wid = 0; % default: no padding
end
i3size = size(I);
ipsize = i3size + [0,2*wid,0];
i2size = [ipsize(1),ipsize(2)*ipsize(3)];
% pad along x, then reshape (append along x)
I2 = reshape(padarray(I,[0,wid,0],'replicate','both'),i2size);
% median filter (MEX), then reshape (unwrap x -> z)
IF = reshape(filtfun(I2),ipsize);
% unpad
IF = IF(:,wid+1:end-wid,:);
|
github
|
uoguelph-mlrg/vlr-master
|
pofwxy.m
|
.m
|
vlr-master/vlr/ops/wprobs/pofwxy.m
| 1,942 |
utf_8
|
0910a4197ff0a8ad2d9916de41df59dd
|
% [pXYW,U] = pofwxy(Y,X,W,op,varargin)
%
% POFWXY computes the weighted conditional probability of X given Y using
% the user specified weighted conditional probability operator.
% This implementation uses a relatively fast sort-lookup technique.
%
% Inputs:
% Y - N-D data which is binned, then for each bin, the matching indices
% are used to select data in X for computing the probability.
% X - N-D data (same size) on which the probability operation acts.
% W - N-D (same size) weights for each value in X
% op - weighted probability operator - e.g. @wmean or
% @(x,w)ksdensity(x,0.5,'weights',w);
%
% varargin: passed straight to biny to bin the values in Y (see help biny).
% N - number of bins
% mi - minmax (input)
% mo - minmax (output)
%
% Outputs:
% pXYW - weighted conditional probability of x given y, by w
% U - unique bin values (of Y)
%
% Jesse Knight 2016
function [pXYW,U] = pofwxy(Y,X,W,op,varargin)
% bin the data for easy lookup
[YU,U] = biny(Y,varargin{:});
% sort the data for faster lookup of paired data
[YS,s] = sort(YU(:)); % sorting source data
XS = X(s); % sorting paired data same order
WS = W(s); % sorting weights same order
% initialize the source data histogram (internal)
pY = nan(numel(U),1);
% calculating source histogram
for u = 1:numel(U)
idx = (YS(:)==U(u)); % lookup indices
pY(u) = sum(idx); % count these
end
% initialize paired data output
pXYW = zeros(numel(U),1);
% index ranges in sorted XS and WS: faster than lookup
idx = [0,cumsum(pY')];
% calculating paired data weighted histogram
for u = 1:numel(U)
if (idx(u+1) > idx(u)+1) % not empty indices
idxu = idx(u)+1:idx(u+1);
if any(WS(idxu)) % not empty weights
pXYW(u) = op( XS(idxu), WS(idxu) );
else % empty weights
pXYW(u) = nan;
end
else % empty indices
pXYW(u) = nan;
end
end
|
github
|
uoguelph-mlrg/vlr-master
|
wstd.m
|
.m
|
vlr-master/vlr/ops/wprobs/wstd.m
| 220 |
utf_8
|
03578ce41c95f7e4c9027ef77fcb7de7
|
% [mu] = wstd(Y,X)
%
% WSTD gives the standard deviation of Y, weighted by X
%
% Jesse Knight 2016
function [sig] = wstd(Y,X,wm)
if nargin == 2
wm = wmean(Y,X);
end
sig = sqrt(sum(((Y(:)-wm).^2).*X(:)) / sum(X(:)));
|
github
|
uoguelph-mlrg/vlr-master
|
wmean.m
|
.m
|
vlr-master/vlr/ops/wprobs/wmean.m
| 151 |
utf_8
|
f907f4b7682d3d2eb7c13bebfa12b557
|
% [mu] = wmean(Y,X)
%
% WMEAN gives the mean of Y, weighted by X
%
% Jesse Knight 2016
function [mu] = wmean(Y,X)
mu = sum(Y(:).*X(:)) / sum(X(:));
|
github
|
uoguelph-mlrg/vlr-master
|
pofwy.m
|
.m
|
vlr-master/vlr/ops/wprobs/pofwy.m
| 981 |
utf_8
|
cf9fab4b86f13881388aabe995319507
|
% [pYW,U] = pofwy(Y,W,varargin)
%
% POFWY is a weighted histogram (normalized for unit norm).
% This implementation uses a relatively fast data-removal technique.
%
% Inputs:
% Y - N-D data for which to compute the probability distribution.
% W - N-D (same size) weights for each value in Y.
%
% varargin: passed straight to biny to bin the values in Y (see help biny).
% N - number of bins
% mi - minmax (input)
% mo - minmax (output)
%
% Output arguments:
% pYW - normalized histogram of Y, weighted by W
% U - unique bin values
%
% Jesse Knight 2016
function [pYW,YU,U] = pofwy(Y,W,varargin)
% bin the data for easy lookup
[YU,U] = biny(Y,varargin{:});
YU = YU(:);
% initialize the output
pYW = nan(numel(U),1);
sw = sum(W(:));
% calculating weighted histogram
for u = 1:numel(U)
idx = (YU==U(u)); % lookup indices
pYW(u) = sum(W(idx)); % sum these weights
end
pYW = pYW./sw; % normalization by sum of weights
|
github
|
uoguelph-mlrg/vlr-master
|
pofxy.m
|
.m
|
vlr-master/vlr/ops/wprobs/pofxy.m
| 1,790 |
utf_8
|
f5b8573203f927209f8bdd4ac0c34b4a
|
% [pXY,pY,U] = pofxy(Y,X,op,varargin)
%
% POFXY computes the conditional probability of X given Y - p(X|Y),
% "p of given y", using the user specified conditional probability operator.
% This implementation uses a relatively fast sort-lookup technique.
%
% Inputs:
% Y - N-D data which is binned, then for each bin, the matching indices
% are used to select data in X for computing the probability.
% X - N-D data (same size) on which the probability operation acts.
% op - probability operator - e.g. @mean or @(x)ksdensity(x,0.5);
%
% varargin: passed straight to biny to bin the values in Y (see help biny).
% N - number of bins
% mi - minmax (input)
% mo - minmax (output)
%
% Outputs:
% pXY - conditional probability of x given y
% pY - normalized histogram of Y
% U - unique bin values (of Y)
%
% Jesse Knight 2016
function [pXY,pY,U] = pofxy(Y,X,op,varargin)
assert(strcmp(class(Y),class(X)),'Class of Y and X must match.');
% bin the data for easy lookup
[YU,U] = biny(Y,varargin{:});
% sort the data for faster lookup of paired data
[YS,s] = sort(YU(:)); % sorting source data
XS = X(s); % sorting paired data same order
% initialize the source data output
pY = nan(numel(U),1);
% calculating source histogram
for u = 1:numel(U)
idx = (YS(:)==U(u)); % lookup indices
pY(u) = sum(idx); % count these
end
% initialize paired data output
pXY = zeros(numel(U),1);
% index ranges in sorted XS: faster than lookup
idx = [0,cumsum(pY')];
% calculating paired data histogram
for u = 1:numel(U)
if idx(u+1) > idx(u)+1 % not empty
idxu = idx(u)+1 : idx(u+1);
pXY(u) = op(XS(idxu));
else % empty
pXY(u) = nan;
end
end
pY = pY'./numel(XS); % normalize the source histogram
|
github
|
uoguelph-mlrg/vlr-master
|
pofy.m
|
.m
|
vlr-master/vlr/ops/wprobs/pofy.m
| 974 |
utf_8
|
a40253c6b020f79cbfa044cbb2671e5a
|
% [pY,YU,U] = pofy(Y,varargin)
%
% POFY is an anaolgue to the hist function - p(Y), "p of y" - with different
% control over the parameters; also serves as a template for other
% conditional probability functions: pofxy, pofwy, pofxwy.
%
% Inputs:
% Y - N-D data for which to compute the probability distribution.
%
% varargin: passed straight to biny to bin the values in Y (see help biny).
% N - number of bins
% mi - minmax (input)
% mo - minmax (output)
%
% Outputs:
% pY - normalized histogram of Y
% YU - values of Y in the specified bins (vectorized)
% U - unique bin values
%
% Jesse Knight 2016
function [pY,YU,U] = pofy(Y,varargin)
% bin the data for easy lookup
[YU,U] = biny(Y,varargin{:});
YU = YU(:);
% initialize the output
pY = nan(numel(U),1);
% calculating histogram
for u = 1:numel(U)
idx = (YU==U(u)); % lookup indices
pY(u) = sum(idx); % count these
end
pY = pY./numel(Y); % normalize
|
github
|
uoguelph-mlrg/vlr-master
|
alphatrim.m
|
.m
|
vlr-master/vlr/ops/alpha/alphatrim.m
| 1,401 |
utf_8
|
8300b8cb6e2a64f533ba806289c76cbd
|
% [idx, ytrims] = alphatrim(Y, trims, mask)
%
% ALPHATRIM computes a mask for an N-D array indicating values which are
% within the specified alpha-"trims" (on the interval [0,1]).
% An additional mask can be specified by the user to further refine the
% alpha-trim data; however the output indices may contain values outside
% this mask. The cutoff values are also returned. This implementation
% uses a fast sorting-based method.
%
% Inputs:
% Y - ND array of real-valued data
% trims - 2-element vector on the interval [0,1] dictating what fractions
% of the data in Y to exclude
% mask - (optional) additional mask within which to seach to find the
% alpha-trims only.
%
% Outputs:
% idx - indicies of valid elements: within alpha trims
% ytrims - values corresponding to the alpha trim cutoffs
%
% Jesse Knight 2016
function [idx, ytrims] = alphatrim(Y, trims, mask)
% vectorize the data with/out the mask
if nargin == 3
YB = Y(logical(mask));
if isempty(YB)
idx = []; ytrims = []; return;
end
else
YB = Y(:);
end
NY = numel(YB); % count the elements
[YS] = sort(YB); % sort the values
ntrims = NY.*trims; % find alpha trims in sorted-index space
ytrims = [YS(round(max(1, ntrims(1)))),... % store the cutoff values
YS(round(min(NY,ntrims(2))))]; % ...
idx = (Y > ytrims(1)) & (Y < ytrims(2)); %
|
github
|
uoguelph-mlrg/vlr-master
|
alphaclip.m
|
.m
|
vlr-master/vlr/ops/alpha/alphaclip.m
| 372 |
utf_8
|
fc6099fab820eda592b7e0c9fd7cb389
|
% ALPHACLIP
% This function calls alphatrim, then clips the data in Y
% according to the computed limits.
% A mask can be used for the alpha computation, but then ignored for the clip.
function [Yclip] = alphaclip(Y, trims, mask)
if nargin == 3
[~, ytrims] = alphatrim(Y, trims, mask);
elseif nargin == 2
[~, ytrims] = alphatrim(Y, trims);
end
Yclip = clip(Y,ytrims);
|
github
|
uoguelph-mlrg/vlr-master
|
clip.m
|
.m
|
vlr-master/vlr/ops/alpha/clip.m
| 194 |
utf_8
|
114ba2c3f9af8c549c9f80d6eca381f1
|
% [X] = clip(X,mm);
%
% CLIP truncates the data in X to the range mm so that no values are outside
% this range.
%
% Jesse Knight 2016
function [X] = clip(X,mm)
X = max(mm(1),min(mm(2),X));
|
github
|
uoguelph-mlrg/vlr-master
|
momi.m
|
.m
|
vlr-master/vlr/ops/alpha/momi.m
| 211 |
utf_8
|
0293bb4e29d850d0ed39f0cd653512b7
|
% [X,mm] = momi(X);
%
% MOMI normalizes the data in X to the range [0,1] using the max-min
% of the data.
%
% Jesse Knight 2016
function [X,mm] = momi(X)
mm = [min(X(:)),max(X(:))];
X = (X-mm(1))./diff(mm);
|
github
|
Brain-Modulation-Lab/bml-master
|
bml_timealign.m
|
.m
|
bml-master/sync/bml_timealign.m
| 8,001 |
utf_8
|
1b05fa067b77138fcbfa7e7c64991951
|
function [slave_delta_t, max_corr, master, slave] = bml_timealign(cfg, master, slave)
% BML_TIMEALIGN aligns slave to master and returns the slave's delta t
%
% Use as
% slave_delta_t = bml_timealign(master, slave)
% slave_delta_t = bml_timealign(cfg, master, slave)
% [slave_delta_t, max_corr] = bml_timealign(cfg, master, slave)
% [slave_delta_t, max_corr, master, slave] = bml_timealign(cfg, master, slave)
%
%
% cfg is a configuration structure with fields:
% cfg.resample_freq - double: frequency to resample and aligned master and
% slave (Hz). Defaults to 10000.
% cfg.method - string: method use for preprocessing master and slave
% 'env' or 'envelope' (default) - see BML_ENVELOPE_BINABS
% 'lpf' or 'low-pass-filter' - see ft_preproc_lowpassfilter
% cfg.env_freq - double: frequency of the envelope. Defaults to 100Hz
% cfg.lpf_freq - double: cut-frequency of the low-pass filter. Defaults to
% 4000Hz.
% cfg.scan - double: time window in which to scan for a maximal correlation
% if a scalar is given the time window is [-scan, scan]
% if a length 2 vector is given it should be [-a, b], where 'a'
% and 'b' are positive numbers in seconds.
% cfg.freqreltol - double: frequency relative tolerance. defaults to 1e-5
% cfg.penalty_tau - double: penalty time use to weight the correlation.
% This allows to bound slave_delta_t (as with cfg.scan) but in
% a continuous way. If empty (default) no penalty is applied.
% cfg.penalty_n - double: penalty 'hill-coefficient' use to weight the
% correlation. Defines how abrupt is the penalty increase when
% slave_delta_t > cfg.penalty_tau. Defaults to 2.
% cfg.ft_feedback - string: default to 'no'. Defines verbosity of fieldtrip
% functions
% cfg.simulate_aliasing - bool, indicates if alising should be simulated
% on the slave when downsampling. Useful if one if the signals was not
% low-pass filtered at aquisition time (e.g. natus DC
% channels). Defaults to true.
%
% master - FT_DATATYPE_RAW continuous with single channel and trial
% slave - FT_DATATYPE_RAW continuous with single channel and trial
%
% returns
% slave_delta_t - double: time in seconds by which to shift the slave to
% align it to master
% max_corr - double: maximum correlation coefficient achieved for the shift
% slave_delta_t
% master - FT_DATATYPE_RAW: master raw after applying the preprocessing
% slave - FT_DATATYPE_RAW: slave raw after applying the preprocessing
if nargin == 2
slave = master;
master = cfg;
cfg = [];
elseif nargin ~= 3
error('incorrect number of arguments in call');
end
resample_freq = bml_getopt(cfg,'resample_freq', 10000);
scan = bml_getopt(cfg, 'scan');
freqreltol = bml_getopt(cfg, 'freqreltol', 1e-5);
method = string(bml_getopt(cfg, 'method', 'envelope'));
env_freq = bml_getopt(cfg,'env_freq', 100);
lpf_freq = bml_getopt(cfg,'lpf_freq', 4000);
penalty_tau = bml_getopt(cfg,'penalty_tau');
penalty_n = bml_getopt(cfg,'penalty_n', 2);
simulate_aliasing = bml_getopt(cfg,'simulate_aliasing', 1);
ft_feedback = bml_getopt(cfg,'ft_feedback','no');
ft_feedback = ft_feedback{1};
%assert single trial and channel
if numel(master.trial) > 1; error('master should be single trial raw'); end
if numel(slave.trial) > 1; error('slave should be single trial raw'); end
if numel(master.label) > 1; error('master should be single channel raw'); end
if numel(slave.label) > 1; error('slave should be single channel raw'); end
%calculating scan range
mc=[]; sc=[]; %master and slave time coordinates
mc.s1=1; mc.s2=length(master.time{1});
mc.t1=master.time{1}(1); mc.t2=master.time{1}(end);
sc.s1=1; sc.s2=length(slave.time{1});
sc.t1=slave.time{1}(1); sc.t2=slave.time{1}(end);
max_scan_range = [mc.t1 - sc.t2, mc.t2 - sc.t1];
if prod(max_scan_range) > 0 % if files do not overlap
slave_delta_t=nan;
max_corr=nan;
warning('files do not overlap');
return
end
if isempty(scan)
scan = max_scan_range;
elseif length(scan)==1
scan=[max(-scan,max_scan_range(1)), min(scan,max_scan_range(2))];
elseif length(scan)==2
scan=[max(scan(1),max_scan_range(1)), min(scan(2),max_scan_range(2))];
else
error('invalid use of cfg.scan argument');
end
%robust estimation of mean and std
master_median = median(master.trial{1});
slave_median = median(slave.trial{1});
master_std = robust_std(master.trial{1});
slave_std = robust_std(slave.trial{1});
if master_std==0; error('master can''t be correlated'); end
if slave_std==0; error('slave can''t be correlated'); end
%cropping and padding to correlation time window
ctw = [sc.t1+scan(1), sc.t2+scan(2)];
master = bml_pad(master, ctw(1), ctw(2), 0);
slave = bml_pad(slave, master.time{1}(1), master.time{1}(end), 0);
%common resample frequency
cfg=[]; cfg.feedback=ft_feedback;
cfg.resamplefs=resample_freq;
cfg.trackcallinfo=false;
cfg.showcallinfo='no';
master = ft_resampledata(cfg, master);
cfg=[]; cfg.feedback=ft_feedback;
cfg.trackcallinfo=false;
cfg.showcallinfo='no';
if simulate_aliasing
cfg.time=master.time; cfg.method='linear';
slave = ft_resampledata(cfg, slave);
else
error('Low pass filter to avoid aliasing not implemented');
end
%checking slave resampling
if abs(slave.fsample/master.fsample-1) < freqreltol
slave.fsample = master.fsample;
else
error('failed to resample slave to master''s time');
end
is_nan=isnan(slave.trial{1});
if sum(is_nan)>0
master.trial{1} = master.trial{1}(:,~is_nan);
master.time{1} = master.time{1}(:,~is_nan);
slave.trial{1} = slave.trial{1}(:,~is_nan);
slave.time{1} = slave.time{1}(:,~is_nan);
end
%methods
if ismember(lower(method),{'env','envelope'}) %envelope correlation
cfg=[]; cfg.freq = env_freq; %calculating envelops
master = bml_envelope_binabs(cfg,master);
slave = bml_envelope_binabs(cfg,slave);
try_polarity=false;
elseif ismember(lower(method),{'lpf','low-pass-filter'}) %low-pass-filter
master.trial{1} = ft_preproc_lowpassfilter(master.trial{1},...
master.fsample, lpf_freq, 4, 'but', 'twopass');
slave.trial{1} = ft_preproc_lowpassfilter(slave.trial{1},...
slave.fsample, lpf_freq, 4, 'but', 'twopass');
try_polarity=true;
else
error('unknown method');
end
%normalizing data
master.trial{1} = (master.trial{1} - master_median) / master_std;
slave.trial{1} = (slave.trial{1} - slave_median) / slave_std;
%correlation
[corr,lag]=xcorr(master.trial{1}(1,:), slave.trial{1}(1,:),...
floor(max(abs(scan))*master.fsample),'coeff');
[max_corr_idx,max_corr] = find_delta_corr(corr,lag,penalty_tau,penalty_n);
if try_polarity
[corr_m,lag_m]=xcorr(master.trial{1}(1,:), (-1).* slave.trial{1}(1,:),...
floor(max(abs(scan))*master.fsample),'coeff');
[max_corr_idx_m,max_corr_m] = find_delta_corr(corr_m,lag_m,penalty_tau,penalty_n);
if max_corr_m > max_corr
slave.trial{1}=(-1).* slave.trial{1};
max_corr_idx = max_corr_idx_m;
max_corr = max_corr_m;
lag=lag_m;
end
end
slave_delta_t = lag(max_corr_idx)/master.fsample;
slave.time{1} = slave.time{1} + slave_delta_t;
end
% private function
function [max_corr_idx,max_corr] = find_delta_corr(corr,lag,penalty_tau,penalty_n)
if ~isempty(penalty_tau)
[~,max_corr_idx]=max(corr./((penalty_tau*master.fsample)^penalty_n + abs(lag).^penalty_n));
max_corr=corr(max_corr_idx);
else
[max_corr,max_corr_idx]=max(corr);
end
end
|
github
|
Brain-Modulation-Lab/bml-master
|
bml_annot2coord.m
|
.m
|
bml-master/sync/bml_annot2coord.m
| 1,787 |
utf_8
|
afdf2310f69c8d9b32bb7079222ebb29
|
function coord = bml_annot2coord(annot, Fs)
% BML_ANNOT2COORD gets s1,t1,s2,t2 coordinates from annot and Fs
%
% Use as
% coord = bml_annot2coord(annot, Fs)
%
% annot - ANNOT table with 'starts', 'ends' and optionally 'Fs' variables
% (all other vars ignored)
% Fs - numeric, exact sampling frequency of returned s1,t1,s2,t2 coords.
% if absent a Fs var in annot is required
%
% returns a table/struct if annot is a table/struct
if istable(annot)
if exist('Fs','var')
annot.Fs(:) = Fs;
end
assert(ismember('Fs',annot.Properties.VariableNames),"Fs required");
assert(ismember('starts',annot.Properties.VariableNames),"starts required");
assert(ismember('ends',annot.Properties.VariableNames),"ends required");
coord = annot;
coord.s1(:)=0;
coord.t1(:)=0;
coord.s2(:)=0;
coord.t2(:)=0;
for i=1:height(annot)
i_coord = annot2coord(annot.starts(i),annot.ends(i),annot.Fs(i));
coord.s1(i)=i_coord.s1;
coord.t1(i)=i_coord.t1;
coord.s2(i)=i_coord.s2;
coord.t2(i)=i_coord.t2;
end
elseif isstruct(annot)
if exist('Fs','var')
annot.Fs = Fs;
end
assert(ismember('Fs',fields(annot)),"Fs required");
assert(ismember('starts',fields(annot)),"starts required");
assert(ismember('ends',fields(annot)),"ends required");
coord = annot2coord(annot.starts,annot.ends,annot.Fs);
else
error('Unknown type for annot. Table or struct accepted.');
end
end
function simple_coord = annot2coord(starts,ends,Fs)
pTT = 9; %pTT = pTimeTol = -log10(timetol)
simple_coord=[];
simple_coord.s1=1;
simple_coord.t1=round(starts+0.5/Fs,pTT);
simple_coord.s2=round((ends-starts)*Fs)-1;
simple_coord.t2=simple_coord.t1 + (simple_coord.s2 - simple_coord.s1)/Fs;
end
|
github
|
Brain-Modulation-Lab/bml-master
|
inpolyhedron.m
|
.m
|
bml-master/anat/inpolyhedron.m
| 22,474 |
utf_8
|
3bab4b4d7bfb720f1c2d2e1ce95779ba
|
function IN = inpolyhedron(varargin)
%INPOLYHEDRON Tests if points are inside a 3D triangulated (faces/vertices) surface
%
% IN = INPOLYHEDRON(FV,QPTS) tests if the query points (QPTS) are inside
% the patch/surface/polyhedron defined by FV (a structure with fields
% 'vertices' and 'faces'). QPTS is an N-by-3 set of XYZ coordinates. IN
% is an N-by-1 logical vector which will be TRUE for each query point
% inside the surface. By convention, surface normals point OUT from the
% object (see FLIPNORMALS option below if to reverse this convention).
%
% INPOLYHEDRON(FACES,VERTICES,...) takes faces/vertices separately, rather than in
% an FV structure.
%
% IN = INPOLYHEDRON(..., X, Y, Z) voxelises a mask of 3D gridded query points
% rather than an N-by-3 array of points. X, Y, and Z coordinates of the grid
% supplied in XVEC, YVEC, and ZVEC respectively. IN will return as a 3D logical
% volume with SIZE(IN) = [LENGTH(YVEC) LENGTH(XVEC) LENGTH(ZVEC)], equivalent to
% syntax used by MESHGRID. INPOLYHEDRON handles this input faster and with a lower
% memory footprint than using MESHGRID to make full X, Y, Z query points matrices.
%
% INPOLYHEDRON(...,'PropertyName',VALUE,'PropertyName',VALUE,...) tests query
% points using the following optional property values:
%
% TOL - Tolerance on the tests for "inside" the surface. You can think of
% tol as the distance a point may possibly lie above/below the surface, and still
% be perceived as on the surface. Due to numerical rounding nothing can ever be
% done exactly here. Defaults to ZERO. Note that in the current implementation TOL
% only affects points lying above/below a surface triangle (in the Z-direction).
% Points coincident with a vertex in the XY plane are considered INside the surface.
% More formal rules can be implemented with input/feedback from users.
%
% GRIDSIZE - Internally, INPOLYHEDRON uses a divide-and-conquer algorithm to
% split all faces into a chessboard-like grid of GRIDSIZE-by-GRIDSIZE regions.
% Performance will be a tradeoff between a small GRIDSIZE (few iterations, more
% data per iteration) and a large GRIDSIZE (many iterations of small data
% calculations). The sweet-spot has been experimentally determined (on a win64
% system) to be correlated with the number of faces/vertices. You can overwrite
% this automatically computed choice by specifying a GRIDSIZE parameter.
%
% FACENORMALS - By default, the normals to the FACE triangles are computed as the
% cross-product of the first two triangle edges. You may optionally specify face
% normals here if they have been pre-computed.
%
% FLIPNORMALS - (Defaults FALSE). To match a wider convention, triangle
% face normals are presumed to point OUT from the object's surface. If
% your surface normals are defined pointing IN, then you should set the
% FLIPNORMALS option to TRUE to use the reverse of this convention.
%
% Example:
% tmpvol = zeros(20,20,20); % Empty voxel volume
% tmpvol(5:15,8:12,8:12) = 1; % Turn some voxels on
% tmpvol(8:12,5:15,8:12) = 1;
% tmpvol(8:12,8:12,5:15) = 1;
% fv = isosurface(tmpvol, 0.99); % Create the patch object
% fv.faces = fliplr(fv.faces); % Ensure normals point OUT
% % Test SCATTERED query points
% pts = rand(200,3)*12 + 4; % Make some query points
% in = inpolyhedron(fv, pts); % Test which are inside the patch
% figure, hold on, view(3) % Display the result
% patch(fv,'FaceColor','g','FaceAlpha',0.2)
% plot3(pts(in,1),pts(in,2),pts(in,3),'bo','MarkerFaceColor','b')
% plot3(pts(~in,1),pts(~in,2),pts(~in,3),'ro'), axis image
% % Test STRUCTURED GRID of query points
% gridLocs = 3:2.1:19;
% [x,y,z] = meshgrid(gridLocs,gridLocs,gridLocs);
% in = inpolyhedron(fv, gridLocs,gridLocs,gridLocs);
% figure, hold on, view(3) % Display the result
% patch(fv,'FaceColor','g','FaceAlpha',0.2)
% plot3(x(in), y(in), z(in),'bo','MarkerFaceColor','b')
% plot3(x(~in),y(~in),z(~in),'ro'), axis image
%
% See also: UNIFYMESHNORMALS (on the <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=43013">file exchange</a>)
% TODO-list
% - Optmise overall memory footprint. (need examples with MEM errors)
% - Implement an "ignore these" step to speed up calculations for:
% * Query points outside the convex hull of the faces/vertices input
% - Get a better/best gridSize calculation. User feedback?
% - Detect cases where X-rays or Y-rays would be better than Z-rays?
%
% Author: Sven Holcombe
% - 10 Jun 2012: Version 1.0
% - 28 Aug 2012: Version 1.1 - Speedup using accumarray
% - 07 Nov 2012: Version 2.0 - BEHAVIOUR CHANGE
% Query points coincident with a VERTEX are now IN an XY triangle
% - 18 Aug 2013: Version 2.1 - Gridded query point handling with low memory footprint.
% - 10 Sep 2013: Version 3.0 - BEHAVIOUR CHANGE
% NEW CONVENTION ADOPTED to expect face normals pointing IN
% Vertically oriented faces are now ignored. Speeds up
% computation and fixes bug where presence of vertical faces
% produced NaN distance from a query pt to facet, making all
% query points under facet erroneously NOT IN polyhedron.
% - 25 Sep 2013: Version 3.1 - Dropped nested unique call which was made
% mostly redundant via v2.1 gridded point handling. Also
% refreshed grid size selection via optimisation.
% - 25 Feb 2014: Version 3.2 - Fixed indeterminate behaviour for query
% points *exactly* in line with an "overhanging" vertex.
% - 11 Nov 2016: Version 3.3 - Used quoted semicolons ':' inside function
% handle calls to conform with new 2015b interpreter
%%
% FACETS is an unpacked arrangement of faces/vertices. It is [3-by-3-by-N],
% with 3 1-by-3 XYZ coordinates of N faces.
[facets, qPts, options] = parseInputs(varargin{:});
numFaces = size(facets,3);
if ~options.griddedInput % SCATTERED QUERY POINTS
numQPoints = size(qPts,1);
else % STRUCTURED QUERY POINTS
numQPoints = prod(cellfun(@numel,qPts(1:2)));
end
% Precompute 3d normals to all facets (triangles). Do this via the cross
% product of the first edge vector with the second. Normalise the result.
allEdgeVecs = facets([2 3 1],:,:) - facets(:,:,:);
if isempty(options.facenormals)
allFacetNormals = bsxfun(@times, allEdgeVecs(1,[2 3 1],:), allEdgeVecs(2,[3 1 2],:)) - ...
bsxfun(@times, allEdgeVecs(2,[2 3 1],:), allEdgeVecs(1,[3 1 2],:));
allFacetNormals = bsxfun(@rdivide, allFacetNormals, sqrt(sum(allFacetNormals.^2,2)));
else
allFacetNormals = permute(options.facenormals,[3 2 1]);
end
if options.flipnormals
allFacetNormals = -allFacetNormals;
end
% We use a Z-ray intersection so we don't even need to consider facets that
% are purely vertically oriented (have zero Z-component).
isFacetUseful = allFacetNormals(:,3,:) ~= 0;
%% Setup grid referencing system
% Function speed can be thought of as a function of grid size. A small number of grid
% squares means iterating over fewer regions (good) but with more faces/qPts to
% consider each time (bad). For any given mesh/queryPt configuration, there will be a
% sweet spot that minimises computation time. There will also be a constraint from
% memory available - low grid sizes means considering many queryPt/faces at once,
% which will require a larger memory footprint. Here we will let the user specify
% gridsize directly, or we will estimate the optimum size based on prior testing.
if ~isempty(options.gridsize)
gridSize = options.gridsize;
else
% Coefficients (with 95% confidence bounds):
p00 = -47; p10 = 12.83; p01 = 20.89;
p20 = 0.7578; p11 = -6.511; p02 = -2.586;
p30 = -0.1802; p21 = 0.2085; p12 = 0.7521;
p03 = 0.09984; p40 = 0.005815; p31 = 0.007775;
p22 = -0.02129; p13 = -0.02309;
GSfit = @(x,y)p00 + p10*x + p01*y + p20*x^2 + p11*x*y + p02*y^2 + p30*x^3 + p21*x^2*y + p12*x*y^2 + p03*y^3 + p40*x^4 + p31*x^3*y + p22*x^2*y^2 + p13*x*y^3;
gridSize = min(150 ,max(1, ceil(GSfit(log(numQPoints),log(numFaces)))));
if isnan(gridSize), gridSize = 1; end
end
%% Find candidate qPts -> triangles pairs
% We have a large set of query points. For each query point, find potential
% triangles that would be pierced by vertical rays through the qPt. First,
% a simple filter by XY bounding box
% Calculate the bounding box of each facet
minFacetCoords = permute(min(facets(:,1:2,:),[],1),[3 2 1]);
maxFacetCoords = permute(max(facets(:,1:2,:),[],1),[3 2 1]);
% Set rescale values to rescale all vertices between 0(-eps) and 1(+eps)
scalingOffsetsXY = min(minFacetCoords,[],1) - eps;
scalingRangeXY = max(maxFacetCoords,[],1) - scalingOffsetsXY + 2*eps;
% Based on scaled min/max facet coords, get the [lowX lowY highX highY] "grid" index
% of all faces
lowToHighGridIdxs = floor(bsxfun(@rdivide, ...
bsxfun(@minus, ... % Use min/max coordinates of each facet (+/- the tolerance)
[minFacetCoords-options.tol maxFacetCoords+options.tol],...
[scalingOffsetsXY scalingOffsetsXY]),...
[scalingRangeXY scalingRangeXY]) * gridSize) + 1;
% Build a grid of cells. In each cell, place the facet indices that encroach into
% that grid region. Similarly, each query point will be assigned to a grid region.
% Note that query points will be assigned only one grid region, facets can cover many
% regions. Furthermore, we will add a tolerance to facet region assignment to ensure
% a query point will be compared to facets even if it falls only on the edge of a
% facet's bounding box, rather than inside it.
cells = cell(gridSize);
[unqLHgrids,~,facetInds] = unique(lowToHighGridIdxs,'rows');
tmpInds = accumarray(facetInds(isFacetUseful),find(isFacetUseful),[size(unqLHgrids,1),1],@(x){x});
for xi = 1:gridSize
xyMinMask = xi >= unqLHgrids(:,1) & xi <= unqLHgrids(:,3);
for yi = 1:gridSize
cells{yi,xi} = cat(1,tmpInds{xyMinMask & yi >= unqLHgrids(:,2) & yi <= unqLHgrids(:,4)});
% The above line (with accumarray) is faster with equiv results than:
% % cells{yi,xi} = find(ismember(facetInds, xyInds));
end
end
% With large number of facets, memory may be important:
clear lowToHightGridIdxs LHgrids facetInds tmpInds xyMinMask minFacetCoords maxFacetCoords
%% Compute edge unit vectors and dot products
% Precompute the 2d unit vectors making up each facet's edges in the XY plane.
allEdgeUVecs = bsxfun(@rdivide, allEdgeVecs(:,1:2,:), sqrt(sum(allEdgeVecs(:,1:2,:).^2,2)));
% Precompute the inner product between edgeA.edgeC, edgeB.edgeA, edgeC.edgeB
allEdgeEdgeDotPs = sum(allEdgeUVecs .* -allEdgeUVecs([3 1 2],:,:),2) - 1e-9;
%% Gather XY query locations
% Since query points are most likely given as a (3D) grid of query locations, we only
% need to consider the unique XY locations when asking which facets a vertical ray
% through an XY location would pierce.
if ~options.griddedInput % SCATTERED QUERY POINTS
qPtsXY = @(varargin)qPts(:,1:2);
qPtsXYZViaUnqIndice = @(ind)qPts(ind,:);
outPxIndsViaUnqIndiceMask = @(ind,mask)ind(mask);
outputSize = [size(qPts,1),1];
reshapeINfcn = @(INMASK)INMASK;
minFacetDistanceFcn = @minFacetToQptDistance;
else % STRUCTURED QUERY POINTS
[xmat,ymat] = meshgrid(qPts{1:2});
qPtsXY = [xmat(:) ymat(:)];
% A standard set of Z locations will be shifted around by different
% unqQpts XY coordinates.
zCoords = qPts{3}(:) * [0 0 1];
qPtsXYZViaUnqIndice = @(ind)bsxfun(@plus, zCoords, [qPtsXY(ind,:) 0]);
% From a given indice and mask, we will turn on/off the IN points under
% that indice based on the mask. The easiest calculation is to setup
% the IN matrix as a numZpts-by-numUnqPts mask. At the end, we must
% unpack/reshape this 2D mask to a full 3D logical mask
numZpts = size(zCoords,1);
baseZinds = 1:numZpts;
outPxIndsViaUnqIndiceMask = @(ind,mask)(ind-1)*numZpts + baseZinds(mask);
outputSize = [numZpts, size(qPtsXY,1)];
reshapeINfcn = @(INMASK)reshape(INMASK', cellfun(@numel, qPts([2 1 3])));
minFacetDistanceFcn = @minFacetToQptsDistance;
end
% Start with every query point NOT inside the polyhedron. We will
% iteratively find those query points that ARE inside.
IN = false(outputSize);
% Determine with grids each query point falls into.
qPtGridXY = floor(bsxfun(@rdivide, bsxfun(@minus, qPtsXY(':',':'), scalingOffsetsXY),...
scalingRangeXY) * gridSize) + 1;
[unqQgridXY,~,qPtGridInds] = unique(qPtGridXY,'rows');
% We need only consider grid indices within those already set up
ptsToConsidMask = ~any(qPtGridXY<1 | qPtGridXY>gridSize, 2);
if ~any(ptsToConsidMask)
IN = reshapeINfcn(IN);
return;
end
% Build the reference list
cellQptContents = accumarray(qPtGridInds(ptsToConsidMask),find(ptsToConsidMask), [],@(x){x});
gridsToCheck = unqQgridXY(~any(unqQgridXY<1 | unqQgridXY>gridSize, 2),:);
cellQptContents(cellfun('isempty',cellQptContents)) = [];
gridIndsToCheck = sub2ind(size(cells), gridsToCheck(:,2), gridsToCheck(:,1));
% For ease of multiplication, reshape qPt XY coords to [1-by-2-by-1-by-N]
qPtsXY = permute(qPtsXY(':',':'),[4 2 3 1]);
% There will be some grid indices with query points but without facets.
emptyMask = cellfun('isempty',cells(gridIndsToCheck))';
for i = find(~emptyMask)
% We get all the facet coordinates (ie, triangle vertices) of triangles
% that intrude into this grid location. The size is [3-by-2-by-N], for
% the [3vertices-by-XY-by-Ntriangles]
allFacetInds = cells{gridIndsToCheck(i)};
candVerts = facets(:,1:2,allFacetInds);
% We need the XY coordinates of query points falling into this grid.
allqPtInds = cellQptContents{i};
queryPtsXY = qPtsXY(:,:,:,allqPtInds);
% Get unit vectors pointing from each triangle vertex to my query point(s)
vert2ptVecs = bsxfun(@minus, queryPtsXY, candVerts);
vert2ptUVecs = bsxfun(@rdivide, vert2ptVecs, sqrt(sum(vert2ptVecs.^2,2)));
% Get unit vectors pointing around each triangle (along edge A, edge B, edge C)
edgeUVecs = allEdgeUVecs(:,:,allFacetInds);
% Get the inner product between edgeA.edgeC, edgeB.edgeA, edgeC.edgeB
edgeEdgeDotPs = allEdgeEdgeDotPs(:,:,allFacetInds);
% Get inner products between each edge unit vec and the UVs from qPt to vertex
edgeQPntDotPs = sum(bsxfun(@times, edgeUVecs, vert2ptUVecs),2);
qPntEdgeDotPs = sum(bsxfun(@times,vert2ptUVecs, -edgeUVecs([3 1 2],:,:)),2);
% If both inner products 2 edges to the query point are greater than the inner
% product between the two edges themselves, the query point is between the V
% shape made by the two edges. If this is true for all 3 edge pair, the query
% point is inside the triangle.
resultIN = all(bsxfun(@gt, edgeQPntDotPs, edgeEdgeDotPs) & bsxfun(@gt, qPntEdgeDotPs, edgeEdgeDotPs),1);
resultONVERTEX = any(any(isnan(vert2ptUVecs),2),1);
result = resultIN | resultONVERTEX;
qPtHitsTriangles = any(result,3);
% If NONE of the query points pierce ANY triangles, we can skip forward
if ~any(qPtHitsTriangles), continue, end
% In the next step, we'll need to know the indices of ALL the query points at
% each of the distinct XY coordinates. Let's get their indices into "qPts" as a
% cell of length M, where M is the number of unique XY points we had found.
for ptNo = find(qPtHitsTriangles(:))'
% Which facets does it pierce?
piercedFacetInds = allFacetInds(result(1,1,:,ptNo));
% Get the 1-by-3-by-N set of triangle normals that this qPt pierces
piercedTriNorms = allFacetNormals(:,:,piercedFacetInds);
% Pick the first vertex as the "origin" of a plane through the facet. Get the
% vectors from each query point to each facet origin
facetToQptVectors = bsxfun(@minus, ...
qPtsXYZViaUnqIndice(allqPtInds(ptNo)),...
facets(1,:,piercedFacetInds));
% Calculate how far you need to go up/down to pierce the facet's plane.
% Positive direction means "inside" the facet, negative direction means
% outside.
facetToQptDists = bsxfun(@rdivide, ...
sum(bsxfun(@times,piercedTriNorms,facetToQptVectors),2), ...
abs(piercedTriNorms(:,3,:)));
% Since it's possible for two triangles sharing the same vertex to
% be the same distance away, I want to sum up all the distances of
% triangles that are closest to the query point. Simple case: The
% closest triangle is unique Edge case: The closest triangle is one
% of many the same distance and direction away. Tricky case: The
% closes triangle has another triangle the equivalent distance
% but facing the opposite direction
IN( outPxIndsViaUnqIndiceMask(allqPtInds(ptNo), ...
minFacetDistanceFcn(facetToQptDists)<options.tol...
)) = true;
end
end
% If they provided X,Y,Z vectors of query points, our output is currently a
% 2D mask and must be reshaped to [LEN(Y) LEN(X) LEN(Z)].
IN = reshapeINfcn(IN);
%% Called subfunctions
% vertices = [
% 0.9046 0.1355 -0.0900
% 0.8999 0.3836 -0.0914
% 1.0572 0.2964 -0.0907
% 0.8735 0.1423 -0.1166
% 0.8685 0.4027 -0.1180
% 1.0337 0.3112 -0.1173
% 0.9358 0.1287 -0.0634
% 0.9313 0.3644 -0.0647
% 1.0808 0.2816 -0.0641
% ];
% faces = [
% 1 2 5
% 1 5 4
% 2 3 6
% 2 6 5
% 3 1 4
% 3 4 6
% 6 4 5
% 2 1 8
% 8 1 7
% 3 2 9
% 9 2 8
% 1 3 7
% 7 3 9
% 7 9 8
% ];
% point = [vertices(3,1),vertices(3,2),1.5];
function closestTriDistance = minFacetToQptDistance(facetToQptDists)
% FacetToQptDists is a 1pt-by-1-by-Nfacets array of how far you need to go
% up/down to pierce each facet's plane. If the Qpt was directly over an
% "overhang" vertex, then two facets with opposite orientation will be
% equally distant from the Qpt, with one distance positive and one
% negative. In such cases, it is impossible for the Qpt to actually be
% "inside" this pair of facets, so their distance is updated to Inf.
[~,minInd] = min(abs(facetToQptDists),[],3);
while any( abs(facetToQptDists + facetToQptDists(minInd)) < 1e-15 )
% Since the above comparison is made every time, but the below variable
% setting is done only in the rare case that a query point coincides
% with an overhang vertex, it is more efficient to re-compute the
% equality when it's true, rather than store the result every time.
facetToQptDists( abs(facetToQptDists) - abs(facetToQptDists(minInd)) < 1e-15) = inf;
if ~any(isfinite(facetToQptDists))
break;
end
[~,minInd] = min(abs(facetToQptDists),[],3);
end
closestTriDistance = facetToQptDists(minInd);
function closestTriDistance = minFacetToQptsDistance(facetToQptDists)
% As above, but facetToQptDists is an Mpts-by-1-by-Nfacets array.
% The multi-point version is a little more tricky. While below is quite a
% bit slower when the while loop is entered, it is very rarely entered and
% very fast to make just the initial comparison.
[minVals,minInds] = min(abs(facetToQptDists),[],3);
while any(...
any(abs(bsxfun(@plus,minVals,facetToQptDists))<1e-15,3) & ...
any(abs(bsxfun(@minus,minVals,facetToQptDists))<1e-15,3))
maskP = abs(bsxfun(@plus,minVals,facetToQptDists))<1e-15;
maskN = abs(bsxfun(@minus,minVals,facetToQptDists))<1e-15;
mustAlterMask = any(maskP,3) & any(maskN,3);
for i = find(mustAlterMask)'
facetToQptDists(i,:,maskP(i,:,:) | maskN(i,:,:)) = inf;
end
[newMv,newMinInds] = min(abs(facetToQptDists(mustAlterMask,:,:)),[],3);
minInds(mustAlterMask) = newMinInds(:);
minVals(mustAlterMask) = newMv(:);
end
% Below is a tiny speedup on basically a sub2ind call.
closestTriDistance = facetToQptDists((minInds-1)*size(facetToQptDists,1) + (1:size(facetToQptDists,1))');
%% Input handling subfunctions
function [facets, qPts, options] = parseInputs(varargin)
% Gather FACES and VERTICES
if isstruct(varargin{1}) % inpolyhedron(FVstruct, ...)
if ~all(isfield(varargin{1},{'vertices','faces'}))
error( 'Structure FV must have "faces" and "vertices" fields' );
end
faces = varargin{1}.faces;
vertices = varargin{1}.vertices;
varargin(1) = []; % Chomp off the faces/vertices
else % inpolyhedron(FACES, VERTICES, ...)
faces = varargin{1};
vertices = varargin{2};
varargin(1:2) = []; % Chomp off the faces/vertices
end
% Unpack the faces/vertices into [3-by-3-by-N] facets. It's better to
% perform this now and have FACETS only in memory in the main program,
% rather than FACETS, FACES and VERTICES
facets = vertices';
facets = permute(reshape(facets(:,faces'), 3, 3, []),[2 1 3]);
% Extract query points
if length(varargin)<2 || ischar(varargin{2}) % inpolyhedron(F, V, [x(:) y(:) z(:)], ...)
qPts = varargin{1};
varargin(1) = []; % Chomp off the query points
else % inpolyhedron(F, V, xVec, yVec, zVec, ...)
qPts = varargin(1:3);
% Chomp off the query points and tell the world that it's gridded input.
varargin(1:3) = [];
varargin = [varargin {'griddedInput',true}];
end
% Extract configurable options
options = parseOptions(varargin{:});
% Check if face normals are unified
if options.testNormals
options.normalsAreUnified = checkNormalUnification(faces);
end
function options = parseOptions(varargin)
IP = inputParser;
if verLessThan('matlab', 'R2013b')
fcn = 'addParamValue';
else
fcn = 'addParameter';
end
IP.(fcn)('gridsize',[], @(x)isscalar(x) && isnumeric(x))
IP.(fcn)('tol', 0, @(x)isscalar(x) && isnumeric(x))
IP.(fcn)('tol_ang', 1e-5, @(x)isscalar(x) && isnumeric(x))
IP.(fcn)('facenormals',[]);
IP.(fcn)('flipnormals',false);
IP.(fcn)('griddedInput',false);
IP.(fcn)('testNormals',false);
IP.parse(varargin{:});
options = IP.Results;
|
github
|
Brain-Modulation-Lab/bml-master
|
fast_wavtransform.m
|
.m
|
bml-master/timefreq/private/fast_wavtransform.m
| 3,461 |
utf_8
|
b467542a7bf46f12e7e87fdecb046f7a
|
function Y=fast_wavtransform(fq,TS,sr,width)
% Y=fast_wavtransform(fq,TS,sr,width)
%
%uses multiplication in the fourier domain (rather than convolution) to
% speed compution on LARGE datasets;
%error will occur if length of a given wavelet is longer than the input
% signal;
%warning: since all computation is executed simultaneously for speed, this
% function may be RAM intesive
%
%inputs:
% fq=vector of frequency (Hz) values on which to center wavelets
% TS=vector or 2D matrix of timeseries (assumes longer dimension is time)
% sr=sampling rate (Hz)
% width=vector of wavelet c-parameter for corresponding frequencies in fq
% (if length(width)~=length(fq) then width(1) is used for all fq);
% note: std in frequency of a given wavelet=fq/width
%
%outputs:
% Y=matrix of transformed data (dimension containing fq layers is in the
% order as in fq)
%
%TAW_060215
if ~nargin
help fast_wavtransform
end
nfq=length(fq);
dt=1/sr;
if length(width)~=length(fq)
width=repmat(width(1),nfq);
end
[ntp,nts]=size(TS);
if nts>ntp
TS=TS';
tmp=ntp; ntp=nts; nts=tmp;
end
m=complex(zeros(ntp,nfq),zeros(ntp,nfq));
for nf=1:nfq
w=width(nf);
sf=fq(nf)/w;
st=1/(2*pi*sf);
t=-3*st:dt:3*st;
%t=-(w/2)*st:dt:(w/2)*st;
nt=length(t);
m(1:nt,nf)=morwav(fq(nf),t,st)';
m(:,nf)=circshift(m(:,nf),floor((ntp-nt)*0.5));
end
Y=reshape(ifft(reshape(repmat(reshape(fft(TS),ntp,1,nts),1,nfq,1),...
ntp,nts*nfq) .* repmat(fft(m),1,nts)),ntp,nfq,[]);
Y=circshift(Y,floor(ntp*0.5),1);
end
function y = morwav(f,t,st)
A = 1/sqrt(st*sqrt(pi));
y = A*exp(-t.^2/(2*st^2)).*exp(1i*2*pi*f.*t);
%y=y./sum(abs(y));
end
|
github
|
Brain-Modulation-Lab/bml-master
|
padarray.m
|
.m
|
bml-master/utils/padarray.m
| 7,389 |
utf_8
|
00ff76c42a05000c70ecfad1e2087fdb
|
function b = padarray(varargin)
%PADARRAY Pad an array.
% B = PADARRAY(A,PADSIZE) pads array A with PADSIZE(k) number of zeros
% along the k-th dimension of A. PADSIZE should be a vector of
% positive integers.
%
% B = PADARRAY(A,PADSIZE,PADVAL) pads array A with PADVAL (a scalar)
% instead of with zeros.
%
% B = PADARRAY(A,PADSIZE,PADVAL,DIRECTION) pads A in the direction
% specified by the string DIRECTION. DIRECTION can be one of the
% following strings.
%
% String values for DIRECTION
% 'pre' Pads before the first array element along each
% dimension .
% 'post' Pads after the last array element along each
% dimension.
% 'both' Pads before the first array element and after the
% last array element along each dimension.
%
% By default, DIRECTION is 'both'.
%
% B = PADARRAY(A,PADSIZE,METHOD,DIRECTION) pads array A using the
% specified METHOD. METHOD can be one of these strings:
%
% String values for METHOD
% 'circular' Pads with circular repetion of elements.
% 'replicate' Repeats border elements of A.
% 'symmetric' Pads array with mirror reflections of itself.
%
% Class Support
% -------------
% When padding with a constant value, A can be numeric or logical.
% When padding using the 'circular', 'replicate', or 'symmetric'
% methods, A can be of any class. B is of the same class as A.
%
% Example
% -------
% Add three elements of padding to the beginning of a vector. The
% padding elements contain mirror copies of the array.
%
% b = padarray([1 2 3 4],3,'symmetric','pre')
%
% Add three elements of padding to the end of the first dimension of
% the array and two elements of padding to the end of the second
% dimension. Use the value of the last array element as the padding
% value.
%
% B = padarray([1 2; 3 4],[3 2],'replicate','post')
%
% Add three elements of padding to each dimension of a
% three-dimensional array. Each pad element contains the value 0.
%
% A = [1 2; 3 4];
% B = [5 6; 7 8];
% C = cat(3,A,B)
% D = padarray(C,[3 3],0,'both')
%
% See also CIRCSHIFT, IMFILTER.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.11.4.3 $ $Date: 2003/08/23 05:53:08 $
[a, method, padSize, padVal, direction] = ParseInputs(varargin{:});
if isempty(a),% treat empty matrix similar for any method
if strcmp(direction,'both')
sizeB = size(a) + 2*padSize;
else
sizeB = size(a) + padSize;
end
b = mkconstarray(class(a), padVal, sizeB);
else
switch method
case 'constant'
b = ConstantPad(a, padSize, padVal, direction);
case 'circular'
b = CircularPad(a, padSize, direction);
case 'symmetric'
b = SymmetricPad(a, padSize, direction);
case 'replicate'
b = ReplicatePad(a, padSize, direction);
end
end
if (islogical(a))
b = logical(b);
end
%%%
%%% ConstantPad
%%%
function b = ConstantPad(a, padSize, padVal, direction)
numDims = numel(padSize);
% Form index vectors to subsasgn input array into output array.
% Also compute the size of the output array.
idx = cell(1,numDims);
sizeB = zeros(1,numDims);
for k = 1:numDims
M = size(a,k);
switch direction
case 'pre'
idx{k} = (1:M) + padSize(k);
sizeB(k) = M + padSize(k);
case 'post'
idx{k} = 1:M;
sizeB(k) = M + padSize(k);
case 'both'
idx{k} = (1:M) + padSize(k);
sizeB(k) = M + 2*padSize(k);
end
end
% Initialize output array with the padding value. Make sure the
% output array is the same type as the input.
b = mkconstarray(class(a), padVal, sizeB);
b(idx{:}) = a;
%%%
%%% CircularPad
%%%
function b = CircularPad(a, padSize, direction)
numDims = numel(padSize);
% Form index vectors to subsasgn input array into output array.
% Also compute the size of the output array.
idx = cell(1,numDims);
for k = 1:numDims
M = size(a,k);
dimNums = 1:M;
p = padSize(k);
switch direction
case 'pre'
idx{k} = dimNums(mod(-p:M-1, M) + 1);
case 'post'
idx{k} = dimNums(mod(0:M+p-1, M) + 1);
case 'both'
idx{k} = dimNums(mod(-p:M+p-1, M) + 1);
end
end
b = a(idx{:});
%%%
%%% SymmetricPad
%%%
function b = SymmetricPad(a, padSize, direction)
numDims = numel(padSize);
% Form index vectors to subsasgn input array into output array.
% Also compute the size of the output array.
idx = cell(1,numDims);
for k = 1:numDims
M = size(a,k);
dimNums = [1:M M:-1:1];
p = padSize(k);
switch direction
case 'pre'
idx{k} = dimNums(mod(-p:M-1, 2*M) + 1);
case 'post'
idx{k} = dimNums(mod(0:M+p-1, 2*M) + 1);
case 'both'
idx{k} = dimNums(mod(-p:M+p-1, 2*M) + 1);
end
end
b = a(idx{:});
%%%
%%% ReplicatePad
%%%
function b = ReplicatePad(a, padSize, direction)
numDims = numel(padSize);
% Form index vectors to subsasgn input array into output array.
% Also compute the size of the output array.
idx = cell(1,numDims);
for k = 1:numDims
M = size(a,k);
p = padSize(k);
onesVector = ones(1,p);
switch direction
case 'pre'
idx{k} = [onesVector 1:M];
case 'post'
idx{k} = [1:M M*onesVector];
case 'both'
idx{k} = [onesVector 1:M M*onesVector];
end
end
b = a(idx{:});
%%%
%%% ParseInputs
%%%
function [a, method, padSize, padVal, direction] = ParseInputs(varargin)
% default values
a = [];
method = 'constant';
padSize = [];
padVal = 0;
direction = 'both';
% checknargin(2,4,nargin,mfilename);
a = varargin{1};
padSize = varargin{2};
% checkinput(padSize, {'double'}, {'real' 'vector' 'nonnan' 'nonnegative' ...
% 'integer'}, mfilename, 'PADSIZE', 2);
% Preprocess the padding size
if (numel(padSize) < ndims(a))
padSize = padSize(:);
padSize(ndims(a)) = 0;
end
if nargin > 2
firstStringToProcess = 3;
if ~ischar(varargin{3})
% Third input must be pad value.
padVal = varargin{3};
% checkinput(padVal, {'numeric' 'logical'}, {'scalar'}, ...
% mfilename, 'PADVAL', 3);
firstStringToProcess = 4;
end
for k = firstStringToProcess:nargin
validStrings = {'circular' 'replicate' 'symmetric' 'pre' ...
'post' 'both'};
string = checkstrs(varargin{k}, validStrings, mfilename, ...
'METHOD or DIRECTION', k);
switch string
case {'circular' 'replicate' 'symmetric'}
method = string;
case {'pre' 'post' 'both'}
direction = string;
otherwise
error('Images:padarray:unexpectedError', '%s', ...
'Unexpected logic error.')
end
end
end
% Check the input array type
if strcmp(method,'constant') && ~(isnumeric(a) || islogical(a))
id = sprintf('Images:%s:badTypeForConstantPadding', mfilename);
msg1 = sprintf('Function %s expected A (argument 1)',mfilename);
msg2 = 'to be numeric or logical for constant padding.';
error(id,'%s\n%s',msg1,msg2);
end
|
github
|
Brain-Modulation-Lab/bml-master
|
toString.m
|
.m
|
bml-master/utils/toString.m
| 12,967 |
utf_8
|
e68dc0969f6d1e1b05650c9b17e14f36
|
function s = toString(v, varargin)
%TOSTRING creates a string representation of any MATLAB variable
% STRINGREP=RPTGEN.TOSTRING(VARIABLE, CHARLIMIT)
% Copyright 1997-2017 The MathWorks, Inc.
%--------1---------2---------3---------4---------5---------6---------7---------8
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Convert string arguments to character array arguments
n = numel(varargin);
for i = 1:n
if isstring(varargin{i})
varargin{i} = char(varargin{i});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[charLimit, cr] = locParseInputArgs(varargin{:});
if ischar(v)
s = locRenderChar(v, charLimit, cr);
elseif isstring(v)
if isscalar(v)
s = locRenderChar(char(v), charLimit, cr);
else
s = locRenderStringArray(v, charLimit, cr);
end
elseif isnumeric(v)
s = locRenderNumeric(v, charLimit, cr);
elseif iscellstr(v)
s = locRenderCellStr(v, charLimit, cr);
elseif iscell(v)
s = locRenderCell(v, charLimit, cr);
elseif isstruct(v)
s = locRenderStruct(v, charLimit, cr);
elseif isobject(v)
s = locRenderMCOSObject(v);
elseif isa(v, 'DAStudio.Object')
s = locRenderDAObject(v, charLimit, cr);
else
s = locRenderViaDISP(v, charLimit, cr);
end
%-------------------------------------------------------------------------------
function sizeString = locRenderSizeString(sizeVector, isMinimize)
% locRenderSizeString accepts a size vector (i.e. the output from SIZE) and
% renders it as AxBxC.
if ((nargin > 1) && isMinimize ...
&& (length(sizeVector) < 3) ... % check length "[1 1]"
&& (max(sizeVector) == 1)) % check elements are all 1s
% Renders empty if sizeVector is "[1 1]"
sizeString = '';
else
% Render output as "AxBxCx"
sizeString = sprintf('%ix', sizeVector);
% Remove trailing x
sizeString(end) = ' ';
end
%-------------------------------------------------------------------------------
function string = locRenderStruct(value, charLimit, cr)
siz = size(value);
nDims = length(siz);
if ((nDims > 2) || (max(siz) > 1))
% 3d or N-d array - always collapse
compactStruct = 1;
else
% Render via DISP method for structures
% >> aStruct = struct('a',123,'b','xyz');
% >> rptgen.toString(aStruct);
string = locRenderViaDISP(value, inf, cr);
compactStruct = (length(string) > charLimit);
end
if compactStruct
% Test code for following code paths
% >> aStruct = struct('a',123,'b','xyz','c',123,'d','xyz','e',1,'f',2);
% >> aStructMultiDims = repmat(aStruct,[2 2])
sizStr = locRenderSizeString(siz, true);
% Note the %%s used for a possibily another call to SPRINTF
string = sprintf('[%s%s w/ fields: %%s]', sizStr, 'struct');
if (length(string) > charLimit+8)
% >> rptgen.toString(aStructMultiDims, 10);
% [2x2 struct]
string = sprintf('[%s%s]', sizStr, 'struct');
else
% Construct list of fieldnames
f = rptgen.makeSingleLineText(fieldnames(value), ', ');
if (length(f) > charLimit - length(string))
f = f(1:charLimit-length(string));
if (length(f) < 3)
% >> rptgen.toString(aStructMultiDims, 20)
% [2x2 struct w/ fields: ...]
f = '...';
else
% >> rptgen.toString(aStructMultiDims, 40)
% [2x2 struct w/ fields: a, b, c, d,...]
f(end-2:end) = '...';
end
end
% Second SPRINTF. Note, string contains %%s.
string = sprintf(string, f);
end
end
% Replace carriage returns
string = strrep(string, newline, cr);
%-------------------------------------------------------------------------------
function string = locRenderCell(value, charLimit, cr)
siz = size(value);
nDims = length(siz);
isCollapse = false;
if isempty(value)
% >> rptgen.toString({''})
string = '{}';
elseif (nDims < 3)
% 3d or N-d array - always collapse
% >> a = cell(2,2);
% >> a{1,1} = 11;
% >> a{1,2} = '1,2';
% >> a{2,1} = 21;
% >> a{2,2} = '2,2';
% >> rptgen.toString(a)
% >> rptgen.toString(a, 5)
string = '{';
for i = 1:siz(1)
j = 1;
sLength = length(string);
while (j <= siz(2)) && ~isCollapse
% Pass in a character limit roughly corresponding to the percentage
% of cells we have left to go
pctCharLimit = (charLimit-sLength)/((i-1)*siz(2)+j);
string = [ string ...
' ' ...
rptgen.toString(value{i,j}, pctCharLimit, ' ') ...
' ,' ]; %#ok
j = j+1;
sLength = length(string);
isCollapse = ~(sLength <= charLimit);
end
string(end) = ';';
% NOTE* Below was 'string(end+1)=cr;', but this fails when value is not a string
string = [string cr]; %#ok
end
string(end-1) = '}';
string(end) = [];
else
% 3d or N-d array - always collapse
% >> a = cell(2,2);
% >> a{1,1} = 11;
% >> a{1,2} = '1,2';
% >> a{2,1} = 21;
% >> a{2,2} = '2,2';
% rptgen.toString(repmat(a,[2 2 2]))
isCollapse = true;
end
if isCollapse
string = sprintf('[%s cell]', locRenderSizeString(siz));
end
%-------------------------------------------------------------------------------
function string = locRenderStringArray(value, charLimit, cr)
value = num2cell(value);
siz = size(value);
nDims = length(siz);
isCollapse = false;
if isempty(value)
% >> rptgen.toString({''})
string = '[]';
elseif (nDims < 3)
% 3d or N-d array - always collapse
% >> a = ["a","b";"c";"d"];
% >> rptgen.toString(a)
% >> rptgen.toString(a, 5)
string = '[';
for i = 1:siz(1)
j = 1;
sLength = length(string);
while (j <= siz(2)) && ~isCollapse
% Pass in a character limit roughly corresponding to the percentage
% of cells we have left to go
pctCharLimit = (charLimit-sLength)/((i-1)*siz(2)+j);
if i > 1
leftQuote = ' "';
else
leftQuote = '"';
end
string = [ string ...
leftQuote ...
rptgen.toString(value{i,j}, pctCharLimit) ...
'",' ]; %#ok
j = j+1;
sLength = length(string);
isCollapse = ~(sLength <= charLimit);
end
string(end) = ';';
% NOTE* Below was 'string(end+1)=cr;', but this fails when value is not a string
string = [string cr]; %#ok
end
string(end-1) = ']';
string(end) = [];
else
% 3d or N-d array - always collapse
% >> a = ["a","b";"c";"d"];
% rptgen.toString(repmat(a,[2 2 2]))
isCollapse = true;
end
if isCollapse
string = sprintf('[%s string array]', locRenderSizeString(siz));
end
%-------------------------------------------------------------------------------
function string = locRenderViaDISP(value, charLimit, cr)
% value called by EVALC
try
string = evalc('disp(value)');
% Eliminate leading and trailing \n's
string = regexprep(string, '^\n+|\n+$', '');
% Replace carriage returns
string = strrep(string, newline, cr);
forceCollapse = false;
catch ex %#ok<NASGU>
forceCollapse = true;
end
if (forceCollapse || (length(string) > charLimit))
siz = size(value);
string = sprintf('[%s%s]', locRenderSizeString(siz), class(value));
end
%-------------------------------------------------------------------------------
function string = locRenderNumeric(value, charLimit, cr)
siz = size(value);
nElem = prod(siz);
nDims = length(siz);
% Get typical string length for a given display format
dispFormat = get(0, 'Format');
switch dispFormat(1)
case 'b'
% >> format bank
typNumStrLen = 4;
precision = 2;
case 'l'
% >> format long
typNumStrLen = 17;
precision = 7;
otherwise
% >> format short
typNumStrLen = 6;
precision = [];
end
if ((nDims > 2) || (nElem*typNumStrLen > charLimit))
% Show in collapse form
% >> rptgen.toString(rand(100), 100)
% [100x100 double]
string = sprintf('<%s%s>', locRenderSizeString(siz), class(value));
elseif (nElem == 1)
% Obey current FORMAT setting by using DISP
% >> aNumber = int16(255);
% >> format hex
% >> rptgen.toString(aNumber);
string = strtrim(locRenderViaDISP(value, charLimit, cr));
elseif (nElem == 0)
% >> rptgen.toString(zeros(0));
string = '[]';
else
% Can not use DISP to get the correct display format because DISP depends
% on the size of the command window. Use NUM2STR instead.
% NUM2STR works best a FULL matrix (not sparse)
% >> aNumber = zeros(5);
% >> aSparse = sparse(aNumber);
% >> rptgen.toString(aSparse)
% [0 0 ;
% 0 0 ]
% NOTE: This does not work with FORMAT not defined above.
% g947514: Cast value to double to ensure that num2str works with all
% numeric types, including fixed-point (fi) types.
if isinteger(value) || isempty(precision)
% >> format short
% >> rptgen.toString([1 2 3]) % test empty precision
string = num2str(double(full(value)));
else
string = num2str(double(full(value)), precision);
end
brackets = '[]';
% Blank columns are the leading and trailing two columns beform the CR
blankColumn = blanks(size(string,1))';
% Second to last column
semicolonColumn = ';';
semicolonColumn = semicolonColumn(ones(size(string,1),1));
% Last column, carriage return (CR) column
crColumn = cr(ones(size(string,1),1));
% Construct output
string = [blankColumn, string, blankColumn, semicolonColumn, crColumn];
string(1,1) = brackets(1);
string(end,end-1) = brackets(2);
string(end,end) = ' ';
% Make sure that out is single-line for concatenating w/ others
string = string';
string = string(:)';
% Make sure there are no zeros in the string
string(string == 0) = ' ';
end
%-------------------------------------------------------------------------------
function string = locRenderChar(value, charLimit, cr)
siz = size(value);
nElem = prod(siz);
nDims = length(siz);
if (nDims > 2) || (nElem > charLimit)
% Multi-dimension text & extremely long text
% >> rptgen.toString(repmat('adsfasdf',[3 3 3]))
% >> rptgen.toString('adsfasdf', 2)
string = sprintf('[%schar]',locRenderSizeString(siz));
elseif (nDims > 1)
% Multiline text
% >> rptgen.toString(repmat('ab',[2 2]))
string = rptgen.makeSingleLineText(value, cr);
else
% Single line text
% >> rptgen.toString('abc')
string = v;
end
%-------------------------------------------------------------------------------
function string = locRenderCellStr(value, charLimit, cr, objType)
siz = size(value);
nDims = length(siz);
if (nargin < 4)
objType = 'cellstr';
end
if (nDims < 3) && (min(siz) == 1)
% Handles [nx1] and [1xn] cell array dimensions
% >> a = cell(1,2)
% >> a{1,1} = '1,1'
% >> a{1,2} = '1,2'
% >> rptgen.toString(a)
string = rptgen.makeSingleLineText(value, cr);
if (length(string) > charLimit)
string = sprintf('[%s %s]', locRenderSizeString(siz), objType);
end
else
% Handles [nxm] cell array dimensions, ie [2x2]
% >> a = cell(2,2)
% >> a{1,1} = '1,1'
% >> a{1,2} = '1,2'
% >> a{2,1} = '2,1'
% >> a{2,2} = '2,2'
% >> rptgen.toString(a)
string = locRenderCell(value, charLimit, cr);
end
%-------------------------------------------------------------------------------
function string = locRenderDAObject(value, charLimit, cr)
% >> a = handle(1);
% >> for i = 1:100
% >> a(i) = rptgen.cfr_text
% >> end
% >> rptgen.toString(a,inf)
% >> rptgen.toString(a)
value = value(:);
vLen = length(value);
cellStr = cell(1, vLen);
for i = 1:vLen
cellStr{i} = getDisplayLabel(value(i));
end
string = locRenderCellStr(cellStr, charLimit, cr, 'DAStudio.Object');
%-------------------------------------------------------------------------------
function string = locRenderMCOSObject(value)
sz = size(value);
szStr = locRenderSizeString(sz, true);
string = sprintf('<%s %s>', szStr, class(value));
%-------------------------------------------------------------------------------
function [charLimit, cr] = locParseInputArgs(varargin)
if (nargin == 2)
charLimit = floor(varargin{1});
cr = varargin{2};
elseif (nargin == 1)
charLimit = floor(varargin{1});
cr = newline;
else % nargin == 0
charLimit = inf;
cr = newline;
end
if (charLimit <= 0)
charLimit = inf;
end
|
github
|
Brain-Modulation-Lab/bml-master
|
bml_getidx.m
|
.m
|
bml-master/utils/bml_getidx.m
| 1,222 |
utf_8
|
76d9bb4c7bf96f74e77d1ddcf0a1115f
|
function idx = bml_getidx(element,collection)
% BML_GETIDX gets the first indices of the elements in the collection (or domain)
%
% Use as
% idx = bml_getidx(element,collection)
%
% index 0 for elements not found
%
% Use as
% index = bml_get_index(element,collection)
%
% elements - array or cell
% domain - collection of elements from where to extract the index
%
% returns an array of natural indices
if ischar(element)
element = {element};
end
if iscellstr(element)
assert(iscellstr(collection),'incompatible elements and collection');
idx = cellfun(@(x) zero_if_empty(find(strcmp(collection,x),1)),element,'UniformOutput',true);
elseif iscell(element)
assert(iscell(collection),'incompatible elements and collection');
idx = cellfun(@(x) zero_if_empty(find(collection==x,1)),element,'UniformOutput',true);
elseif isnumeric(element)
assert(isnumeric(collection),'incompatible elements and collection');
idx = arrayfun(@(x) zero_if_empty(find(collection==x,1)),element);
else
error('unknown type for element');
end
if size(idx,1) > size(idx,2)
idx = idx';
end
end
function y = zero_if_empty(x)
if isempty(x)
y = 0;
else
y = x;
end
end
|
github
|
Brain-Modulation-Lab/bml-master
|
linspecer.m
|
.m
|
bml-master/utils/linspecer.m
| 8,162 |
utf_8
|
13346085b958ab6ff2bd20616dfa4473
|
% function lineStyles = linspecer(N)
% This function creates an Nx3 array of N [R B G] colors
% These can be used to plot lots of lines with distinguishable and nice
% looking colors.
%
% lineStyles = linspecer(N); makes N colors for you to use: lineStyles(ii,:)
%
% colormap(linspecer); set your colormap to have easily distinguishable
% colors and a pleasing aesthetic
%
% lineStyles = linspecer(N,'qualitative'); forces the colors to all be distinguishable (up to 12)
% lineStyles = linspecer(N,'sequential'); forces the colors to vary along a spectrum
%
% % Examples demonstrating the colors.
%
% LINE COLORS
% N=6;
% X = linspace(0,pi*3,1000);
% Y = bsxfun(@(x,n)sin(x+2*n*pi/N), X.', 1:N);
% C = linspecer(N);
% axes('NextPlot','replacechildren', 'ColorOrder',C);
% plot(X,Y,'linewidth',5)
% ylim([-1.1 1.1]);
%
% SIMPLER LINE COLOR EXAMPLE
% N = 6; X = linspace(0,pi*3,1000);
% C = linspecer(N)
% hold off;
% for ii=1:N
% Y = sin(X+2*ii*pi/N);
% plot(X,Y,'color',C(ii,:),'linewidth',3);
% hold on;
% end
%
% COLORMAP EXAMPLE
% A = rand(15);
% figure; imagesc(A); % default colormap
% figure; imagesc(A); colormap(linspecer); % linspecer colormap
%
% See also NDHIST, NHIST, PLOT, COLORMAP, 43700-cubehelix-colormaps
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% by Jonathan Lansey, March 2009-2013 ? Lansey at gmail.com %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%% credits and where the function came from
% The colors are largely taken from:
% http://colorbrewer2.org and Cynthia Brewer, Mark Harrower and The Pennsylvania State University
%
%
% She studied this from a phsychometric perspective and crafted the colors
% beautifully.
%
% I made choices from the many there to decide the nicest once for plotting
% lines in Matlab. I also made a small change to one of the colors I
% thought was a bit too bright. In addition some interpolation is going on
% for the sequential line styles.
%
%
%%
function lineStyles=linspecer(N,varargin)
if nargin==0 % return a colormap
lineStyles = linspecer(128);
return;
end
if ischar(N)
lineStyles = linspecer(128,N);
return;
end
if N<=0 % its empty, nothing else to do here
lineStyles=[];
return;
end
% interperet varagin
qualFlag = 0;
colorblindFlag = 0;
if ~isempty(varargin)>0 % you set a parameter?
switch lower(varargin{1})
case {'qualitative','qua'}
if N>12 % go home, you just can't get this.
warning('qualitiative is not possible for greater than 12 items, please reconsider');
else
if N>9
warning(['Default may be nicer for ' num2str(N) ' for clearer colors use: whitebg(''black''); ']);
end
end
qualFlag = 1;
case {'sequential','seq'}
lineStyles = colorm(N);
return;
case {'white','whitefade'}
lineStyles = whiteFade(N);return;
case 'red'
lineStyles = whiteFade(N,'red');return;
case 'blue'
lineStyles = whiteFade(N,'blue');return;
case 'green'
lineStyles = whiteFade(N,'green');return;
case {'gray','grey'}
lineStyles = whiteFade(N,'gray');return;
case {'colorblind'}
colorblindFlag = 1;
otherwise
warning(['parameter ''' varargin{1} ''' not recognized']);
end
end
% *.95
% predefine some colormaps
set3 = colorBrew2mat({[141, 211, 199];[ 255, 237, 111];[ 190, 186, 218];[ 251, 128, 114];[ 128, 177, 211];[ 253, 180, 98];[ 179, 222, 105];[ 188, 128, 189];[ 217, 217, 217];[ 204, 235, 197];[ 252, 205, 229];[ 255, 255, 179]}');
set1JL = brighten(colorBrew2mat({[228, 26, 28];[ 55, 126, 184]; [ 77, 175, 74];[ 255, 127, 0];[ 255, 237, 111]*.85;[ 166, 86, 40];[ 247, 129, 191];[ 153, 153, 153];[ 152, 78, 163]}'));
set1 = brighten(colorBrew2mat({[ 55, 126, 184]*.85;[228, 26, 28];[ 77, 175, 74];[ 255, 127, 0];[ 152, 78, 163]}),.8);
% colorblindSet = {[215,25,28];[253,174,97];[171,217,233];[44,123,182]};
colorblindSet = {[215,25,28];[253,174,97];[171,217,233]*.8;[44,123,182]*.8};
set3 = dim(set3,.93);
if colorblindFlag
switch N
% sorry about this line folks. kind of legacy here because I used to
% use individual 1x3 cells instead of nx3 arrays
case 4
lineStyles = colorBrew2mat(colorblindSet);
otherwise
colorblindFlag = false;
warning('sorry unsupported colorblind set for this number, using regular types');
end
end
if ~colorblindFlag
switch N
case 1
lineStyles = { [ 55, 126, 184]/255};
case {2, 3, 4, 5 }
lineStyles = set1(1:N);
case {6 , 7, 8, 9}
lineStyles = set1JL(1:N)';
case {10, 11, 12}
if qualFlag % force qualitative graphs
lineStyles = set3(1:N)';
else % 10 is a good number to start with the sequential ones.
lineStyles = cmap2linspecer(colorm(N));
end
otherwise % any old case where I need a quick job done.
lineStyles = cmap2linspecer(colorm(N));
end
end
lineStyles = cell2mat(lineStyles);
end
% extra functions
function varIn = colorBrew2mat(varIn)
for ii=1:length(varIn) % just divide by 255
varIn{ii}=varIn{ii}/255;
end
end
function varIn = brighten(varIn,varargin) % increase the brightness
if isempty(varargin),
frac = .9;
else
frac = varargin{1};
end
for ii=1:length(varIn)
varIn{ii}=varIn{ii}*frac+(1-frac);
end
end
function varIn = dim(varIn,f)
for ii=1:length(varIn)
varIn{ii} = f*varIn{ii};
end
end
function vOut = cmap2linspecer(vIn) % changes the format from a double array to a cell array with the right format
vOut = cell(size(vIn,1),1);
for ii=1:size(vIn,1)
vOut{ii} = vIn(ii,:);
end
end
%%
% colorm returns a colormap which is really good for creating informative
% heatmap style figures.
% No particular color stands out and it doesn't do too badly for colorblind people either.
% It works by interpolating the data from the
% 'spectral' setting on http://colorbrewer2.org/ set to 11 colors
% It is modified a little to make the brightest yellow a little less bright.
function cmap = colorm(varargin)
n = 100;
if ~isempty(varargin)
n = varargin{1};
end
if n==1
cmap = [0.2005 0.5593 0.7380];
return;
end
if n==2
cmap = [0.2005 0.5593 0.7380;
0.9684 0.4799 0.2723];
return;
end
frac=.95; % Slight modification from colorbrewer here to make the yellows in the center just a bit darker
cmapp = [158, 1, 66; 213, 62, 79; 244, 109, 67; 253, 174, 97; 254, 224, 139; 255*frac, 255*frac, 191*frac; 230, 245, 152; 171, 221, 164; 102, 194, 165; 50, 136, 189; 94, 79, 162];
x = linspace(1,n,size(cmapp,1));
xi = 1:n;
cmap = zeros(n,3);
for ii=1:3
cmap(:,ii) = pchip(x,cmapp(:,ii),xi);
end
cmap = flipud(cmap/255);
end
function cmap = whiteFade(varargin)
n = 100;
if nargin>0
n = varargin{1};
end
thisColor = 'blue';
if nargin>1
thisColor = varargin{2};
end
switch thisColor
case {'gray','grey'}
cmapp = [255,255,255;240,240,240;217,217,217;189,189,189;150,150,150;115,115,115;82,82,82;37,37,37;0,0,0];
case 'green'
cmapp = [247,252,245;229,245,224;199,233,192;161,217,155;116,196,118;65,171,93;35,139,69;0,109,44;0,68,27];
case 'blue'
cmapp = [247,251,255;222,235,247;198,219,239;158,202,225;107,174,214;66,146,198;33,113,181;8,81,156;8,48,107];
case 'red'
cmapp = [255,245,240;254,224,210;252,187,161;252,146,114;251,106,74;239,59,44;203,24,29;165,15,21;103,0,13];
otherwise
warning(['sorry your color argument ' thisColor ' was not recognized']);
end
cmap = interpomap(n,cmapp);
end
% Eat a approximate colormap, then interpolate the rest of it up.
function cmap = interpomap(n,cmapp)
x = linspace(1,n,size(cmapp,1));
xi = 1:n;
cmap = zeros(n,3);
for ii=1:3
cmap(:,ii) = pchip(x,cmapp(:,ii),xi);
end
cmap = (cmap/255); % flipud??
end
|
github
|
Brain-Modulation-Lab/bml-master
|
checkstrs.m
|
.m
|
bml-master/utils/checkstrs.m
| 3,194 |
utf_8
|
ef0e640d970917243b1b5d2587c626ca
|
function out = checkstrs(in, valid_strings, function_name, ...
variable_name, argument_position)
%CHECKSTRS Check validity of option string.
% OUT = CHECKSTRS(IN,VALID_STRINGS,FUNCTION_NAME,VARIABLE_NAME, ...
% ARGUMENT_POSITION) checks the validity of the option string IN. It
% returns the matching string in VALID_STRINGS in OUT. CHECKSTRS looks
% for a case-insensitive nonambiguous match between IN and the strings
% in VALID_STRINGS.
%
% VALID_STRINGS is a cell array containing strings.
%
% FUNCTION_NAME is a string containing the function name to be used in the
% formatted error message.
%
% VARIABLE_NAME is a string containing the documented variable name to be
% used in the formatted error message.
%
% ARGUMENT_POSITION is a positive integer indicating which input argument
% is being checked; it is also used in the formatted error message.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.3.4.4 $ $Date: 2003/05/03 17:51:45 $
% Except for IN, input arguments are not checked for validity.
% checkinput(in, 'char', 'row', function_name, variable_name, argument_position);
start = regexpi(valid_strings, ['^' in]);
if ~iscell(start)
start = {start};
end
matches = ~cellfun('isempty',start);
idx = find(matches);
num_matches = length(idx);
if num_matches == 1
out = valid_strings{idx};
else
out = substringMatch(valid_strings(idx));
if isempty(out)
% Convert valid_strings to a single string containing a space-separated list
% of valid strings.
list = '';
for k = 1:length(valid_strings)
list = [list ', ' valid_strings{k}];
end
list(1:2) = [];
msg1 = sprintf('Function %s expected its %s input argument, %s,', ...
upper(function_name), num2ordinal(argument_position), ...
variable_name);
msg2 = 'to match one of these strings:';
if num_matches == 0
msg3 = sprintf('The input, ''%s'', did not match any of the valid strings.', in);
id = sprintf('Images:%s:unrecognizedStringChoice', function_name);
else
msg3 = sprintf('The input, ''%s'', matched more than one valid string.', in);
id = sprintf('Images:%s:ambiguousStringChoice', function_name);
end
error(id,'%s\n%s\n\n %s\n\n%s', msg1, msg2, list, msg3);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function str = substringMatch(strings)
% STR = substringMatch(STRINGS) looks at STRINGS (a cell array of
% strings) to see whether the shortest string is a proper substring of
% all the other strings. If it is, then substringMatch returns the
% shortest string; otherwise, it returns the empty string.
if isempty(strings)
str = '';
else
len = cellfun('prodofsize',strings);
[tmp,sortIdx] = sort(len);
strings = strings(sortIdx);
start = regexpi(strings(2:end), ['^' strings{1}]);
if isempty(start) || (iscell(start) && any(cellfun('isempty',start)))
str = '';
else
str = strings{1};
end
end
|
github
|
Brain-Modulation-Lab/bml-master
|
bml_compute_ISI.m
|
.m
|
bml-master/spksunit/bml_compute_ISI.m
| 623 |
utf_8
|
b9abb334f0f85327c343fde18039b1ba
|
function [isits] = bml_compute_ISI(D, fs,ISIFILTER)
%BML_COMPUTE_INSTANTISI Summary of this function goes here
% Author: Witek Lipski
I = isi(D);
isits = zeros(size(D));
k = find(D);
for i=1:length(I)
isits(k(i):(k(i)+I(i))) = I(i);
end
isits = isits/fs;
isits = movmean(isits,[ISIFILTER, ISIFILTER]);
end
% helper function isi
function I = isi(D)
spike_samples = find(D~=0);
if length(spike_samples) < 2
disp('ISI aborting: Not enough spikes in D.');
else
I = zeros(length(spike_samples)-1,1);
for i = 1:length(spike_samples)-1
I(i) = spike_samples(i+1)-spike_samples(i);
end
end
end
|
github
|
Brain-Modulation-Lab/bml-master
|
bml_compute_Spikelocked_clusterperm.m
|
.m
|
bml-master/spksunit/bml_compute_Spikelocked_clusterperm.m
| 6,726 |
utf_8
|
bac42a07dc26d8ab9ea3c067c41876bb
|
function Stim = bml_compute_Spikelocked_clusterperm( spkSampRate, IFR,ISITS,D, n_trials, basetimes, trialtimes, respInterval,alpha,minTsig,n_btsp)
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
Stim.respInterval = respInterval;
Stim.DispInterval = -1: 1/spkSampRate : Stim.respInterval(2) + 1;
Stim.n_trials = n_trials;
Stim.spkSampRate = spkSampRate;
Stim.trial_nsamples = round(spkSampRate*diff(respInterval)) + 1;
% Baseline data (hard-coded to take one second back from basetimes)
Stim.base_samples = round(spkSampRate*basetimes);
Stim.base_nsamples = round(spkSampRate) + 1; % hard/coded baseline 1 s
% build baseline segments
Stim.IFRbase = cell2mat(arrayfun(@(x) IFR((Stim.base_samples(x)-spkSampRate):Stim.base_samples(x)), ...
1:n_trials, 'uniformoutput', false)');
Stim.ISITSbase = cell2mat(arrayfun(@(x) ISITS((Stim.base_samples(x)-spkSampRate):Stim.base_samples(x)), ...
1:n_trials, 'uniformoutput', false)');
Stim.FRbaseline = mean(Stim.IFRbase(:));
Stim.ISITSbaseline = mean(Stim.ISITSbase(:));
% Trial data
Stim.trial_samples = round(spkSampRate*trialtimes);
Stim.DD = cell2mat(arrayfun(@(x) ...
D((Stim.trial_samples(x)+round(spkSampRate*Stim.respInterval(1))): ...
(Stim.trial_samples(x)+round(spkSampRate*Stim.respInterval(2)))), ...
1:n_trials, 'uniformoutput', false)');
Stim.IFRdata = cell2mat(arrayfun(@(x) ...
IFR((Stim.trial_samples(x)+round(spkSampRate*Stim.respInterval(1))): ...
(Stim.trial_samples(x)+round(spkSampRate*Stim.respInterval(2)))), ...
1:n_trials, 'uniformoutput', false)');
Stim.ISITSdata = cell2mat(arrayfun(@(x) ...
ISITS((Stim.trial_samples(x)+round(spkSampRate*Stim.respInterval(1))): ...
(Stim.trial_samples(x)+round(spkSampRate*Stim.respInterval(2)))), ...
1:n_trials, 'uniformoutput', false)');
% Wilcoxon + ClusterBased perm test
Stim = do_clustermod(Stim,alpha,minTsig,n_btsp,"IFR");
Stim = do_clustermod(Stim,alpha,minTsig,n_btsp,"ISITS");
% try
% Stim = do_clustermod(Stim,alpha,minTsig,n_btsp,"IFR");
% Stim = do_clustermod(Stim,alpha,minTsig,n_btsp,"ISITS");
% catch
% warning("no enough samples")
% end
%
function Stim = do_clustermod(Stim,alpha,minTsig,n_btsp,flag_neural)
if contains(flag_neural,"IFR")
Y = Stim.IFRdata;
Y_baseline = Stim.IFRbase;
elseif contains(flag_neural,"ISITS")
Y = Stim.ISITSdata;
Y_baseline = Stim.ISITSbase;
end
[pstats,~,stats] = arrayfun(@(x) signrank(Y(:,x),mean(Y_baseline,2,'omitnan'),"method","approximate"),1:Stim.trial_nsamples);
zstats = [stats.zval];
Stim.Zscore = zstats;
Psig = bwconncomp(pstats < alpha);
n_clusters = Psig.NumObjects;
zcluster = cellfun(@(x) sum(zstats(x)),Psig.PixelIdxList);
zclust_btsp = [];
data_all = [Y_baseline Y];
nsamples_all = size(data_all,2);
for btsp_i = 1 : n_btsp
if mod(btsp_i,100) == 0
fprintf("launching btsp %d/%d \n",btsp_i,n_btsp)
end
base_id = zeros(Stim.n_trials,Stim.base_nsamples);
trial_id = zeros(Stim.n_trials,Stim.trial_nsamples);
% trial-wise permutation
for trial_i = 1 : Stim.n_trials
base_id(trial_i,:) = randperm(nsamples_all,Stim.base_nsamples);
trial_id(trial_i,:) = setdiff(1:nsamples_all,base_id(trial_i,:));
end
data_btsp = data_all(trial_id);
base_btsp = mean(data_all(base_id),2,'omitnan');
[pstats_btsp,~,stats_btsp] = arrayfun(@(x) ranksum(data_btsp(~ismissing(data_btsp(:,x)),x),base_btsp),1:Stim.trial_nsamples);
zstats_btsp = [stats_btsp.zval];
Psig_btsp = bwconncomp(pstats_btsp < 0.05);
zclust_btsp = [zclust_btsp cellfun(@(x) sum(zstats_btsp(x)),Psig_btsp.PixelIdxList)];
end
%% check properties of significant periods
sign_mod_length = cellfun(@(x) numel(x)/Stim.spkSampRate,Psig.PixelIdxList);
if n_clusters > 0
% figure("renderer","painters")
% h = histogram(zclust_btsp,'facecolor','k');
% hold on
for cluster_i = 1 : n_clusters
if contains(flag_neural,"IFR")
Stim.IFRmod(cluster_i).Zclust = zcluster(cluster_i);
Stim.IFRmod(cluster_i).Zlength = sign_mod_length(cluster_i);
Stim.IFRmod(cluster_i).Zlength_enough = sign_mod_length(cluster_i) >= minTsig/1000;
Stim.IFRmod(cluster_i).Pbtsp = mean(zclust_btsp>= zcluster(cluster_i));
Stim.IFRmod(cluster_i).Zflag = Stim.IFRmod(cluster_i).Pbtsp < 0.05;
Stim.IFRmod(cluster_i).tbins = Psig.PixelIdxList{cluster_i};
elseif contains(flag_neural,"ISITS")
Stim.ISITSmod(cluster_i).Zclust = zcluster(cluster_i);
Stim.ISITSmod(cluster_i).Zlength = sign_mod_length(cluster_i);
Stim.ISITSmod(cluster_i).Zlength_enough = sign_mod_length(cluster_i) >= minTsig/1000;
Stim.ISITSmod(cluster_i).Pbtsp = mean(zclust_btsp >= zcluster(cluster_i));
Stim.ISITSmod(cluster_i).Zflag = Stim.ISITSmod(cluster_i).Pbtsp < 0.05;
Stim.ISITSmod(cluster_i).tbins = Psig.PixelIdxList{cluster_i};
end
%text(zcluster(plot_i),max(h.Values) + .05*max(h.Values),sprintf("P_{Z_{%d}} = %1.3f",plot_i,Stim.IFRmod(plot_i).Pbtsp))
% if zcluster(plot_i) < 0
% plot([zcluster(plot_i) zcluster(plot_i)],[0 max(h.Values)],'b--','linewidth',1.4)
%
% else
% plot([zcluster(plot_i) zcluster(plot_i)],[0 max(h.Values)],'r--','linewidth',1.4)
% end
end
% xlabel("Cluster-wise Z")
% ylabel("count")
% plot([prctile(zclust_btsp,2.5) prctile(zclust_btsp,2.5)], [0 max(h.Values)],'k--','linewidth',1.4)
% plot([prctile(zclust_btsp,97.5) prctile(zclust_btsp,97.5)], [0 max(h.Values)],'k--','linewidth',1.4)
% box off
% disp("displaying and saving figure...")
% saveas(gcf,figname,"png")
% saveas(gcf,figname,"pdf")
% saveas(gcf,figname,"eps")
% close gcf
end
end
end
|
github
|
Brain-Modulation-Lab/bml-master
|
bml_fdr_bh.m
|
.m
|
bml-master/stat/bml_fdr_bh.m
| 8,817 |
utf_8
|
4231e2545caae52ffd58f9a2a2564bcd
|
% fdr_bh() - Executes the Benjamini & Hochberg (1995) and the Benjamini &
% Yekutieli (2001) procedure for controlling the false discovery
% rate (FDR) of a family of hypothesis tests. FDR is the expected
% proportion of rejected hypotheses that are mistakenly rejected
% (i.e., the null hypothesis is actually true for those tests).
% FDR is a somewhat less conservative/more powerful method for
% correcting for multiple comparisons than procedures like Bonferroni
% correction that provide strong control of the family-wise
% error rate (i.e., the probability that one or more null
% hypotheses are mistakenly rejected).
%
% This function also returns the false coverage-statement rate
% (FCR)-adjusted selected confidence interval coverage (i.e.,
% the coverage needed to construct multiple comparison corrected
% confidence intervals that correspond to the FDR-adjusted p-values).
%
%
% Usage:
% >> [h, crit_p, adj_ci_cvrg, adj_p]=fdr_bh(pvals,q,method,report);
%
% Required Input:
% pvals - A vector or matrix (two dimensions or more) containing the
% p-value of each individual test in a family of tests.
%
% Optional Inputs:
% q - The desired false discovery rate. {default: 0.05}
% method - ['pdep' or 'dep'] If 'pdep,' the original Bejnamini & Hochberg
% FDR procedure is used, which is guaranteed to be accurate if
% the individual tests are independent or positively dependent
% (e.g., Gaussian variables that are positively correlated or
% independent). If 'dep,' the FDR procedure
% described in Benjamini & Yekutieli (2001) that is guaranteed
% to be accurate for any test dependency structure (e.g.,
% Gaussian variables with any covariance matrix) is used. 'dep'
% is always appropriate to use but is less powerful than 'pdep.'
% {default: 'pdep'}
% report - ['yes' or 'no'] If 'yes', a brief summary of FDR results are
% output to the MATLAB command line {default: 'no'}
%
%
% Outputs:
% h - A binary vector or matrix of the same size as the input "pvals."
% If the ith element of h is 1, then the test that produced the
% ith p-value in pvals is significant (i.e., the null hypothesis
% of the test is rejected).
% crit_p - All uncorrected p-values less than or equal to crit_p are
% significant (i.e., their null hypotheses are rejected). If
% no p-values are significant, crit_p=0.
% adj_ci_cvrg - The FCR-adjusted BH- or BY-selected
% confidence interval coverage. For any p-values that
% are significant after FDR adjustment, this gives you the
% proportion of coverage (e.g., 0.99) you should use when generating
% confidence intervals for those parameters. In other words,
% this allows you to correct your confidence intervals for
% multiple comparisons. You can NOT obtain confidence intervals
% for non-significant p-values. The adjusted confidence intervals
% guarantee that the expected FCR is less than or equal to q
% if using the appropriate FDR control algorithm for the
% dependency structure of your data (Benjamini & Yekutieli, 2005).
% FCR (i.e., false coverage-statement rate) is the proportion
% of confidence intervals you construct
% that miss the true value of the parameter. adj_ci=NaN if no
% p-values are significant after adjustment.
% adj_p - All adjusted p-values less than or equal to q are significant
% (i.e., their null hypotheses are rejected). Note, adjusted
% p-values can be greater than 1.
%
%
% References:
% Benjamini, Y. & Hochberg, Y. (1995) Controlling the false discovery
% rate: A practical and powerful approach to multiple testing. Journal
% of the Royal Statistical Society, Series B (Methodological). 57(1),
% 289-300.
%
% Benjamini, Y. & Yekutieli, D. (2001) The control of the false discovery
% rate in multiple testing under dependency. The Annals of Statistics.
% 29(4), 1165-1188.
%
% Benjamini, Y., & Yekutieli, D. (2005). False discovery rate?adjusted
% multiple confidence intervals for selected parameters. Journal of the
% American Statistical Association, 100(469), 71?81. doi:10.1198/016214504000001907
%
%
% Example:
% nullVars=randn(12,15);
% [~, p_null]=ttest(nullVars); %15 tests where the null hypothesis
% %is true
% effectVars=randn(12,5)+1;
% [~, p_effect]=ttest(effectVars); %5 tests where the null
% %hypothesis is false
% [h, crit_p, adj_ci_cvrg, adj_p]=fdr_bh([p_null p_effect],.05,'pdep','yes');
% data=[nullVars effectVars];
% fcr_adj_cis=NaN*zeros(2,20); %initialize confidence interval bounds to NaN
% if ~isnan(adj_ci_cvrg),
% sigIds=find(h);
% fcr_adj_cis(:,sigIds)=tCIs(data(:,sigIds),adj_ci_cvrg); % tCIs.m is available on the
% %Mathworks File Exchagne
% end
%
%
% For a review of false discovery rate control and other contemporary
% techniques for correcting for multiple comparisons see:
%
% Groppe, D.M., Urbach, T.P., & Kutas, M. (2011) Mass univariate analysis
% of event-related brain potentials/fields I: A critical tutorial review.
% Psychophysiology, 48(12) pp. 1711-1725, DOI: 10.1111/j.1469-8986.2011.01273.x
% http://www.cogsci.ucsd.edu/~dgroppe/PUBLICATIONS/mass_uni_preprint1.pdf
%
%
% For a review of FCR-adjusted confidence intervals (CIs) and other techniques
% for adjusting CIs for multiple comparisons see:
%
% Groppe, D.M. (in press) Combating the scientific decline effect with
% confidence (intervals). Psychophysiology.
% http://biorxiv.org/content/biorxiv/early/2015/12/10/034074.full.pdf
%
%
% Author:
% David M. Groppe
% Kutaslab
% Dept. of Cognitive Science
% University of California, San Diego
% March 24, 2010
%%%%%%%%%%%%%%%% REVISION LOG %%%%%%%%%%%%%%%%%
%
% 5/7/2010-Added FDR adjusted p-values
% 5/14/2013- D.H.J. Poot, Erasmus MC, improved run-time complexity
% 10/2015- Now returns FCR adjusted confidence intervals
function [h, crit_p, adj_ci_cvrg, adj_p]=bml_fdr_bh(pvals,q,method,report)
if nargin<1,
error('You need to provide a vector or matrix of p-values.');
else
if ~isempty(find(pvals<0,1)),
error('Some p-values are less than 0.');
elseif ~isempty(find(pvals>1,1)),
error('Some p-values are greater than 1.');
end
end
if nargin<2,
q=.05;
end
if nargin<3,
method='pdep';
end
if nargin<4,
report='no';
end
s=size(pvals);
if (length(s)>2) || s(1)>1,
[p_sorted, sort_ids]=sort(reshape(pvals,1,prod(s)));
else
%p-values are already a row vector
[p_sorted, sort_ids]=sort(pvals);
end
[dummy, unsort_ids]=sort(sort_ids); %indexes to return p_sorted to pvals order
m=length(p_sorted); %number of tests
if strcmpi(method,'pdep'),
%BH procedure for independence or positive dependence
thresh=(1:m)*q/m;
wtd_p=m*p_sorted./(1:m);
elseif strcmpi(method,'dep')
%BH procedure for any dependency structure
denom=m*sum(1./(1:m));
thresh=(1:m)*q/denom;
wtd_p=denom*p_sorted./[1:m];
%Note, it can produce adjusted p-values greater than 1!
%compute adjusted p-values
else
error('Argument ''method'' needs to be ''pdep'' or ''dep''.');
end
if nargout>3,
%compute adjusted p-values; This can be a bit computationally intensive
adj_p=zeros(1,m)*NaN;
[wtd_p_sorted, wtd_p_sindex] = sort( wtd_p );
nextfill = 1;
for k = 1 : m
if wtd_p_sindex(k)>=nextfill
adj_p(nextfill:wtd_p_sindex(k)) = wtd_p_sorted(k);
nextfill = wtd_p_sindex(k)+1;
if nextfill>m
break;
end;
end;
end;
adj_p=reshape(adj_p(unsort_ids),s);
end
rej=p_sorted<=thresh;
max_id=find(rej,1,'last'); %find greatest significant pvalue
if isempty(max_id),
crit_p=0;
h=pvals*0;
adj_ci_cvrg=NaN;
else
crit_p=p_sorted(max_id);
h=pvals<=crit_p;
adj_ci_cvrg=1-thresh(max_id);
end
if strcmpi(report,'yes'),
n_sig=sum(p_sorted<=crit_p);
if n_sig==1,
fprintf('Out of %d tests, %d is significant using a false discovery rate of %f.\n',m,n_sig,q);
else
fprintf('Out of %d tests, %d are significant using a false discovery rate of %f.\n',m,n_sig,q);
end
if strcmpi(method,'pdep'),
fprintf('FDR/FCR procedure used is guaranteed valid for independent or positively dependent tests.\n');
else
fprintf('FDR/FCR procedure used is guaranteed valid for independent or dependent tests.\n');
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.