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
|
BrainStormCenter/Psychometric-master
|
myregress.m
|
.m
|
Psychometric-master/myregress.m
| 2,565 |
utf_8
|
93be5fda7f4d4faaeca5c51dcfe72fdd
|
% myregress.m
%
% purpose: regression statistics
% usage: [d] = myregress(x, y, m1,dispfit)
% x = column vector of independent variable
% y = column vector of dependent variable
% m1 = slope to check difference of
% m = slope of regression line
% b = y-intercept
% r2 = coefficient of determination
% pm = p-value for slope
% pb = p-value for y-intercept
% by: justin gardner
% date: 9/3/98
function [d b r2 pm pb] = myregress(x, y,m1,dispfit)
if ((nargin <2) || (nargin > 4))
help myregress, return,
end
if (nargin <3)
m1 = 0;
end
if (nargin <4)
dispfit = 0;
end
if (dispfit == 1)
dispfit = 'k-';
end
% make into column vectors
if (size(x,1)==1),x=x';,end
if (size(y,1)==1),y=y';,end
% denan
goodvals = find(~isnan(x) & ~isnan(y));
x = x(goodvals);
y = y(goodvals);
n = length(x);
if (n <= 2)
d.b = nan;d.m = nan;d.r2 = nan;d.pm = nan;d.pb = nan;d.r = nan;
return
end
% precalculate sum terms
sumx = sum(x);
sumy = sum(y);
sumx2 = sum(x.^2);
sumy2 = sum(y.^2);
sumxy = sum(x.*y);
% use formulas to calculate slope and y-intercept
m = (n*sumxy-sumx*sumy)/(n*sumx2-sumx^2);
b = (sumy*sumx2 - sumx*sumxy)/(n*sumx2 - sumx^2);
% find least squares fit for a line of the form y = m*x + b
%A = x;
%A(:,2) = 1;
%coef = ((A'*A)^-1)*A'*y;
%m = coef(1);
%b = coef(2);
% calculate r^2
num = ((m*x + b) - y).^2;
denom = (y-mean(y)).^2;
r2 = 1 - (sum(num)/sum(denom));
% calculate standard error of the estimate
Sx = std(x);
Sy = std(y);
Syx = sqrt(((n-1)/(n-2))*(Sy^2-(m^2)*Sx^2));
% calculate standard error of the slope
Sm = (1/sqrt(n-1))*(Syx/Sx);
% calculate standard error of the y-intercept
Sb = Syx * sqrt((1/n) + (mean(x)^2)/((n-1)*Sx^2));
if (n <= 2), pm = -1;, pb = -1;, return;, end;
% calculate t-statistic and p-value for slope
% note, use incomplete beta function because
% matlab's tpdf function gives strange results.
Tm = (m-m1)/Sm;
if isnan(Tm)
pm = nan;
else
pm = betainc((n-2)/((n-2)+Tm^2),(n-2)/2,.5);
end
% calculate t-statistic and p-value for y-intercept
Tb = b/Sb;
pb = betainc((n-2)/((n-2)+Tb^2),(n-2)/2,.5);
% get all stats into structure
d.m = m;d.b = b;d.r2 = r2;d.pm = pm;d.pb = pb;
% Straight-forward of computing regression coefficient
%d.r = 0;
%for i = 1:n
% d.r = d.r+(x(i)-mean(x))*(y(i)-mean(y))
%end
%d.r = d.r/((n-1)*Sx*Sy);
% r is related to slope by:
d.r = d.m*Sx/Sy;
% plot the results on current axis
if (dispfit)
a = axis;
hold on
plot([a(1) a(2)],b+m*[a(1) a(2)],dispfit);
end
if nargout > 1
d = d.m;
end
|
github
|
BrainStormCenter/Psychometric-master
|
JC_FCcalc.m
|
.m
|
Psychometric-master/JC_FCcalc.m
| 4,861 |
utf_8
|
67c70b06521404774c4756de9cd5cbc1
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CREATED BY: JOCHEN WEBER
%
% CREATED ON: 2016-11-25
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% JC_FCcalc computes one map for each VOI-by-VTC combination, such that
% for each VOI in the VOI files list, a map is written out.
function JC_FCcalc(fcfiles, roifiles)
% JC_FCCALC Calculate functional connectivity maps
% JC_FCCALC(FCFILES, ROIFILES) calculates the functional connectivity
% between the mean of each ROI mask file (averaged across voxels) and
% the functional connectivity files in FCFILES.
%
% Note: the files MUST already be in the same space!
% requires CHAR or CELL input
if ischar(fcfiles)
fcfiles = cellstr(fcfiles);
elseif ~iscell(fcfiles)
error('JCfunc:calc:invalidArgument', 'Invalid FCFILES argument.');
end
fcfiles = fcfiles(:);
if ~all(cellfun(@ischar, fcfiles)) || any(cellfun('isempty', fcfiles)) || ...
any(cellfun('isempty', regexpi(fcfiles, '\.nii$'))) || ...
sum(cellfun(@exist, fcfiles)) ~= (2 * numel(fcfiles))
error('JCfunc:calc:invalidArgument', 'Invalid FCFILES argument.');
end
if ischar(roifiles)
roifiles = cellstr(roifiles);
elseif ~iscell(roifiles)
error('JCfunc:calc:invalidArgument', 'Invalid ROIFILES argument.');
end
roifiles = roifiles(:);
if ~all(cellfun(@ischar, roifiles)) || any(cellfun('isempty', roifiles)) || ...
any(cellfun('isempty', regexpi(roifiles, '\.nii$'))) || ...
sum(cellfun(@exist, roifiles)) ~= (2 * numel(roifiles))
error('JCfunc:calc:invalidArgument', 'Invalid FCFILES argument.');
end
% iterate over ROI files
roiinfo = cell(numel(roifiles), 4);
for fc = 1:numel(roifiles)
roivoi = spm_vol([roifiles{fc} ',1']);
roidata = spm_read_vols(roivoi);
roiinfo{fc, 1} = find(roidata(:) >= 0.5);
roiinfo{fc, 2} = roivoi.dim;
roiinfo{fc, 3} = roivoi.mat;
[roipath, roiinfo{fc, 4}] = fileparts(roifiles{fc});
end
if fc > 1 && (any(any(diff(cat(3, roiinfo{:, 2}), 1, 3), 3), 2) || ...
any(any(any(diff(cat(3, roiinfo{:, 3}), 1, 3), 1), 2)))
error('JCfunc:calc:invalidArgument', 'ROI files must match in space.');
end
% iterate over FC files
for fc = 1:numel(fcfiles)
% try
try
% for new filename
[fcpath, fcname] = fileparts(fcfiles{fc});
if isempty(fcpath)
fcpath = pwd;
end
% load file
fcvols = spm_vol(fcfiles{fc});
nvols = numel(fcvols);
if nvols < 20 || ~isequal(fcvols(1).dim, roiinfo{1, 2}) || ...
~isequal(fcvols(1).mat, roiinfo{1, 3})
warning('Jcfunc:calc:invalidFile', 'Bad FC file: %s', fcfiles{fc});
continue;
end
% load data
fcdata = spm_read_vols(fcvols);
% transpose
szdata = size(fcdata);
fcdata = reshape(fcdata, prod(szdata(1:3)), szdata(4));
udata = ~any(isinf(fcdata) | isnan(fcdata), 2) & any(fcdata ~= 0, 2);
% for each ROI
for rc = 1:numel(roifiles)
% update udata
mdata = false(size(udata));
mdata(roiinfo{rc, 1}) = true;
mdata = mdata & udata;
% don't compute if no good voxels for this ROI
if ~any(mdata(:))
rdata = reshape(NaN .* ones(size(mdata)), szdata(1:3));
% compute
else
rdata = ztrans(mean(fcdata(mdata(:), :))', 1);
rdata = reshape(atanh((1 / (nvols - 1)) .* ...
sum(fcdata * sparse(1:nvols, 1:nvols, rdata, nvols, nvols, nvols), 2)), ...
szdata(1:3));
end
% create volume
rvolname = [fcpath filesep 'z' fcname '_' roiinfo{rc, 4} '.nii'];
fprintf('Writing %s...\n', rvolname);
rvol = spm_create_vol( ...
struct('fname', rvolname, 'dim', szdata(1:3), 'dt', [64, 0], ...
'pinfo', [1; 0; 352], 'mat', roiinfo{1, 3}, 'n', [1, 1], ...
'descrip', sprintf('FC (%s:%s)', fcname, roiinfo{rc, 4})));
spm_write_vol(rvol, rdata);
end
% error handling
catch eobj
warning(eobj.identifier, eobj.message);
end
end
%% sub-functions
% ztrans (see @neuroelf/private/ztrans for comments)
function ztc = ztrans(tc, dim)
ts = size(tc);
td = ts(dim);
if dim == 1
tc = reshape(tc, ts(1), prod(ts(2:end)));
elseif dim > 2 || numel(ts) > 2
if dim == numel(ts)
tc = reshape(tc, prod(ts(1:dim-1)), td);
else
tc = reshape(tc, prod(ts(1:dim-1)), td, prod(ts(dim+1:end)));
end
dim = 2;
end
if dim == 1
sref = {ones(1, td), ':'};
elseif numel(ts) == 2
sref = {':', ones(1, td)};
else
sref = {':', ones(1, td), ':'};
end
zsh = sum(tc, dim) ./ td;
ztc = tc - zsh(sref{:});
zf = 1 ./ sqrt(sum((1 / (td - 1)) .* (ztc .* ztc), dim));
zf(isinf(zf) | isnan(zf)) = 0;
ztc = reshape(ztc .* zf(sref{:}), ts);
|
github
|
BrainStormCenter/Psychometric-master
|
s02_preprocessing.m
|
.m
|
Psychometric-master/automated_processing/s02_preprocessing.m
| 13,367 |
utf_8
|
ce0ca9eeba4a71fbc1137f1f9e1daa26
|
%
% CREATED BY: JOCHEN WEBER
% CREATED ON: 11/22/16
%
% MODIFIED BY: JASON CRAGGS
% MODIFIED ON: 2019-05-09
%
% MODIFIED BY: JACOB GOTBERG
% MODIFIED ON: 2019-03-02
%
% PURPOSE: PREPROCESS FMRI SCANS FOR ANALYSIS
%
% USAGE: matlab -r "prog 2_preprocessing.m dirname"
%
%'/storage/hpc/group/sleeplab/preprocessed/SPIN2_013_V1_unknown'
function []=s02_preprocessing(dirname)
disp("*** Starting 2_preprocessing ***")
fprintf("Pre Processing file %s\n", dirname)
% initialize SPM defaults and job manager
disp("Loading SPM12")
spm12path = '/storage/hpc/group/sleeplab/software/spm12';
addpath(spm12path)
spm('defaults','FMRI');
spm_jobman('initcfg');
clear matlabbatch;
disp("SPM12 Loaded")
% check SPM version
if ~strcmpi(spm('ver'), 'spm12')
error('spm:version:wrongSPMVersion', 'This script requires SPM12.');
end
% configure root path and subject pattern, as well as file patterns
anatpattern = 'SPIN2_*_t1_*.nii';
funcpattern = 'SPIN2_*_fMRI_*.nii';
% set variables, number of volumes and functional slices, TR
nvols = 120;
nslices = 36;
TR = 2.46;
% SLICE ACQUISITION ORDER IS INTERLEAVED BUT THE
% FIRST SLICE ACQUIRED IS SLICE #2; THEREFORE THE
% CORRECT SPM SPECIFICATION IS [2:2:42 1:2:42]
% slice aquisition order (interleaved bottom) and reference slice
if mod(nslices, 2) == 1
sliceorder = [1:2:nslices, 2:2:nslices];
else
sliceorder = [2:2:nslices, 1:2:nslices];
end
refslice = sliceorder(1);
% reslice voxel size and bounding box
wvox = 2;
wbbox = [-78, -112, -70; 78, 76, 85];
% smoothing kernel (EPI)
epismk = 6;
% compute TA
TA = TR - (TR / nslices);
% set primary path
cd(dirname);
% hard code to 5 per protocol at MRI machine
%runz = dir('*fMRI*');
numruns = 5; %size(runz, 1)
% gzip -d everything
gzipfiles = dir('*.gz');
if ~isempty(gzipfiles)
system('gzip -d *.gz');
end
% locate files
anatfile = dir(anatpattern);
funcfiles = dir(funcpattern);
if numel(anatfile) ~= 1 || numel(funcfiles) ~= numruns
warning('spm:prepro:invalidNumberOfFiles', ...
'Number of files incorrect for %s.', dirname);
return
end
if exist(['swa' funcfiles(end).name], 'file') == 2
fprintf('%s already preprocessed.\n', dirname);
return
end
% check number of slices
vol = spm_vol(funcfiles(1).name);
if vol(1).dim(3) ~= nslices
warning('spm:prepro:invalidNumberOfSlices', ...
'Number of slices mismatch for %s.', dirname);
return
end
% change filetype of functional data to float32 (reduce precision loss)
for fc = 1:numruns
vol = spm_vol(funcfiles(fc).name);
if vol(1).dt(1) == 16
continue;
end
fprintf('Converting %s in %s to float32...\n', funcfiles(fc).name, dirname);
voldata = spm_read_vols(vol);
[vol.dt] = deal([16, 0]);
for vc = 1:numel(vol)
vol(vc).pinfo(3) = vol(1).pinfo(3) + (vc - 1) * prod([4, vol(1).dim]);
end
delete(funcfiles(fc).name);
for vc = 1:numel(vol)
spm_write_vol(vol(vc), voldata(:, :, :, vc));
end
end
% smooth the structural
%matlabbatch{1}.spm.spatial.smooth.data = {'/storage/hpc/group/sleeplab/preprocessed/SPIN2_013_V1_unknown/SPIN2_013_t1_space_sag_p2_iso_s02.nii,1'};
anat_file = fullfile(dirname, anatfile.name);
file_to_smooth = strcat(anat_file, ",1");
anat = cellstr(file_to_smooth);
matlabbatch{1}.spm.spatial.smooth.data = anat;
matlabbatch{1}.spm.spatial.smooth.fwhm = [12 12 12];
matlabbatch{1}.spm.spatial.smooth.dtype = 0;
matlabbatch{1}.spm.spatial.smooth.im = 0;
matlabbatch{1}.spm.spatial.smooth.prefix = 's';
fprintf('Smoothing %s in %s...\n', anatfile.name, dirname);
spm_jobman('run', matlabbatch);
%spm_jobman('interactive',matlabbatch);
clear matlabbatch;
% coregister smoothed struct to old T1 template
sanat_file = fullfile(dirname, strcat("s",anatfile.name));
sanat = cellstr(sanat_file);
matlabbatch{1}.spm.spatial.coreg.estimate.ref = {[spm12path '/toolbox/OldNorm/T1.nii,1']};
matlabbatch{1}.spm.spatial.coreg.estimate.source = sanat;
matlabbatch{1}.spm.spatial.coreg.estimate.other = anat;
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.cost_fun = 'nmi';
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.sep = [4, 2];
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.tol = [0.02 0.02 0.02 ...
0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001];
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.fwhm = [7, 7];
fprintf('Coregistering (roughly) s%s in %s to T1 template...\n', anatfile.name, dirname);
spm_jobman('run', matlabbatch);
clear matlabbatch;
%delete(sanat);
% segment the structural
def_file = fullfile(dirname, strcat("y_", anatfile.name));
DefField = cellstr(def_file);
manat_file = fullfile(dirname, strcat("m", anatfile.name));
manat = cellstr(fullfile(dirname, strcat("m", anatfile.name)));
tpms = repmat({[spm12path filesep 'tpm' filesep 'TPM.nii,']}, 1, 6);
for tc = 1:6
tpms{tc} = {[tpms{tc} char(48+tc)]};
end
matlabbatch{1}.spm.spatial.preproc.channel.vols = anat;
matlabbatch{1}.spm.spatial.preproc.channel.biasreg = 0.001;
matlabbatch{1}.spm.spatial.preproc.channel.biasfwhm = 60;
matlabbatch{1}.spm.spatial.preproc.channel.write = [0, 1];
matlabbatch{1}.spm.spatial.preproc.tissue = struct('tpm', tpms, ...
'ngaus', {1, 1, 2, 3, 4, 2}, ...
'native', {[1, 1], [1, 1], [1, 1], [0, 0], [0, 0], [0, 0]}, ...
'warped', {[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]});
matlabbatch{1}.spm.spatial.preproc.warp.mrf = 1;
matlabbatch{1}.spm.spatial.preproc.warp.cleanup = 1;
matlabbatch{1}.spm.spatial.preproc.warp.reg = [0, 0.001, 0.5, 0.05, 0.2];
matlabbatch{1}.spm.spatial.preproc.warp.affreg = 'mni';
matlabbatch{1}.spm.spatial.preproc.warp.fwhm = 0;
matlabbatch{1}.spm.spatial.preproc.warp.samp = 3;
matlabbatch{1}.spm.spatial.preproc.warp.write = [1, 1];
if exist(def_file, 'file') ~= 2 || exist(manat_file, 'file') ~= 2
spm_jobman('run', matlabbatch);
end
clear matlabbatch;
% normalize the segmented structural to T1 template
matlabbatch{1}.spm.spatial.normalise.write.subj.def = DefField;
matlabbatch{1}.spm.spatial.normalise.write.subj.resample = manat;
matlabbatch{1}.spm.spatial.normalise.write.woptions.bb = ...
[-78, -112, -70; 78, 76, 85];
matlabbatch{1}.spm.spatial.normalise.write.woptions.vox = [1 1 1];
matlabbatch{1}.spm.spatial.normalise.write.woptions.interp = 4;
matlabbatch{1}.spm.spatial.normalise.write.woptions.prefix = 'w';
fprintf('Warping anatomical %s in %s to MNI space...\n', anatfile.name, dirname);
spm_jobman('run', matlabbatch);
clear matlabbatch;
% skull strip the segmented structural
c1 = fullfile(dirname, strcat("c1", anatfile.name));
c2 = fullfile(dirname, strcat("c2", anatfile.name));
c3 = fullfile(dirname, strcat("c3", anatfile.name));
sx = ['xm' anatfile.name];
matlabbatch{1}.spm.util.imcalc.input = cellstr([manat; c1; c2; c3]);
matlabbatch{1}.spm.util.imcalc.output = sx;
matlabbatch{1}.spm.util.imcalc.outdir = {''};
matlabbatch{1}.spm.util.imcalc.expression = 'i1.*((i2+i3+i4)>=.5)';
matlabbatch{1}.spm.util.imcalc.var = struct('name', {}, 'value', {});
matlabbatch{1}.spm.util.imcalc.options.dmtx = 0;
matlabbatch{1}.spm.util.imcalc.options.mask = 0;
matlabbatch{1}.spm.util.imcalc.options.interp = 1;
matlabbatch{1}.spm.util.imcalc.options.dtype = 4;
fprintf('Skull stripping m%s in %s...\n', anatfile.name, dirname);
spm_jobman('run', matlabbatch);
clear matlabbatch;
% generate func file names
fprintf('Starting func file names');
funcfiles = {strcat('/', funcfiles.name)};
meanfuncfile = sprintf('%smeana%s,1', dirname, funcfiles{1});
smeanfuncfile = sprintf('%ssmeana%s,1', dirname, funcfiles{1});
afuncfiles = funcfiles;
wafuncfiles = funcfiles;
for fc = 1:numruns
disp(fc);
funcfiles{fc} = repmat(funcfiles(fc), nvols, 1);
afuncfiles{fc} = funcfiles{fc};
wafuncfiles{fc} = funcfiles{fc};
for vc = 1:nvols
funcfiles{fc}{vc} = sprintf('%s%s,%d', dirname, funcfiles{fc}{vc}, vc);
afuncfiles{fc}{vc} = sprintf('%sa%s,%d', dirname, afuncfiles{fc}{vc}, vc);
wafuncfiles{fc}{vc} = sprintf('%swa%s,%d', dirname, wafuncfiles{fc}{vc}, vc);
end
end
% slice-timing of functional data
matlabbatch{1}.spm.temporal.st.scans = funcfiles;
matlabbatch{1}.spm.temporal.st.nslices = nslices;
matlabbatch{1}.spm.temporal.st.tr = TR;
matlabbatch{1}.spm.temporal.st.ta = TA;
matlabbatch{1}.spm.temporal.st.so = sliceorder;
matlabbatch{1}.spm.temporal.st.refslice = refslice;
matlabbatch{1}.spm.temporal.st.prefix = 'a';
fprintf('Slice-time correcting data in %s...\n', dirname);
spm_jobman('run', matlabbatch);
clear matlabbatch;
% motion correction/realignment (+ mean image)
matlabbatch{1}.spm.spatial.realign.estwrite.data = afuncfiles;
matlabbatch{1}.spm.spatial.realign.estwrite.eoptions = struct( ...
'quality', 0.9, 'sep', 4, 'fwhm', 5, 'rtm', 1, 'interp', 2, 'wrap', [0, 0, 0], 'weight', '');
matlabbatch{1}.spm.spatial.realign.estwrite.roptions = struct( ...
'which', [0, 1], 'interp', 4, 'wrap', [0, 0, 0,], 'mask', 1, 'prefix', 'r');
fprintf('Realignment of data in %s...\n', dirname);
spm_jobman('run', matlabbatch);
clear matlabbatch;
% smooth mean functional (for first step of coreg)
matlabbatch{1}.spm.spatial.smooth.data = {meanfuncfile};
matlabbatch{1}.spm.spatial.smooth.fwhm = [12, 12, 12];
matlabbatch{1}.spm.spatial.smooth.dtype = 0;
matlabbatch{1}.spm.spatial.smooth.im = 0;
matlabbatch{1}.spm.spatial.smooth.prefix = 's';
fprintf('Smoothing %s in %s (for coreg)...\n', meanfuncfile, dirname);
spm_jobman('run', matlabbatch);
clear matlabbatch;
% coregister funcs to EPI template
matlabbatch{1}.spm.spatial.coreg.estimate.ref = ...
{[spm12path filesep 'toolbox' filesep 'OldNorm' filesep 'EPI.nii,1']};
matlabbatch{1}.spm.spatial.coreg.estimate.source = {smeanfuncfile};
matlabbatch{1}.spm.spatial.coreg.estimate.other = [{meanfuncfile}; cat(1, afuncfiles{:})];
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.cost_fun = 'nmi';
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.sep = [4, 2];
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.tol = [0.02 0.02 0.02 ...
0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001];
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.fwhm = [7, 7];
fprintf('Coregistering smoothed mean-func in %s to EPI template...\n', dirname);
spm_jobman('run', matlabbatch);
clear matlabbatch;
% coregister funcs to T1
matlabbatch{1}.spm.spatial.coreg.estimate.ref = {[dirname sx]};
matlabbatch{1}.spm.spatial.coreg.estimate.source = {meanfuncfile};
matlabbatch{1}.spm.spatial.coreg.estimate.other = cat(1, afuncfiles{:});
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.cost_fun = 'nmi';
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.sep = [4, 2];
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.tol = [0.02 0.02 0.02 ...
0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001];
matlabbatch{1}.spm.spatial.coreg.estimate.eoptions.fwhm = [7, 7];
fprintf('Coregistering mean-func in %s to skull-stripped anatomical...\n', dirname);
spm_jobman('run', matlabbatch);
clear matlabbatch;
% MNI-normalize EPI data
matlabbatch{1}.spm.spatial.normalise.write.subj.def = {DefField};
matlabbatch{1}.spm.spatial.normalise.write.subj.resample = cat(1, afuncfiles{:});
matlabbatch{1}.spm.spatial.normalise.write.woptions.bb = wbbox;
matlabbatch{1}.spm.spatial.normalise.write.woptions.vox = repmat(wvox, 1, 3);
matlabbatch{1}.spm.spatial.normalise.write.woptions.interp = 4;
matlabbatch{1}.spm.spatial.normalise.write.woptions.prefix = 'w';
fprintf('MNI-warping EPI data in %s using %gmm voxel size...\n', dirname, wvox);
spm_jobman('run', matlabbatch);
clear matlabbatch
% smooth EPI data
matlabbatch{1}.spm.spatial.smooth.data = cat(1, wafuncfiles{:});
matlabbatch{1}.spm.spatial.smooth.fwhm = repmat(epismk, 1, 3);
matlabbatch{1}.spm.spatial.smooth.dtype = 0;
matlabbatch{1}.spm.spatial.smooth.im = 0;
matlabbatch{1}.spm.spatial.smooth.prefix = 's';
fprintf('Smoothing warped EPI data in %s with %gmm kernel...\n', dirname, epismk);
spm_jobman('run', matlabbatch);
clear matlabbatch;
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr_class_roi.m
|
.m
|
choco-packages-master/packages/matlab-coecis/tools/ncorr/ncorr_class_roi.m
| 66,847 |
utf_8
|
b4e72c2e366297dd03223cfb0a283d2d
|
classdef ncorr_class_roi < handle
% This is the class definition for the region of interest.
% Properties ---------------------------------------------------------%
properties(SetAccess = private)
type; % string
mask; % logical array
region; % struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{})
boundary; % struct('add',{},'sub',{})
data; % varying struct
end
% Methods ------------------------------------------------------------%
methods(Access = public)
% Constructor
function obj = ncorr_class_roi
obj.type = '';
obj.mask = false(0);
obj.region = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
obj.boundary = struct('add',{},'sub',{});
obj.data = struct();
end
function set_roi(obj,type_i,data_i)
% This function sets the region of interest.
%
% Inputs ---------------------------------------------------------%
% type_i - string; describes how ROI was made. Supported types
% shown below:
% 'load' - mask was loaded from an image file. data_i is
% struct('mask',{},'cutoff',{}).
% 'draw' - mask was drawn. data_i is
% struct('mask',{}','drawobjects',{},'cutoff',{}).
% 'region' - region and size of the mask are provided.
% data_i is struct('region',{},'size_mask',{}).
% 'boundary' - boundary and size of the mask are provided.
% data_i is struct('boundary',{},'size_mask',{}).
% data_i - struct; contains input data for the type of ROI.
%
% Outputs --------------------------------------------------------%
% None
%
% Returns error if type is wrong.
if (~strcmp(type_i,'load') && ~strcmp(type_i,'draw') && ~strcmp(type_i,'region') && ~strcmp(type_i,'boundary'))
error('Incorrect type provided.');
end
if (strcmp(type_i,'load') || strcmp(type_i,'draw'))
% This is the "load" and "draw" types, which mean a
% mask for the ROI is provided directly.
% Get mask - mask is directly provided for 'load' and 'draw'
mask_prelim = data_i.mask;
% Create region(s) - these are 4-way connected/contiguous
[region_prelim,removed] = ncorr_alg_formregions(mask_prelim,int32(data_i.cutoff),false);
% Get 20 largest contiguous regions. This is to prevent
% boundary routine from running very slowly if there are a
% bunch of small regions
cutoff_regions = 20;
[val_sorted,idx_sorted] = sort([region_prelim.totalpoints],'descend'); %#ok<ASGLU>
idx_sorted = idx_sorted-1; % Convert to zero based
if (length(idx_sorted) > cutoff_regions)
region_prelim = region_prelim(idx_sorted(1:cutoff_regions)+1);
removed = true;
end
% Update mask if regions were removed
if (removed)
mask_prelim(:) = false;
for i = 0:length(region_prelim)-1
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
for k = 0:2:region_prelim(i+1).noderange(j+1)-1
vec_y = region_prelim(i+1).nodelist(j+1,k+1):region_prelim(i+1).nodelist(j+1,k+2);
mask_prelim(vec_y+1,x+1) = true;
end
end
end
end
% Now get the boundaries - Do the "add boundaries"
% first. One per region.
boundary_prelim = struct('add',cell(length(region_prelim),1),'sub',cell(length(region_prelim),1));
for i = 0:length(region_prelim)-1
% Get mask corresponding to region - must do this
% because boundary tracing algorithm is 8-way
% connected, but the region is 4-way connected. I
% used the 8-way connected boundary because it is
% smoother. Note that if two 4-way connected
% regions are just touching at corners they are
% technically considered 8-way connected, which is
% why each 4-way region must be analyzed separately.
regionmask_buffer = false(size(mask_prelim));
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
for k = 0:2:region_prelim(i+1).noderange(j+1)-1
vec_y = region_prelim(i+1).nodelist(j+1,k+1):region_prelim(i+1).nodelist(j+1,k+2);
regionmask_buffer(vec_y+1,x+1) = true;
end
end
% Get add boundary:
% Use the top of the left most point in the region.
% Send this coordinate and the regionmask_buffer
% corresponding to this region to determine the
% boundary
boundary_buffer = ncorr_alg_formboundary(int32([region_prelim(i+1).leftbound region_prelim(i+1).nodelist(1,1)]),int32(0),regionmask_buffer);
% Append boundary
boundary_prelim(i+1).add = boundary_buffer;
% Get inverse of regionmask_buffer, and then do logical
% "and" with the filled in outer boundary. This
% leaves only internal regions
regionmask_inv_buffer = false(size(mask_prelim));
% Get filled-in outter boundary - note that this
% does not fill the boundary exactly since the
% algorithm uses double precision points to
% estimate the boundary.
ncorr_alg_formmask(struct('pos_imroi',boundary_prelim(i+1).add,'type','poly','addorsub','add'),regionmask_inv_buffer);
regionmask_inv_buffer = regionmask_inv_buffer & ~regionmask_buffer;
% Form mask_boundary - this keeps track of the sub
% boundaries already analyzed so we dont count one
% twice.
mask_boundary = false(size(mask_prelim)); % Make a copy to keep track of which points have been used to analyze the boundary
% Get sub boundaries:
boundary_prelim(i+1).sub = cell(0);
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
% Make sure noderange is greater than 2, or
% else this portion doesnt have a hole
if (region_prelim(i+1).noderange(j+1) > 2)
for k = 0:2:region_prelim(i+1).noderange(j+1)-3 % Dont test last node pair
% Only use bottom nodes - only test
% bottom nodes since these are the
% first points adjacent to a hole
y_bottom = region_prelim(i+1).nodelist(j+1,k+2);
% Test one pixel below bottom node. Make
% sure this pixel hasnt already been analyzed,
% and is also within the inverse regionmask
% buffer
if (regionmask_inv_buffer(y_bottom+2,x+1) && ~mask_boundary(y_bottom+2,x+1))
% This is a boundary point which
% hasn't been analyzed yet
boundary_prelim(i+1).sub{end+1} = ncorr_alg_formboundary(int32([x y_bottom+1]),int32(0),regionmask_inv_buffer);
% update mask_boundary
mask_boundary(sub2ind(size(mask_boundary),boundary_prelim(i+1).sub{end}(:,2)+1,boundary_prelim(i+1).sub{end}(:,1)+1)) = true;
end
end
end
end
end
elseif (strcmp(type_i,'region'))
% This is the 'region' option; regions are supplied
% directly. It's possible that analysis yielded regions
% directly (like unioning).
% Form mask
mask_prelim = false(data_i.size_mask);
% Form region
region_prelim = data_i.region;
% Update mask from region:
for i = 0:length(region_prelim)-1
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
for k = 0:2:region_prelim(i+1).noderange(j+1)-1
vec_y = region_prelim(i+1).nodelist(j+1,k+1):region_prelim(i+1).nodelist(j+1,k+2);
mask_prelim(vec_y+1,x+1) = true;
end
end
end
% For the custom case, do not form a real boundary, since
% regions may not longer be contigous. Do form one boundary
% per region though.
for i = 0:length(region_prelim)-1
boundary_prelim(i+1).add = [-1 -1]; %#ok<AGROW>
boundary_prelim(i+1).sub = {}; %#ok<AGROW>
end
elseif (strcmp(type_i,'boundary'))
% This is the 'boundary' option; a boundary is supplied
% directly. This allows Ncorr to update the mask based
% on displacement values at the boundary point. Note
% there will be one region per "add" boundary, this
% preserves the correspondences between a region and
% boundary.
% Form mask
mask_prelim = false(data_i.size_mask);
% Form boundary
boundary_prelim = data_i.boundary;
% Fill a region for each boundary -> Get the region
% corresponding to that mask -> append all
% regions.
% Set drawobjects which are sent to ncorr_alg_formmask
region_prelim = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
for i = 0:length(boundary_prelim)-1
% Initialize counter and draw objects
drawobjects = struct('pos_imroi',{},'type',{},'addorsub',{});
counter = 0;
drawobjects(counter+1).pos_imroi = boundary_prelim(i+1).add;
drawobjects(counter+1).type = 'poly';
drawobjects(counter+1).addorsub = 'add';
counter = counter+1;
for j = 0:length(boundary_prelim(i+1).sub)-1
drawobjects(counter+1).pos_imroi = boundary_prelim(i+1).sub{j+1};
drawobjects(counter+1).type = 'poly';
drawobjects(counter+1).addorsub = 'sub';
counter = counter+1;
end
% Get mask corresponding to this boundary
ncorr_alg_formmask(drawobjects,mask_prelim);
% Get region
[region_buffer,removed] = ncorr_alg_formregions(mask_prelim,int32(0),false); %#ok<NASGU>
% There must be one region per boundary to preserve
% their correspondence. It's possible for the region
% for a boundary to "pinch" or form more than one.
if (isempty(region_buffer))
% Form an empty ROI list if region_buffer is
% empty - this keeps the correspondence between
% the boundary and region
region_buffer = struct('nodelist',[-1 -1],'noderange',0,'leftbound',0,'rightbound',0,'upperbound',0,'lowerbound',0,'totalpoints',0);
elseif (length(region_buffer) > 1)
% Select biggest ROI if there are more than
% one. This could possibly happen if a boundary
% is "pinched" or closes. Unlikely- but may
% happen.
idx_max = find([region_buffer.totalpoints] == max([region_buffer.totalpoints]),1,'first');
region_buffer = region_buffer(idx_max);
end
% Merge
region_prelim(i+1) = region_buffer;
end
% Update mask from region:
for i = 0:length(region_prelim)-1
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
for k = 0:2:region_prelim(i+1).noderange(j+1)-1
vec_y = region_prelim(i+1).nodelist(j+1,k+1):region_prelim(i+1).nodelist(j+1,k+2);
mask_prelim(vec_y+1,x+1) = true;
end
end
end
end
% Set properties
obj.type = type_i;
obj.mask = mask_prelim;
obj.region = region_prelim;
obj.boundary = boundary_prelim;
obj.data = data_i;
end
function roi_reduced = reduce(obj,spacing)
% This function reduces the ROI. Its possible some regions will
% be deleted after the reduction; a placeholder is still used to
% preserve the number of regions.
%
% Inputs ---------------------------------------------------------%
% spacing - integer; spacing parameter
%
% Outputs --------------------------------------------------------%
% roi_reduced - ncorr_class_roi; reduced ROI
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
% Initialize output
roi_reduced = ncorr_class_roi.empty;
if (spacing == 0)
% Don't do anything, the ROI is not actually being reduced.
% Just make a deep copy of this ROI and return;
roi_reduced(1) = ncorr_class_roi;
p = properties(obj);
for i = 0:length(p)-1
roi_reduced.(p{i+1}) = obj.(p{i+1});
end
else
% Form reduced region and its template
region_reduced = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
region_reduced_template = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
for i = 0:length(obj.region)-1
% Find new bounds - left and right bounds are the
% upper limit.
region_reduced_template(1).leftbound = ceil(obj.region(i+1).leftbound/(spacing+1));
region_reduced_template.rightbound = floor(obj.region(i+1).rightbound/(spacing+1));
region_reduced_template.upperbound = inf; % Initialize to infinitely high so it can updated
region_reduced_template.lowerbound = -inf; % Initialize to infinitely low so it can updated
% Initialize nodelist, noderange, and totalpoints
region_reduced_template.nodelist = -ones(max(1,region_reduced_template.rightbound-region_reduced_template.leftbound+1),size(obj.region(i+1).nodelist,2));
region_reduced_template.noderange = zeros(max(1,region_reduced_template.rightbound-region_reduced_template.leftbound+1),1);
region_reduced_template.totalpoints = 0;
% Scan columns - calculate nodelist, noderange,
% and totalpoints
for j = region_reduced_template.leftbound*(spacing+1)-obj.region(i+1).leftbound:spacing+1:region_reduced_template.rightbound*(spacing+1)-obj.region(i+1).leftbound
% This is the column which lies on the grid;
% Form the reduced nodelist and noderange for
% this column
x_reduced = (j-(region_reduced_template.leftbound*(spacing+1)-obj.region(i+1).leftbound))/(spacing+1);
for k = 0:2:obj.region(i+1).noderange(j+1)-1
% Find upper and lower bounds for each node pair -
% it is possible that entire node pair is skipped
% over by the spacing
node_top_reduced = ceil(obj.region(i+1).nodelist(j+1,k+1)/(spacing+1));
node_bottom_reduced = floor(obj.region(i+1).nodelist(j+1,k+2)/(spacing+1));
if (node_bottom_reduced >= node_top_reduced)
% Add this node pair
region_reduced_template.nodelist(x_reduced+1,region_reduced_template.noderange(x_reduced+1)+1) = node_top_reduced;
region_reduced_template.nodelist(x_reduced+1,region_reduced_template.noderange(x_reduced+1)+2) = node_bottom_reduced;
% Update node range
region_reduced_template.noderange(x_reduced+1) = region_reduced_template.noderange((j-(region_reduced_template.leftbound*(spacing+1)-obj.region(i+1).leftbound))/(spacing+1)+1)+2;
% Update totalpoints
region_reduced_template.totalpoints = region_reduced_template.totalpoints + (node_bottom_reduced-node_top_reduced+1);
% Update upper and lower bounds
if (node_top_reduced < region_reduced_template.upperbound)
region_reduced_template.upperbound = node_top_reduced;
end
if (node_bottom_reduced > region_reduced_template.lowerbound)
region_reduced_template.lowerbound = node_bottom_reduced;
end
end
end
end
% See if region is empty - if so use a placeholder.
if (region_reduced_template.totalpoints == 0)
region_reduced_template.nodelist = [-1 -1];
region_reduced_template.noderange = 0;
region_reduced_template.leftbound = 0;
region_reduced_template.rightbound = 0;
region_reduced_template.upperbound = 0;
region_reduced_template.lowerbound = 0;
end
% Insert template into reduced region
region_reduced(i+1) = region_reduced_template;
end
% Create new ROI
roi_reduced(1) = ncorr_class_roi;
roi_reduced.set_roi('region',struct('region',region_reduced,'size_mask',size(obj.mask(1:spacing+1:end,1:spacing+1:end))));
end
end
function roi_union = get_union(obj,mask_i,spacing)
% This function returns the union of the current ROI and the
% inputted mask (which may be reduced).
%
% Inputs ---------------------------------------------------------%
% mask_i - logical array; mask used to union
% spacing - integer; indicates how much mask_i has been reduced.
%
% Outputs --------------------------------------------------------%
% roi_union - ncorr_class_roi; union of this ROI with mask_i.
%
% Returns error if ROI has not been set yet or if the sizes dont
% match.
if (isempty(obj.type))
error('ROI has not been set yet');
elseif (~isequal(size(obj.mask(1:spacing+1:end,1:spacing+1:end)),size(mask_i)))
error('Reduced mask and input mask are not the same size');
end
% Initialize output
roi_union = ncorr_class_roi;
% Get reduced ROI
roi_reduced = obj.reduce(spacing);
% Get unioned mask
mask_union = obj.mask(1:spacing+1:end,1:spacing+1:end) & mask_i;
% Get unioned region, this will not necessarily be contiguous anymore
region_union = ncorr_alg_formunion(roi_reduced.formatted(),mask_union);
% Create new ROI
roi_union.set_roi('region',struct('region',region_union,'size_mask',size(mask_union)));
end
function roi_update = update_roi(obj,plot_u,plot_v,roi_plot,size_mask_update,spacing,radius)
% This function returns an updated ROI, based on the inputted
% displacement fields. This works by updating the boundary and
% redrawing the mask. This assumes boundary can be subpixel, so it
% interpolates a new position based on the displacement field.
% Furthermore, displacement fields are reduced by a spacing factor,
% so it's required as an input.
%
% Inputs ---------------------------------------------------------%
% plot_u - double array; u displacement plot
% plot_v - double array; v displacement plot
% roi_plot - ncorr_class_roi; ROI corresponding to displacement
% plots
% size_mask_update - integer array; size of the updated mask. Can
% be a different size than obj.mask if different sized image are
% used
% spacing - integer; spacing parameter
% radius - integer; subset radius
%
% Outputs --------------------------------------------------------%
% roi_update - ncorr_class_roi; updated ROI.
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
% Extrapolate displacement plots to improve interpolation near the
% boundary points.
% border_interp is the border added to the displacements when they are
% extrapolated.
border_interp = 20; % MUST BE GREATER THAN OR EQUAL TO 2!!!!
plot_u_interp = ncorr_alg_extrapdata(plot_u,roi_plot.formatted(),int32(border_interp));
plot_v_interp = ncorr_alg_extrapdata(plot_v,roi_plot.formatted(),int32(border_interp));
% Convert displacement plots to B-spline coefficients; these are used
% for interpolation. Make sure to do this for each region.
for i = 0:length(roi_plot.region)-1
plot_u_interp{i+1} = ncorr_class_img.form_bcoef(plot_u_interp{i+1});
plot_v_interp{i+1} = ncorr_class_img.form_bcoef(plot_v_interp{i+1});
end
% Initialize new boundary - preserve the number and
% correspondences of the "add" boundaries, even if a
% boundary is empty
boundary_update = struct('add',{},'sub',{});
for i = 0:length(obj.boundary)-1
boundary_update(i+1).add = interp_border(obj.boundary(i+1).add, ...
plot_u_interp{i+1}, ...
plot_v_interp{i+1}, ...
roi_plot, ...
i, ...
size_mask_update, ...
border_interp, ...
spacing, ...
radius);
for j = 0:length(obj.boundary(i+1).sub)-1
boundary_update(i+1).sub{j+1} = interp_border(obj.boundary(i+1).sub{j+1}, ...
plot_u_interp{i+1}, ...
plot_v_interp{i+1}, ...
roi_plot, ...
i, ...
size_mask_update, ...
border_interp, ...
spacing, ...
radius);
end
end
% Set new ROI - note that size_mask_update must be used
% instead of the size of the current mask. This is because
% different sized current images can be used.
roi_update = ncorr_class_roi;
roi_update.set_roi('boundary',struct('boundary',boundary_update,'size_mask',size_mask_update));
end
function roi_f = formatted(obj)
% This function returns the formatted ROI, which can be inputted to a
% mex function. Mex functions can receive ncorr_class_roi as either
% a class or structure.
%
% Inputs ---------------------------------------------------------%
% none;
%
% Outputs --------------------------------------------------------%
% roi_f - ncorr_class_roi; formatted ROI.
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
% Must make deep copy first
roi_f = ncorr_class_roi;
p = properties(obj);
for i = 0:length(p)-1
roi_f.(p{i+1}) = obj.(p{i+1});
end
% Now format properties
for i = 0:length(obj.region)-1
roi_f.region(i+1).nodelist = int32(roi_f.region(i+1).nodelist);
roi_f.region(i+1).noderange = int32(roi_f.region(i+1).noderange);
roi_f.region(i+1).leftbound = int32(roi_f.region(i+1).leftbound);
roi_f.region(i+1).rightbound = int32(roi_f.region(i+1).rightbound);
roi_f.region(i+1).upperbound = int32(roi_f.region(i+1).upperbound);
roi_f.region(i+1).lowerbound = int32(roi_f.region(i+1).lowerbound);
roi_f.region(i+1).totalpoints = int32(roi_f.region(i+1).totalpoints);
end
end
% ----------------------------------------------------------------%
% Get functions --------------------------------------------------%
% ----------------------------------------------------------------%
function [num_region,idx_nodelist] = get_num_region(obj,x,y,list_region)
% This function determines which region x and y lie in, excluding
% the regions indicated by list_region
%
% Inputs ---------------------------------------------------------%
% x - integer; x_coordinate
% y - integer; y_coordinate
% list_region - logical array; indices of regions to search
% if x and y are contained within it. If list_region(i) == true,
% then skip over region(i).
%
% Output ---------------------------------------------------------%
% num_region - integer; index of region that contains x
% and y. Returns -1 if x and y are not within the regions
% specified by region.
% idx_nodelist - integer; index of node pair that contains y
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
% Initialize outputs
num_region = -1;
idx_nodelist = 0;
% Initialize withinroi to false
withinroi = false;
for i = 0:length(obj.region)-1
if (list_region(i+1)) % Skip this ROI
continue;
else
if (x >= obj.region(i+1).leftbound && x <= obj.region(i+1).rightbound) % Check to make sure x coordinate is within bounds
idx_region = x-obj.region(i+1).leftbound;
for j = 0:2:obj.region(i+1).noderange(idx_region+1)-1 % Check to see if point is within node pairs
if (y >= obj.region(i+1).nodelist(idx_region+1,j+1) && y <= obj.region(i+1).nodelist(idx_region+1,j+2))
withinroi = true;
idx_nodelist = j;
num_region = i;
break;
end
end
end
if (withinroi)
break;
end
end
end
end
function regionmask = get_regionmask(obj,num_region)
% This function returns a mask corresponding only to the region
% indicated by num_region.
%
% Inputs ---------------------------------------------------------%
% num_region - integer; number of region to use to form mask.
%
% Outputs --------------------------------------------------------%
% regionmask - logical array; mask corresponding to num_region
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
regionmask = false(size(obj.mask));
for i = 0:size(obj.region(num_region+1).noderange,1)-1
x = i + obj.region(num_region+1).leftbound;
for j = 0:2:obj.region(num_region+1).noderange(i+1)-1
vec_y = obj.region(num_region+1).nodelist(i+1,j+1):obj.region(num_region+1).nodelist(i+1,j+2);
regionmask(vec_y+1,x+1) = true;
end
end
end
function total_fullregions = get_fullregions(obj)
% This function returns the number of regions which are
% nonempty. Generally used to see if ROI is empty or not.
%
% Inputs ---------------------------------------------------------%
% none;
%
% Outputs --------------------------------------------------------%
% total_fullregions - integer; number of nonemtpy regions
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
total_fullregions = 0;
for i = 0:length(obj.region)-1
if (obj.region(i+1).totalpoints > 0)
total_fullregions = total_fullregions+1;
end
end
end
function cirroi = get_cirroi(obj,x,y,radius,subsettrunc)
% This function returns a contiguous circular region for the subset
% located at x and y.
%
% Inputs ---------------------------------------------------------%
% x - integer; x_coordinate of subset
% y - integer; y_coordinate of subset
% radius - integer; radius of subset
% subsettrunc - logical; indicates whether to enable subset
% truncation or not
%
% Outputs --------------------------------------------------------%
% cirroi - circular subset; this is the circular subset
% corresponding to the points specified at x and y. Contains
% struct('mask',{},'region',{},'boundary',{},'x',{},'y',{},'radius',{})
%
% Returns error if ROI has not been set yet or if x and y are not
% within the ROI. Note that the boundary field in cirroi is
% currently not being used.
% Find idx_nodelist and num_region
[num_region,idx_nodelist] = obj.get_num_region(x,y,false(size(obj.region)));
if (isempty(obj.type))
error('ROI has not been set yet');
elseif (num_region == -1)
error('x and y coordinates are not within the ROI');
end
% Initialize cirroi structure
cirroi = struct('mask',{},'region',{},'boundary',{},'x',{},'y',{},'radius',{});
cirroi_template = struct('mask',{},'region',{},'boundary',{},'x',{},'y',{},'radius',{});
% Store x,y, and radius
cirroi_template(1).mask = false(2*radius+1);
cirroi_template.region = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
cirroi_template.boundary = [];
cirroi_template.x = x;
cirroi_template.y = y;
cirroi_template.radius = radius;
% Find max_nodewidth_buffer - this is the maximum width
% of the nodelist.
max_nodewidth_buffer = 0;
for i = 0:length(obj.region)-1
if (size(obj.region(i+1).nodelist,2) > max_nodewidth_buffer)
max_nodewidth_buffer = size(obj.region(i+1).nodelist,2);
end
end
% Initialize cirroi nodelist and noderange
cirroi_template.region(1).nodelist = -ones(cirroi_template.radius*2+1,max_nodewidth_buffer);
cirroi_template.region.noderange = zeros(cirroi_template.radius*2+1,1);
% Initialize totalpoints
cirroi_template.region.totalpoints = 0;
% Now find circle nodes
% Fill must be contiguous and begins at the centerpoint
queue_nodelist = -ones(size(cirroi_template.region.nodelist,1)*size(cirroi_template.region.nodelist,2),1); % Initialize to max size to prevent resizing
queue_nodeindex = zeros(size(cirroi_template.region.nodelist,1)*size(cirroi_template.region.nodelist,2)/2,1); % Index of nodepair with respect to cirroi;
length_queue = 0; %#ok<NASGU> % length of the queue_nodelist
queue_nodelist_buffer = -ones(1,2);
queue_nodeindex_buffer = 0; %#ok<NASGU>
% Initialize parameter which indicates whether the subset
% has been truncated
circ_untrunc = true;
% Node pair which contains the center point is added to queue first; this
% guarantees the circular region is contiguous WRT the centerpoint
if (obj.region(num_region+1).nodelist(cirroi_template.x-obj.region(num_region+1).leftbound+1,idx_nodelist+1) < cirroi_template.y-cirroi_template.radius) % make sure top node is within the circle
node_top = cirroi_template.y-cirroi_template.radius;
else
node_top = obj.region(num_region+1).nodelist(cirroi_template.x-obj.region(num_region+1).leftbound+1,idx_nodelist+1);
circ_untrunc = false;
end
if (obj.region(num_region+1).nodelist(cirroi_template.x-obj.region(num_region+1).leftbound+1,idx_nodelist+2) > cirroi_template.y+cirroi_template.radius) % make sure bottom node is within the circle
node_bottom = cirroi_template.y+cirroi_template.radius;
else
node_bottom = obj.region(num_region+1).nodelist(cirroi_template.x-obj.region(num_region+1).leftbound+1,idx_nodelist+2);
circ_untrunc = false;
end
% Update mask
cirroi_template.mask(node_top-(cirroi_template.y-cirroi_template.radius)+1:node_bottom-(cirroi_template.y-cirroi_template.radius)+1,cirroi_template.radius+1) = true;
% Update queue
queue_nodelist(1:2) = [node_top node_bottom];
queue_nodeindex(1) = cirroi_template.radius;
length_queue = 2;
% Form activelines and then inactivate nodepair from nodelist
% Activelines keeps track of which node pairs have been
% analyzed
activelines = true(size(obj.region(num_region+1).nodelist,1),size(obj.region(num_region+1).nodelist,2)/2);
activelines((cirroi_template.x-obj.region(num_region+1).leftbound)+1,idx_nodelist/2+1) = false;
% Enter while loop. Exit when queue is empty
while (length_queue ~= 0)
% STEPS:
% 1) Load nodepair from queue
% 2) Update queue
% 3) Add nodepair to cirroi, sort, and then update
% 4) Compare nodepair to nodepairs left and right and add nodes to queue
% 5) Update totalpoints
% Step 1) Pop queue
queue_nodelist_buffer(1:2) = queue_nodelist(length_queue-1:length_queue);
queue_nodeindex_buffer = queue_nodeindex(length_queue/2);
% Step 2)
length_queue = length_queue-2;
% Step 3)
if (cirroi_template.region.noderange(queue_nodeindex_buffer+1) == 0)
% Just place directly
cirroi_template.region.nodelist(queue_nodeindex_buffer+1,1:2) = queue_nodelist_buffer(1:2);
else
% Merge nodes
inserted = false;
for i = 0:2:cirroi_template.region.noderange(queue_nodeindex_buffer+1)-1
if (queue_nodelist_buffer(2) < cirroi_template.region.nodelist(queue_nodeindex_buffer+1,i+1))
nodelist_buffer = cirroi_template.region.nodelist(queue_nodeindex_buffer+1,i+1:cirroi_template.region.noderange(queue_nodeindex_buffer+1));
cirroi_template.region.nodelist(queue_nodeindex_buffer+1,i+1:i+2) = queue_nodelist_buffer;
cirroi_template.region.nodelist(queue_nodeindex_buffer+1,i+3:cirroi_template.region.noderange(queue_nodeindex_buffer+1)+2) = nodelist_buffer;
inserted = true;
break
end
end
if (~inserted)
% Append at the end
cirroi_template.region.nodelist(queue_nodeindex_buffer+1,cirroi_template.region.noderange(queue_nodeindex_buffer+1)+1:cirroi_template.region.noderange(queue_nodeindex_buffer+1)+2) = queue_nodelist_buffer;
end
end
cirroi_template.region.noderange(queue_nodeindex_buffer+1) = cirroi_template.region.noderange(queue_nodeindex_buffer+1)+2;
% Step 4)
idx_froi = queue_nodeindex_buffer+(cirroi_template.x-cirroi_template.radius)-obj.region(num_region+1).leftbound;
% Compare to node pairs LEFT
if (queue_nodeindex_buffer > 0 && idx_froi > 0) % makes sure previous node is within cirroi
for i = 0:2:obj.region(num_region+1).noderange(idx_froi)-1
if (activelines(idx_froi,i/2+1) == 0) % Nodes are inactive
continue
end
upperlim = ceil(-sqrt(cirroi_template.radius^2-(((queue_nodeindex_buffer-1)+(cirroi_template.x-cirroi_template.radius))-cirroi_template.x)^2)+cirroi_template.y);
lowerlim = floor(sqrt(cirroi_template.radius^2-(((queue_nodeindex_buffer-1)+(cirroi_template.x-cirroi_template.radius))-cirroi_template.x)^2)+cirroi_template.y);
if (obj.region(num_region+1).nodelist(idx_froi,i+2) < queue_nodelist_buffer(1)) % lower node comes before upper node of buffer
continue;
elseif (obj.region(num_region+1).nodelist(idx_froi,i+1) <= queue_nodelist_buffer(2) && obj.region(num_region+1).nodelist(idx_froi,i+2) >= queue_nodelist_buffer(1)) % nodes interact
if (obj.region(num_region+1).nodelist(idx_froi,i+1) < upperlim) % make sure upper node is within the circle
node_top = upperlim;
else
node_top = obj.region(num_region+1).nodelist(idx_froi,i+1);
circ_untrunc = false;
end
if (obj.region(num_region+1).nodelist(idx_froi,i+2) > lowerlim) % make sure lower node is within the circle
node_bottom = lowerlim;
else
node_bottom = obj.region(num_region+1).nodelist(idx_froi,i+2);
circ_untrunc = false;
end
if (node_top > node_bottom || node_top > queue_nodelist_buffer(2) || node_bottom < queue_nodelist_buffer(1)) % This can occur along diagonal boundaries by virtue of how the four way direction contiguous algorithm works. If this happens, break, because it is no longer contiugous
continue;
end
% Add to queue
queue_nodelist(length_queue+1:length_queue+2) = [node_top node_bottom]; % add to queue
queue_nodeindex(length_queue/2+1) = queue_nodeindex_buffer-1;
length_queue = length_queue + 2;
% Make node pair inactive
activelines((idx_froi-1)+1,i/2+1) = false;
% Update mask
cirroi_template.mask(node_top-(cirroi_template.y-cirroi_template.radius)+1:node_bottom-(cirroi_template.y-cirroi_template.radius)+1,queue_nodeindex_buffer) = true;
else
break;
end
end
end
% Compare to node pairs RIGHT
if (queue_nodeindex_buffer < 2*cirroi_template.radius && idx_froi < obj.region(num_region+1).rightbound-obj.region(num_region+1).leftbound) % makes sure next node is within cirroiint
for i = 0:2:obj.region(num_region+1).noderange(idx_froi+2)-1
if (activelines(idx_froi+2,i/2+1) == 0)
continue
end
upperlim = ceil(-sqrt(cirroi_template.radius^2-(((queue_nodeindex_buffer+1)+(cirroi_template.x-cirroi_template.radius))-cirroi_template.x)^2)+cirroi_template.y);
lowerlim = floor(sqrt(cirroi_template.radius^2-(((queue_nodeindex_buffer+1)+(cirroi_template.x-cirroi_template.radius))-cirroi_template.x)^2)+cirroi_template.y);
if (obj.region(num_region+1).nodelist(idx_froi+2,i+2) < queue_nodelist_buffer(1)) % lower node comes before upper node of buffer
continue;
elseif (obj.region(num_region+1).nodelist(idx_froi+2,i+1) <= queue_nodelist_buffer(2) && obj.region(num_region+1).nodelist(idx_froi+2,i+2) >= queue_nodelist_buffer(1)) % nodes interact
if (obj.region(num_region+1).nodelist(idx_froi+2,i+1) < upperlim) % make sure upper node is within the circle
node_top = upperlim;
else
node_top = obj.region(num_region+1).nodelist(idx_froi+2,i+1);
circ_untrunc = false;
end
if (obj.region(num_region+1).nodelist(idx_froi+2,i+2) > lowerlim) % make sure lower node is within the circle
node_bottom = lowerlim;
else
node_bottom = obj.region(num_region+1).nodelist(idx_froi+2,i+2);
circ_untrunc = false;
end
if (node_top > node_bottom || node_top > queue_nodelist_buffer(2) || node_bottom < queue_nodelist_buffer(1)) % This can occur along diagonal boundaries by virtue of how the four way direction contiguous algorithm works. If this happens, break, because it is no longer contiugous
continue;
end
% Add to queue
queue_nodelist(length_queue+1:length_queue+2) = [node_top node_bottom]; % add to queue
queue_nodeindex(length_queue/2+1) = queue_nodeindex_buffer+1; %
length_queue = length_queue + 2;
% Make node pair inactive
activelines((idx_froi+1)+1,i/2+1) = false;
% Update mask
cirroi_template.mask(node_top-(cirroi_template.y-cirroi_template.radius)+1:node_bottom-(cirroi_template.y-cirroi_template.radius)+1,queue_nodeindex_buffer+2) = true;
else
break;
end
end
end
% Update totalpoints
cirroi_template.region.totalpoints = cirroi_template.region.totalpoints + (queue_nodelist_buffer(2)-queue_nodelist_buffer(1)+1);
end
% Set Bounds - since noderange length is always
% 2*radius+1, set left and right bounds to:
cirroi_template.region.leftbound = cirroi_template.x - cirroi_template.radius;
cirroi_template.region.rightbound = cirroi_template.x + cirroi_template.radius;
% Find upper and lower bounds:
cirroi_template.region.upperbound = size(obj.mask,1);
cirroi_template.region.lowerbound = 0;
for i = 0:size(cirroi_template.region.noderange,1)-1 % Find max and min x-values of cirroi
if (cirroi_template.region.noderange(i+1) > 0)
if (cirroi_template.region.upperbound > cirroi_template.region.nodelist(i+1,1))
cirroi_template.region.upperbound = cirroi_template.region.nodelist(i+1,1);
end
if (cirroi_template.region.lowerbound < cirroi_template.region.nodelist(i+1,cirroi_template.region.noderange(i+1)))
cirroi_template.region.lowerbound = cirroi_template.region.nodelist(i+1,cirroi_template.region.noderange(i+1));
end
end
end
% If subset is truncated, do some special analysis to construct
% the cirroi. At this point, it's only contiguous. I've added
% this portion to truncate a part of the subset if this option
% is enabled. This is helpful for analyzing cracks so the subset
% does not wrap around the crack tip. Also make sure to check
% if any of the noderanges are zero, as this will not trigger a
% truncation.
if (subsettrunc && (~circ_untrunc || any(cirroi_template.region.noderange == 0)))
% Get boundary
point_topleft = [-1 -1]; % Initialize
for i = 0:size(cirroi_template.mask,2)-1
for j = 0:size(cirroi_template.mask,1)-1
if (cirroi_template.mask(j+1,i+1))
point_topleft = [i j]; % This is the first point.
break;
end
end
if (cirroi_template.mask(j+1,i+1))
break;
end
end
boundary_cirroi = ncorr_alg_formboundary(int32(point_topleft),int32(7),cirroi_template.mask);
% Find closest point -> Find line equation -> Find
% number of points to the left and right of the
% line; the side with the least amount of points
% will be discarded
dists = (boundary_cirroi(:,1)-cirroi_template.radius).^2 + (boundary_cirroi(:,2)-cirroi_template.radius).^2;
[val_min,idx_min] = min(dists);
idx_min = idx_min-1; % Zero based indexing
% Make sure closest point is not on the boundary,
% which can happen since the boundary isnt
% perfectly circular
if (ceil(sqrt(val_min)) < cirroi_template.radius)
% Nonlinear solver
idx_space = 3;
idx_plus = mod(idx_min+idx_space,size(boundary_cirroi,1));
idx_minus = mod(idx_min-idx_space,size(boundary_cirroi,1));
% Initialize points to calculate derivatives with
x_plus_f = 0;
x_min_f = 0;
x_minus_f = 0;
y_plus_f = 0;
y_min_f = 0;
y_minus_f = 0;
% Set filt length
length_filt = 2;
for i = -length_filt:length_filt
x_plus_f = x_plus_f + boundary_cirroi(mod(idx_plus+i,size(boundary_cirroi,1))+1,1);
x_min_f = x_min_f + boundary_cirroi(mod(idx_min+i,size(boundary_cirroi,1))+1,1);
x_minus_f = x_minus_f + boundary_cirroi(mod(idx_minus+i,size(boundary_cirroi,1))+1,1);
y_plus_f = y_plus_f + boundary_cirroi(mod(idx_plus+i,size(boundary_cirroi,1))+1,2);
y_min_f = y_min_f + boundary_cirroi(mod(idx_min+i,size(boundary_cirroi,1))+1,2);
y_minus_f = y_minus_f + boundary_cirroi(mod(idx_minus+i,size(boundary_cirroi,1))+1,2);
end
% Divide by length
x_plus_f = x_plus_f/(2*length_filt+1);
x_min_f = x_min_f/(2*length_filt+1);
x_minus_f = x_minus_f/(2*length_filt+1);
y_plus_f = y_plus_f/(2*length_filt+1);
y_min_f = y_min_f/(2*length_filt+1);
y_minus_f = y_minus_f/(2*length_filt+1);
% Get derivatives
dx_di_f = (x_plus_f - x_minus_f)/(2*idx_space);
d2x_di2_f = (x_plus_f-2*x_min_f+x_minus_f)/(idx_space^2);
dy_di_f = (y_plus_f - y_minus_f)/(2*idx_space);
d2y_di2_f = (y_plus_f-2*y_min_f+y_minus_f)/(idx_space^2);
% Do one iteration to find change in index
deltai = ((-x_min_f*dx_di_f+cirroi_template.radius*dx_di_f) + (-y_min_f*dy_di_f+cirroi_template.radius*dy_di_f))/((dx_di_f^2+x_min_f*d2x_di2_f-cirroi_template.radius*d2x_di2_f)+(dy_di_f^2+y_min_f*d2y_di2_f-cirroi_template.radius*d2y_di2_f));
% Test deltai, make sure its between subsequent spacings; If
% not then set the points minus and plus points
if (abs(deltai) < idx_space)
% Calculate two points based on dx_di_i and dy_di_i
x_i = x_min_f + dx_di_f*deltai + (1/2)*d2x_di2_f*deltai^2;
y_i = y_min_f + dy_di_f*deltai + (1/2)*d2y_di2_f*deltai^2;
dx_di_i = dx_di_f + d2x_di2_f*deltai;
dy_di_i = dy_di_f + d2y_di2_f*deltai;
% Set stepsize - the magnitude doesnt matter
stepsize = 0.5;
% Get points
p0 = [x_i-dx_di_i*stepsize y_i-dy_di_i*stepsize];
p1 = [x_i+dx_di_i*stepsize y_i+dy_di_i*stepsize];
else
% Set points to averaged points on either side
p0 = [x_minus_f y_minus_f];
p1 = [x_plus_f y_plus_f];
end
% Find which side to clear: p_subset is a point defined
% to be part of the subset, so the side opposite of
% p_subset needs to be cleared. If the center of the
% subset does not lie on boundary, then find displacement
% from closest point to p0. Add this displacement to
% the center, and then determine which side the center
% is on.
p_subset = [0 0]; % Initialize
if (isequal(boundary_cirroi(idx_min+1,:),[cirroi_template.radius cirroi_template.radius]))
% Center is the closest point. Find valid points
% around the boundary and get the centroid of
% these points.
width_win = 1; % This determines window of points collected
counter = 0; % Counts number of points added so a proper average can be taken
for i = -width_win:width_win
x_mask = boundary_cirroi(idx_min+1,1)+i;
for j = -width_win:width_win
y_mask = boundary_cirroi(idx_min+1,2)+j;
% Make sure points are within mask and
% that the mask is valid here.
if (x_mask >= 0 && x_mask <= 2*cirroi_template.radius && y_mask >= 0 && y_mask <= 2*cirroi_template.radius && ...
cirroi_template.mask(y_mask+1,x_mask+1))
p_subset = p_subset + [x_mask y_mask];
counter = counter+1;
end
end
end
% Divide by counter to get the average
p_subset = p_subset/counter;
% Debug ------%
%{
figure(1); imshow(cirroi_template.mask); hold on;
plot(p0(1,1),p0(1,2),'rx');
plot(p1(1,1),p1(1,2),'rx');
plot(p_subset(1,1),p_subset(1,2),'gx');
hold off;
%}
% ------------%
else
% Set the center point
p_subset = [cirroi_template.radius cirroi_template.radius];
% Debug ------%
%{
figure(1); imshow(cirroi_template.mask); hold on;
plot(p0(1,1),p0(1,2),'rx');
plot(p1(1,1),p1(1,2),'rx');
plot(p_subset(1,1),p_subset(1,2),'gx');
hold off;
%}
% ------------%
end
% Normalize point against line since it can shift
disp_p0 = p0 - boundary_cirroi(idx_min+1,:);
p_subset = p_subset + disp_p0;
% Now determine which side p_subset lies and
% clear the other side
sign_clear = -sign((p1(1)-p0(1))*(p_subset(2)-p0(2))-(p_subset(1)-p0(1))*(p1(2)-p0(2)));
mask_cirroi_prelim = cirroi_template.mask; % Make a copy
for i = 0:size(cirroi_template.region.noderange,1)-1
for j = 0:2:cirroi_template.region.noderange(i+1)-1
for k = cirroi_template.region.nodelist(i+1,j+1):cirroi_template.region.nodelist(i+1,j+2)
p2 = [i k-(cirroi_template.y-cirroi_template.radius)];
if (sign((p1(1)-p0(1))*(p2(2)-p0(2))-(p2(1)-p0(1))*(p1(2)-p0(2))) == sign_clear)
% Clear points on this side
mask_cirroi_prelim(p2(2)+1,p2(1)+1) = false;
end
end
end
end
% Get region again from the mask, then select the
% biggest region. This is required because subset
% truncation does not preserve the cirroi's contiguous
% nature. Setting the last parameter to true for
% formregion will make the length of the noderange the
% same as the width of the mask
[region_cirroi_prelim,removed] = ncorr_alg_formregions(mask_cirroi_prelim,int32(0),true); %#ok<NASGU>
% Its possible for region to be empty. Must check it. If
% its empty, then abandon subset truncation.
if (~isempty(region_cirroi_prelim))
% Only keep the region with the max number of
% totalpoints
region_cirroi_prelim = region_cirroi_prelim([region_cirroi_prelim.totalpoints] == max([region_cirroi_prelim.totalpoints]));
% Update mask then store it
mask_cirroi_prelim(:) = false;
for i = 0:size(cirroi_template.region.noderange,1)-1
for j = 0:2:region_cirroi_prelim.noderange(i+1)-1
for k = region_cirroi_prelim.nodelist(i+1,j+1):region_cirroi_prelim.nodelist(i+1,j+2)
mask_cirroi_prelim(k+1,i+1) = true;
end
end
end
% Store mask
cirroi_template.mask = mask_cirroi_prelim;
% Store region with greatest number of nodes
cirroi_template.region = region_cirroi_prelim;
% Bring back to regular coords
for i = 0:size(cirroi_template.region.noderange,1)-1
if (cirroi_template.region.noderange(i+1) > 0)
cirroi_template.region.nodelist(i+1,1:cirroi_template.region.noderange(i+1)) = cirroi_template.region.nodelist(i+1,1:cirroi_template.region.noderange(i+1)) + (cirroi_template.y-cirroi_template.radius);
end
end
cirroi_template.region.leftbound = cirroi_template.region.leftbound + (cirroi_template.x-cirroi_template.radius);
cirroi_template.region.rightbound = cirroi_template.region.rightbound + (cirroi_template.x-cirroi_template.radius);
cirroi_template.region.upperbound = cirroi_template.region.upperbound + (cirroi_template.y-cirroi_template.radius);
cirroi_template.region.lowerbound = cirroi_template.region.lowerbound + (cirroi_template.y-cirroi_template.radius);
end
% Debug
%{
figure(2), imshow(cirroi_template.mask);
hold on;
plot(boundary_cirroi(idx_min+1,1)+1,boundary_cirroi(idx_min+1,2)+1,'bx');
plot(p0(1)+1,p0(2)+1,'gs');
plot(p1(1)+1,p1(2)+1,'gs');
hold off;
%}
end
end
%-----------------------------------------------------%
%-----------------------------------------------------%
%-----------------------------------------------------%
% Assign outputs
cirroi(1) = cirroi_template;
end
%-----------------------------------------------------------------%
% For debugging --------------------------------------------------%
%-----------------------------------------------------------------%
function debug_region(obj)
if (isempty(obj.type))
error('ROI has not been set yet');
end
mask_debug = false(size(obj.mask));
for i = 0:length(obj.region)-1
regionmask_debug = false(size(obj.mask));
for j = 0:size(obj.region(i+1).noderange,1)-1
x = j + obj.region(i+1).leftbound;
for k = 0:2:obj.region(i+1).noderange(j+1)-1
vec_y = obj.region(i+1).nodelist(j+1,k+1):obj.region(i+1).nodelist(j+1,k+2);
mask_debug(vec_y+1,x+1) = true;
regionmask_debug(vec_y+1,x+1) = true;
end
end
% figure, imshow(regionmask_debug); - This can potential be a lot of figures
end
figure, imshow(mask_debug);
if (isequal(mask_debug,obj.mask))
disp('SUCCESS - mask matches region');
else
error('FAILURE - for some reason mask and region are different');
end
end
function debug_boundary(obj)
if (isempty(obj.type))
error('ROI has not been set yet');
end
figure, imshow(obj.mask);
hold on;
for i = 0:length(obj.boundary)-1
plot(obj.boundary(i+1).add(:,1)+1,obj.boundary(i+1).add(:,2)+1,'go');
for j = 0:length(obj.boundary(i+1).sub)-1
plot(obj.boundary(i+1).sub{j+1}(:,1)+1,obj.boundary(i+1).sub{j+1}(:,2)+1,'rx');
end
end
hold off;
end
end
end
function boundary_update = interp_border(boundary,plot_u_interp,plot_v_interp,roi,num_region,size_mask_update,border_interp,spacing,radius)
% Updates boundary based on old boundary and displacement plots.
% Does not preserve length of the boundary. If points are found to travel
% outside a radius length around the size_mask_update, they are discarded.
%
% Inputs -----------------------------------------------------------------%
% boundary - double array; boundary we're trying to update - uses pixel
% units.
% plot_u_interp - double array; b-spline coefficients of u displacement
% field
% plot_v_interp - double array; b-spline coefficients of v displacement
% field
% roi - ncorr_class_roi; ROI corresponding to displacement fields. Note
% that roi is reduced.
% num_region - integer; number corresponding to region
% size_mask_update - integer array; size of the new mask (can be different
% from the mask in ROI if different sized current images are used).
% border_interp - integer; border around b-spline coefficients
% spacing - integer; spacing parameter
% radius - integer; subset radius
%
% Outputs ----------------------------------------------------------------%
% boundary_update - double array; updated boundary coordinates
%
% Note, if boundary_update is found to be empty after analysis, it will
% return [-1 -1] so it is not empty. This is a temporary workaround because
% the ncorr_alg_formmask function does not support empty polygons.
% Get scaled coordinates since displacement plots are reduced.
boundary_scaled = boundary/(spacing+1);
% Get interpolated u displacements - can return NaN if out of range
interp_u = ncorr_alg_interpqbs(boundary_scaled,plot_u_interp,roi.region(num_region+1).leftbound,roi.region(num_region+1).upperbound,border_interp);
% Get interpolated v displacements - can return NaN if out of range
interp_v = ncorr_alg_interpqbs(boundary_scaled,plot_v_interp,roi.region(num_region+1).leftbound,roi.region(num_region+1).upperbound,border_interp);
% Update boundary
boundary_update = boundary;
boundary_update(:,1) = boundary_update(:,1) + interp_u;
boundary_update(:,2) = boundary_update(:,2) + interp_v;
% Set points near boundary to NaN;
for i = 0:size(boundary_update,1)-1
if (boundary_update(i+1,1) < radius || boundary_update(i+1,1) > size_mask_update(2)-radius || ...
boundary_update(i+1,2) < radius || boundary_update(i+1,2) > size_mask_update(1)-radius)
boundary_update(i+1,:) = NaN;
end
end
% Remove all coordinates that have NaN
counter = 0;
while (counter < size(boundary_update,1))
if (any(isnan(boundary_update(counter+1,:))))
boundary_update(counter+1,:) = [];
counter = counter-1;
end
counter = counter+1;
end
% Check to see if boundary is empty
if (isempty(boundary_update))
boundary_update = [-1 -1];
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr.m
|
.m
|
choco-packages-master/packages/matlab-coecis/tools/ncorr/ncorr.m
| 215,473 |
utf_8
|
0869c73f18c3ca178d6efe7202e0fe69
|
classdef ncorr < handle
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% Version: 1.2.2
% Date: 6/13/2017
% Programmed by: Justin Blaber
% Principle Investigator: Antonia Antoniou
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% Start Ncorr with:
%
% handles_ncorr = ncorr;
%
% NOTE: Images/masks can be set using the GUI menu or by using
% "handles_ncorr.set_ref(data)", "handles_ncorr.set_cur(data)",
% "handles_ncorr.set_roi_ref(data)", or "handles_ncorr.set_roi_cur(data)".
% These will manually set the reference image, current image(s), or
% region of interest if these have been calculated or
% modified using MATLAB and exist in the main workspace. Sometimes the
% reference and current images can be obtained using an average of a
% series of images. The region of interest can also be calculated using
% various thresholding and edge detecting algorithms. Displacement and
% strain data can be obtained through handles_ncorr.data_dic in case the
% user is interested in doing further calculations on the deformation
% data. In addition, if the menu freezes for some reason due to an error,
% it can be unfrozen with "handles_ncorr.refresh()". Lastly, calling
% "delete(handles_ncorr)" will force close Ncorr.
%
%
% MAIN CONSIDERATIONS:
%
% 1) All program data and appdata in the ncorr object are SET by callbacks directly.
% 2) "Downstream" program data (i.e. dependent data) and appdata are
% CLEARED with the "clear_downstream()" function before setting the
% new data.
% 3) UI objects are modified by the update* functions through the wrapper
% function "util_wrapcallbackall" and not within callback directly.
%
% The point of doing this was to make each callback as clear and
% uncluttered as possible. The clearing of "downstream" data and updating
% of UI controls are mainly for upkeep.
%
%
% MAIN FLOW OF CALLBACK:
%
% 1) Update UI controls. Generally, if a menu option updates information,
% it will freeze the top menu to prevent users from calling other
% options while the first one is running.
% 2) Check if data will be overwritten with: "overwrite = clear_downstream('callback')"
% This returns a logical value which is true if the user chooses
% to proceed and also clears the downstream data.
% 3) Perform calculations
% 4) If calculations succeed, store the data directly in the callback
% 5) Update UI controls. This unfreezes the top menu and updates it,
% as well as sets any images (such as the reference/current image)
% if they were loaded.
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% NCORR_GUI* FUNCTIONS:
%
% These functions contain GUIs which are called by the callbacks within
% this "ncorr" object. These are, unlike "ncorr," functions that
% utilize "uiwait" and nested functions instead of an object. Thus, when
% the function returns, all workspace data within those functions get
% cleared. Some of these ncorr_gui* functions have an input called
% "params_init" which contains initialization data if the function has
% been called before. Most of these functions use a modal window because
% they must be set before proceeding. These figure are generally not
% resizeable, and their size is checked with "ncorr_util_formatwindow" to
% ensure the top right edges of the window are within the screen.
%
% The initialization of the ncorr_gui_functions generally proceeds as:
%
% 1) Initialize outputs
% 2) Create GUI handles
% 3) Run the constructor function
%
% The callbacks have the general flow:
%
% 1) Possibly freeze menu if it exists
% 2) Get data with "getappdata()"
% 3) Perform calculations
% 4) Set data with "setappdata()"
% 5) Possibly unfreeze menu if it exists and update UI controls
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% NCORR_ALG* FUNCTIONS:
%
% These functions contain source-code for algorithms used with the ncorr
% object callbacks and ncorr_gui* functions. Most of these algorithms are
% mex files written in C++ and must be compiled with "compile_func_cpp_mex()"
% or mex before using ncorr.
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% NCORR_UTIL* FUNCTIONS:
%
% These functions contain certain utilities used by ncorr, such as
% checking whether the window is within the screen, formatting a colobar,
% etc.
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
properties (SetAccess = private)
% GUI handles:
handles_gui;
% DIC data:
reference;
current;
data_dic;
% Installation data:
support_openmp;
total_cores;
end
% Constructor
methods(Access = public)
function obj = ncorr
% Set default UI control font size here before UI opens. Larger
% font sizes can make the GUI too large. This seems to be an
% error in earlier versions of Matlab
set(0,'defaultuicontrolfontsize',7);
% Initialize GUI and get GUI handles
obj.handles_gui = init_gui(obj);
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@obj.constructor,obj.handles_gui.figure));
end
% Constructor ----------------------------------------------------%
function constructor(obj)
% Check MATLAB version and toolbox compatibility -------------%
if (obj.check_matlabcompat() ~= out.success)
% Force close
obj.callback_close_function([],[],true);
return;
end
% Check MEX installation and load/set ncorr_installinfo.txt --%
if (obj.check_mexinstall() ~= out.success)
% Force close
obj.callback_close_function([],[],true);
return;
end
% Set path ---------------------------------------------------%
% Path to ncorr install directory must be set or else program
% can freeze when loading images from a different directory -
% not sure why this happens.
% Note that if ncorr.m is not in the current directory, then
% path has already been set.
listing = dir;
if (isempty(strfind(lower(path),lower(pwd))) && any(strcmp('ncorr.m',{listing.name})))
% Ask user if its okay to add path
contbutton = questdlg('Path has not been set. Path must be set before running program. Press yes to add path.','Continue Operation','Yes','No','Yes');
if (strcmp(contbutton,'Yes'))
% Add Path
path(path,pwd);
else
% Force close, ncorr may not to work if path is not set
obj.callback_close_function([],[],true);
return;
end
end
% Initialize opengl ------------------------------------------%
% In earlier versions of Matlab this will fix inverted plots
% Plotting tools are also run based on opengl
if (ispc)
data_opengl = opengl('data');
if (~data_opengl.Software)
% Set opengl to software
opengl('software');
end
end
% Start timer to fetch name of the handle that points to ncorr.
% Use a timer because, to my knowledge, there isn't a callback
% option if the handle pointing to ncorr gets cleared.
timer_ncorr = timer('executionMode', 'fixedRate', ...
'Period', 1/5, ...
'TimerFcn', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_update_title(obj,hObject,eventdata),obj.handles_gui.figure));
start(timer_ncorr);
% Program Data -----------------------------------------------%
% Reference image info
obj.reference = struct('imginfo',{},'roi',{});
% Current image(s) info
obj.current = struct('imginfo',{},'roi',{});
% DIC data
obj.data_dic = struct('displacements',struct('plot_u_dic',{}, ... % U plot after DIC (can be regular or eulerian)
'plot_v_dic',{}, ... % V plot after DIC (can be regular or eulerian)
'plot_corrcoef_dic',{}, ... % Correlaton coef plot after DIC (can be regular or eulerian)
'roi_dic',{}, ... % ROI after DIC
'plot_u_ref_formatted',{}, ... % formatted U plot WRT reference image used for displaying displacements
'plot_v_ref_formatted',{}, ... % formatted V plot WRT reference image used for displaying displacements
'roi_ref_formatted',{}, ... % ROI after formatting used for plotting displacements
'plot_u_cur_formatted',{}, ... % formatted U plot WRT current image used for displaying displacements
'plot_v_cur_formatted',{}, ... % formatted V plot WRT current image used for displaying displacements
'roi_cur_formatted',{}), ... % ROI after formatting used for plotting displacements
'dispinfo',struct('type',{}, ... % Type of DIC: either regular or backward
'radius',{}, ... % Radius for DIC
'spacing',{}, ... % Spacing for DIC
'cutoff_diffnorm',{}, ... % Cutoff for norm of the difference vector
'cutoff_iteration',{}, ... % Cutoff for the number of iterations
'total_threads',{}, ... % Number of threads for computation
'stepanalysis',struct('enabled',{},'type',{},'auto',{},'step',{}), ... % Indicates whether or not to implement step analysis for high strain
'subsettrunc',{}, ... % Indicates whether or not to implement subset truncation for DIC analysis
'imgcorr',struct('idx_ref',{},'idx_cur',{}), ... % Image correspondences
'pixtounits',{}, ... % Ratio of "units" to pixels. Assumes pixels are square
'units',{}, ... % String to display units
'cutoff_corrcoef',{}, ... % Correlation coefficient cutoff for each formatted displacement plot
'lenscoef',{}), ... % Radial lens distortion coefficient
'strains',struct('plot_exx_ref_formatted',{}, ... % Exx Green-Lagragian strain plot
'plot_exy_ref_formatted',{}, ... % Exy Green-Lagragian strain plot
'plot_eyy_ref_formatted',{}, ... % Exy Green-Lagragian strain plot
'roi_ref_formatted',{}, ... % ROI used for plotting strains
'plot_exx_cur_formatted',{}, ... % Exx Eulerian-Almansi strain plot
'plot_exy_cur_formatted',{}, ... % Exy Eulerian-Almansi strain plot
'plot_eyy_cur_formatted',{}, ... % Exy Eulerian-Almansi strain plot
'roi_cur_formatted',{}), ... % ROI used for plotting strains
'straininfo',struct('radius',{}, ... % Strain radius used for calculating strains
'subsettrunc',{})); % Indicates whether or not to implement subset truncation for strain analysis
% Appdata - setting these to '[]' technically does nothing, but
% it is included here to show what appdata are/will be present in the
% figure
% handles_plot are the handles for the data plots:
setappdata(obj.handles_gui.figure,'handles_plot',[]);
% num_cur is the current image which is currently being displayed:
setappdata(obj.handles_gui.figure,'num_cur',[]);
% timer_ncorr is the timer for this instantiation of ncorr;
% it is used for fetching the name of the handle points to
% ncorr in the current workspace
setappdata(obj.handles_gui.figure,'timer',timer_ncorr);
% Set visible
set(obj.handles_gui.figure,'Visible','on');
end
% Destructor -----------------------------------------------------%
% This ensures data is deleted if delete is called directly on the
% ncorr handle.
function delete(obj)
if (ishandle(obj.handles_gui.figure))
% Setting 3rd argument to true results in a force close.
obj.callback_close_function([],[],true);
end
end
% Public methods -------------------------------------------------%
% These are used for setting the reference image, current image, or
% ROI manually.
function set_ref(obj,ref_prelim)
% Form wrapped function
handle_set_ref = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(ref_prelim)set_ref_source(obj,ref_prelim),obj.handles_gui.figure));
% Call wrapped function
handle_set_ref(ref_prelim);
end
function set_cur(obj,cur_prelim)
% Form wrapped function
handle_set_cur = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(cur_prelim)set_cur_source(obj,cur_prelim),obj.handles_gui.figure));
% Call wrapped function
handle_set_cur(cur_prelim);
end
function set_roi_ref(obj,mask_prelim)
% Form wrapped function
handle_set_roi_ref = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(mask_prelim)set_roi_ref_source(obj,mask_prelim),obj.handles_gui.figure));
% Call wrapped function
handle_set_roi_ref(mask_prelim);
end
function set_roi_cur(obj,mask_prelim)
% Form wrapped function
handle_set_roi_cur = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(mask_prelim)set_roi_cur_source(obj,mask_prelim),obj.handles_gui.figure));
% Call wrapped function
handle_set_roi_cur(mask_prelim);
end
function refresh(obj)
% Form wrapped function
handle_refresh = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@()refresh_source(obj),obj.handles_gui.figure));
% Call wrapped function
handle_refresh();
end
end
methods(Access = private)
% ----------------------------------------------------------------%
% Local Utility Function(s) --------------------------------------%
% ----------------------------------------------------------------%
function handle_wrapcallback = util_wrapcallbackall(obj,handle_callback)
% This function wraps the callback with the update* UI functions. It
% also checks to see if an error was generated, and if it was, it
% will rethrow it and recomplete the finishing update* UI functions
% to ensure the menu unfreezes. Note that the error will not be
% rethrown if the figure is closed.
%
% Inputs ---------------------------------------------------------%
% handle_callback - function handle;
%
% Outputs --------------------------------------------------------%
% handle_wrapcallback - function handle;
handle_wrapcallback = @updatestatecallback;
function updatestatecallback(varargin)
try
% Beginning of callback - freeze menu;
obj.freeze_menu();
% Run callback
handle_callback(varargin{:});
% End of callback;
% Update axes
obj.update_axes('set');
% Update UI menu
obj.update_topmenu();
% Update state text
obj.update_dicstatetext();
% Unfreeze top layer of menu
obj.unfreeze_menu();
catch err
% If figure still exists, update UI and then rethrow
% error
if (isvalid(obj) && ishandle(obj.handles_gui.figure))
% Error is generated in callback
obj.update_axes('set');
% Update UI menu
obj.update_topmenu();
% Update state text
obj.update_dicstatetext();
% Unfreeze top layer of menu
obj.unfreeze_menu();
% Rethrow error
rethrow(err);
end
end
end
end
function name = util_get_name(obj)
% This function will obtain the name of the variable in the main
% workspace that points to this ncorr object
% Initialize output
name = '';
% Get all variables in base workspace
basevars = evalin('base','whos');
% Grab variables of class ncorr
ncorrvars = basevars(strcmp({basevars.class},class(obj)));
% Cycle through variables and find which one is equivalent to
% this object
for i = 1:length(ncorrvars)
if (eq(evalin('base',ncorrvars(i).name),obj))
% Its possible there are more than one handle that
% point to this object, if that's the case just return
% the first one
name = ncorrvars(i).name;
break;
end
end
end
%-----------------------------------------------------------------%
% Handle Functions Source ----------------------------------------%
%-----------------------------------------------------------------%
function set_ref_source(obj,ref_prelim)
% This function allows the manual uploading of a reference image;
% only a single image is permitted.
% Check to make sure input is of the correct form
if (ncorr_util_properimgfmt(ref_prelim,'Reference image') == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_ref');
if (overwrite)
% Set data
obj.reference(1).imginfo = ncorr_class_img;
obj.reference(1).imginfo.set_img('load',struct('img',ref_prelim,'name','reference','path',''));
obj.reference(1).roi = ncorr_class_roi.empty;
end
end
end
function set_cur_source(obj,cur_prelim)
% This function allows the manual uploading of a current image -
% if a single image is uploaded it must be a double array. If multiple
% images are uploaded, they must be in a cell array.
% Check to make sure input is a cell
if (~iscell(cur_prelim))
% Wrap cur_prelim in a cell
cur_prelim = {cur_prelim};
end
% Make sure each image has the correct format
cursameformat = true;
for i = 0:length(cur_prelim)-1
if (ncorr_util_properimgfmt(cur_prelim{i+1},'Current image') ~= out.success)
cursameformat = false;
break;
end
end
if (cursameformat)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_cur');
if (overwrite)
% It's possible to run out of memory here, so put this
% in a try-catch block
try
% Set data
for i = 0:length(cur_prelim)-1
obj.current(i+1).imginfo = ncorr_class_img;
obj.current(i+1).imginfo.set_img('load',struct('img',cur_prelim{i+1},'name',['current_' num2str(i+1)],'path',''));
obj.current(i+1).roi = ncorr_class_roi.empty;
end
setappdata(obj.handles_gui.figure,'num_cur',length(cur_prelim)-1);
catch %#ok<CTCH>
h_error = errordlg('Loading current images failed, most likely because Ncorr ran out of memory.','Error','modal');
uiwait(h_error);
% Clear all current images because exception could have
% been thrown midway through setting current images
obj.current(:) = [];
setappdata(obj.handles_gui.figure,'num_cur',[]);
end
end
else
h_error = errordlg('Loading current images failed because the image data format was incorrect.','Error','modal');
uiwait(h_error);
end
end
function set_roi_ref_source(obj,mask_prelim)
% This function allows the manual uploading of a region of
% interest.
% Check to make sure reference image has been loaded first -
% for menu callbacks this isn't necessary since these options
% will only become callable if "upstream" data has been loaded
if (~isempty(obj.reference))
% Make sure ROI is the same size as the reference image and
% is of class logical.
if (isequal(size(mask_prelim),[obj.reference.imginfo.height obj.reference.imginfo.width]) && islogical(mask_prelim))
% Form roi_prelim
roi_prelim = ncorr_class_roi;
roi_prelim.set_roi('load',struct('mask',mask_prelim,'cutoff',2000));
% Make sure ROI is not empty
if (roi_prelim.get_fullregions > 0)
% At this point, roi_prelim fits the critera for a ROI. Show ROI
% overlayed and ask user if ROI is appropriate:
outstate = ncorr_gui_loadroi(obj.reference.imginfo, ...
roi_prelim, ...
get(obj.handles_gui.figure,'OuterPosition'));
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_roi');
if (overwrite)
% At this point, ROI is acceptable, has been
% approved by the user, and will now be set.
% Package data:
dispinfo_template.type = 'regular';
dispinfo_template.radius = [];
dispinfo_template.spacing = [];
dispinfo_template.cutoff_diffnorm = [];
dispinfo_template.cutoff_iteration = [];
dispinfo_template.total_threads = [];
dispinfo_template.stepanalysis = struct('enabled',{},'type',{},'auto',{},'step',{});
dispinfo_template.subsettrunc = [];
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
obj.reference(1).roi = roi_prelim;
end
end
else
h_error = errordlg('ROI must contain a large contiguous region.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Input must be of class logical and the same size as the reference image','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Reference image has not been loaded yet','Error','modal');
uiwait(h_error);
end
end
function set_roi_cur_source(obj,mask_prelim)
% This function allows the manual uploading of a region of
% interest. This ROI corresponds to the LAST current image.
% Check to make sure current image(s) have been loaded first -
% for menu callbacks this isn't necessary since these options
% will only become callable if "upstream" data has been loaded
if (~isempty(obj.current))
% Make sure ROI is the same size as the last current image
if (isequal(size(mask_prelim),[obj.current(end).imginfo.height obj.current(end).imginfo.width]) && islogical(mask_prelim))
% Form roi_prelim
roi_prelim = ncorr_class_roi;
roi_prelim.set_roi('load',struct('mask',mask_prelim,'cutoff',2000));
% Make sure ROI is not empty
if (roi_prelim.get_fullregions > 0)
% At this point, roi_prelim fits the critera for a ROI. Show ROI
% overlayed and ask user if ROI is appropriate:
outstate = ncorr_gui_loadroi(obj.current(end).imginfo, ...
roi_prelim, ...
get(obj.handles_gui.figure,'OuterPosition'));
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_roi');
if (overwrite)
% At this point, ROI is acceptable, has been
% approved by the user, and will now be set.
% Package data:
dispinfo_template.type = 'backward';
dispinfo_template.radius = [];
dispinfo_template.spacing = [];
dispinfo_template.cutoff_diffnorm = [];
dispinfo_template.cutoff_iteration = [];
dispinfo_template.total_threads = [];
dispinfo_template.stepanalysis = struct('enabled',{},'type',{},'auto',{},'step',{});
dispinfo_template.subsettrunc = [];
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
obj.current(end).roi = roi_prelim;
end
end
else
h_error = errordlg('ROI must contain a large contiguous region.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Input must be of class logical and the same size as the last current image','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Current image(s) have not been loaded yet.','Error','modal');
uiwait(h_error);
end
end
function refresh_source(obj) %#ok<MANU>
% Call this function if there's an error and the menu needs to be
% unfrozen.
end
%-----------------------------------------------------------------%
% Menu Callbacks -------------------------------------------------%
%-----------------------------------------------------------------%
function callback_topmenu_loadref(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for loading a reference image from the
% GUI.
% false means lazy loading isnt used
[ref_prelim,outstate] = ncorr_util_loadimgs(false);
if (outstate == out.success && length(ref_prelim) == 1)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_ref');
if (overwrite)
% Set Image
obj.reference(1).imginfo = ref_prelim;
obj.reference(1).roi = ncorr_class_roi.empty;
end
elseif (outstate == out.success && length(ref_prelim) > 1)
h_error = errordlg('Please select only one reference image.','Error','modal');
uiwait(h_error);
end
end
function callback_topmenu_loadcur(obj,hObject,eventdata,lazyparam) %#ok<INUSL>
% This is the callback for loading current image(s) from the GUI.
[cur_prelim,outstate] = ncorr_util_loadimgs(lazyparam);
if (outstate == out.success)
overwrite = obj.clear_downstream('set_cur');
if (overwrite)
% Set Image
for i = 0:length(cur_prelim)-1
obj.current(i+1).imginfo = cur_prelim(i+1);
obj.current(i+1).roi = ncorr_class_roi.empty;
end
% Display last current image
setappdata(obj.handles_gui.figure,'num_cur',length(cur_prelim)-1);
end
end
end
function callback_topmenu_loaddata(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for loading data from a previous analysis.
% Get data filename
[filename,pathname] = uigetfile({'*.mat'},'Select the previous DIC data (must be .dat)');
if (~isequal(filename,0) && ~isequal(pathname,0));
try
% Load data
struct_load = load(fullfile(pathname,filename));
loadsuccess = true;
catch %#ok<CTCH>
% Probably out of memory
loadsuccess = false;
end
if (loadsuccess)
if (isfield(struct_load,'reference_save') && isfield(struct_load,'current_save') && isfield(struct_load,'data_dic_save'))
% The data has the correct fields
if (isa(struct_load.reference_save,'struct') && ...
isa(struct_load.current_save,'struct') && ...
isa(struct_load.data_dic_save,'struct'))
% Make sure data_dic has the correct
% fields. Easiest way to do this is to assign
% the saved data to a structure with the
% correct fields, an error will result if the
% fields are wrong
data_dic_prelim = obj.data_dic; % This will copy fields - only used temporarily
try
data_dic_prelim(1) = struct_load.data_dic_save; %#ok<NASGU>
loaddatasuccess = true;
catch %#ok<CTCH>
% Some fields are not correct
loaddatasuccess = false;
end
if (loaddatasuccess)
% See if data will be overwritten
overwrite = obj.clear_downstream('all');
if (overwrite)
% Put in try block - its possible to run
% out of memory here.
try
% Do reference image first
[ref_prelim,outstate_ref] = ncorr_util_loadsavedimg(struct_load.reference_save);
% Do current images next
cur_prelim = ncorr_class_img.empty;
for i = 0:length(struct_load.current_save)-1
[cur_buffer,outstate_cur] = ncorr_util_loadsavedimg(struct_load.current_save(i+1));
if (outstate_cur == out.success)
cur_prelim(i+1) = cur_buffer;
else
break;
end
end
if (outstate_ref == out.success && outstate_cur == out.success)
% Store data:
% Set reference:
obj.reference(1).imginfo = ref_prelim;
obj.reference(1).roi = struct_load.reference_save.roi;
% Set current:
for i = 0:length(struct_load.current_save)-1
obj.current(i+1).imginfo = cur_prelim(i+1);
obj.current(i+1).roi = struct_load.current_save(i+1).roi;
end
setappdata(obj.handles_gui.figure,'num_cur',length(struct_load.current_save)-1);
% Set dic data:
obj.data_dic(1) = struct_load.data_dic_save;
else
% Images could not be found
% Form error message
msg_error{1} = 'Images could not be located. Make sure they are in the current directory or were not moved from the locations listed here:';
msg_error{2} = fullfile(struct_load.reference_save.path,struct_load.reference_save.name);
max_display = 10;
for i = 0:min(length(struct_load.current_save),max_display)-1
msg_error{end+1} = fullfile(struct_load.current_save(i+1).path,struct_load.current_save(i+1).name); %#ok<AGROW>
end
if (length(struct_load.current_save) > max_display)
msg_error{end+1} = '...';
end
h_error = errordlg(msg_error,'Error','modal');
uiwait(h_error);
end
catch %#ok<CTCH>
h_error = errordlg('Loading failed, most likely because Ncorr ran out of memory.','Error','modal');
uiwait(h_error);
% Clear everything - its possible
% exception was caught while
% loading data midway.
obj.reference(:) = [];
obj.current(:) = [];
setappdata(obj.handles_gui.figure,'num_cur',[]);
fields_data_dic = fieldnames(obj.data_dic);
for i = 0:length(fields_data_dic)-1
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
end
else
h_error = errordlg('The data is not valid, please load data saved specifically from ncorr.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('The data is not valid, please load data saved specifically from ncorr.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('The data is not valid, please load data saved specifically from ncorr.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Loading failed, most likely because Ncorr ran out of memory.','Error','modal');
uiwait(h_error);
end
end
end
function callback_topmenu_savedata(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for saving data.
% Get save data filename
[filename,pathname] = uiputfile({'*.mat'},'Save DIC data (must be .dat)');
if (~isequal(filename,0) && ~isequal(pathname,0));
% Check if data will be overwritten in directory
overwrite = true;
if (exist(fullfile(pathname,filename),'file'))
contbutton = questdlg('File already exists. Do you want to overwrite?','Continue Operation','Yes','No','Yes');
if (strcmp(contbutton,'No'))
overwrite = false;
end
end
if (overwrite)
% Must deal with image data, ROI data, and data_dic.
% 1) Images: Save the file names if they are 'file' or 'lazy'
% If they were set through the workspace (i.e. 'load') then save the
% image as double precision.
% 2) ROIs: For the ROIs, save each directly.
% 3) Data: Save data_dic directly.
reference_save = struct('type',{},'gs',{},'name',{},'path',{},'roi',{});
current_save = struct('type',{},'gs',{},'name',{},'path',{},'roi',{});
% Images ---------------------------------------------%
% Reference image:
reference_save(1).type = obj.reference.imginfo.type;
reference_save.gs = [];
if (strcmp(obj.reference.imginfo.type,'load'))
% Must save gs data directly
reference_save.gs = obj.reference.imginfo.get_gs();
end
reference_save.name = obj.reference.imginfo.name;
reference_save.path = obj.reference.imginfo.path;
reference_save.roi = obj.reference.roi; %#ok<STRNU>
% Current image(s):
for i = 0:length(obj.current)-1
current_save(i+1).type = obj.current(i+1).imginfo.type;
current_save(i+1).gs = [];
if (strcmp(obj.current(i+1).imginfo.type,'load'))
% Must save gs data directly
current_save(i+1).gs = obj.current(i+1).imginfo.get_gs();
end
current_save(i+1).name = obj.current(i+1).imginfo.name;
current_save(i+1).path = obj.current(i+1).imginfo.path;
current_save(i+1).roi = obj.current(i+1).roi;
end
% Data -----------------------------------------------%
data_dic_save = obj.data_dic; %#ok<NASGU>
% Save -----------------------------------------------%
try
% The v7.3 flag helps save larger files
save(fullfile(pathname,filename),'reference_save','current_save','data_dic_save','-v7.3');
catch %#ok<CTCH>
% If saving fails, its generally because the files
% are too large.
h_error = errordlg('Saving failed, probably because the amount of data being saved is too large.','Error','modal');
uiwait(h_error);
end
end
end
end
function callback_topmenu_clear(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for the clearing all the data.
obj.clear_downstream('all');
end
function callback_topmenu_sethandle(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for setting the handle to ncorr in the case
% that it gets cleared from the workspace
% Get Name
name = util_get_name(obj);
if (isempty(name))
% Prompt user for what handle he/she wants to use
[handle_name,outstate] = gui_sethandle(get(obj.handles_gui.figure,'OuterPosition'));
if (outstate == out.success)
% Assign handles to base workspace
assignin('base',handle_name,obj);
end
else
% Handle already exists
e = msgbox(['Handle already exists and is called: ' name],'WindowStyle','modal');
uiwait(e);
end
end
function callback_topmenu_reinstall(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for reinstalling the mex files.
% Check if ncorr.m is in current directory
listing = dir;
if (any(strcmp('ncorr.m',{listing.name})))
% Ask user if its okay to reinstall
contbutton = questdlg('Are you sure you want to reinstall? All data will be lost if proceeding.','Continue Operation','Yes','No','Yes');
if (strcmp(contbutton,'Yes'))
% Clear ncorr_installinfo.txt file - this is the standard
% way to reinstall
filename = 'ncorr_installinfo.txt';
fid = fopen(filename,'w'); % This will clear file
if (fid ~= -1)
fclose(fid); % Close file
% Force close
obj.callback_close_function([],[],true);
% Reopen ncorr - this will cause reinstallation since
% ncorr_installinfo.txt has been cleared
handles_ncorr = ncorr;
% Get name
name = util_get_name(obj);
if (~isempty(name))
% If there is a name then assign the name to the
% ncorr object.
assignin('base',name,handles_ncorr);
end
else
% Error
h_error = errordlg('For some reason ncorr was not able to clear "ncorr_installinfo.txt" file, reinstall cannot take place.','Error','modal');
uiwait(h_error);
end
end
else
% Error
h_error = errordlg('Please navigate to folder containing ncorr.m first before reinstalling.','Error','modal');
uiwait(h_error);
end
end
function callback_exit_callback(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for exiting the program.
% 3rd argument is set to false, which queries user about
% closing if DIC data has been computed.
obj.callback_close_function([],[],false);
end
function callback_topmenu_set_roi_ref(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for loading the region of interest from the
% GUI
% Get ROIs ---------------------------------------------------%
% Check if ROI has been set before - must be from the regular
% analysis, as backward DIC analysis will also set a reference ROI
params_init = ncorr_class_roi.empty;
if (~isempty(obj.reference) && ~isempty(obj.reference.roi) && ...
~isempty(obj.data_dic.dispinfo) && strcmp(obj.data_dic.dispinfo.type,'regular'))
params_init(1) = obj.reference.roi;
end
[roi_prelim,outstate] = ncorr_gui_setrois(obj.reference.imginfo, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_roi');
if (overwrite)
% Package data:
dispinfo_template.type = 'regular';
dispinfo_template.radius = [];
dispinfo_template.spacing = [];
dispinfo_template.cutoff_diffnorm = [];
dispinfo_template.cutoff_iteration = [];
dispinfo_template.total_threads = [];
dispinfo_template.stepanalysis = struct('enabled',{},'type',{},'auto',{},'step',{});
dispinfo_template.subsettrunc = [];
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
obj.reference(1).roi = roi_prelim;
end
end
end
function callback_topmenu_set_roi_cur(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for loading the region of interest from
% the GUI
% Get ROIs ---------------------------------------------------%
% Check if ROI has been set before - must be from the backward
% analysis, as backward dic analysis will also set a current ROI
params_init = ncorr_class_roi.empty;
if (~isempty(obj.current) && ~isempty(obj.current(end).roi) && ...
~isempty(obj.data_dic.dispinfo) && strcmp(obj.data_dic.dispinfo.type,'backward'))
params_init(1) = obj.current(end).roi;
end
[roi_prelim,outstate] = ncorr_gui_setrois(obj.current(end).imginfo, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_roi');
if (overwrite)
% Package data:
dispinfo_template.type = 'backward';
dispinfo_template.radius = [];
dispinfo_template.spacing = [];
dispinfo_template.cutoff_diffnorm = [];
dispinfo_template.cutoff_iteration = [];
dispinfo_template.total_threads = [];
dispinfo_template.stepanalysis = struct('enabled',{},'type',{},'auto',{},'step',{});
dispinfo_template.subsettrunc = [];
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
obj.current(end).roi = roi_prelim;
end
end
end
function callback_topmenu_setdicparameters(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for setting DIC parameters
% Check if DIC parameters were set before - if dic parameters
% are being set, the data_dic.dispinfo field is gauranteed
% nonempty, so you don't need to check this first.
params_init = {};
if (~isempty(obj.data_dic.dispinfo.radius) && ...
~isempty(obj.data_dic.dispinfo.spacing) && ...
~isempty(obj.data_dic.dispinfo.cutoff_diffnorm) && ...
~isempty(obj.data_dic.dispinfo.cutoff_iteration) && ...
~isempty(obj.data_dic.dispinfo.total_threads) && ...
~isempty(obj.data_dic.dispinfo.stepanalysis) && ...
~isempty(obj.data_dic.dispinfo.subsettrunc))
params_init = {obj.data_dic.dispinfo.radius, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.cutoff_diffnorm, ...
obj.data_dic.dispinfo.cutoff_iteration, ...
obj.data_dic.dispinfo.total_threads, ...
obj.data_dic.dispinfo.stepanalysis, ...
obj.data_dic.dispinfo.subsettrunc};
end
% Get Params -------------------------------------------------%
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
% Show reference image for regular analysis
[radius_prelim,spacing_prelim,cutoff_diffnorm_prelim,cutoff_iteration_prelim,total_threads_prelim,stepanalysis_prelim,subsettrunc_prelim,outstate] = ncorr_gui_setdicparams(obj.reference.imginfo, ...
obj.reference.roi, ...
obj.support_openmp, ...
obj.total_cores, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
else
% Show last current image for backward analysis
[radius_prelim,spacing_prelim,cutoff_diffnorm_prelim,cutoff_iteration_prelim,total_threads_prelim,stepanalysis_prelim,subsettrunc_prelim,outstate] = ncorr_gui_setdicparams(obj.current(end).imginfo, ...
obj.current(end).roi, ...
obj.support_openmp, ...
obj.total_cores, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
end
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_dicparameters');
if (overwrite)
% Package data:
dispinfo_template.type = obj.data_dic.dispinfo.type;
dispinfo_template.radius = radius_prelim;
dispinfo_template.spacing = spacing_prelim;
dispinfo_template.cutoff_diffnorm = cutoff_diffnorm_prelim;
dispinfo_template.cutoff_iteration = cutoff_iteration_prelim;
dispinfo_template.total_threads = total_threads_prelim;
dispinfo_template.stepanalysis = stepanalysis_prelim;
dispinfo_template.subsettrunc = subsettrunc_prelim;
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
end
end
end
function callback_topmenu_dic(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for performing DIC.
% Merge images. This makes it convenient for the idx
% tracker if step analysis is used
imgs = [obj.reference obj.current];
% Initialize
rois_dic_prelim = ncorr_class_roi.empty;
displacements_prelim = struct('plot_u',{},'plot_v',{},'plot_corrcoef',{},'plot_validpoints',{});
imgcorr_prelim = struct('idx_ref',{},'idx_cur',{});
seedinfo_buffer = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
% Imgcorr starts out empty so this guarantees at least one
% iteration. Make sure to exit when all images have been
% analyzed.
while (isempty(imgcorr_prelim) || imgcorr_prelim(end).idx_cur < length(imgs)-1)
% Update idx_ref
if (isempty(imgcorr_prelim))
imgcorr_prelim(1).idx_ref = 0;
else
% Use previous last current image as the new
% reference image
imgcorr_prelim(end+1).idx_ref = imgcorr_prelim(end).idx_cur; %#ok<AGROW>
end
% Update idx_cur
if (obj.data_dic.dispinfo.stepanalysis.enabled && strcmp(obj.data_dic.dispinfo.stepanalysis.type,'leapfrog'))
% If leapfrog is used, then set current image to a
% preset increment
imgcorr_prelim(end).idx_cur = min(imgcorr_prelim(end).idx_ref+obj.data_dic.dispinfo.stepanalysis.step,length(imgs)-1);
else
% If this is not leapfrog, set the current image to
% the last image. This number will get updated
% depending on how many images are successfully
% analyzed and seeded
imgcorr_prelim(end).idx_cur = length(imgs)-1;
end
% Do DIC analysis - only send initial parameters if
% stepanalysis is enabled with automatic seed
% propagation and an interation has already been done.
params_init = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});
if (obj.data_dic.dispinfo.stepanalysis.enabled && ...
obj.data_dic.dispinfo.stepanalysis.auto && ...
~isempty(seedinfo_buffer))
% Get previous seeds as initial parameters if step
% analysis and automatic seed propagation are enabled.
% If these are provided then the seeds are automatically
% updated
params_init = seedinfo_buffer;
end
% Returns failed if exception is thrown; for both
% failed and cancel just return.
[displacements_buffer,rois_dic_buffer,seedinfo_buffer,outstate_dic] = ncorr_alg_dicanalysis(imgs(imgcorr_prelim(end).idx_ref+1:imgcorr_prelim(end).idx_cur+1), ...
obj.data_dic.dispinfo.radius, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.cutoff_diffnorm, ...
obj.data_dic.dispinfo.cutoff_iteration, ...
obj.data_dic.dispinfo.total_threads, ...
obj.data_dic.dispinfo.stepanalysis.enabled, ...
obj.data_dic.dispinfo.subsettrunc, ...
imgcorr_prelim(end).idx_ref, ...
length(obj.current), ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
if (outstate_dic ~= out.success)
% DIC analysis was cancelled or failed by throwing
% an exception, for both cases return
return;
end
% Update ROIs
for i = 0:length(displacements_buffer)-1
imgs(i+imgcorr_prelim(end).idx_ref+2).roi = imgs(imgcorr_prelim(end).idx_ref+1).roi.update_roi(displacements_buffer(i+1).plot_u, ...
displacements_buffer(i+1).plot_v, ...
rois_dic_buffer(i+1), ...
[imgs(i+imgcorr_prelim(end).idx_ref+2).imginfo.height imgs(i+imgcorr_prelim(end).idx_ref+2).imginfo.width], ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.radius);
end
% Store outputs
for i = 0:length(displacements_buffer)-1
displacements_prelim(i+imgcorr_prelim(end).idx_ref+1) = displacements_buffer(i+1);
rois_dic_prelim(i+imgcorr_prelim(end).idx_ref+1) = rois_dic_buffer(i+1);
end
% Update imgcorr_prelim if stepanalysis is enabled
% - this is necessary since not all images are
% necessarily analyzed.
if (obj.data_dic.dispinfo.stepanalysis.enabled)
imgcorr_prelim(end).idx_cur = imgcorr_prelim(end).idx_ref + length(displacements_buffer);
end
end
else
% Imgcorr starts out empty so this guarantees at least one
% iteration. Make sure to exit when all images have been
% analyzed.
while (isempty(imgcorr_prelim) || imgcorr_prelim(end).idx_cur > 0)
% Update idx_ref
if (isempty(imgcorr_prelim))
imgcorr_prelim(1).idx_ref = length(imgs)-1;
else
% Use previous last current image as the new
% reference image
imgcorr_prelim(end+1).idx_ref = imgcorr_prelim(end).idx_cur; %#ok<AGROW>
end
% Update idx_cur
if (obj.data_dic.dispinfo.stepanalysis.enabled && strcmp(obj.data_dic.dispinfo.stepanalysis.type,'leapfrog'))
% If leapfrog is used, then set current image to a
% preset increment
imgcorr_prelim(end).idx_cur = max(imgcorr_prelim(end).idx_ref-obj.data_dic.dispinfo.stepanalysis.step,0);
else
% If this is not leapfrog, set the current image to
% the last image. This number will get updated
% depending on how many images are successfully
% analyzed and seeded
imgcorr_prelim(end).idx_cur = 0;
end
% Do DIC analysis - only send initial parameters if
% stepanalysis is enabled with automatic seed
% propagation and an interation has already been done.
params_init = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});
if (obj.data_dic.dispinfo.stepanalysis.enabled && ...
obj.data_dic.dispinfo.stepanalysis.auto && ...
~isempty(seedinfo_buffer))
% Get previous seeds as initial parameters if step
% analysis and automatic seed propagation are enabled.
% If these are provided then the seeds are automatically
% updated
params_init = seedinfo_buffer;
end
% Returns failed if exception is thrown; for both
% failed and cancel just return.
[displacements_buffer,rois_dic_buffer,seedinfo_buffer,outstate_dic] = ncorr_alg_dicanalysis(imgs(imgcorr_prelim(end).idx_ref+1:-1:imgcorr_prelim(end).idx_cur+1), ...
obj.data_dic.dispinfo.radius, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.cutoff_diffnorm, ...
obj.data_dic.dispinfo.cutoff_iteration, ...
obj.data_dic.dispinfo.total_threads, ...
obj.data_dic.dispinfo.stepanalysis.enabled, ...
obj.data_dic.dispinfo.subsettrunc, ...
length(obj.current)-imgcorr_prelim(end).idx_ref, ...
length(obj.current), ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
if (outstate_dic ~= out.success)
% DIC analysis was cancelled or failed by throwing
% an exception, for both cases return
return;
end
% Update ROIs
for i = 0:length(displacements_buffer)-1
imgs(imgcorr_prelim(end).idx_ref-i).roi = imgs(imgcorr_prelim(end).idx_ref+1).roi.update_roi(displacements_buffer(i+1).plot_u, ...
displacements_buffer(i+1).plot_v, ...
rois_dic_buffer(i+1), ...
[imgs(imgcorr_prelim(end).idx_ref-i).imginfo.height imgs(imgcorr_prelim(end).idx_ref-i).imginfo.width], ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.radius);
end
% Update displacements
for i = 0:length(displacements_buffer)-1
% Displacements must be updated if more than two
% images were analyzed. Also, leave the last
% displacement field in the buffer alone since
% it's already WRT the correct configuration
if (i > 0)
% Update displacement fields
params_init = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});
if (obj.data_dic.dispinfo.stepanalysis.auto)
params_init = seedinfo_buffer(:,:,end-i);
end
% Returns failed if exception is thrown; for both
% failed and cancel just return.
[displacement_buffer_update,roi_dic_buffer_update,seedinfo_buffer_update,outstate_dic] = ncorr_alg_dicanalysis([imgs(imgcorr_prelim(end).idx_ref-length(displacements_buffer)+i+1) imgs(imgcorr_prelim(end).idx_ref-length(displacements_buffer)+1)], ...
obj.data_dic.dispinfo.radius, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.cutoff_diffnorm, ...
obj.data_dic.dispinfo.cutoff_iteration, ...
obj.data_dic.dispinfo.total_threads, ...
obj.data_dic.dispinfo.stepanalysis.enabled, ...
obj.data_dic.dispinfo.subsettrunc, ...
length(obj.current)-imgcorr_prelim(end).idx_ref+i, ...
length(obj.current), ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init); %#ok<ASGLU>
if (outstate_dic ~= out.success)
% DIC analysis was cancelled or failed by throwing
% an exception, for both cases return
return;
end
% Store Displacements
displacements_prelim(imgcorr_prelim(end).idx_ref-length(displacements_buffer)+i) = displacement_buffer_update;
rois_dic_prelim(imgcorr_prelim(end).idx_ref-length(displacements_buffer)+i) = roi_dic_buffer_update;
else
% Directly store displacements
displacements_prelim(imgcorr_prelim(end).idx_ref) = displacements_buffer(end);
rois_dic_prelim(imgcorr_prelim(end).idx_ref) = rois_dic_buffer(end);
end
end
% Update imgcorr_prelim - this is necessary since
% not all images are necessarily analyzed.
if (obj.data_dic.dispinfo.stepanalysis.enabled)
imgcorr_prelim(end).idx_cur = imgcorr_prelim(end).idx_ref - length(displacements_buffer);
end
end
end
% Save the data
% See if data will be overwritten
overwrite = obj.clear_downstream('dicanalysis');
if (overwrite)
% Package the data:
for i = 0:length(obj.current)-1
displacements_template(i+1).plot_u_dic = displacements_prelim(i+1).plot_u; %#ok<AGROW>
displacements_template(i+1).plot_v_dic = displacements_prelim(i+1).plot_v; %#ok<AGROW>
displacements_template(i+1).plot_corrcoef_dic = displacements_prelim(i+1).plot_corrcoef; %#ok<AGROW>
displacements_template(i+1).roi_dic = rois_dic_prelim(i+1); %#ok<AGROW>
displacements_template(i+1).plot_u_ref_formatted = []; %#ok<AGROW>
displacements_template(i+1).plot_v_ref_formatted = []; %#ok<AGROW>
displacements_template(i+1).roi_ref_formatted = []; %#ok<AGROW>
displacements_template(i+1).plot_u_cur_formatted = []; %#ok<AGROW>
displacements_template(i+1).plot_v_cur_formatted = []; %#ok<AGROW>
displacements_template(i+1).roi_cur_formatted = []; %#ok<AGROW>
end
dispinfo_template.type = obj.data_dic.dispinfo.type;
dispinfo_template.radius = obj.data_dic.dispinfo.radius;
dispinfo_template.spacing = obj.data_dic.dispinfo.spacing;
dispinfo_template.cutoff_diffnorm = obj.data_dic.dispinfo.cutoff_diffnorm;
dispinfo_template.cutoff_iteration = obj.data_dic.dispinfo.cutoff_iteration;
dispinfo_template.total_threads = obj.data_dic.dispinfo.total_threads;
dispinfo_template.stepanalysis = obj.data_dic.dispinfo.stepanalysis;
dispinfo_template.subsettrunc = obj.data_dic.dispinfo.subsettrunc;
dispinfo_template.imgcorr = imgcorr_prelim;
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
% Updated ROIs
obj.reference.roi = imgs(1).roi;
for i = 0:length(obj.current)-1
obj.current(i+1).roi = imgs(i+2).roi;
end
% Displacement info
obj.data_dic.dispinfo(1) = dispinfo_template;
for i = 0:length(obj.current)-1
% Store displacements
obj.data_dic.displacements(i+1) = displacements_template(i+1);
end
% Tell user analysis is done
msgbox('DIC Analysis completed successfully. Press ok to finish.','WindowStyle','modal');
end
end
function callback_topmenu_formatdisp(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for formatting the displacements.
% Merge images. This makes it convenient for the idx
% tracker
imgs = [obj.reference.imginfo obj.current.imginfo];
% Check if format has been done before
params_init = cell(0);
if (~isempty(obj.data_dic.dispinfo.pixtounits) && ...
~isempty(obj.data_dic.dispinfo.units) && ...
~isempty(obj.data_dic.dispinfo.cutoff_corrcoef) && ...
~isempty(obj.data_dic.dispinfo.lenscoef))
params_init = {obj.data_dic.dispinfo.pixtounits, ...
obj.data_dic.dispinfo.units, ...
obj.data_dic.dispinfo.cutoff_corrcoef, ...
obj.data_dic.dispinfo.lenscoef};
end
% Initialize
plots_disp_f_prelim = struct('plot_u_ref_formatted',{},'plot_v_ref_formatted',{},'plot_u_cur_formatted',{},'plot_v_cur_formatted',{});
rois_f_ref_prelim = ncorr_class_roi.empty;
rois_f_cur_prelim = ncorr_class_roi.empty;
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
% Gather reference and current images in the correct order
imgs_ref = ncorr_class_img.empty;
imgs_cur = ncorr_class_img.empty;
for i = 0:length(obj.data_dic.dispinfo.imgcorr)-1
imgs_ref = horzcat(imgs_ref,repmat(imgs(obj.data_dic.dispinfo.imgcorr(i+1).idx_ref+1),1,obj.data_dic.dispinfo.imgcorr(i+1).idx_cur-obj.data_dic.dispinfo.imgcorr(i+1).idx_ref)); %#ok<AGROW>
imgs_cur = horzcat(imgs_cur,imgs(obj.data_dic.dispinfo.imgcorr(i+1).idx_ref+2:obj.data_dic.dispinfo.imgcorr(i+1).idx_cur+1)); %#ok<AGROW>
end
% Format step displacements ------------------------------%
[plots_disp_f_step_prelim,rois_f_step_prelim,pixtounits_prelim,units_prelim,cutoff_corrcoef_prelim,lenscoef_prelim,outstate_formatdisp_step] = ncorr_gui_formatdisp(imgs_ref, ...
imgs_cur, ...
[obj.data_dic.displacements.roi_dic], ...
{obj.data_dic.displacements.plot_u_dic}, ...
{obj.data_dic.displacements.plot_v_dic}, ...
{obj.data_dic.displacements.plot_corrcoef_dic}, ...
obj.data_dic.dispinfo.spacing, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
% Check if analysis was cancelled
if (outstate_formatdisp_step ~= out.success)
return;
end
% Convert plots back to pixel displacements
for i = 0:length(obj.current)-1
plots_disp_f_step_prelim(i+1).plot_u_formatted = plots_disp_f_step_prelim(i+1).plot_u_formatted./pixtounits_prelim;
plots_disp_f_step_prelim(i+1).plot_v_formatted = plots_disp_f_step_prelim(i+1).plot_v_formatted./pixtounits_prelim;
end
% Add plots ----------------------------------------------%
% Gather images that dont need to be added
for i = obj.data_dic.dispinfo.imgcorr(1).idx_ref:obj.data_dic.dispinfo.imgcorr(1).idx_cur-1
plots_disp_f_prelim(i+1).plot_u_ref_formatted = plots_disp_f_step_prelim(i+1).plot_u_formatted;
plots_disp_f_prelim(i+1).plot_v_ref_formatted = plots_disp_f_step_prelim(i+1).plot_v_formatted;
rois_f_ref_prelim(i+1) = rois_f_step_prelim(i+1);
end
% Reduce reference ROI
roi_ref_reduced = obj.reference.roi.reduce(obj.data_dic.dispinfo.spacing);
% Add other plots
plot_added_buffer = cell(0);
% Cycle over imgcorr - skip first index in imgcorr
for i = 1:length(obj.data_dic.dispinfo.imgcorr)-1
for j = obj.data_dic.dispinfo.imgcorr(i+1).idx_ref:obj.data_dic.dispinfo.imgcorr(i+1).idx_cur-1
% Get idxs of displacement fields used to add
idx_dispadd = [[obj.data_dic.dispinfo.imgcorr(1:i).idx_cur]-1 j];
% Get added plots
[plot_added_buffer{1},outstate_add] = ncorr_alg_addanalysis({plots_disp_f_step_prelim(idx_dispadd+1).plot_u_formatted}, ...
{plots_disp_f_step_prelim(idx_dispadd+1).plot_v_formatted}, ...
rois_f_step_prelim(idx_dispadd+1), ...
obj.data_dic.dispinfo.spacing, ...
j+1, ...
length(obj.current));
% See if analysis was cancelled
if (outstate_add ~= out.success)
return;
end
% Store "added" plots
plots_disp_f_prelim(j+1).plot_u_ref_formatted = plot_added_buffer{1}.plot_u_added;
plots_disp_f_prelim(j+1).plot_v_ref_formatted = plot_added_buffer{1}.plot_v_added;
rois_f_ref_prelim(j+1) = roi_ref_reduced.get_union(plot_added_buffer{1}.plot_validpoints,0);
end
end
% Convert plots to Eulerian ------------------------------%
% Get Eulerian displacements
plot_eulerian_buffer = cell(0);
roi_eulerian_buffer = cell(0);
for i = 0:length(obj.current)-1
% Convert displacements from Lagrangian to Eulerian perspective
[plot_eulerian_buffer{1},roi_eulerian_buffer{1},outstate_convert] = ncorr_alg_convertanalysis(obj.current(i+1), ...
obj.reference, ...
{plots_disp_f_prelim(i+1).plot_u_ref_formatted}, ...
{plots_disp_f_prelim(i+1).plot_v_ref_formatted}, ...
rois_f_ref_prelim(i+1), ...
obj.data_dic.dispinfo.spacing, ...
i, ...
length(obj.current));
% See if analysis was cancelled or failed. Return for
% both.
if (outstate_convert ~= out.success)
return;
end
% Store
plots_disp_f_prelim(i+1).plot_u_cur_formatted = plot_eulerian_buffer{1}.plot_u_new;
plots_disp_f_prelim(i+1).plot_v_cur_formatted = plot_eulerian_buffer{1}.plot_v_new;
rois_f_cur_prelim(i+1) = roi_eulerian_buffer{1};
end
% Make sure to convert displacements back to real units from
% pixels. Also multiply Eulerian displacements by -1 to
% make them truly Eulerian
for i = 0:length(obj.current)-1
% Lagrangian
plots_disp_f_prelim(i+1).plot_u_ref_formatted = plots_disp_f_prelim(i+1).plot_u_ref_formatted.*pixtounits_prelim;
plots_disp_f_prelim(i+1).plot_v_ref_formatted = plots_disp_f_prelim(i+1).plot_v_ref_formatted.*pixtounits_prelim;
% Eulerian
plots_disp_f_prelim(i+1).plot_u_cur_formatted = -plots_disp_f_prelim(i+1).plot_u_cur_formatted.*pixtounits_prelim;
plots_disp_f_prelim(i+1).plot_v_cur_formatted = -plots_disp_f_prelim(i+1).plot_v_cur_formatted.*pixtounits_prelim;
end
else
% Gather reference and current images in the correct order
imgs_ref = imgs(2:end);
imgs_cur = ncorr_class_img.empty;
for i = length(obj.data_dic.dispinfo.imgcorr)-1:-1:0
imgs_cur = horzcat(imgs_cur,repmat(imgs(obj.data_dic.dispinfo.imgcorr(i+1).idx_cur+1),1,obj.data_dic.dispinfo.imgcorr(i+1).idx_ref-obj.data_dic.dispinfo.imgcorr(i+1).idx_cur)); %#ok<AGROW>
end
% Format step displacements ------------------------------%
[plots_disp_f_step_prelim,rois_f_step_prelim,pixtounits_prelim,units_prelim,cutoff_corrcoef_prelim,lenscoef_prelim,outstate_formatdisp_step] = ncorr_gui_formatdisp(imgs_ref, ...
imgs_cur, ...
[obj.data_dic.displacements.roi_dic], ...
{obj.data_dic.displacements.plot_u_dic}, ...
{obj.data_dic.displacements.plot_v_dic}, ...
{obj.data_dic.displacements.plot_corrcoef_dic}, ...
obj.data_dic.dispinfo.spacing, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
% Check if analysis was cancelled
if (outstate_formatdisp_step ~= out.success)
return;
end
% Convert plots to pixel displacements
for i = 0:length(obj.current)-1
plots_disp_f_step_prelim(i+1).plot_u_formatted = plots_disp_f_step_prelim(i+1).plot_u_formatted./pixtounits_prelim;
plots_disp_f_step_prelim(i+1).plot_v_formatted = plots_disp_f_step_prelim(i+1).plot_v_formatted./pixtounits_prelim;
end
% Add plots ------------------------------------------%
% Gather images that dont need to be added
for i = obj.data_dic.dispinfo.imgcorr(end).idx_cur:obj.data_dic.dispinfo.imgcorr(end).idx_ref-1
plots_disp_f_prelim(i+1).plot_u_cur_formatted = plots_disp_f_step_prelim(i+1).plot_u_formatted;
plots_disp_f_prelim(i+1).plot_v_cur_formatted = plots_disp_f_step_prelim(i+1).plot_v_formatted;
rois_f_cur_prelim(i+1) = rois_f_step_prelim(i+1);
end
% Add other plots
plot_added_buffer = cell(0);
counter = obj.data_dic.dispinfo.imgcorr(end).idx_ref+1;
% Cycle over imgcorr - skip over last index
for i = 0:length(obj.data_dic.dispinfo.imgcorr)-2
for j = obj.data_dic.dispinfo.imgcorr(i+1).idx_ref-1:-1:obj.data_dic.dispinfo.imgcorr(i+1).idx_cur
% Get idxs of displacement fields used to add
idx_dispadd = [j [obj.data_dic.dispinfo.imgcorr(i+2:end).idx_ref]-1];
% Get added plots
[plot_added_buffer{1},outstate_add] = ncorr_alg_addanalysis({plots_disp_f_step_prelim(idx_dispadd+1).plot_u_formatted}, ...
{plots_disp_f_step_prelim(idx_dispadd+1).plot_v_formatted}, ...
rois_f_step_prelim(idx_dispadd+1), ...
obj.data_dic.dispinfo.spacing, ...
counter, ...
length(obj.current));
% See if analysis was cancelled
if (outstate_add ~= out.success)
return;
end
% Reduce current ROI
roi_cur_reduced = obj.current(j+1).roi.reduce(obj.data_dic.dispinfo.spacing);
% Store "added" plots
plots_disp_f_prelim(j+1).plot_u_cur_formatted = plot_added_buffer{1}.plot_u_added;
plots_disp_f_prelim(j+1).plot_v_cur_formatted = plot_added_buffer{1}.plot_v_added;
rois_f_cur_prelim(j+1) = roi_cur_reduced.get_union(plot_added_buffer{1}.plot_validpoints,0);
% Update counter
counter = counter+1;
end
end
% Convert plots to Lagrangian ----------------------------%
% Get Lagrangian Displacements
plot_lagrangian_buffer = cell(0);
roi_lagrangian_buffer = cell(0);
[plot_lagrangian_buffer{1},roi_lagrangian_buffer{1},outstate_convert] = ncorr_alg_convertanalysis(obj.reference, ...
obj.current, ...
{plots_disp_f_prelim.plot_u_cur_formatted}, ...
{plots_disp_f_prelim.plot_v_cur_formatted}, ...
rois_f_cur_prelim, ...
obj.data_dic.dispinfo.spacing, ...
0, ...
length(obj.current));
% See if analysis was cancelled or failed. Return for
% both.
if (outstate_convert ~= out.success)
return;
end
% Make sure to convert displacements back to real units from
% pixels. Also multiply Eulerian displacements by -1 to
% make them truly
% Eulerian
for i = 0:length(obj.current)-1
% Lagrangian
plots_disp_f_prelim(i+1).plot_u_ref_formatted = plot_lagrangian_buffer{1}(i+1).plot_u_new.*pixtounits_prelim;
plots_disp_f_prelim(i+1).plot_v_ref_formatted = plot_lagrangian_buffer{1}(i+1).plot_v_new.*pixtounits_prelim;
rois_f_ref_prelim(i+1) = roi_lagrangian_buffer{1}(i+1);
% Eulerian
plots_disp_f_prelim(i+1).plot_u_cur_formatted = -plots_disp_f_prelim(i+1).plot_u_cur_formatted.*pixtounits_prelim;
plots_disp_f_prelim(i+1).plot_v_cur_formatted = -plots_disp_f_prelim(i+1).plot_v_cur_formatted.*pixtounits_prelim;
end
end
% Dont query overwrite, just do it since formatting
% displacement data and calculating strain maps is quick
obj.clear_downstream('formatdisp');
% For regular analysis just store formatted rois
% Package data:
for i = 0:length(obj.current)-1
displacements_template(i+1).plot_u_dic = obj.data_dic.displacements(i+1).plot_u_dic; %#ok<AGROW>
displacements_template(i+1).plot_v_dic = obj.data_dic.displacements(i+1).plot_v_dic; %#ok<AGROW>
displacements_template(i+1).plot_corrcoef_dic = obj.data_dic.displacements(i+1).plot_corrcoef_dic; %#ok<AGROW>
displacements_template(i+1).roi_dic = obj.data_dic.displacements(i+1).roi_dic; %#ok<AGROW>
displacements_template(i+1).plot_u_ref_formatted = plots_disp_f_prelim(i+1).plot_u_ref_formatted; %#ok<AGROW>
displacements_template(i+1).plot_v_ref_formatted = plots_disp_f_prelim(i+1).plot_v_ref_formatted; %#ok<AGROW>
displacements_template(i+1).roi_ref_formatted = rois_f_ref_prelim(i+1); %#ok<AGROW>
displacements_template(i+1).plot_u_cur_formatted = plots_disp_f_prelim(i+1).plot_u_cur_formatted; %#ok<AGROW>
displacements_template(i+1).plot_v_cur_formatted = plots_disp_f_prelim(i+1).plot_v_cur_formatted; %#ok<AGROW>
displacements_template(i+1).roi_cur_formatted = rois_f_cur_prelim(i+1); %#ok<AGROW>
end
dispinfo_template.type = obj.data_dic.dispinfo.type;
dispinfo_template.radius = obj.data_dic.dispinfo.radius;
dispinfo_template.spacing = obj.data_dic.dispinfo.spacing;
dispinfo_template.cutoff_diffnorm = obj.data_dic.dispinfo.cutoff_diffnorm;
dispinfo_template.cutoff_iteration = obj.data_dic.dispinfo.cutoff_iteration;
dispinfo_template.total_threads = obj.data_dic.dispinfo.total_threads;
dispinfo_template.stepanalysis = obj.data_dic.dispinfo.stepanalysis;
dispinfo_template.subsettrunc = obj.data_dic.dispinfo.subsettrunc;
dispinfo_template.imgcorr = obj.data_dic.dispinfo.imgcorr;
dispinfo_template.pixtounits = pixtounits_prelim;
dispinfo_template.units = units_prelim;
dispinfo_template.cutoff_corrcoef = cutoff_corrcoef_prelim;
dispinfo_template.lenscoef = lenscoef_prelim;
% Store data:
for i = 0:length(obj.current)-1
obj.data_dic.displacements(i+1) = displacements_template(i+1);
end
obj.data_dic.dispinfo(1) = dispinfo_template;
end
function callback_topmenu_calcstrain(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for computing the strains after the
% displacements have been formatted.
% Get strain radius ------------------------------------------%
% Check if strain has been calculated before
params_init = [];
if (~isempty(obj.data_dic.straininfo) && ~isempty(obj.data_dic.straininfo.radius) && ~isempty(obj.data_dic.straininfo.subsettrunc))
params_init(1) = obj.data_dic.straininfo.radius;
params_init(2) = obj.data_dic.straininfo.subsettrunc;
end
% Get strain parameters
[radius_strain_prelim,subsettrunc_prelim,outstate_radius_strain] = ncorr_gui_setstrainradius(obj.reference.imginfo, ...
[obj.current.imginfo], ...
[obj.data_dic.displacements.roi_ref_formatted], ...
[obj.data_dic.displacements.roi_cur_formatted], ...
{obj.data_dic.displacements.plot_u_ref_formatted}, ...
{obj.data_dic.displacements.plot_v_ref_formatted}, ...
{obj.data_dic.displacements.plot_u_cur_formatted}, ...
{obj.data_dic.displacements.plot_v_cur_formatted}, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.pixtounits, ...
obj.data_dic.dispinfo.units, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
% See if analysis was cancelled
if (outstate_radius_strain ~= out.success)
return;
end
% Calculate strains --------------------------------------%
% Calculate displacement gradients through least squares
% plane fit first
% Lagrangian
plots_dispgrad_ref_prelim = struct('plot_dudx',{},'plot_dudy',{},'plot_dvdx',{},'plot_dvdy',{},'plot_validpoints',{});
plots_dispgrad_cur_prelim = struct('plot_dudx',{},'plot_dudy',{},'plot_dvdx',{},'plot_dvdy',{},'plot_validpoints',{});
% Lagrangian
for i = 0:length(obj.current)-1
[plots_dispgrad_ref_prelim(i+1),outstate_dispgrad_ref] = ncorr_alg_dispgrad(obj.data_dic.displacements(i+1).plot_u_ref_formatted, ...
obj.data_dic.displacements(i+1).plot_v_ref_formatted, ...
obj.data_dic.displacements(i+1).roi_ref_formatted.formatted(), ...
int32(radius_strain_prelim), ...
obj.data_dic.dispinfo.pixtounits, ...
int32(obj.data_dic.dispinfo.spacing), ...
logical(subsettrunc_prelim), ...
int32(i), ...
int32(length(obj.current)));
% See if analysis was cancelled
if (outstate_dispgrad_ref ~= out.success)
return;
end
end
% Eulerian
for i = 0:length(obj.current)-1
% Eulerian
[plots_dispgrad_cur_prelim(i+1),outstate_dispgrad_cur] = ncorr_alg_dispgrad(obj.data_dic.displacements(i+1).plot_u_cur_formatted, ...
obj.data_dic.displacements(i+1).plot_v_cur_formatted, ...
obj.data_dic.displacements(i+1).roi_cur_formatted.formatted(), ...
int32(radius_strain_prelim), ...
obj.data_dic.dispinfo.pixtounits, ...
int32(obj.data_dic.dispinfo.spacing), ...
logical(subsettrunc_prelim), ...
int32(i), ...
int32(length(obj.current)));
% See if analysis was cancelled
if (outstate_dispgrad_cur ~= out.success)
return;
end
end
% Store
% Dont query overwrite, just do it since calculating strain maps is quick
obj.clear_downstream('strains');
% Package info:
for i = 0:length(obj.current)-1
% Green Lagrangian
strains_template(i+1).plot_exx_ref_formatted = (1/2)*(2*plots_dispgrad_ref_prelim(i+1).plot_dudx+plots_dispgrad_ref_prelim(i+1).plot_dudx.^2+plots_dispgrad_ref_prelim(i+1).plot_dvdx.^2); %#ok<AGROW>
strains_template(i+1).plot_exy_ref_formatted = (1/2)*(plots_dispgrad_ref_prelim(i+1).plot_dudy+plots_dispgrad_ref_prelim(i+1).plot_dvdx+plots_dispgrad_ref_prelim(i+1).plot_dudx.*plots_dispgrad_ref_prelim(i+1).plot_dudy+plots_dispgrad_ref_prelim(i+1).plot_dvdx.*plots_dispgrad_ref_prelim(i+1).plot_dvdy); %#ok<AGROW>
strains_template(i+1).plot_eyy_ref_formatted = (1/2)*(2*plots_dispgrad_ref_prelim(i+1).plot_dvdy+plots_dispgrad_ref_prelim(i+1).plot_dudy.^2+plots_dispgrad_ref_prelim(i+1).plot_dvdy.^2); %#ok<AGROW>
strains_template(i+1).roi_ref_formatted = obj.data_dic.displacements(i+1).roi_ref_formatted.get_union(plots_dispgrad_ref_prelim(i+1).plot_validpoints,0); %#ok<AGROW>
% Eulerian-Almansi
strains_template(i+1).plot_exx_cur_formatted = (1/2)*(2*plots_dispgrad_cur_prelim(i+1).plot_dudx-plots_dispgrad_cur_prelim(i+1).plot_dudx.^2-plots_dispgrad_cur_prelim(i+1).plot_dvdx.^2); %#ok<AGROW>
strains_template(i+1).plot_exy_cur_formatted = (1/2)*(plots_dispgrad_cur_prelim(i+1).plot_dudy+plots_dispgrad_cur_prelim(i+1).plot_dvdx-plots_dispgrad_cur_prelim(i+1).plot_dudx.*plots_dispgrad_cur_prelim(i+1).plot_dudy-plots_dispgrad_cur_prelim(i+1).plot_dvdx.*plots_dispgrad_cur_prelim(i+1).plot_dvdy); %#ok<AGROW>
strains_template(i+1).plot_eyy_cur_formatted = (1/2)*(2*plots_dispgrad_cur_prelim(i+1).plot_dvdy-plots_dispgrad_cur_prelim(i+1).plot_dudy.^2-plots_dispgrad_cur_prelim(i+1).plot_dvdy.^2); %#ok<AGROW>
strains_template(i+1).roi_cur_formatted = obj.data_dic.displacements(i+1).roi_cur_formatted.get_union(plots_dispgrad_cur_prelim(i+1).plot_validpoints,0); %#ok<AGROW>
end
% Store info:
for i = 0:length(obj.current)-1
obj.data_dic.strains(i+1) = strains_template(i+1);
end
obj.data_dic.straininfo(1).radius = radius_strain_prelim;
obj.data_dic.straininfo(1).subsettrunc = subsettrunc_prelim;
% Tell user calculating strains was successful
msgbox('Strains calculation complete. Press ok to finish.','WindowStyle','modal');
end
function callback_topmenu_viewplot(obj,hObject,eventdata,type_fig) %#ok<INUSL>
% This is the callback for viewing the plots after the
% displacements have been formatted and after the strains
% have been computed.
% Get Data
handles_plot = getappdata(obj.handles_gui.figure,'handles_plot');
% Deactivate closerequestfcn - this prevents any closing of
% figures when handles_plot is being updated
for i = 0:length(handles_plot)-1
set(handles_plot(i+1),'CloseRequestFcn','');
end
% Cycle over figures (it's possible type fig has more than one
% type).
for i = 0:length(type_fig)-1
% Check if plot already exists
plotexists = false;
for j = 0:length(handles_plot)-1
if (strcmp(getappdata(handles_plot(j+1),'type_plot'),type_fig{i+1}))
% Plot already exists, bring it back to focus
figure(handles_plot(j+1));
plotexists = true;
break;
end
end
if (~plotexists)
% Get params_init;
params_init = cell(0);
if (~isempty(handles_plot))
% All windows will have the same paramters so just
% grab the info from the first window
params_init{1} = getappdata(handles_plot(1),'num_cur'); % {1} = num_cur
% Get data
params_init{2} = getappdata(handles_plot(1),'scalebarlength'); % {2} = scalebarlength
params_init{3} = getappdata(handles_plot(1),'val_checkbox_scalebar'); % {3} = scalebar;
params_init{4} = getappdata(handles_plot(1),'val_checkbox_axes'); % {4} = axes;
params_init{5} = getappdata(handles_plot(1),'val_popupmenu'); % {5} = lagrangian or eulerian
params_init{6} = strcmp(get(getappdata(handles_plot(1),'handle_zoom'),'Enable'),'on'); % {6} = zoomed
params_init{7} = strcmp(get(getappdata(handles_plot(1),'handle_pan'),'Enable'),'on'); % {7} = panned
end
% Go over friends list; find the right most figure and
% make this the figure whose coordinates are used for
% pos_parent.
if (isempty(handles_plot))
% Use coordinates of ncorr
pos_parent = get(obj.handles_gui.figure,'OuterPosition');
else
% Plots already exist, fight right most plot
pos_parent = get(handles_plot(1),'OuterPosition');
for j = 1:length(handles_plot)-1
pos_buf = get(handles_plot(j+1),'OuterPosition');
if (pos_buf(1) + pos_buf(3) > pos_parent(1) + pos_parent(3))
pos_parent = pos_buf;
elseif (pos_buf(1) + pos_buf(3) == pos_parent(1) + pos_parent(3))
% If they are equal, get the one that is
% lower
if (pos_buf(2) < pos_parent(2))
pos_parent = pos_buf;
end
end
end
end
% Create new plot - This function will return all
% gui handles. Store these as "friends" so plots can
% remain consistent. The figure has already has its
% closereqestfcn disabled
handles_gui_new = ncorr_gui_viewplots(obj.reference.imginfo, ...
[obj.current.imginfo], ...
obj.data_dic, ...
type_fig{i+1}, ...
pos_parent, ...
params_init);
% Figure can be invalid if the ROI is empty
if (ishandle(handles_gui_new.figure))
% Set delete functions
set(handles_gui_new.figure,'DeleteFcn',ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata)callback_update_handles_plot(obj,hObject,eventdata),obj.handles_gui.figure));
% Update friends list - this allows the things to
% sync
if (isempty(handles_plot))
% Check if a plot already exists - if it does then get
% the old friends list from the first plot
friends_old = [];
else
friends_old = getappdata(handles_plot(1),'friends');
end
friends_new = horzcat(friends_old,{handles_gui_new});
% Link the axes
vec_friends = [friends_new{:}];
linkaxes([vec_friends.axes_formatplot],'xy');
% Set Data
% First update handles_gui_new
setappdata(handles_gui_new.figure,'friends',friends_new);
% Now update the preexisting handles
for j = 0:length(handles_plot)-1
setappdata(handles_plot(j+1),'friends',friends_new);
end
% Now store figure handle
handles_plot = horzcat(handles_plot,handles_gui_new.figure); %#ok<AGROW>
end
end
end
% Reactivate closerequestfcns
for i = 0:length(handles_plot)-1
set(handles_plot(i+1),'CloseRequestFcn','closereq');
end
% Store Data
setappdata(obj.handles_gui.figure,'handles_plot',handles_plot);
end
function callback_topmenu_closeplots(obj,hObject,eventdata) %#ok<INUSD>
% This callback closes all the open plots.
obj.close_dicplots('all');
end
%-----------------------------------------------------------------%
% Other Callbacks ------------------------------------------------%
%-----------------------------------------------------------------%
function callback_update_title(obj,hObject,eventdata) %#ok<INUSD>
% This function will update the title of ncorr to display the
% handle pointing to ncorr
% Get Name
name = util_get_name(obj);
if (isempty(name))
% No handle exists
set(obj.handles_gui.figure,'Name','Ncorr');
else
% Handle exists
set(obj.handles_gui.figure,'Name',['Ncorr - ' name]);
end
end
function callback_edit_imgnum(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for setting the image number directly
% Get data
num_cur = getappdata(obj.handles_gui.figure,'num_cur');
% Get img num
num_cur_prelim = str2double(get(obj.handles_gui.edit_imgnum,'string'));
if (ncorr_util_isintbb(num_cur_prelim,1,length(obj.current),'Current image number') == out.success)
% convert num_cur_prelim to zero based indexed
num_cur = num_cur_prelim-1;
end
% Set data
setappdata(obj.handles_gui.figure,'num_cur',num_cur);
end
function callback_button_left(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for the left button to display different
% current images
% Get data
num_cur = getappdata(obj.handles_gui.figure,'num_cur');
% Check for overshoot
if (num_cur > 0)
num_cur = num_cur-1;
end
% Set data
setappdata(obj.handles_gui.figure,'num_cur',num_cur);
end
function callback_button_right(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for the right button to display different
% current images
% Get data
num_cur = getappdata(obj.handles_gui.figure,'num_cur');
% Check for overshoot
if (num_cur < length(obj.current)-1)
num_cur = num_cur+1;
end
% Set data
setappdata(obj.handles_gui.figure,'num_cur',num_cur);
end
function callback_update_handles_plot(obj,hObject,eventdata) %#ok<INUSD>
% This function is called when a plot figure is closed; this
% function removes the figure handle from handles_plot.
% Get data
handles_plot = getappdata(obj.handles_gui.figure,'handles_plot');
% Disable closerequestfcns - ensure other plots aren't closed
% while the handle is being updated.
for i = 0:length(handles_plot)-1
set(handles_plot(i+1),'CloseRequestFcn','');
end
% Determine index of closing figure
closingfig = gcbf;
idx_closingfig = -1;
for i = 0:length(handles_plot)-1
if (handles_plot(i+1) == closingfig) % update handle array
idx_closingfig = i;
break;
end
end
% Delete closing figure from handles_plot
handles_plot(idx_closingfig+1) = [];
% Update Friends
for i = 0:length(handles_plot)-1
% Get friends list for each plot handle. Delete the friend
% that contains closing fig
% Get data
friends = getappdata(handles_plot(i+1),'friends');
for j = 0:length(friends)-1
if (friends{j+1}.figure == closingfig)
friends(j+1) = [];
break;
end
end
% Set data
setappdata(handles_plot(i+1),'friends',friends);
end
% Reenable CloseRequestfFcns
for i = 0:length(handles_plot)-1
set(handles_plot(i+1),'CloseRequestFcn','closereq');
end
% Set data
setappdata(obj.handles_gui.figure,'handles_plot',handles_plot);
end
function callback_close_function(obj,hObject,eventdata,force) %#ok<INUSL>
% Force will cause a force close if it's true - this situation
% occurs when the user manually deletes the GUI handle
closencorr = false;
if (~force && ~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements))
contbutton = questdlg('Prior DIC data has been detected. If you continue without saving, this data will be deleted. Do you want to proceed?','Continue Operation','Yes','No','Yes');
if (strcmp(contbutton,'Yes'))
closencorr = true;
end
else
% Force close if user calls "delete(handles_ncorr)" or if
% dic analysis has not been run yet.
closencorr = true;
end
if (closencorr)
% Close plot figures
obj.close_dicplots('all');
% Delete timer
timer_ncorr = getappdata(obj.handles_gui.figure,'timer');
if (isa(timer_ncorr,'timer') && isvalid(timer_ncorr))
stop(timer_ncorr);
delete(timer_ncorr);
end
% Close GUI
delete(obj.handles_gui.figure);
% Delete data
delete(obj);
end
end
%-----------------------------------------------------------------%
% Other Functions ------------------------------------------------%
%-----------------------------------------------------------------%
function close_dicplots(obj,closetype)
% This is the function for closing either the displacement plots,
% strain plots, or all the plots.
% Displacement plots
if (strcmp(closetype,'displacements') || strcmp(closetype,'all'));
% Get data
handles_plot = getappdata(obj.handles_gui.figure,'handles_plot');
handles_plot_close = [];
for i = 0:length(handles_plot)-1
type_plot = getappdata(handles_plot(i+1),'type_plot');
if (strcmp(type_plot,'u') || strcmp(type_plot,'v'))
handles_plot_close = horzcat(handles_plot_close,handles_plot(i+1)); %#ok<AGROW>
end
end
% Close figures
close(handles_plot_close); % handles_plot updates after this
end
% Strain plots
if (strcmp(closetype,'strains') || strcmp(closetype,'all'));
% Get Data
handles_plot = getappdata(obj.handles_gui.figure,'handles_plot');
handles_plot_close = [];
for i = 0:length(handles_plot)-1
type_plot = getappdata(handles_plot(i+1),'type_plot');
if (strcmp(type_plot,'exx') || strcmp(type_plot,'exy') || strcmp(type_plot,'eyy'))
handles_plot_close = horzcat(handles_plot_close,handles_plot(i+1)); %#ok<AGROW>
end
end
% Close figures
close(handles_plot_close); % handles_plot updates after this
end
end
function overwrite = clear_downstream(obj,action)
% Middle of callback - alert user if data is going to be
% overwritten and then clear downstream data.
% Initialize - set default to true.
overwrite = true;
% See whether to query overwrite
if (strcmp(action,'all') || strcmp(action,'set_ref') || strcmp(action,'set_cur') || strcmp(action,'set_roi') || strcmp(action,'set_dicparameters') || strcmp(action,'dicanalysis'))
% Only query if displacements have been set, since this is
% usually the most time consuming process
if (~isempty(obj.data_dic.displacements))
contbutton = questdlg('Prior DIC data has been detected. If you continue without saving, this data will be deleted. Do you want to proceed?','Continue Operation','Yes','No','Yes');
if (~strcmp(contbutton,'Yes'))
overwrite = false;
end
end
end
% If overwrite is permitted, then clear downstream data.
if (overwrite)
% Get field names since they are used a lot
fields_data_dic = fieldnames(obj.data_dic);
fields_dic_data_dispinfo = fieldnames(obj.data_dic.dispinfo);
% Handle each step accordingly
if (strcmp(action,'all'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% All info needs to be deleted
obj.reference(:) = [];
obj.current(:) = [];
setappdata(obj.handles_gui.figure,'num_cur',[]);
for i = 0:length(fields_data_dic)-1
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
elseif (strcmp(action,'set_ref'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% Clear all reference info
obj.reference(:) = [];
% For current images, clear all ROIs if analysis
% was regular. If it was backward, then clear all
% ROIs except for the last one
if (~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo))
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
for i = 0:length(obj.current)-1
obj.current(i+1).roi = ncorr_class_roi.empty;
end
else
for i = 0:length(obj.current)-2
obj.current(i+1).roi = ncorr_class_roi.empty;
end
end
end
% Clear everything in data_dic except for dispinfo
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete everything except for the type in
% dispinfo. If the type was regular, then delete
% that too
if (~isempty(obj.data_dic.dispinfo))
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
obj.data_dic.dispinfo(:) = [];
else
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
end
end
elseif (strcmp(action,'set_cur'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% Delete reference ROI if type is backward
if (~isempty(obj.reference) && ~isempty(obj.data_dic.dispinfo))
if (strcmp(obj.data_dic.dispinfo.type,'backward'))
obj.reference.roi = ncorr_class_roi.empty;
end
end
% Clear all current images
obj.current(:) = [];
setappdata(obj.handles_gui.figure,'num_cur',[]);
% Clear everything in data_dic except for dispinfo
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete everything except for the type in
% dispinfo. If the type was backward, then delete
% that too
if (~isempty(obj.data_dic.dispinfo))
if (strcmp(obj.data_dic.dispinfo.type,'backward'))
obj.data_dic.dispinfo(:) = [];
else
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
end
end
elseif (strcmp(action,'set_roi'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% Clear all ROIs in reference image
if (~isempty(obj.reference))
obj.reference.roi = ncorr_class_roi.empty;
end
% Clear all ROIS in current image
if (~isempty(obj.current))
for i = 0:length(obj.current)-1
obj.current(i+1).roi = ncorr_class_roi.empty;
end
end
% Clear all data_dic
for i = 0:length(fields_data_dic)-1
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
elseif (strcmp(action,'set_dicparameters'))
% Close DIC figs if they exist -----------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% If type is regular, delete all current ROIS.
% If type is backward, delete all ROIS except for
% last current ROI
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
for i = 0:length(obj.current)-1
obj.current(i+1).roi = ncorr_class_roi.empty;
end
else
obj.reference.roi = ncorr_class_roi.empty;
for i = 0:length(obj.current)-2
obj.current(i+1).roi = ncorr_class_roi.empty;
end
end
% Clear everything in data_dic except for dispinfo
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete everything in dispinfo except for the type
fields_dic_data_dispinfo = fieldnames(obj.data_dic.dispinfo);
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
elseif (strcmp(action,'dicanalysis'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% If type is regular, delete all current ROIs.
% If type is backward, delete all ROIs except for
% last current ROI
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
for i = 0:length(obj.current)-1
obj.current(i+1).roi = ncorr_class_roi.empty;
end
else
obj.reference.roi = ncorr_class_roi.empty;
for i = 0:length(obj.current)-2
obj.current(i+1).roi = ncorr_class_roi.empty;
end
end
% Delete all info except dispinfo
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete downstream data in data_dic.dispinfo:
fields_dic_data_dispinfo = fieldnames(obj.data_dic.dispinfo);
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'radius') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'spacing') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'cutoff_diffnorm') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'cutoff_iteration') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'total_threads') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'stepanalysis') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'subsettrunc'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
elseif (strcmp(action,'formatdisp'))
% Close DIC figs if they exist -----------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% Delete all info except for displacements and
% dispinfo;
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'displacements') && ...
~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete downstream data in data_dic.dispinfo:
fields_dic_data_dispinfo = fieldnames(obj.data_dic.dispinfo);
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'radius') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'spacing') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'cutoff_diffnorm') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'cutoff_iteration') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'total_threads') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'stepanalysis') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'subsettrunc') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'imgcorr'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
% Delete downstream data in data_dic.displacements:
dic_data_disp_fields = fieldnames(obj.data_dic.displacements);
for i = 0:length(dic_data_disp_fields)-1
if (~strcmp(dic_data_disp_fields{i+1},'plot_u_dic') && ...
~strcmp(dic_data_disp_fields{i+1},'plot_v_dic') && ...
~strcmp(dic_data_disp_fields{i+1},'plot_corrcoef_dic') && ...
~strcmp(dic_data_disp_fields{i+1},'roi_dic'))
for j = 0:length(obj.data_dic.displacements)-1
obj.data_dic.displacements(j+1).(dic_data_disp_fields{i+1})(:) = [];
end
end
end
elseif (strcmp(action,'strains'))
% Close strain figs if they exist --------------------%
obj.close_dicplots('strains');
% Clear downstream data ------------------------------%
% Delete all info except dispinfo and displacements
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo') && ...
~strcmp(fields_data_dic{i+1},'displacements'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
end
end
end
function freeze_menu(obj)
% This function disables the menu when callbacks are executing
set(obj.handles_gui.topmenu_file,'Enable','off');
set(obj.handles_gui.topmenu_regionofinterest,'Enable','off');
set(obj.handles_gui.topmenu_analysis,'Enable','off');
set(obj.handles_gui.topmenu_plot,'Enable','off');
end
function unfreeze_menu(obj)
% This function enables the menu when callbacks are done
set(obj.handles_gui.topmenu_file,'Enable','on');
set(obj.handles_gui.topmenu_regionofinterest,'Enable','on');
set(obj.handles_gui.topmenu_analysis,'Enable','on');
set(obj.handles_gui.topmenu_plot,'Enable','on');
end
function update_topmenu(obj)
% This function updates menu items depending on what is loaded
% Reference image is loaded:
if (~isempty(obj.reference))
set(obj.handles_gui.topmenu_setroi_ref,'Enable','on');
else
set(obj.handles_gui.topmenu_setroi_ref,'Enable','off');
end
% Current image is loaded:
if (~isempty(obj.current))
set(obj.handles_gui.topmenu_setroi_cur,'Enable','on');
else
set(obj.handles_gui.topmenu_setroi_cur,'Enable','off');
end
% Reference image, current image, and ROI are loaded:
% Must check if analysis is regular or backward because ROIs
% can be set through the DIC analysis
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo) && ...
((strcmp(obj.data_dic.dispinfo.type,'regular') && ~isempty(obj.reference.roi)) || ...
((strcmp(obj.data_dic.dispinfo.type,'backward') && ~isempty(obj.current(end).roi)))))
set(obj.handles_gui.topmenu_setdicparameters,'Enable','on');
else
set(obj.handles_gui.topmenu_setdicparameters,'Enable','off');
end
% Reference image, current image, and DIC parameters are loaded:
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo) && ...
~isempty(obj.data_dic.dispinfo.radius) && ...
~isempty(obj.data_dic.dispinfo.spacing) && ...
~isempty(obj.data_dic.dispinfo.cutoff_diffnorm) && ...
~isempty(obj.data_dic.dispinfo.cutoff_iteration) && ...
~isempty(obj.data_dic.dispinfo.total_threads) && ...
~isempty(obj.data_dic.dispinfo.stepanalysis) && ...
~isempty(obj.data_dic.dispinfo.subsettrunc))
set(obj.handles_gui.topmenu_perfdic,'Enable','on');
else
set(obj.handles_gui.topmenu_perfdic,'Enable','off');
end
% Reference image, current image, and DIC analysis are loaded:
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements))
set(obj.handles_gui.topmenu_savedata,'Enable','on');
set(obj.handles_gui.topmenu_formatdisp,'Enable','on');
else
set(obj.handles_gui.topmenu_savedata,'Enable','off');
set(obj.handles_gui.topmenu_formatdisp,'Enable','off');
end
% Reference image, current image, DIC data, and formatted
% displacements are loaded:
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements) && ...
~isempty(obj.data_dic.dispinfo.pixtounits) && ...
~isempty(obj.data_dic.dispinfo.units) && ...
~isempty(obj.data_dic.dispinfo.cutoff_corrcoef) && ...
~isempty(obj.data_dic.dispinfo.lenscoef))
set(obj.handles_gui.topmenu_calcstrain,'Enable','on');
set(obj.handles_gui.topmenu_viewdispplot_u,'Enable','on');
set(obj.handles_gui.topmenu_viewdispplot_v,'Enable','on');
set(obj.handles_gui.topmenu_viewdispplot_all,'Enable','on');
set(obj.handles_gui.topmenu_closeplots,'Enable','on');
else
set(obj.handles_gui.topmenu_calcstrain,'Enable','off');
set(obj.handles_gui.topmenu_viewdispplot_u,'Enable','off');
set(obj.handles_gui.topmenu_viewdispplot_v,'Enable','off');
set(obj.handles_gui.topmenu_viewdispplot_all,'Enable','off');
set(obj.handles_gui.topmenu_closeplots,'Enable','off');
end
% Reference image, current image, DIC data, and strains are
% loaded
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo)&& ~isempty(obj.data_dic.displacements) && ...
~isempty(obj.data_dic.straininfo) && ~isempty(obj.data_dic.strains))
set(obj.handles_gui.topmenu_viewstrainplot_exx,'Enable','on');
set(obj.handles_gui.topmenu_viewstrainplot_exy,'Enable','on');
set(obj.handles_gui.topmenu_viewstrainplot_eyy,'Enable','on');
set(obj.handles_gui.topmenu_viewstrainplot_all,'Enable','on');
else
set(obj.handles_gui.topmenu_viewstrainplot_exx,'Enable','off');
set(obj.handles_gui.topmenu_viewstrainplot_exy,'Enable','off');
set(obj.handles_gui.topmenu_viewstrainplot_eyy,'Enable','off');
set(obj.handles_gui.topmenu_viewstrainplot_all,'Enable','off');
end
end
function update_dicstatetext(obj)
% This function updates state text depending on what is loaded
% Reference image:
if (~isempty(obj.reference))
set(obj.handles_gui.text_refloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_refloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% Current image:
if (~isempty(obj.current))
set(obj.handles_gui.text_curloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_curloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% ROI: Must check if analysis is regular or backward because ROIs
% can be set through the DIC analysis
if (~isempty(obj.data_dic.dispinfo)&& ...
((strcmp(obj.data_dic.dispinfo.type,'regular') && ~isempty(obj.reference.roi)) || ...
((strcmp(obj.data_dic.dispinfo.type,'backward') && ~isempty(obj.current(end).roi)))))
set(obj.handles_gui.text_roiloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_roiloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% DIC parameters:
if (~isempty(obj.data_dic.dispinfo) && ...
~isempty(obj.data_dic.dispinfo.radius) && ...
~isempty(obj.data_dic.dispinfo.spacing) && ...
~isempty(obj.data_dic.dispinfo.cutoff_diffnorm) && ...
~isempty(obj.data_dic.dispinfo.cutoff_iteration) && ...
~isempty(obj.data_dic.dispinfo.total_threads) && ...
~isempty(obj.data_dic.dispinfo.stepanalysis) && ...
~isempty(obj.data_dic.dispinfo.subsettrunc))
set(obj.handles_gui.text_dicparametersloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_dicparametersloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% DIC analysis:
if (~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements))
set(obj.handles_gui.text_dicloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_dicloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% Displacements formatted:
if (~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements) && ...
~isempty(obj.data_dic.dispinfo.pixtounits) && ...
~isempty(obj.data_dic.dispinfo.units) && ...
~isempty(obj.data_dic.dispinfo.cutoff_corrcoef) && ...
~isempty(obj.data_dic.dispinfo.lenscoef))
set(obj.handles_gui.text_disploaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_disploaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% Strains:
if (~isempty(obj.data_dic.straininfo) && ~isempty(obj.data_dic.strains))
set(obj.handles_gui.text_strainloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_strainloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
end
function update_axes(obj,action)
% Get data
num_cur = getappdata(obj.handles_gui.figure,'num_cur');
% Updates axes, axes buttons, and axes texts below:
if (strcmp(action,'set'))
% Reference axes
if (isempty(obj.reference))
% Clear reference image
cla(obj.handles_gui.axes_ref);
set(obj.handles_gui.text_refname,'String','Name: ');
set(obj.handles_gui.text_refresolution,'String','Resolution: ');
else
% Set reference image and format axes
imshow(obj.reference.imginfo.get_img(),[obj.reference.imginfo.min_gs obj.reference.imginfo.max_gs],'Parent',obj.handles_gui.axes_ref);
set(obj.handles_gui.axes_ref ,'Visible','off');
% Show image text
set(obj.handles_gui.text_refname,'String',['Name: ' obj.reference.imginfo.name]);
set(obj.handles_gui.text_refresolution,'String',['Resolution: ' num2str(obj.reference.imginfo.width) ' x ' num2str(obj.reference.imginfo.height)]);
end
% Current axes
if (isempty(obj.current))
% Disable buttons
set(obj.handles_gui.button_right,'Enable','off');
set(obj.handles_gui.button_left,'Enable','off');
set(obj.handles_gui.edit_imgnum,'Enable','off');
set(obj.handles_gui.edit_imgnum,'String',num2str(num_cur));
% Reset current image:
cla(obj.handles_gui.axes_cur);
% Update current image name and resolution:
set(obj.handles_gui.text_curname,'String','Name: ');
set(obj.handles_gui.text_curresolution,'String','Resolution: ');
else
% Set current image and format axes
imshow(obj.current(num_cur+1).imginfo.get_img(),[obj.current(num_cur+1).imginfo.min_gs obj.current(num_cur+1).imginfo.max_gs],'Parent',obj.handles_gui.axes_cur);
set(obj.handles_gui.axes_cur ,'Visible','off');
% Format/show text
set(obj.handles_gui.text_curname,'String',['Name: ' obj.current(num_cur+1).imginfo.name]);
set(obj.handles_gui.text_curresolution,'String',['Resolution: ' num2str(obj.current(num_cur+1).imginfo.width) ' x ' num2str(obj.current(num_cur+1).imginfo.height)]);
% Set left/right buttons and editbox
set(obj.handles_gui.edit_imgnum,'String',num2str(num_cur+1));
if (length(obj.current) == 1)
set(obj.handles_gui.button_right,'Enable','off');
set(obj.handles_gui.button_left,'Enable','off');
set(obj.handles_gui.edit_imgnum,'Enable','off');
elseif (num_cur == 0)
set(obj.handles_gui.button_right,'Enable','on');
set(obj.handles_gui.button_left,'Enable','off');
set(obj.handles_gui.edit_imgnum,'Enable','on');
elseif (num_cur == length(obj.current)-1)
set(obj.handles_gui.button_right,'Enable','off');
set(obj.handles_gui.button_left,'Enable','on');
set(obj.handles_gui.edit_imgnum,'Enable','on');
else
set(obj.handles_gui.button_right,'Enable','on');
set(obj.handles_gui.button_left,'Enable','on');
set(obj.handles_gui.edit_imgnum,'Enable','on');
end
end
% ROI axes
if (~isempty(obj.data_dic.dispinfo) && strcmp(obj.data_dic.dispinfo.type,'regular'))
% Set reference ROI
imshow(obj.reference.roi.mask,'Parent',obj.handles_gui.axes_roi);
set(obj.handles_gui.axes_roi,'Visible','off');
elseif (~isempty(obj.data_dic.dispinfo) && strcmp(obj.data_dic.dispinfo.type,'backward'))
% Set last current ROI
imshow(obj.current(end).roi.mask,'Parent',obj.handles_gui.axes_roi);
set(obj.handles_gui.axes_roi,'Visible','off');
else
% Clear ROI
cla(obj.handles_gui.axes_roi);
end
end
end
function outstate = check_matlabcompat(obj) %#ok<MANU>
% This function checks the matlab compatibility.
% Initialize output
outstate = out.failed;
vm = datevec(version('-date'));
if (vm(1) < 2009)
% Pop error message but allow user to continue
h_error = errordlg('Developed using MATLAB 2009; may not work for versions before this date. Ncorr will continue.','Error','modal');
uiwait(h_error);
end
% Check to make sure correct toolboxes are installed ---------%
% Requires the image processing toolbox and the statistics
% toolbox
% Note that Matlab combined their statistics and machine
% learning toolboxes so just search for "Statistics" to work
% for both cases.
v = ver;
if (isempty(strfind([v.Name],'Image Processing Toolbox')) || isempty(strfind([v.Name],'Statistics')))
h_error = errordlg('Requires the image processing and statistics toolbox.','Error','modal');
uiwait(h_error);
return;
end
% Set output
outstate = out.success;
end
function outstate = check_mexinstall(obj)
% Check to see if mex files exist and loads ncorr_installinfo ----%
% Initialize output
outstate = out.cancelled;
% Files to compile:
% These are stand alone .cpp files compiled with '-c' flag:
lib_ncorr_cpp = {'standard_datatypes','ncorr_datatypes','ncorr_lib'};
% These are .cpp mex functions compiled with libraries
func_ncorr_cpp = {'ncorr_alg_formmask', ...
'ncorr_alg_formregions', ...
'ncorr_alg_formboundary', ...
'ncorr_alg_formthreaddiagram', ...
'ncorr_alg_formunion', ...
'ncorr_alg_extrapdata', ...
'ncorr_alg_adddisp', ...
'ncorr_alg_convert', ...
'ncorr_alg_dispgrad'};
% These are .cpp mex functions compiled with libraries and possibly openmp:
func_ncorr_openmp_cpp = {'ncorr_alg_testopenmp','ncorr_alg_calcseeds','ncorr_alg_rgdic'};
% Get object extension:
if (ispc) % pc
objext = 'obj';
elseif (isunix) % unix
objext = 'o';
end
% See if these files have already been compiled:
compile = false;
% Check libraries first
for i = 0:length(lib_ncorr_cpp)-1
if (~exist([lib_ncorr_cpp{i+1} '.' objext],'file'))
compile = true;
break;
end
end
% Check ncorr functions next
for i = 0:length(func_ncorr_cpp)-1
if (~exist([func_ncorr_cpp{i+1} '.' mexext],'file'))
compile = true;
break;
end
end
% Check ncorr functions with openmp
for i = 0:length(func_ncorr_openmp_cpp)-1
if (~exist([func_ncorr_openmp_cpp{i+1} '.' mexext],'file'))
compile = true;
break;
end
end
if (compile)
% One of the compiled files is missing - tell user that ncorr
% will recompile files.
e = msgbox('One of the compiled files is missing. If using automatic installation, then mex files will compile; if using manual installation, please close Ncorr and make sure all the files compiled properly.','WindowStyle','modal');
uiwait(e);
end
if (~compile)
% Functions have already been compiled - check
% "ncorr_installinfo.txt" file to verify openmp support.
% If "ncorr_installinfo.txt" has incorrect formatting, then
% files will be recompiled. If "ncorr_installinfo.txt" is
% empty, ncorr will take this as the standard way to
% reinstall mex files.
try
% ncorr_installinfo should have the format of:
% [support_openmp_prelim total_cores]
ncorr_installinfo = dlmread('ncorr_installinfo.txt');
if (size(ncorr_installinfo,1) == 1 && size(ncorr_installinfo,2) == 2)
% ncorr_installinfo.txt has the correct number of
% elements
if ((ncorr_installinfo(1) == 0 || ncorr_installinfo(1) == 1) && ...
ncorr_installinfo(2) >= 1)
% Assuming contents have not been modified
% by user, set them:
obj.support_openmp = logical(ncorr_installinfo(1));
obj.total_cores = ncorr_installinfo(2);
else
% ncorr_installinfo.txt has incorrect values
h_error = errordlg('For some reason "ncorr_installinfo.txt" has incorrect values. Program will recompile if using automatic installing. If manually installing Ncorr, please close it and make sure the "ncorr_installinfo.txt" was created correctly.','Error','modal');
uiwait(h_error);
% recompile files
compile = true;
end
elseif (isempty(ncorr_installinfo))
% ncorr_installinfo is empty, this is the stanard
% way to reinstall Ncorr.
h_error = msgbox('"ncorr_installinfo.txt" file is empty. Program will recompile if using automatic installing. If manually installing Ncorr, please close it and make sure the "ncorr_installinfo.txt" was created correctly.','WindowStyle','modal');
uiwait(h_error);
% recompile files
compile = true;
else
% ncorr_installinfo.txt has extra values which
% aren't supposed to be there
h_error = errordlg('For some reason the "ncorr_installinfo.txt" file has extra or missing values. Program will recompile if using automatic installing. If manually installing Ncorr, please close it and make sure the "ncorr_installinfo.txt" was created correctly.','Error','modal');
uiwait(h_error);
% recompile files
compile = true;
end
catch %#ok<CTCH>
% Returns error if file does not exist or format is
% wrong
h_error = msgbox('For some reason the "ncorr_installinfo.txt" file is missing or has improper format. Program will recompile if using automatic installing. If manually installing Ncorr, please close it and make sure the "ncorr_installinfo.txt" was created correctly.','WindowStyle','modal');
uiwait(h_error);
% recompile files
compile = true;
end
end
if (~compile)
% Check if previous installation was corrupted by OpenMP
% support which does not actually exist
if (obj.support_openmp)
if (~ncorr_alg_testopenmp())
% recompile files
compile = true;
end
end
end
%-------------------------------------------------------------%
% BEGIN COMPILE SECTION %
%-------------------------------------------------------------%
% COMMENT THIS SECTION OUT AND MANUALLY COMPILE IF AUTOMATIC %
% COMPILATION FAILS!!! %
% ------------------------------------------------------------%
try
if (compile)
% Check if ncorr.m is in current directory
listing = dir;
if (any(strcmp('ncorr.m',{listing.name})))
% Ask user about openmp support
[support_openmp_prelim,total_cores_prelim,outstate_install] = gui_install(get(obj.handles_gui.figure,'OuterPosition'));
% See if openmp GUI was cancelled
if (outstate_install ~= out.success)
return;
end
% Get compiler flags for openmp support. Depends
% on both OS and compiler.
flags_f = {};
if (support_openmp_prelim)
% Get compiler information
info_comp = mex.getCompilerConfigurations('cpp');
if ((isfield(struct(info_comp),'Details') && isfield(struct(info_comp.Details),'CompilerExecutable')))
% Get compiler
compiler = info_comp.Details.CompilerExecutable;
if (~isempty(strfind(compiler,'cl')))
% This is Microsoft visual studio
% Openmp flag is /openmp
flags_f = horzcat(flags_f{:},{'COMPFLAGS="$COMPFLAGS'},{'/openmp'},{'/DNCORR_OPENMP"'});
elseif (~isempty(strfind(compiler,'g++')))
% This is the GNU compiler; this is
% assumed to be Linux.
% NOTE: GCC must manually link
% against -lgomp. -lgomp also has
% to be placed as the very last
% library or else it will not compile
% correctly.
% Openmp flag is -fopenmp
flags_f = horzcat(flags_f{:},{'CXXFLAGS="$CXXFLAGS'},{'-fopenmp'},{'-DNCORR_OPENMP"'},{'CXXLIBS="$CXXLIBS'},{'-lgomp"'});
else
% C++ compiler is set up, but was not
% recognized as either gcc or cl
h_error = errordlg('C++ compiler is set up in mex, but was not recognized as G++ or Visual Studio. Either comment out the compile section in ncorr and manually compile the mex functions, or restart ncorr and disable openmp support.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
else
% C++ compiler not installed in mex.
h_error = errordlg('C++ compiler was not found. If a C++ compiler was manually installed that supports openmp, then either comment out the compile section in ncorr and manually compile the functions or restart ncorr and disable openmp.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
end
% Compile libraries:
compile_lib_cpp_mex(lib_ncorr_cpp);
% Compile functions:
compile_func_cpp_mex(func_ncorr_cpp,lib_ncorr_cpp,{});
% Compile function with openmp:
compile_func_cpp_mex(func_ncorr_openmp_cpp,lib_ncorr_cpp,flags_f);
% Write to ncorr_installinfo.txt file, this file will be
% used next time ncorr is started up to avoid
% having to reinput this information.
filename = 'ncorr_installinfo.txt';
fid = fopen(filename,'w');
if (fid ~= -1)
fclose(fid);
% Write info to file:
dlmwrite(filename,[support_openmp_prelim total_cores_prelim]);
% Set support variables:
obj.support_openmp = support_openmp_prelim;
obj.total_cores = total_cores_prelim;
else
% Error
h_error = errordlg('For some reason ncorr was not able to create "ncorr_installinfo.txt" file.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
else
% Error
h_error = errordlg('Please navigate to folder containing ncorr.m first before reinstalling.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
end
catch %#ok<CTCH>
h_error = errordlg('Files did not compile properly. Make sure mex has a c++ compiler set and that the file names have not been altered or moved. If this is the case, then try reopening and installing ncorr without openmp. If problems persist, then try commenting out the compile section in ncorr and manually compiling the functions. Instructions for compilation are available in the manual at ncorr.com','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
%-------------------------------------------------------------%
% END OF COMPILE SECTION %
%-------------------------------------------------------------%
% Check if openmp is actually enabled by calling
% ncorr_alg_testopenmp
if (obj.support_openmp)
if (~ncorr_alg_testopenmp())
% openmp was enabled and files were compiled, but openmp
% isn't actually supported.
h_error = errordlg('Files compiled, but it was determined that OpenMP is not actually supported. Please reinstall Ncorr in single threaded mode or use a compiler which supports OpenMP.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
end
% Set output
outstate = out.success;
end
%-----------------------------------------------------------------%
% Create UI Controls for GUI and Assign Callbacks ----------------%
%-----------------------------------------------------------------%
function handles_gui = init_gui(obj)
% Initialize GUI Figure --------------------------------------%
% Start Ncorr in the middle of the screen
set(0,'units','characters'); % Set this every time incase user changes units of root
pos_screen = get(0,'screensize');
height_ncorr = 25;
width_ncorr= 167;
left_ncorr = (pos_screen(3)-width_ncorr)/2;
bottom_ncorr = (pos_screen(4)-height_ncorr)/2;
handles_gui.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', [left_ncorr bottom_ncorr width_ncorr height_ncorr], ...
'Name', 'Ncorr', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'Visible','off', ...
'IntegerHandle','off', ...
'Interruptible','off');
% Set closerequestfcn
set(handles_gui.figure,'CloseRequestFcn',obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_close_function(obj,hObject,eventdata,false),handles_gui.figure)));
% Menu Items -------------------------------------------------%
% Under File
handles_gui.topmenu_file = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_file', ...
'Label', 'File', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_loadref = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_loadref', ...
'Label', 'Load Reference Image', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_loadref(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_loadcur = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_loadcur', ...
'Label', 'Load Current Image(s)', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_loadcur_all = uimenu( ...
'Parent', handles_gui.topmenu_loadcur, ...
'Tag', 'topmenu_loadcur_all', ...
'Label', 'Load All (memory heavy)', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_loadcur(obj,hObject,eventdata,false),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_loadcur_lazy = uimenu( ...
'Parent', handles_gui.topmenu_loadcur, ...
'Tag', 'topmenu_loadcur_lazy', ...
'Label', 'Load Lazy (slower but less memory)', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_loadcur(obj,hObject,eventdata,true),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_loaddata = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_loaddata', ...
'Label', 'Load Data', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_loaddata(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_savedata = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_savedata', ...
'Label', 'Save Data', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_savedata(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_clear = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_clear', ...
'Label', 'Clear Data', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_clear(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_sethandle = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_sethandle', ...
'Label', 'Set Handle', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_sethandle(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_reinstall = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_reinstall', ...
'Label', 'Reinstall', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_reinstall(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_exit = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_exit', ...
'Label', 'Exit', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_exit_callback(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
% Under region of interest
handles_gui.topmenu_regionofinterest = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_regionofinterest', ...
'Label', 'Region of Interest', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_setroi_ref = uimenu( ...
'Parent', handles_gui.topmenu_regionofinterest, ...
'Tag', 'topmenu_setroi_ref', ...
'Label', 'Set Reference ROI', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_set_roi_ref(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_setroi_cur = uimenu( ...
'Parent', handles_gui.topmenu_regionofinterest, ...
'Tag', 'topmenu_setroi_cur', ...
'Label', 'Set Current ROI (For "Backward" Analysis)', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_set_roi_cur(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
% Under Analysis
handles_gui.topmenu_analysis = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_analysis', ...
'Label', 'Analysis', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_setdicparameters = uimenu( ...
'Parent', handles_gui.topmenu_analysis, ...
'Tag', 'topmenu_setdicparameters', ...
'Label', 'Set DIC Parameters', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_setdicparameters(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_perfdic = uimenu( ...
'Parent', handles_gui.topmenu_analysis, ...
'Tag', 'topmenu_perfdic', ...
'Label', 'Perform DIC Analysis', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_dic(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_formatdisp = uimenu( ...
'Parent', handles_gui.topmenu_analysis, ...
'Tag', 'topmenu_formatdisp', ...
'Label', 'Format Displacements', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_formatdisp(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_calcstrain = uimenu( ...
'Parent', handles_gui.topmenu_analysis, ...
'Tag', 'topmenu_calcstrain', ...
'Label', 'Calculate Strains', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_calcstrain(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
% Under plot - Do not wrap with wrapcallbackall
handles_gui.topmenu_plot = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_plot', ...
'Label', 'Plot', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewdispplot = uimenu( ...
'Parent', handles_gui.topmenu_plot, ...
'Tag', 'topmenu_viewdispplot', ...
'Label', 'View Displacement Plots', ...
'Checked', 'off', ...
'Enable', 'on', ...
'Interruptible','off');
handles_gui.topmenu_viewdispplot_u = uimenu( ...
'Parent', handles_gui.topmenu_viewdispplot, ...
'Tag', 'topmenu_viewdispplot_u', ...
'Label', 'U', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'u'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewdispplot_v = uimenu( ...
'Parent', handles_gui.topmenu_viewdispplot, ...
'Tag', 'topmenu_viewdispplot_v', ...
'Label', 'V', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'v'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewdispplot_all = uimenu( ...
'Parent', handles_gui.topmenu_viewdispplot, ...
'Tag', 'topmenu_viewdispplot_all', ...
'Label', 'All', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'u','v'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot = uimenu( ...
'Parent', handles_gui.topmenu_plot, ...
'Tag', 'topmenu_viewstrainpplot', ...
'Label', 'View Strains Plots', ...
'Checked', 'off', ...
'Enable', 'on', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot_exx = uimenu( ...
'Parent', handles_gui.topmenu_viewstrainplot, ...
'Tag', 'topmenu_viewstrainpplot_exx', ...
'Label', 'Exx', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'exx'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot_exy = uimenu( ...
'Parent', handles_gui.topmenu_viewstrainplot, ...
'Tag', 'topmenu_viewstrainpplot_exy', ...
'Label', 'Exy', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'exy'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot_eyy = uimenu( ...
'Parent', handles_gui.topmenu_viewstrainplot, ...
'Tag', 'topmenu_viewstrainpplot_eyy', ...
'Label', 'Eyy', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'eyy'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot_all = uimenu( ...
'Parent', handles_gui.topmenu_viewstrainplot, ...
'Tag', 'topmenu_viewstrainpplot_all', ...
'Label', 'All', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'exx','exy','eyy'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_closeplots = uimenu( ...
'Parent', handles_gui.topmenu_plot, ...
'Tag', 'topmenu_viewstrainpplot_all', ...
'Label', 'Close All Plots', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_closeplots(obj,hObject,eventdata),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
% Panels -----------------------------------------------------%
handles_gui.group_state = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_state', ...
'Units', 'characters', ...
'Position', [2 13.8 35 10.7], ...
'Title', 'Program State', ...
'Interruptible','off');
handles_gui.group_ref = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_ref', ...
'Units', 'characters', ...
'Position', [39.0 0.75 62 23.75], ...
'Title', 'Reference Image', ...
'Interruptible','off');
handles_gui.group_cur = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_cur', ...
'Units', 'characters', ...
'Position', [103 0.75 62 23.75], ...
'Title', 'Current Image(s)', ...
'Interruptible','off');
handles_gui.group_roi = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_roi', ...
'Units', 'characters', ...
'Position', [2 0.75 35 12.3], ...
'Title', 'Region of Interest', ...
'Interruptible','off');
% Axes -------------------------------------------------------%
handles_gui.axes_ref = axes( ...
'Parent', handles_gui.group_ref, ...
'Tag', 'axes_ref', ...
'Units', 'characters', ...
'Position', [2 4 57 18], ...
'Visible', 'off', ...
'handlevisibility','off', ...
'Interruptible','off');
handles_gui.axes_cur = axes( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'axes_cur', ...
'Units', 'characters', ...
'Position', [2 4 57 18], ...
'Visible', 'off', ...
'handlevisibility','off', ...
'Interruptible','off');
handles_gui.axes_roi = axes( ...
'Parent', handles_gui.group_roi, ...
'Tag', 'axes_roi', ...
'Units', 'characters', ...
'Position', [2 1 29.5 9.6],...
'Visible', 'off', ...
'handlevisibility','off', ...
'Interruptible','off');
% Image texts ------------------------------------------------%
handles_gui.text_refname = uicontrol( ...
'Parent', handles_gui.group_ref, ...
'Tag', 'text_refname', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 2 56.9 1.3], ...
'String', 'Name: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_refresolution = uicontrol( ...
'Parent', handles_gui.group_ref, ...
'Tag', 'text_refresolution', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 .5 56.9 1.3], ...
'String', 'Resolution: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_curname = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'text_curname', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 2 56.9 1.3], ...
'String', 'Name: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_curresolution = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'text_curresolution', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 .5 56.9 1.3], ...
'String', 'Resolution: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% State texts ------------------------------------------------%
handles_gui.text_refloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_refloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 7.7 21 1.3], ...
'String', 'Reference Image', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_curloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_curloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 6.5 21 1.3], ...
'String', 'Current Image(s)', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_roiloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_roiloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 5.3 21 1.3], ...
'String', 'Region of Interest', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_dicparamsloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_dicparamsloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 4.1 21 1.3], ...
'String', 'DIC Parameters', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_dicloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_dicloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 2.9 21 1.3], ...
'String', 'DIC Analysis', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_disploaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_disploaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 1.7 21 1.3], ...
'String', 'Displacements', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_strainloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_strainloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 .5 21 1.3], ...
'String', 'Strains', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% More state texts -------------------------------------------%
handles_gui.text_refloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_refloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 7.7 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_curloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_curloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 6.5 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_roiloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_roiloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 5.3 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_dicparametersloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_dicparametersloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 4.1 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_dicloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_dicloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 2.9 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_disploaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_disploaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 1.7 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_strainloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_strainloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 0.5 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
% Editbox ----------------------------------------------------%
handles_gui.edit_imgnum = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'edit_imgnum', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [44 1.3 7 1.6], ...
'String', '', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_edit_imgnum(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
% Pushbuttons ------------------------------------------------%
handles_gui.button_left = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'button_left', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [37 1.2 6 1.8], ...
'String', '<', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_button_left(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.button_right = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'button_right', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [52 1.2 6 1.8], ...
'String', '>', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_button_right(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
end
end
end
%-------------------------------------------------------------------------%
% Other functions --------------------------------------------------------%
%-------------------------------------------------------------------------%
function [handle_name,outstate] = gui_sethandle(pos_parent)
% This is a GUI for setting the name of the variable that points to ncorr.
%
% Inputs -----------------------------------------------------------------%
% pos_parent - integer array; this is the position of the parent figure
% which determines where to position this figure
%
% Outputs ----------------------------------------------------------------%
% handle_name - string; name of new handle
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Data ---------------------------------------------------------------%
% Initialize outputs
outstate = out.cancelled;
handle_name = '';
% Get GUI handles - Part of output
handles_gui_sethandle = init_gui();
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui_sethandle.figure));
% Callbacks and functions --------------------------------------------%
function constructor()
% Set Data
setappdata(handles_gui_sethandle.figure,'handle_name_prelim','');
% Set Visible
set(handles_gui_sethandle.figure,'Visible','on');
end
function callback_edit_string_handle(hObject,eventdata) %#ok<INUSD>
% Get data
handle_name_prelim = getappdata(handles_gui_sethandle.figure,'handle_name_prelim');
% Get Name
handle_name_buffer = get(handles_gui_sethandle.edit_string_handle,'string');
if (isvarname(handle_name_buffer))
handle_name_prelim = handle_name_buffer;
else
h_error = errordlg('Not a valid variable name.','Error','modal');
uiwait(h_error);
end
% Set Data
setappdata(handles_gui_sethandle.figure,'handle_name_prelim',handle_name_prelim);
update_sidemenu();
end
function callback_button_finish(hObject,eventdata) %#ok<INUSD>
% Get data
handle_name_prelim = getappdata(handles_gui_sethandle.figure,'handle_name_prelim');
% Set output
handle_name = handle_name_prelim;
outstate = out.success;
% Exit
close(handles_gui_sethandle.figure);
end
function callback_button_cancel(hObject,eventdata) %#ok<INUSD>
% Close
close(handles_gui_sethandle.figure);
end
function update_sidemenu(hObject,eventdata) %#ok<INUSD>
% Get data
handle_name_prelim = getappdata(handles_gui_sethandle.figure,'handle_name_prelim');
set(handles_gui_sethandle.edit_string_handle,'String',handle_name_prelim);
end
function handles_gui_sethandle = init_gui()
% Form UIs
handles_gui_sethandle.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', ncorr_util_figpos(pos_parent,[6 40.5]), ...
'Name', 'Set Image Size', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'WindowStyle','modal', ...
'Visible','off', ...
'IntegerHandle','off', ...
'Interruptible','off');
% Text
handles_gui_sethandle.text_string_handle = uicontrol( ...
'Parent', handles_gui_sethandle.figure, ...
'Tag', 'text_string_handle', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 3.5 15 1.3], ...
'String', 'Handle Name:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% Edit box
handles_gui_sethandle.edit_string_handle = uicontrol( ...
'Parent', handles_gui_sethandle.figure, ...
'Tag', 'edit_string_handle', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [17.2 3.6 20.6 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_string_handle,handles_gui_sethandle.figure), ...
'Interruptible','off');
% Buttons
handles_gui_sethandle.button_finish = uicontrol( ...
'Parent', handles_gui_sethandle.figure, ...
'Tag', 'button_finish', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.1 1 12 1.7], ...
'String', 'Finish', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_finish,handles_gui_sethandle.figure), ...
'Interruptible','off');
handles_gui_sethandle.button_cancel = uicontrol( ...
'Parent', handles_gui_sethandle.figure, ...
'Tag', 'button_cancel', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [16 1 12 1.7], ...
'String', 'Cancel', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_cancel,handles_gui_sethandle.figure), ...
'Interruptible','off');
end
% Pause until figure is closed ---------------------------------------%
waitfor(handles_gui_sethandle.figure);
end
function [support_openmp,total_cores,outstate] = gui_install(pos_parent)
% This is a GUI to prompt user if openmp support exists.
%
% Inputs -----------------------------------------------------------------%
% pos_parent - integer array; this is the position of the parent figure
% which determines where to position this figure
%
% Outputs ----------------------------------------------------------------%
% support_openmp - logical; tells whether openmp support exists
% total_cores - integer; tells the number of cores that exist in the case
% that openmp is supported
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Data ---------------------------------------------------------------%
% Initialize outputs
outstate = out.cancelled;
support_openmp = false;
total_cores = 1;
% Get GUI handles
handles_gui = init_gui();
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui.figure));
% Callbacks and functions --------------------------------------------%
function constructor
% Set data
setappdata(handles_gui.figure,'total_cores_prelim',1);
setappdata(handles_gui.figure,'total_cores_min',1);
setappdata(handles_gui.figure,'total_cores_max',64);
setappdata(handles_gui.figure,'val_checkbox_openmp',false);
% Update
update_sidemenu();
% Format window
set(handles_gui.figure,'Visible','on');
end
% Callbacks and functions --------------------------------------------%
function callback_checkbox_openmp(hObject,eventdata) %#ok<INUSD>
% Get data
total_cores_prelim = getappdata(handles_gui.figure,'total_cores_prelim');
val_checkbox_openmp = get(handles_gui.checkbox_openmp,'Value');
if (~val_checkbox_openmp)
% Reset total cores to 1
total_cores_prelim = 1;
end
% Set data
setappdata(handles_gui.figure,'val_checkbox_openmp',val_checkbox_openmp);
setappdata(handles_gui.figure,'total_cores_prelim',total_cores_prelim);
update_sidemenu();
end
function callback_edit_total_cores(hObject,eventdata) %#ok<INUSD>
% Get Data
total_cores_prelim = getappdata(handles_gui.figure,'total_cores_prelim');
total_cores_min = getappdata(handles_gui.figure,'total_cores_min');
total_cores_max = getappdata(handles_gui.figure,'total_cores_max');
% Get buffer
total_cores_buffer = str2double(get(handles_gui.edit_total_cores,'string'));
if (ncorr_util_isintbb(total_cores_buffer,total_cores_min,total_cores_max,'Number of cores') == out.success)
total_cores_prelim = total_cores_buffer;
end
% Set data
setappdata(handles_gui.figure,'total_cores_prelim',total_cores_prelim);
update_sidemenu();
end
function callback_button_finish(hObject,eventdata) %#ok<INUSD>
% Get data
total_cores_prelim = getappdata(handles_gui.figure,'total_cores_prelim');
support_openmp_prelim = getappdata(handles_gui.figure,'val_checkbox_openmp');
% Store
total_cores = total_cores_prelim;
support_openmp = support_openmp_prelim;
outstate = out.success;
% Return
close(handles_gui.figure);
end
function callback_button_cancel(hObject,eventdata) %#ok<INUSD>
close(handles_gui.figure);
end
function update_sidemenu(hObject,eventdata) %#ok<INUSD>
% Get data
val_checkbox_openmp = getappdata(handles_gui.figure,'val_checkbox_openmp');
total_cores_prelim = getappdata(handles_gui.figure,'total_cores_prelim');
set(handles_gui.checkbox_openmp,'Value',val_checkbox_openmp);
if (val_checkbox_openmp)
set(handles_gui.edit_total_cores,'enable','on');
else
set(handles_gui.edit_total_cores,'enable','off');
end
set(handles_gui.edit_total_cores,'String',num2str(total_cores_prelim));
end
function handles_gui = init_gui()
handles_gui.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', ncorr_util_figpos(pos_parent,[9.5 70]), ...
'Name', 'OpenMP support', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'Visible','off', ...
'IntegerHandle','off', ...
'WindowStyle','modal', ...
'Interruptible','off');
handles_gui.text_openmp = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_openmp', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [1.5 5.1 66.7 2.2], ...
'HorizontalAlignment','left', ...
'String', 'Requires multicore CPU and compiler which supports OpenMP installed through mex.', ...
'Value', 0, ...
'Interruptible','off');
handles_gui.text_cores_total = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_core_total', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [10 3.2 18 1.2], ...
'HorizontalAlignment','left', ...
'String', 'Cores:', ...
'Value', 0, ...
'Interruptible','off');
handles_gui.checkbox_openmp = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'checkbox_openmp', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [1.5 7.5 66.7 1.3], ...
'String', 'OpenMP Multithreading', ...
'Value', 0, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_openmp,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_total_cores = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'edit_total_cores', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [22 3.3 8 1.2], ...
'HorizontalAlignment','left', ...
'String', '1', ...
'Enable', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_total_cores,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_finish = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'button_finish', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [42.3 0.7 12 1.8], ...
'String', 'Finish', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_finish,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_cancel = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'button_cancel', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [56 0.7 12 1.8], ...
'String', 'Cancel', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_cancel,handles_gui.figure), ...
'Interruptible','off');
end
% Pause until figure is closed ---------------------------------------%
waitfor(handles_gui.figure);
end
function compile_lib_cpp_mex(lib_cpp)
% This function compiles cpp_function_lib as object files.
%
% Inputs -----------------------------------------------------------------%
% lib_cpp - cell of strings; names of libraries to be compiled as object
% files
%
% Returns error if files are not found.
% Cycle over libraries and compile
for i = 0:length(lib_cpp)-1
% First check if the cpp and header files exist
if (exist([lib_cpp{i+1} '.cpp'],'file') && exist([lib_cpp{i+1} '.h'],'file'))
disp(['Installing ' lib_cpp{i+1} '... Please wait']);
% Generate compiler string
string_compile = horzcat({'-c'},{[lib_cpp{i+1} '.cpp']});
% Compile file
mex(string_compile{:});
else
h_error = errordlg(['Files ' lib_cpp{i+1} '.cpp and ' lib_cpp{i+1} '.h were not found. Please find them and place them in the current directory before proceeding.'],'Error','modal');
uiwait(h_error);
% Spit error to invoke exception
error('Compilation failed because file was not found.');
end
end
end
function compile_func_cpp_mex(func_cpp,lib_cpp,flags_f)
% This function compiles func_cpp and linkes them with the lib_cpp object
% files. If flags are provided then they will be appended when compiling.
%
% Inputs -----------------------------------------------------------------%
% func_cpp - cell of strings; names of .cpp files to be
% compiled
% lib_cpp - cell of strings; names of object files to be linked
% flags_f - cell of strings; formatted compiler flags.
%
% Returns error if library object files or source code files are not found.
% Get the OS to find object extension
if (ispc) % pc
objext = 'obj';
elseif (isunix) % unix
objext = 'o';
end
% Check if lib files have been compiled first
for i = 0:length(lib_cpp)-1
if (~exist([lib_cpp{i+1} '.' objext],'file'))
% Object file doesnt exist, return error
h_error = errordlg(['Library ' lib_cpp{i+1} ' has not yet been compiled. Please compile first and make sure the object file is located in the current directory before proceeding.'],'Error','modal');
uiwait(h_error);
% Spit error to invoke exception
error('Library not compiled yet');
end
end
% Cycle over mex files and compile
for i = 0:length(func_cpp)-1
% First check if the cpp file exists
if (exist([func_cpp{i+1} '.cpp'],'file'))
disp(['Installing ' func_cpp{i+1} '... Please wait']);
% Generate compiler string
string_compile = {[func_cpp{i+1} '.cpp']};
% Append libraries
for j = 0:length(lib_cpp)-1
string_compile = horzcat(string_compile,{[lib_cpp{j+1} '.' objext]}); %#ok<AGROW>
end
% Append flags
string_compile = horzcat(string_compile,flags_f{:}); %#ok<AGROW>
% Compile
mex(string_compile{:});
else
h_error = errordlg(['File ' filename '.cpp was not found. Please find it and place it in the current directory before proceeding'],'Error','modal');
uiwait(h_error);
% Spit error to invoke exception
error('Compilation failed because file was not found.');
end
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr_alg_convertseeds.m
|
.m
|
choco-packages-master/packages/matlab-coecis/tools/ncorr/ncorr_alg_convertseeds.m
| 27,822 |
utf_8
|
126e3f6e6db2afe68f675dff24040d5b
|
function [convertseedinfo,outstate] = ncorr_alg_convertseeds(plot_u_old,plot_v_old,plot_u_interp_old,plot_v_interp_old,roi_old,roi_new,seedwindow,spacing,border_interp)
% This function obtains the "convert" seeds. It will try to seed as many
% "new" regions as possible (one seed per region). It is possible that no
% seeds are returned.
%
% Inputs -----------------------------------------------------------------%
% plot_u_old - double array; u displacements WRT the "old" configuration.
% Units are pixels.
% plot_v_old - double array; v displacements WRT the "old" configuration.
% Units are pixels.
% plot_u_interp_old - cell; array of b-spline coefficients; one per
% region.
% plot_v_interp_old - cell; array of b-spline coefficients; one per
% region;
% roi_old - ncorr_class_roi; ROI corresponding to "old" displacements.
% Note that ROI is already reduced by default.
% roi_new - ncorr_class_roi; ROI corresponding to "new" displacements.
% Note that ROI is already reduced by default.
% seedwindow - integer; half width of window around seed that must contain
% valid points before its processed. This prevents edge points from being
% seeded.
% spacing - integer; this is the spacing parameter.
% border_interp - integer; the amount of padding used around the borders in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% convertseedinfo - struct; contains
% struct('paramvector',{},'num_region_new',{},'num_region_old',{}). The x
% and y coords stored in convertseedinfo will be reduced while the
% displacement values are in pixels.
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
%
% Note that the ordering of plot_u_interp_old and plot_v_interp_old must
% form a correspondence with the regions in roi_old. This means
% plot_u_interp_old{i} must correspond to roi_old.region(i). Regions in
% roi_old and roi_new do not need to form a direct correspondence, but they
% are assumed to be one-to-one. Returns failed if no seeds are found
% Initialize outputs
outstate = out.failed;
convertseedinfo = struct('paramvector',{},'num_region_new',{},'num_region_old',{}); % paramvector = [x_new y_new x_old y_old u_old v_old distance]
% Form convertseedinfo prelim
convertseedinfo_prelim = struct('paramvector',{},'num_region_new',{},'num_region_old',{});
% Keep track of the regions in roi_old that have already been analyzed.
list_region_old = false(length(roi_old.region),1);
% Cycle over every "new" region and attempt to seed.
for i = 0:length(roi_new.region)-1
% Regions are not gauranteed contiguous at this point, so get the
% region corresponding to the largest contiguous area to make sure
% small areas arent seeded.
regionmask_new_buffer = roi_new.get_regionmask(i);
[region_new_buffer,removed] = ncorr_alg_formregions(regionmask_new_buffer,int32(0),false); %#ok<NASGU>
% Check if contiguous region(s) are empty or if there are more than one
if (isempty(region_new_buffer))
% Continue onto next region in roi_new if region_new_buffer is empty
continue;
elseif (length(region_new_buffer) > 1)
% Select biggest region if there are more than one. This could
% possibly happen if a boundary is "pinched" or closes during
% deformation. Unlikely- but may happen.
idx_max = find([region_new_buffer.totalpoints] == max([region_new_buffer.totalpoints]),1,'first');
region_new_buffer = region_new_buffer(idx_max);
end
% Form convertseedinfo buffer
convertseedinfo_buffer = struct('paramvector',{},'num_region_new',{},'num_region_old',{});
% Set num_region_new
convertseedinfo_buffer(1).num_region_new = i;
% Initialize
successregion = false;
for j = 0:size(region_new_buffer.noderange,1)-1
x_new = j + region_new_buffer.leftbound;
% Cycle over each point
for k = 0:2:region_new_buffer.noderange(j+1)-1
for l = region_new_buffer.nodelist(j+1,k+1):region_new_buffer.nodelist(j+1,k+2);
y_new = l;
% Make sure area of half-width seedwindow is valid
% around the seed before attempting to process.
if (all(all(regionmask_new_buffer(max(y_new-seedwindow+1,1):min(y_new+seedwindow+1,end), ...
max(x_new-seedwindow+1,1):min(x_new+seedwindow+1,end)))))
% Analyze point - outstate_calcpoint will either be
% success or failed
[convertseedinfo_buffer.paramvector,convertseedinfo_buffer.num_region_old,outstate_calcpoint] = calcpoint(x_new, ...
y_new, ...
plot_u_old, ...
plot_v_old, ...
plot_u_interp_old, ...
plot_v_interp_old, ...
roi_old, ...
list_region_old, ...
spacing, ...
border_interp);
% Check if nonlinear solver was successful
if (outstate_calcpoint == out.success)
% Check distance; make sure its less than a
% threshold and also make sure that x_old and
% y_old are in valid area
x_old = round(convertseedinfo_buffer.paramvector(3));
y_old = round(convertseedinfo_buffer.paramvector(4));
if (convertseedinfo_buffer.paramvector(7) < 0.005 && ...
x_old >= 0 && x_old < size(roi_old.mask,2) && ...
y_old >= 0 && y_old < size(roi_old.mask,1) && ...
roi_old.mask(y_old+1,x_old+1)) % Should really check regionmask, but for ease just check the whole mask
% Append
convertseedinfo_prelim = horzcat(convertseedinfo_prelim,convertseedinfo_buffer); %#ok<AGROW>
list_region_old(convertseedinfo_buffer.num_region_old+1) = true;
% Break from this region
successregion = true;
end
end
end
% Break if seed was successful or all regions in the
% old configuration have been analyzed
if (successregion || all(list_region_old))
break;
end
end
% Break if seed was successful or all regions in the
% old configuration have been analyzed
if (successregion || all(list_region_old))
break;
end
end
% Break if seed was successful or all regions in the
% old configuration have been analyzed
if (successregion || all(list_region_old))
break;
end
end
end
% Assign Outputs
if (~isempty(convertseedinfo_prelim))
for i = 0:length(convertseedinfo_prelim)-1
convertseedinfo(i+1) = convertseedinfo_prelim(i+1);
end
outstate = out.success;
end
end
%-------------------------------------------------------------------------%
% Nonlinear solver equations ---------------------------------------------%
%-------------------------------------------------------------------------%
function [paramvector,num_region_old,outstate] = calcpoint(x_new,y_new,plot_u_old,plot_v_old,plot_u_interp_old,plot_v_interp_old,roi_old,list_region_old,spacing,border_interp)
% This function obtains the parameters for a "convert" seed.
%
% Inputs -----------------------------------------------------------------%
% x_new - integer; x position WRT the "new" configuration. Note that
% x_new is WRT reduced coordinates.
% y_new - integer; y position WRT the "new" configuration. Note that
% y_new is WRT reduced coordinates.
% plot_u_old - double array; u displacements WRT the "old" configuration.
% Units are pixels.
% plot_v_old - double array; v displacements WRT the "old" configuration.
% Units are pixels.
% plot_u_interp_old - cell; array of b-spline coefficients; one per
% region.
% plot_v_interp_old - cell; array of b-spline coefficients; one per
% region.
% roi_old - ncorr_class_roi; ROI corresponding to "old" displacements.
% Note that ROI is already reduced by default.
% list_region_old - logical array; keeps track of which "old" regions have
% been analyzed
% spacing - integer; this is the spacing parameter.
% border_interp - integer; the amount of padding used around the borders in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% paramvector - double array; [x_new y_new x_old y_old u_old v_old distance]
% num_region_old - integer; The region number which seed resides in for
% the "old" configuration
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize outputs
paramvector = [];
num_region_old = [];
outstate = out.failed;
% Perform global search - note: defvector = [x_old y_old] - reduced
[defvector_init,num_region_old_prelim,outstate_initialguess] = initialguess(x_new, ...
y_new, ...
plot_u_old, ...
plot_v_old, ...
roi_old, ...
list_region_old, ...
spacing);
if (outstate_initialguess == out.success)
% Perform an iterative search
[defvector,u_old,v_old,distance,outstate_iterative] = iterativesearch(x_new, ...
y_new, ...
defvector_init, ...
plot_u_interp_old, ...
plot_v_interp_old, ...
roi_old, ...
num_region_old_prelim, ...
spacing, ...
border_interp);
if (outstate_iterative == out.success)
% Set outputs
paramvector = [x_new y_new defvector u_old v_old distance];
num_region_old = num_region_old_prelim;
outstate = out.success;
end
end
end
function [defvector_init,num_region_old,outstate] = initialguess(x_new,y_new,plot_u_old,plot_v_old,roi_old,list_region_old,spacing)
% This function finds the closest integer displacements as an initial
% guess.
%
% Inputs -----------------------------------------------------------------%
% x_new - integer; x position WRT the "new" configuration. Note that
% x_new is WRT reduced coordinates.
% y_new - integer; y position WRT the "new" configuration. Note that
% y_new is WRT reduced coordinates.
% plot_u_old - double array; u displacements WRT the "old" configuration.
% Units are pixels.
% plot_v_old - double array; v displacements WRT the "old" configuration.
% Units are pixels.
% roi_old - ncorr_class_roi; ROI corresponding to "old" displacements.
% Note that ROI is already reduced by default.
% list_region_old - logical array; keeps track of which "old" regions have
% been analyzed
% spacing - integer; this is the spacing parameter.
%
% Outputs ----------------------------------------------------------------%
% defvector_init - integer array; [x_old y_old] - reduced
% num_region_old - integer; number of region where x_old and y_old were found
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize Outputs
outstate = out.failed;
defvector_init = [];
num_region_old = [];
% Cycle through every point to insure a global minimum
x_old_prelim = -1;
y_old_prelim = -1;
num_region_old_prelim = -1;
distance_prelim = inf; % arbitrarily large number
for i = 0:length(roi_old.region)-1
if (list_region_old(i+1)) % this ROI has been analyzed already
continue;
else
for j = 0:size(roi_old.region(i+1).noderange,1)-1
x_old_buffer = j + roi_old.region(i+1).leftbound;
for k = 0:2:roi_old.region(i+1).noderange(j+1)-1
for l = roi_old.region(i+1).nodelist(j+1,k+1):roi_old.region(i+1).nodelist(j+1,k+2)
y_old_buffer = l;
% Must divide displacement by spacing so
% displacement is WRT reduced coordinates
u_old_buffer = plot_u_old(y_old_buffer+1,x_old_buffer+1)/(spacing+1);
v_old_buffer = plot_v_old(y_old_buffer+1,x_old_buffer+1)/(spacing+1);
distance_buffer = sqrt((x_new-(x_old_buffer+u_old_buffer))^2+(y_new-(y_old_buffer+v_old_buffer))^2);
% Check if this point is better
if (distance_buffer < distance_prelim)
x_old_prelim = x_old_buffer;
y_old_prelim = y_old_buffer;
num_region_old_prelim = i;
distance_prelim = distance_buffer;
end
end
end
end
end
end
if (x_old_prelim ~= -1 && y_old_prelim ~= -1)
defvector_init = [x_old_prelim y_old_prelim];
num_region_old = num_region_old_prelim;
outstate = out.success;
end
end
function [defvector,u_old,v_old,distance,outstate] = iterativesearch(x_new,y_new,defvector_init,plot_u_interp_old,plot_v_interp_old,roi_old,num_region_old,spacing,border_interp)
% This function uses Gauss-Newton iterations to find the subpixel x_old
% and y_old values.
%
% Inputs -----------------------------------------------------------------%
% x_new - integer; x position WRT the "new" configuration. Note that
% x_new is WRT reduced coordinates.
% y_new - integer; y position WRT the "new" configuration. Note that
% y_new is WRT reduced coordinates.
% defvector_init - integer array; of form [x_old y_old]. It's integer
% because these are the initial guesses from the global search.
% plot_u_interp_old - cell; array of b-spline coefficients; one per
% region.
% plot_v_interp_old - cell; array of b-spline coefficients; one per
% region.
% roi_old - ncorr_class_roi; ROI corresponding to "old" displacements.
% Note that ROI is already reduced by default.
% num_region_old - integer; number of region being analyzed
% spacing - integer; this is the spacing parameter.
% border_interp - integer; the amount of padding used around the borders in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% defvector - double array; [x_old y_old] - reduced
% u_old - double; u displacement from x_old to x_new - pixels
% v_old - double; v displacement from y_old to y_new - pixels
% distance - double; distance between [x_new y_new] and [x_old y_old]
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize outputs
outstate = out.failed;
defvector = [];
u_old = [];
v_old = [];
distance = [];
% Gauss Newton optimization - send only b-spline coefficients
% corresponding to the num_region_old
[defvector_prelim,u_old_prelim,v_old_prelim,distance_prelim,gradnorm,outstate_newton] = newton(x_new, ...
y_new, ...
defvector_init, ...
plot_u_interp_old{num_region_old+1}, ...
plot_v_interp_old{num_region_old+1}, ...
roi_old.region(num_region_old+1), ...
spacing, ...
border_interp);
counter = 1;
while (outstate_newton == out.success && gradnorm > 10^-5 && counter < 10)
% Gauss Newton optimization - send only b-spline coefficients
% corresponding to the num_region_old
[defvector_prelim,u_old_prelim,v_old_prelim,distance_prelim,gradnorm,outstate_newton] = newton(x_new, ...
y_new, ...
defvector_prelim, ...
plot_u_interp_old{num_region_old+1}, ...
plot_v_interp_old{num_region_old+1}, ...
roi_old.region(num_region_old+1), ...
spacing, ...
border_interp);
counter = counter + 1;
end
if (outstate_newton == out.success)
% Assign outputs
defvector = defvector_prelim;
u_old = u_old_prelim;
v_old = v_old_prelim;
distance = distance_prelim;
outstate = out.success;
end
end
function [defvector,u_old,v_old,distance,gradnorm,outstate] = newton(x_new,y_new,defvector_init,plot_u_interp_old,plot_v_interp_old,region_old,spacing,border_interp)
% This function actually performs the Gauss-Newton iteration
%
% Inputs -----------------------------------------------------------------%
% x_new - integer; x position WRT the "new" configuration. Note that
% x_new is WRT reduced coordinates.
% y_new - integer; y position WRT the "new" configuration. Note that
% y_new is WRT reduced coordinates.
% defvector_init - double array; of form [x_old y_old]
% plot_u_interp_old - double array; array of b-spline coefficients
% corresponding to region_old
% plot_v_interp_old - double array; array of b-spline coefficients
% corresponding to region_old
% region_old - struct; specific region being analyzed
% spacing - double; this is the spacing parameter.
% border_interp - integer; the amount of padding used around the borders in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% defvector - double array; [x_old y_old] - reduced
% u_old - double; u displacement from x_old to x_new - pixels
% v_old - double; v displacement from y_old to y_new - pixels
% distance - double; distance between [x_new y_new] and [x_old y_old]
% gradnorm - double; norm of the gradient vector - should be close to 0
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize inputs
outstate = out.failed;
defvector = [];
u_old = [];
v_old = [];
gradnorm = [];
distance = [];
% Use interp function local to this m-file since it combines
% interpolation of values and gradients.
[interpvector,outstate_interp] = interpqbs_convert(defvector_init, ...
plot_u_interp_old, ...
plot_v_interp_old, ...
region_old, ...
border_interp);
if (outstate_interp == out.success)
% Determine Gradient - note that interpolation found through
% interpqbs_convert needs to be WRT reduced coordinates; However,
% displacements use pixel units, so they need to be scaled in order
% to be WRT reduced coordinates.
gradient(1) = -2*((x_new-(defvector_init(1)+interpvector(1)/(spacing+1)))*(1+interpvector(3)/(spacing+1))+(y_new-(defvector_init(2)+interpvector(2)/(spacing+1)))*(interpvector(5)/(spacing+1)));
gradient(2) = -2*((x_new-(defvector_init(1)+interpvector(1)/(spacing+1)))*(interpvector(4)/(spacing+1))+(y_new-(defvector_init(2)+interpvector(2)/(spacing+1)))*(1+interpvector(6)/(spacing+1)));
% Determine Hessian
hessian(1,1) = 2*((1+interpvector(3)/(spacing+1))^2+(interpvector(5)/(spacing+1))^2);
hessian(2,1) = 2*((interpvector(4)/(spacing+1))*(1+interpvector(3)/(spacing+1))+(1+interpvector(6)/(spacing+1))*(interpvector(5)/(spacing+1)));
hessian(1,2) = hessian(2,1); % symmetric
hessian(2,2) = 2*((interpvector(4)/(spacing+1))^2+(1+interpvector(6)/(spacing+1))^2);
det_hess = det(hessian);
% Check to make sure hessian is positive definite
% From :http://www.math.northwestern.edu/~clark/285/2006-07/handouts/pos-def.pdf
% Make sure det(hess) > 0 and hess(1,1) > 0
if (det_hess > 0 && hessian(1) > 0)
% Determine new coordinates
defvector_prelim = (defvector_init'-hessian^-1*gradient')';
% Calculate distance - we have to interpolate again with the new
% coordinates
[interpvector,outstate_interp] = interpqbs_convert(defvector_prelim, ...
plot_u_interp_old, ...
plot_v_interp_old, ...
region_old, ...
border_interp);
if (outstate_interp == out.success)
% Store outputs
defvector = defvector_prelim;
u_old = interpvector(1);
v_old = interpvector(2);
distance = sqrt((x_new-(defvector(1)+interpvector(1)/(spacing+1)))^2+(y_new-(defvector(2)+interpvector(2)/(spacing+1)))^2);
gradnorm = norm(gradient);
outstate = out.success;
end
end
end
end
function [interpvector,outstate] = interpqbs_convert(defvector,plot_u_interp_old,plot_v_interp_old,region_old,border_interp)
% This interpolation combines interpolation of values and gradients, so
% it's reimplemented here because it can save some time by combining the
% interpolation.
%
% Inputs -----------------------------------------------------------------%
% defvector - double array; [x_old y_old] - reduced
% plot_u_interp_old - double array; array of b-spline coefficients. Units
% are pixels.
% plot_v_interp_old - double array; array of b-spline coefficients. Units
% are pixels.
% region_old - struct; specific region being analyzed
% border_interp - integer; the amount of padding used around the edges in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% interpvector - double array; [u v du/dx du/dy dv/dx dv/dy]
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize output
outstate = out.failed;
interpvector = [];
% Biquintic Kernel Matrix
QK = [1/120 13/60 11/20 13/60 1/120 0;
-1/24 -5/12 0 5/12 1/24 0;
1/12 1/6 -1/2 1/6 1/12 0;
-1/12 1/6 0 -1/6 1/12 0;
1/24 -1/6 1/4 -1/6 1/24 0;
-1/120 1/24 -1/12 1/12 -1/24 1/120];
% Interpolate if in bounds
x_tilda = defvector(1);
y_tilda = defvector(2);
x_tilda_floor = floor(x_tilda);
y_tilda_floor = floor(y_tilda);
% Make sure top, left, bottom, and right are within the b-spline
% coefficient array. top, left, bottom and right are the bounding
% box of the b-spline coefficients used for interpolation of this
% point;
top = y_tilda_floor-region_old.upperbound+border_interp-2;
left = x_tilda_floor-region_old.leftbound+border_interp-2;
bottom = y_tilda_floor-region_old.upperbound+border_interp+3;
right = x_tilda_floor-region_old.leftbound+border_interp+3;
if (top >= 0 && ...
left >= 0 && ...
bottom < size(plot_u_interp_old,1) && ...
right < size(plot_u_interp_old,2))
% Set coords
x_tilda_delta = x_tilda-x_tilda_floor;
y_tilda_delta = y_tilda-y_tilda_floor;
x_vec(1) = 1.0;
x_vec(2) = x_tilda_delta;
x_vec(3) = x_vec(2)*x_tilda_delta;
x_vec(4) = x_vec(3)*x_tilda_delta;
x_vec(5) = x_vec(4)*x_tilda_delta;
x_vec(6) = x_vec(5)*x_tilda_delta;
y_vec(1) = 1.0;
y_vec(2) = y_tilda_delta;
y_vec(3) = y_vec(2)*y_tilda_delta;
y_vec(4) = y_vec(3)*y_tilda_delta;
y_vec(5) = y_vec(4)*y_tilda_delta;
y_vec(6) = y_vec(5)*y_tilda_delta;
x_vec_dx(1) = 0.0;
x_vec_dx(2) = 1.0;
x_vec_dx(3) = 2.0*x_vec(2);
x_vec_dx(4) = 3.0*x_vec(3);
x_vec_dx(5) = 4.0*x_vec(4);
x_vec_dx(6) = 5.0*x_vec(5);
y_vec_dy(1) = 0.0;
y_vec_dy(2) = 1.0;
y_vec_dy(3) = 2.0*y_vec(2);
y_vec_dy(4) = 3.0*y_vec(3);
y_vec_dy(5) = 4.0*y_vec(4);
y_vec_dy(6) = 5.0*y_vec(5);
% Precompute
QKMAT_u_plot = QK*plot_u_interp_old(top+1:bottom+1,left+1:right+1)*QK';
QKMAT_v_plot = QK*plot_v_interp_old(top+1:bottom+1,left+1:right+1)*QK';
% Get interpolated value
interpvector(1) = y_vec*QKMAT_u_plot*x_vec'; % u
interpvector(2) = y_vec*QKMAT_v_plot*x_vec'; % v
interpvector(3) = y_vec*QKMAT_u_plot*x_vec_dx'; % du/dx
interpvector(4) = y_vec_dy*QKMAT_u_plot*x_vec'; % du/dy
interpvector(5) = y_vec*QKMAT_v_plot*x_vec_dx'; % dv/dx
interpvector(6) = y_vec_dy*QKMAT_v_plot*x_vec'; % dv/dy
outstate = out.success;
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr_gui_viewplots.m
|
.m
|
choco-packages-master/packages/matlab-coecis/tools/ncorr/ncorr_gui_viewplots.m
| 127,861 |
utf_8
|
b5e3358c4dae7e33660ab822d294b67c
|
function handles_gui = ncorr_gui_viewplots(reference,current,data_dic,type_plot,pos_parent,params_init)
% This is a GUI for viewing the displacement/strain plots.
%
% Inputs -----------------------------------------------------------------%
% reference - ncorr_class_img; used for displaying the background image.
% current - ncorr_class_img; used for displaying the background image.
% data_dic - struct; contains displacement and strain info. This is the
% main data structure used in Ncorr.
% type_plot - string; specifies whether plot is u, v, exx, exy, or eyy.
% pos_parent - integer array; this is the position of the parent figure
% which determines where to position this figure
% params_init - cell; {1} = num_cur, {2} = scalebarlength,
% {3} = if handle_scalebar is on, {4} = if handle_axes is on, {5} if
% Lagrangian or Eulerian, {6} if zoomed; {7} if panned. Used to
% coordinate with any existing open plots.
%
% Outputs ----------------------------------------------------------------%
% handles_gui - handles; these are the GUI handles which allow Ncorr to
% manage the closing and synchronization of the open plots
%
% Note that this function checks both roi_ref_formatted and
% roi_cur_formatted to make sure all ROIs are non-empty. This is a very
% unlikely scenario, but if it happens this function will display and error
% dialogue and return.
% Data ---------------------------------------------------------------%
% Get GUI handles
handles_gui = init_gui();
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui.figure));
% Callbacks and functions --------------------------------------------%
function constructor()
% Check to make sure ROIs are full
roifull = true;
if (strcmp(type_plot,'u') || strcmp(type_plot,'v'))
field = 'displacements';
else
field = 'strains';
end
for i = 0:length(current)-1
if (data_dic.(field)(i+1).roi_ref_formatted.get_fullregions == 0 || ...
data_dic.(field)(i+1).roi_cur_formatted.get_fullregions == 0)
roifull = false;
break;
end
end
if (~roifull)
% One of the ROIs is empty, return; CloseRequestFcn is disabled,
% in gui_init(), so reenable it before closing.
set(handles_gui.figure,'CloseRequestFcn','closereq');
h_error = errordlg('Some data plots are empty, please rerun analysis.','Error','modal');
uiwait(h_error);
close(handles_gui.figure);
return;
end
% Set zoom and pan
handle_zoom = zoom(handles_gui.figure);
handle_pan = pan(handles_gui.figure);
% Initialize buffers -----------------------------------------%
if (isempty(params_init))
% Set num_cur - by default show last image in set
num_cur = length(current)-1;
% Set scalebar length - initialize to 3/4 the width of the
% reference image. This uses real units.
scalebarlength_prelim = (3/4)*reference.width*data_dic.dispinfo.pixtounits;
if (floor(scalebarlength_prelim) > 3)
% Use integer
scalebarlength = floor(scalebarlength_prelim);
else
% Use decimal
scalebarlength = scalebarlength_prelim;
end
% handle_scalebar checkbox
val_checkbox_scalebar = true;
% handle_axes checkbox
val_checkbox_axes = true;
% Lagrangian or Eulerian; 1 == Lagrangian
val_popupmenu = 1;
else
% Set num_cur
num_cur = params_init{1};
% Units and handle_scalebar buffer
scalebarlength = params_init{2};
% handle_scalebar checkbox
val_checkbox_scalebar = params_init{3};
% handle_axes checkbox
val_checkbox_axes = params_init{4};
% Lagrangian or Eulerian
val_popupmenu = params_init{5};
% Zoomed
if (params_init{6})
set(handle_zoom,'Enable','on');
end
% Panned
if (params_init{7})
set(handle_pan,'Enable','on');
end
end
% Transparency buffer
transparency_prelim = 0.75;
% Contour lines buffer
contourlines_prelim = 20;
max_contourlines = 100;
% Set slider buffer
slider_buffer = struct('lagrangian',{},'eulerian',{});
for i = 0:length(current)-1
% Set parameters
% Get the data vector corresponding to this plot
data_ref = get_data(type_plot,'lagrangian',i);
slider_buffer(i+1).lagrangian(1) = 0.5; % Initialize to half
slider_buffer(i+1).lagrangian(2) = 0.5; % Initialize to half
slider_buffer(i+1).lagrangian(3:7) = get_sliderparams(data_ref);
% Get the data vector corresponding to this plot
data_cur = get_data(type_plot,'eulerian',i);
slider_buffer(i+1).eulerian(1) = 0.5; % Initialize to half
slider_buffer(i+1).eulerian(2) = 0.5; % Initialize to half
slider_buffer(i+1).eulerian(3:7) = get_sliderparams(data_cur);
end
max_upperbound = 1e10;
min_lowerbound = -1e10;
max_scalebarlength = 1e10;
% Set data
setappdata(handles_gui.figure,'num_cur',num_cur);
setappdata(handles_gui.figure,'transparency_prelim',transparency_prelim);
setappdata(handles_gui.figure,'contourlines_prelim',contourlines_prelim);
setappdata(handles_gui.figure,'max_contourlines',max_contourlines);
setappdata(handles_gui.figure,'scalebarlength',scalebarlength);
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
setappdata(handles_gui.figure,'max_upperbound',max_upperbound);
setappdata(handles_gui.figure,'min_lowerbound',min_lowerbound);
setappdata(handles_gui.figure,'max_scalebarlength',max_scalebarlength);
setappdata(handles_gui.figure,'type_plot',type_plot); % Store this explicitly so type and other parameters can be deduced from 'friends'
setappdata(handles_gui.figure,'friends',[]); % This is used for modifying other viewplots; it stores their figure handles
setappdata(handles_gui.figure,'text_info',[]); % This is the text box that displays when the cursor is over the data plot
setappdata(handles_gui.figure,'val_checkbox_contour',false);
setappdata(handles_gui.figure,'val_checkbox_scalebar',val_checkbox_scalebar);
setappdata(handles_gui.figure,'val_checkbox_axes',val_checkbox_axes);
setappdata(handles_gui.figure,'val_checkbox_minmaxmarkers',false);
setappdata(handles_gui.figure,'val_popupmenu',val_popupmenu);
setappdata(handles_gui.figure,'handle_preview',[]);
setappdata(handles_gui.figure,'handle_scalebar',[]);
setappdata(handles_gui.figure,'handle_axes',[]);
setappdata(handles_gui.figure,'handle_colorbar',[]);
setappdata(handles_gui.figure,'handle_point_max',[]);
setappdata(handles_gui.figure,'handle_point_min',[]);
setappdata(handles_gui.figure,'handle_zoom',handle_zoom);
setappdata(handles_gui.figure,'handle_pan',handle_pan);
% Update - must send the GUI handles; this is because
% update_axes can be used to update other figure handles stored
% in 'friends'.
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
% Set resize and hover function callbacks; This GUI is
% resizable and displays a data cursor when the cursor hovers
% over the data plot.
% Set resize function
set(handles_gui.figure,'ResizeFcn',ncorr_util_wrapcallbacktrycatch(@callback_resizefunction,handles_gui.figure));
% Set hover function
set(handles_gui.figure,'WindowButtonMotionFcn',ncorr_util_wrapcallbacktrycatch(@callback_moveplot,handles_gui.figure));
% Set Visible
set(handles_gui.figure,'Visible','on');
end
function callback_topmenu_save(hObject,eventdata,includeinfo) %#ok<INUSL>
% Get info
num_cur = getappdata(handles_gui.figure,'num_cur');
% Form save figure -----------------------------------------------%
handles_gui_savefig = form_savefig(num_cur,includeinfo,[]);
% Disable close function so figure isnt inadvertently closed.
set(handles_gui_savefig.figure,'CloseRequestFcn','');
% Set size(s) ----------------------------------------------------%
% gui_savesize is a local function with a GUI; it allows the user
% to modify the size of the image
[size_savefig,timedelay,outstate] = gui_savesize(handles_gui_savefig, ...
false, ...
get(handles_gui.figure,'OuterPosition')); %#ok<*ASGLU>
if (outstate == out.success)
% Save image -------------------------------------------------%
[filename,pathname] = uiputfile({'*.jpg';'*.png';'*.bmp';'*.tif'},'Save Image');
if (~isequal(filename,0) && ~isequal(pathname,0))
overwrite = true;
if (exist(fullfile(pathname,filename),'file'))
contbutton = questdlg('File already exists. Do you want to overwrite?','Continue Operation','Yes','No','No');
if strcmp(contbutton,'No')
overwrite = false;
end
end
if (overwrite)
% Get image ------------------------------------------%
img_printscreen = getframe(handles_gui_savefig.figure);
% Save the image
imwrite(img_printscreen.cdata,fullfile(pathname,filename));
end
end
end
% Exit -----------------------------------------------------------%
set(handles_gui_savefig.figure,'CloseRequestFcn','closereq');
close(handles_gui_savefig.figure);
end
function callback_topmenu_savegif(hObject,eventdata) %#ok<INUSD>
% Get data
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
% All current images must have the same size to use this feature
% with the eulerian description
size_cur = size(current(1).get_gs());
samesize_cur = true;
for i = 1:length(current)-1
if (~isequal(size_cur,[current(i+1).height current(i+1).width]))
samesize_cur = false;
break;
end
end
% Save image -----------------------------------------------------%
% Note val_popupmenu equals 1 for the lagrangian perspective, and 2
% for the eulerian perspective
if (val_popupmenu == 1 || (val_popupmenu == 2 && samesize_cur))
% Form initial save figure -----------------------------------%
handles_gui_savefig = form_savefig(0,0,[]);
% Disable close function so figure isnt inadvertently closed
set(handles_gui_savefig.figure,'CloseRequestFcn','');
% Set Size(s) ------------------------------------------------%
% gui_savesize is a local function with a GUI; it allows the user
% to modify the size of the image
[size_savefig,timedelay,outstate] = gui_savesize(handles_gui_savefig, ...
true, ...
get(handles_gui.figure,'OuterPosition'));
if (outstate == out.success)
[filename,pathname] = uiputfile({'*.gif'},'Save Image');
if (~isequal(filename,0) && ~isequal(pathname,0))
overwrite = true;
if (exist(fullfile(pathname,filename),'file'))
contbutton = questdlg('File already exists. Do you want to overwrite?','Continue Operation','Yes','No','No');
if strcmp(contbutton,'No')
overwrite = false;
end
end
if (overwrite)
% Save initial image -----------------------------%
img_printscreen = getframe(handles_gui_savefig.figure);
img_printscreen = frame2im(img_printscreen);
[imind,cm] = rgb2ind(img_printscreen,256);
% Save
imwrite(imind,cm,[pathname filename],'gif','Loopcount',inf);
% Cycle over other images to save
for i = 1:length(current)-1
% Close figure
set(handles_gui_savefig.figure,'CloseRequestFcn','closereq');
close(handles_gui_savefig.figure);
% Form updated save figure -------------------%
handles_gui_savefig = form_savefig(i,0,size_savefig);
% Disable close function for now
set(handles_gui_savefig.figure,'CloseRequestFcn','');
% Get image ----------------------------------%
img_printscreen = getframe(handles_gui_savefig.figure);
img_printscreen = frame2im(img_printscreen);
[imind,cm] = rgb2ind(img_printscreen,256);
% Append
if (i ~= length(current)-1)
imwrite(imind,cm,[pathname filename],'gif','WriteMode','append','DelayTime',timedelay);
else
% This is the last image, make the time
% delay longer so there's a pause at the
% end.
imwrite(imind,cm,[pathname filename],'gif','WriteMode','append','DelayTime',timedelay+0.5);
end
end
end
end
end
% Close last figure
set(handles_gui_savefig.figure,'CloseRequestFcn','closereq');
close(handles_gui_savefig.figure);
else
h_error = errordlg('All current images must have the same size to save gif with the Eulerian description.','Error','modal');
uiwait(h_error);
end
end
%---------------------------------------------------------------------%
% These functions can potentially modify other viewplots -------------%
%---------------------------------------------------------------------%
function callback_popupmenu(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
val_popupmenu = get(handles_gui.popupmenu,'Value');
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'val_popupmenu',val_popupmenu);
% Update
update_axes('set',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'val_popupmenu',val_popupmenu);
% Update this plot
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_checkbox_scalebar(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
val_checkbox_scalebar = get(handles_gui.checkbox_scalebar,'Value');
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'val_checkbox_scalebar',val_checkbox_scalebar);
% Update
update_axes('update',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'val_checkbox_scalebar',val_checkbox_scalebar);
% Update this plot
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_checkbox_axes(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
val_checkbox_axes = get(handles_gui.checkbox_axes,'Value');
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'val_checkbox_axes',val_checkbox_axes);
% Update
update_axes('update',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'val_checkbox_axes',val_checkbox_axes);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_scalebarlength(hObject,eventdata) %#ok<INUSD>
% Get data
scalebarlength = getappdata(handles_gui.figure,'scalebarlength');
max_scalebarlength = getappdata(handles_gui.figure,'max_scalebarlength');
friends = getappdata(handles_gui.figure,'friends');
% Get Value
scalebarlength_buffer = str2double(get(handles_gui.edit_scalebarlength,'string'));
if (ncorr_util_isrealbb(scalebarlength_buffer,0,max_scalebarlength,'Scalebar Length') == out.success)
% Update buffer
scalebarlength = scalebarlength_buffer;
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'scalebarlength',scalebarlength);
% Update
update_axes('update',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
end
% Set data
setappdata(handles_gui.figure,'scalebarlength',scalebarlength);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_imgnum(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
friends = getappdata(handles_gui.figure,'friends');
% Get Value - uses one based indexing
num_cur_prelim = str2double(get(handles_gui.edit_imgnum,'string'));
if (ncorr_util_isintbb(num_cur_prelim,1,length(current),'Current Image number') == out.success)
% Store value - convert back to zero based indexing
num_cur = num_cur_prelim-1;
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'num_cur',num_cur);
% Update
update_axes('set',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
end
% Set data
setappdata(handles_gui.figure,'num_cur',num_cur);
% Update this plot
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_button_zoom(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
handle_zoom = getappdata(handles_gui.figure,'handle_zoom');
if (strcmp(get(handle_zoom,'Enable'),'on'))
% Zoom is already enabled; disable it
val_zoom = false;
set(handle_zoom,'Enable','off');
else
% Zoom not enabled; enable it
val_zoom = true;
set(handle_zoom,'Enable','on');
end
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Get zoom handle from other plot
handle_zoom_sub = getappdata(friends{i+1}.figure,'handle_zoom');
if (val_zoom)
set(handle_zoom_sub,'Enable','on');
else
set(handle_zoom_sub,'Enable','off');
end
% Set data
setappdata(friends{i+1}.figure,'handle_zoom',handle_zoom_sub);
% Update
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'handle_zoom',handle_zoom);
% Update
update_sidemenu(handles_gui);
end
function callback_button_pan(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
handle_pan = getappdata(handles_gui.figure,'handle_pan');
if (strcmp(get(handle_pan,'Enable'),'on'))
% Pan is already enabled; disable it
val_pan = false;
set(handle_pan,'Enable','off');
else
% Pan not enabled; enable it
val_pan = true;
set(handle_pan,'Enable','on');
end
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Get Pan handle from other plot
handle_pan_sub = getappdata(friends{i+1}.figure,'handle_pan');
if (val_pan)
set(handle_pan_sub,'Enable','on');
else
set(handle_pan_sub,'Enable','off');
end
% Set data
setappdata(friends{i+1}.figure,'handle_pan',handle_pan_sub);
% Update
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'handle_pan',handle_pan);
% Update
update_sidemenu(handles_gui);
end
function callback_button_left(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
friends = getappdata(handles_gui.figure,'friends');
% Check for overshoot
if (num_cur > 0)
% Update other plots in friend list
num_cur = num_cur-1;
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'num_cur',num_cur);
% Update
update_axes('set',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
end
% Set data
setappdata(handles_gui.figure,'num_cur',num_cur);
% Update this plot
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_button_right(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
friends = getappdata(handles_gui.figure,'friends');
% Check for overshoot
if (num_cur < length(current)-1)
% Update other plots in friend list
num_cur = num_cur+1;
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'num_cur',num_cur);
% Update
update_axes('set',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
end
% Set data
setappdata(handles_gui.figure,'num_cur',num_cur);
% Update this plot
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function update_sidemenu(handles_gui_sub)
% Get data - MUST USE HANDLES_GUI_SUB!!!
num_cur = getappdata(handles_gui_sub.figure,'num_cur');
scalebarlength = getappdata(handles_gui_sub.figure,'scalebarlength');
transparency_prelim = getappdata(handles_gui_sub.figure,'transparency_prelim');
contourlines_prelim = getappdata(handles_gui_sub.figure,'contourlines_prelim');
slider_buffer = getappdata(handles_gui_sub.figure,'slider_buffer');
val_checkbox_scalebar = getappdata(handles_gui_sub.figure,'val_checkbox_scalebar');
val_checkbox_axes = getappdata(handles_gui_sub.figure,'val_checkbox_axes');
val_checkbox_contour = getappdata(handles_gui_sub.figure,'val_checkbox_contour');
val_popupmenu = getappdata(handles_gui_sub.figure,'val_popupmenu');
handle_zoom = getappdata(handles_gui_sub.figure,'handle_zoom');
handle_pan = getappdata(handles_gui_sub.figure,'handle_pan');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Sliders:
set(handles_gui_sub.slider_transparency,'value',transparency_prelim);
set(handles_gui_sub.slider_upperbound,'value',min(1,max(0,slider_buffer(num_cur+1).(lore)(1))));
set(handles_gui_sub.slider_lowerbound,'value',min(1,max(0,slider_buffer(num_cur+1).(lore)(2))));
% Edit:
set(handles_gui_sub.edit_transparency,'String',num2str(transparency_prelim,'%6.4f'));
set(handles_gui_sub.edit_upperbound,'String',num2str((slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(1)+slider_buffer(num_cur+1).(lore)(4),'%6.4f'));
set(handles_gui_sub.edit_lowerbound,'String',num2str((slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(2)+slider_buffer(num_cur+1).(lore)(4),'%6.4f'));
set(handles_gui_sub.edit_contour,'String',num2str(contourlines_prelim));
set(handles_gui_sub.edit_scalebarlength,'String',num2str(scalebarlength,'%6.2f'));
% Popupmenu:
set(handles_gui_sub.popupmenu,'Value',val_popupmenu);
% Enable scalebar
if (val_checkbox_scalebar)
set(handles_gui_sub.edit_scalebarlength,'Enable','on','backgroundcolor',[0.9412 0.9412 0.9412]);
set(handles_gui_sub.checkbox_scalebar,'Value',true);
else
set(handles_gui_sub.edit_scalebarlength,'Enable','off','backgroundcolor',[0.9412 0.9412 0.9412]);
set(handles_gui_sub.checkbox_scalebar,'Value',false);
end
% Enable axes
if (val_checkbox_axes)
set(handles_gui_sub.checkbox_axes,'Value',true);
else
set(handles_gui_sub.checkbox_axes,'Value',false);
end
% Enable contour
if (val_checkbox_contour)
% Disable trans
set(handles_gui_sub.edit_transparency,'Enable','off');
set(handles_gui_sub.slider_transparency,'Enable','off');
% Enable contours
set(handles_gui_sub.edit_contour,'Enable','on','backgroundcolor',[0.9412 0.9412 0.9412]);
else
% Enable trans
set(handles_gui_sub.edit_transparency,'Enable','on','backgroundcolor',[0.9412 0.9412 0.9412]);
set(handles_gui_sub.slider_transparency,'Enable','on');
% Disable contours
set(handles_gui_sub.edit_contour,'Enable','off');
end
if (strcmp(get(handle_pan,'Enable'),'on'))
set(handles_gui_sub.button_pan,'FontWeight','bold');
else
set(handles_gui_sub.button_pan,'FontWeight','normal');
end
if (strcmp(get(handle_zoom,'Enable'),'on'))
set(handles_gui_sub.button_zoom,'FontWeight','bold');
else
set(handles_gui_sub.button_zoom,'FontWeight','normal');
end
end
function update_axes(action,handles_gui_sub)
% Get data - MUST USE HANDLES_GUI_SUB AND TYPE_PLOT_SUB!!!
num_cur = getappdata(handles_gui_sub.figure,'num_cur');
transparency_prelim = getappdata(handles_gui_sub.figure,'transparency_prelim');
contourlines_prelim = getappdata(handles_gui_sub.figure,'contourlines_prelim');
scalebarlength = getappdata(handles_gui_sub.figure,'scalebarlength');
slider_buffer = getappdata(handles_gui_sub.figure,'slider_buffer');
type_plot_sub = getappdata(handles_gui_sub.figure,'type_plot');
text_info = getappdata(handles_gui_sub.figure,'text_info');
val_checkbox_contour = getappdata(handles_gui_sub.figure,'val_checkbox_contour');
val_checkbox_scalebar = getappdata(handles_gui_sub.figure,'val_checkbox_scalebar');
val_checkbox_axes = getappdata(handles_gui_sub.figure,'val_checkbox_axes');
val_checkbox_minmaxmarkers = getappdata(handles_gui_sub.figure,'val_checkbox_minmaxmarkers');
val_popupmenu = getappdata(handles_gui_sub.figure,'val_popupmenu');
handle_preview = getappdata(handles_gui_sub.figure,'handle_preview');
handle_scalebar = getappdata(handles_gui_sub.figure,'handle_scalebar');
handle_axes = getappdata(handles_gui_sub.figure,'handle_axes');
handle_colorbar = getappdata(handles_gui_sub.figure,'handle_colorbar');
handle_point_max = getappdata(handles_gui_sub.figure,'handle_point_max');
handle_point_min = getappdata(handles_gui_sub.figure,'handle_point_min');
if (val_popupmenu == 1)
lore = 'lagrangian';
img_bg = reference;
else
lore = 'eulerian';
img_bg = current(num_cur+1);
end
% Get data
data = get_data(type_plot_sub,lore,num_cur);
plot_data = get_dataplot(type_plot_sub,lore,num_cur);
roi_data = get_roi(type_plot_sub,lore,num_cur);
if (strcmp(action,'set') || strcmp(action,'save'))
% Get reduced img
img_reduced = img_bg.reduce(data_dic.dispinfo.spacing);
% Set Background Image
imshow(img_reduced.get_img(),[img_reduced.min_gs img_reduced.max_gs],'Parent',handles_gui_sub.axes_formatplot);
hold(handles_gui_sub.axes_formatplot,'on');
% Overlay plot - See if it's a contour plot
if (val_checkbox_contour)
% Format plot
[grid_x,grid_y] = meshgrid(1:size(plot_data,2),1:size(plot_data,1));
alphamap_nan = ~roi_data.mask;
plot_data(alphamap_nan) = NaN;
% Form contour plot
[data_contour,handle_preview] = contourf(grid_x,grid_y,plot_data,contourlines_prelim,'Parent',handles_gui_sub.axes_formatplot);
% Overlay image in NaN regions
% This only works properly when opengl is disabled. When opengl
% is enabled, stacking order is determined by projected Z
% value. This is a problem because images and contourf functions
% have z = 0 value, so sometimes the image will not overlay the
% white regions.
handle_trans = imshow(img_reduced.get_img(),[img_reduced.min_gs img_reduced.max_gs],'Parent',handles_gui_sub.axes_formatplot);
set(handle_trans,'AlphaData',imdilate(alphamap_nan,true(3))); % This dilation covers the border
else
% Regular Plot
handle_preview = imshow(plot_data,[],'Parent',handles_gui_sub.axes_formatplot);
end
% Set axes grid off
set(handles_gui_sub.axes_formatplot,'Visible','off');
% Place markers in min/max location
datamax = max(data);
datamin = min(data);
% Max marker
[y_max,x_max] = find(plot_data == datamax,1);
handle_point_max = impoint(handles_gui_sub.axes_formatplot,x_max,y_max);
setColor(handle_point_max,'g');
set(handle_point_max,'UIContextMenu','');
set(handle_point_max,'ButtonDownFcn','');
% Min Marker
[y_min,x_min] = find(plot_data == datamin,1);
handle_point_min = impoint(handles_gui_sub.axes_formatplot,x_min,y_min);
setColor(handle_point_min,'g');
set(handle_point_min,'UIContextMenu','');
set(handle_point_min,'ButtonDownFcn','');
% Set invisible if markers are disabled
if (~val_checkbox_minmaxmarkers)
set(handle_point_max,'Visible','off');
set(handle_point_min,'Visible','off');
end
% Turn hold off
hold(handles_gui_sub.axes_formatplot,'off');
% Set left/right buttons
if (~strcmp(action,'save'))
set(handles_gui_sub.edit_imgnum,'String',num2str(num_cur+1));
if (length(current) == 1)
set(handles_gui_sub.button_right,'Enable','off');
set(handles_gui_sub.button_left,'Enable','off');
set(handles_gui_sub.edit_imgnum,'Enable','off');
elseif (num_cur == 0)
set(handles_gui_sub.button_right,'Enable','on');
set(handles_gui_sub.button_left,'Enable','off');
set(handles_gui_sub.edit_imgnum,'Enable','on');
elseif (num_cur == length(current)-1)
set(handles_gui_sub.button_right,'Enable','off');
set(handles_gui_sub.button_left,'Enable','on');
set(handles_gui_sub.edit_imgnum,'Enable','on');
else
set(handles_gui_sub.button_right,'Enable','on');
set(handles_gui_sub.button_left,'Enable','on');
set(handles_gui_sub.edit_imgnum,'Enable','on');
end
end
% Static Texts:
if (strcmp(action,'set') || (strcmp(action,'save') && getappdata(handles_gui_sub.figure,'includeinfo')))
set(handles_gui_sub.text_ref_name,'String',['Reference Name: ' reference.name(1:min(end,40))]);
set(handles_gui_sub.text_cur_name,'String',['Current Name: ' current(num_cur+1).name(1:min(end,40))]);
set(handles_gui_sub.text_type,'String',['Analysis type: ' data_dic.dispinfo.type]);
if (strcmp(type_plot_sub,'u') || strcmp(type_plot_sub,'v'))
string_dicparams = ['RG-DIC Radius: ' num2str(data_dic.dispinfo.radius) ' | Subset Spacing: ' num2str(data_dic.dispinfo.spacing)];
else
string_dicparams = ['RG-DIC Radius: ' num2str(data_dic.dispinfo.radius) ' | Strain Radius: ' num2str(data_dic.straininfo.radius) ' | Subset Spacing: ' num2str(data_dic.dispinfo.spacing)];
end
set(handles_gui_sub.text_dicparams,'String', string_dicparams);
set(handles_gui_sub.text_itparams,'String', ['Diffnorm Cutoff: ' num2str(data_dic.dispinfo.cutoff_diffnorm) ' | Iteration Cutoff: ' num2str(data_dic.dispinfo.cutoff_iteration) ' | Threads: ' num2str(data_dic.dispinfo.total_threads)]);
if (data_dic.dispinfo.stepanalysis.enabled)
if (strcmp(data_dic.dispinfo.stepanalysis.type,'seed'))
string_stepanalysis = 'Step Analysis: Enabled | Type: Seed Propagation ';
else
string_stepanalysis = ['Step Analysis: Enabled | Type: Leap Frog | Step: ' num2str(data_dic.dispinfo.stepanalysis.step)];
end
else
string_stepanalysis = 'Step Analysis: Disabled';
end
set(handles_gui_sub.text_stepanalysis,'String',string_stepanalysis);
if (data_dic.dispinfo.subsettrunc)
string_subsettrunc = 'RG-DIC Subset Truncation: Enabled';
else
string_subsettrunc = 'RG-DIC Subset Truncation: Disabled';
end
if (strcmp(type_plot_sub,'exx') || strcmp(type_plot_sub,'exy') || strcmp(type_plot_sub,'eyy'))
if (data_dic.straininfo.subsettrunc)
string_subsettrunc = horzcat(string_subsettrunc,' | Strain Subset Truncation: Enabled'); %#ok<AGROW>
else
string_subsettrunc = horzcat(string_subsettrunc,' | Strain Subset Truncation: Disabled'); %#ok<AGROW>
end
end
set(handles_gui_sub.text_subsettrunc,'String',string_subsettrunc);
string_imgcorr = 'Image Correspondences: ';
for i = 0:length(data_dic.dispinfo.imgcorr)-1 % Might be large
string_imgcorr = horzcat(string_imgcorr,['[' num2str(data_dic.dispinfo.imgcorr(i+1).idx_ref) ' ' num2str(data_dic.dispinfo.imgcorr(i+1).idx_cur) '] ']); %#ok<AGROW>
end
set(handles_gui_sub.text_imgcorr,'String',string_imgcorr);
set(handles_gui_sub.text_pixtounits,'String', ['Units/pixels: ' num2str(data_dic.dispinfo.pixtounits) ' ' data_dic.dispinfo.units '/pixels']);
set(handles_gui_sub.text_cutoff_corrcoef,'String', ['Correlation Coefficient Cutoff: ' num2str(data_dic.dispinfo.cutoff_corrcoef(num_cur+1),'%6.4f')]);
set(handles_gui_sub.text_lenscoef,'String',['Radial Lens Distortion Coefficient: ' num2str(data_dic.dispinfo.lenscoef)]);
if (strcmp(type_plot_sub,'u') || strcmp(type_plot_sub,'v'))
set(handles_gui_sub.text_minmedianmax,'String',['Max: ' num2str(slider_buffer(num_cur+1).(lore)(6),'%6.4f') ' ' data_dic.dispinfo.units ' | Median: ' num2str(slider_buffer(num_cur+1).(lore)(4),'%6.4f') ' ' data_dic.dispinfo.units ' | Min: ' num2str(slider_buffer(num_cur+1).(lore)(7),'%6.4f') ' ' data_dic.dispinfo.units]);
elseif (strcmp(type_plot_sub,'exx') || strcmp(type_plot_sub,'exy') || strcmp(type_plot_sub,'eyy'))
set(handles_gui_sub.text_minmedianmax,'String',['Max: ' num2str(slider_buffer(num_cur+1).(lore)(6),'%6.4f') ' | Median: ' num2str(slider_buffer(num_cur+1).(lore)(4),'%6.4f') ' | Min: ' num2str(slider_buffer(num_cur+1).(lore)(7),'%6.4f')]);
end
end
% Set empty text info
text_info = text(0,0,2,'','Parent',handles_gui_sub.axes_formatplot,'HorizontalAlignment','left','VerticalAlignment','top','BackgroundColor',[1 1 1],'EdgeColor',[0.7 0.7 0.7],'tag','text_info','FontSize',8);
% Update panel text if its strain, since it also displays the
% strain tensor name
if (~strcmp(action,'save') && (strcmp(type_plot_sub,'exx') || strcmp(type_plot_sub,'exy') || strcmp(type_plot_sub,'eyy')))
if (strcmp(type_plot_sub,'exx'))
group_title = 'Exx ';
elseif (strcmp(type_plot_sub,'exy'))
group_title = 'Exy ';
elseif (strcmp(type_plot_sub,'eyy'))
group_title = 'Eyy ';
end
if (val_popupmenu == 1)
group_title = [group_title 'Green-Lagrangian'];
else
group_title = [group_title 'Eulerian-Almansi'];
end
% Update title
set(handles_gui_sub.group_formataxes,'Title',group_title)
end
% Set colormap
ncorr_util_colormap(handles_gui_sub.figure);
end
if (strcmp(action,'set') || strcmp(action,'update') || strcmp(action,'save'))
% Get limits
cmax = (slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(1)+slider_buffer(num_cur+1).(lore)(4);
cmin = (slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(2)+slider_buffer(num_cur+1).(lore)(4);
if (abs(cmin-cmax)<1e-4)
cmax = cmax + 1e-5; % add a small increment to ensure they are not the same number
cmin = cmin - 1e-5;
end
% Update Plot
caxis(handles_gui_sub.axes_formatplot,[cmin cmax]);
% Update transparency for regular plot
if (~val_checkbox_contour)
transparency = transparency_prelim;
alphamap_plot = roi_data.mask.*transparency;
set(handle_preview,'AlphaData',alphamap_plot);
end
% Set colorbar
handle_colorbar = colorbar('peer',handles_gui_sub.axes_formatplot);
set(handle_colorbar,'UIContextMenu','');
set(get(handle_colorbar,'child'),'YData',[cmin cmax]);
set(handle_colorbar,'YLim',[cmin cmax]);
set(handle_colorbar,'Units','Pixels');
% Set max/min markers
if (val_checkbox_minmaxmarkers)
set(handle_point_max,'Visible','on');
set(handle_point_min,'Visible','on');
else
set(handle_point_max,'Visible','off');
set(handle_point_min,'Visible','off');
end
% Check for scale bar
if (val_checkbox_scalebar)
% Need to also test if handle is valid, since it is not
% explicitly cleared when switching img_num
if (isempty(handle_scalebar) || ~ishandle(handle_scalebar))
% Scalebar isnt present, so create it
handle_scalebar = form_scalebar(handles_gui_sub);
else
% Scalebar is already present - just update it
% Get display image dimensions
height_img = floor(img_bg.height/(data_dic.dispinfo.spacing+1));
width_img = floor(img_bg.width/(data_dic.dispinfo.spacing+1));
line_scalebar = findobj(handle_scalebar,'tag','line');
width_sb = scalebarlength/(data_dic.dispinfo.pixtounits*(data_dic.dispinfo.spacing+1)); % Convert to pixels
height_sb = 0.015*height_img; % Height is 1.5% of img height
offset_sb_left = 0.05*width_img; % Offset is 5% from left, and 95% from top
offset_sb_top = 0.95*height_img;
set(line_scalebar,'XData',[offset_sb_left offset_sb_left+width_sb offset_sb_left+width_sb offset_sb_left]);
set(line_scalebar,'YData',[offset_sb_top offset_sb_top offset_sb_top+height_sb offset_sb_top+height_sb]);
% Update bg
bg1 = findobj(handle_scalebar,'tag','bg1');
bg2 = findobj(handle_scalebar,'tag','bg2');
width_bg = (width_sb/width_img+0.06)*width_img;
height_bg = 0.12*height_img; % Height is a 12% of height
offset_bg_left = 0.02*width_img; % Offset is 2% from left, and 86% from top
offset_bg_top = 0.86*height_img;
set(bg1,'XData',[offset_bg_left offset_bg_left+width_bg offset_bg_left+width_bg offset_sb_left+width_sb offset_sb_left+width_sb offset_sb_left offset_sb_left offset_bg_left]);
set(bg1,'YData',[offset_bg_top offset_bg_top offset_bg_top+height_bg offset_sb_top+height_sb offset_sb_top offset_sb_top offset_sb_top+height_sb offset_bg_top+height_bg]);
set(bg2,'XData',[offset_sb_left offset_sb_left+width_sb offset_bg_left+width_bg offset_bg_left]);
set(bg2,'YData',[offset_sb_top+height_sb offset_sb_top+height_sb offset_bg_top+height_bg offset_bg_top+height_bg]);
% Update text
text_scalebar = findobj(handle_scalebar,'tag','text_scalebar');
pos_x_text = offset_sb_left+width_sb/2;
pos_y_text = .905*height_img;
set(text_scalebar,'String',[num2str(scalebarlength) ' ' data_dic.dispinfo.units],'Position',[pos_x_text pos_y_text 1]);
end
else
% See if scalebar exists
if (~isempty(handle_scalebar) && ishandle(handle_scalebar))
delete(handle_scalebar);
end
handle_scalebar = [];
if (~strcmp(action,'save'))
% Disable the edit box for editing scalebar length
set(handles_gui_sub.edit_scalebarlength,'Enable','off');
end
end
% Check for the axes
if (val_checkbox_axes)
if (isempty(handle_axes) || ~ishandle(handle_axes))
% Create plot axes
handle_axes = form_plotaxes(handles_gui_sub);
end
else
if (~isempty(handle_axes) && ishandle(handle_axes))
delete(handle_axes);
end
handle_axes = [];
end
end
% Set data
setappdata(handles_gui_sub.figure,'handle_point_max', handle_point_max);
setappdata(handles_gui_sub.figure,'handle_point_min', handle_point_min);
setappdata(handles_gui_sub.figure,'handle_preview',handle_preview);
setappdata(handles_gui_sub.figure,'handle_scalebar',handle_scalebar);
setappdata(handles_gui_sub.figure,'handle_axes',handle_axes);
setappdata(handles_gui_sub.figure,'handle_colorbar',handle_colorbar);
setappdata(handles_gui_sub.figure,'text_info',text_info);
end
function handle_scalebar = form_scalebar(handles_gui_sub)
% This function creates the scalebar
% Get data
num_cur = getappdata(handles_gui_sub.figure,'num_cur');
scalebarlength = getappdata(handles_gui_sub.figure,'scalebarlength');
val_popupmenu = getappdata(handles_gui_sub.figure,'val_popupmenu');
if (val_popupmenu == 1)
img_bg = reference;
else
img_bg = current(num_cur+1);
end
% Get display image dimensions (these are reduced)
height_img = floor(img_bg.height/(data_dic.dispinfo.spacing+1));
width_img = floor(img_bg.width/(data_dic.dispinfo.spacing+1));
% Form hggroup
handle_scalebar = hggroup('parent',handles_gui_sub.axes_formatplot,'tag','handle_scalebar');
% Form dimensions of scalebar - most importantly, width must be
% converted back to pixels (in reduced coordinates). It must also be
% consistent among plots and based on the scalebarlength parameter.
% Any other parameter, like the scalebar height or offsets, can
% depend on this specific image size for display purposes.
width_sb = scalebarlength/(data_dic.dispinfo.pixtounits*(data_dic.dispinfo.spacing+1));
height_sb = 0.015*height_img; % Height is a 1.5% of im height
offset_sb_left = 0.05*width_img; % Offset is 5% from left, and 95% from top
offset_sb_top = 0.95*height_img;
% BG - Form BG with two patches with a hole for the scale bar.
% For some reason alpha is applied to all overlapping patches
width_bg = (width_sb/width_img+0.06)*width_img;
height_bg = 0.12*height_img; % Height is a 12% of height
offset_bg_left = 0.02*width_img; % Offset is 2% from left, and 86% from top
offset_bg_top = 0.86*height_img;
patch([offset_bg_left offset_bg_left+width_bg offset_bg_left+width_bg offset_sb_left+width_sb offset_sb_left+width_sb offset_sb_left offset_sb_left offset_bg_left], ...
[offset_bg_top offset_bg_top offset_bg_top+height_bg offset_sb_top+height_sb offset_sb_top offset_sb_top offset_sb_top+height_sb offset_bg_top+height_bg], ...
[1 1 1 1 1 1 1 1], ...
'k','parent',handle_scalebar,'linestyle','none','FaceAlpha',0.5,'tag','bg1');
patch([offset_sb_left offset_sb_left+width_sb offset_bg_left+width_bg offset_bg_left], ...
[offset_sb_top+height_sb offset_sb_top+height_sb offset_bg_top+height_bg offset_bg_top+height_bg], ...
[1 1 1 1], ...
'k','parent',handle_scalebar,'linestyle','none','FaceAlpha',0.5,'tag','bg2');
% Line - The actual scale bar
patch([offset_sb_left offset_sb_left+width_sb offset_sb_left+width_sb offset_sb_left], ...
[offset_sb_top offset_sb_top offset_sb_top+height_sb offset_sb_top+height_sb], ...
[1 1 1 1], ...
'w','parent',handle_scalebar,'FaceAlpha',1,'tag','line');
% Text
pos_x_text = offset_sb_left+width_sb/2;
pos_y_text = .905*height_img;
pos_img = get(handles_gui_sub.axes_formatplot,'Position');
size_text = max(0.5*min(0.5*pos_img(4),0.14*pos_img(3)),8);
text(pos_x_text,pos_y_text,1,[num2str(scalebarlength) ' ' data_dic.dispinfo.units],'parent',handle_scalebar,'color','w', ...
'HorizontalAlignment','center','VerticalAlignment','middle','FontWeight','bold','FontSize',size_text,'tag','text_scalebar');
end
function handle_axes = form_plotaxes(handles_gui_sub)
% This function forms the axes seen at the top left of the plot
% Get data
num_cur = getappdata(handles_gui_sub.figure,'num_cur');
val_popupmenu = getappdata(handles_gui_sub.figure,'val_popupmenu');
if (val_popupmenu == 1)
img_bg = reference;
else
img_bg = current(num_cur+1);
end
% Do this WRT the display image
height_img = floor(img_bg.height/(data_dic.dispinfo.spacing+1));
width_img = floor(img_bg.width/(data_dic.dispinfo.spacing+1));
% Form hggroup
handle_axes = hggroup('parent',handles_gui_sub.axes_formatplot,'tag','handle_axes');
length_axes = 0.15*max(width_img,height_img);
width_axes = 0.012*max(width_img,height_img);
arrowwidth_axes = 1.0*width_axes;
width_bg = width_axes*0.4;
% BG
patch([0 width_axes+width_bg width_axes+width_bg width_axes+arrowwidth_axes+2*width_bg 0],[0 0 length_axes-width_bg length_axes-width_bg length_axes+width_axes+arrowwidth_axes+width_bg],[1 1 1 1 1], ...
'w','parent',handle_axes,'linestyle','none','tag','bg1');
patch([0 length_axes+width_axes+arrowwidth_axes+width_bg length_axes-width_bg length_axes-width_bg 0],[0 0 width_axes+arrowwidth_axes+2*width_bg width_axes+width_bg width_axes+width_bg],[1 1 1 1 1], ...
'w','parent',handle_axes,'linestyle','none','tag','bg2');
% Lines
patch([0 width_axes width_axes width_axes+arrowwidth_axes 0],[0 0 length_axes length_axes length_axes+width_axes+arrowwidth_axes],[1 1 1 1 1], ...
'k','parent',handle_axes,'linestyle','none','tag','arrow1');
patch([0 length_axes+width_axes+arrowwidth_axes length_axes length_axes 0],[0 0 width_axes+arrowwidth_axes width_axes width_axes],[1 1 1 1 1], ...
'k','parent',handle_axes,'linestyle','none','tag','arrow2');
% Text BG
spacing_textbg = 2.5*width_axes;
offset_text = 3*width_axes;
pos_text = length_axes+width_axes+arrowwidth_axes+width_bg+offset_text;
pos_img = get(handles_gui_sub.axes_formatplot,'Position');
size_text = max(0.5*min(0.5*pos_img(4),0.14*pos_img(3)),8);
patch([offset_text-spacing_textbg offset_text+spacing_textbg offset_text+spacing_textbg offset_text-spacing_textbg],[pos_text-spacing_textbg pos_text-spacing_textbg pos_text+spacing_textbg pos_text+spacing_textbg],[1 1 1 1], ...
'k','parent',handle_axes,'linestyle','none','FaceAlpha',0.5,'tag','text_bg1');
patch([pos_text-spacing_textbg pos_text+spacing_textbg pos_text+spacing_textbg pos_text-spacing_textbg],[offset_text-spacing_textbg offset_text-spacing_textbg offset_text+spacing_textbg offset_text+spacing_textbg],[1 1 1 1], ...
'k','parent',handle_axes,'linestyle','none','FaceAlpha',0.5,'tag','text_bg2');
% Text
text(offset_text,pos_text,1,'Y','parent',handle_axes,'color','w', ...
'HorizontalAlignment','center','VerticalAlignment','middle','FontWeight','bold','FontSize',size_text,'tag','text_x');
text(pos_text,offset_text,1,'X','parent',handle_axes,'color','w', ...
'HorizontalAlignment','center','VerticalAlignment','middle','FontWeight','bold','FontSize',size_text,'tag','text_y');
end
%---------------------------------------------------------------------%
%---------------------------------------------------------------------%
%---------------------------------------------------------------------%
function callback_slider_transparency(hObject,eventdata) %#ok<INUSD>
% Get data
transparency_prelim = get(handles_gui.slider_transparency,'value');
% Set data
setappdata(handles_gui.figure,'transparency_prelim',transparency_prelim);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_slider_upperbound(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Update data
slider_buffer(num_cur+1).(lore)(1) = get(handles_gui.slider_upperbound,'value');
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_slider_lowerbound(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Update data
slider_buffer(num_cur+1).(lore)(2) = get(handles_gui.slider_lowerbound,'value');
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_checkbox_contour(hObject,eventdata) %#ok<INUSD>
% Get data
val_checkbox_contour = get(handles_gui.checkbox_contour,'Value');
% Set data
setappdata(handles_gui.figure,'val_checkbox_contour',val_checkbox_contour);
% Update
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_checkbox_minmaxmarkers(hObject,eventdata) %#ok<INUSD>
% Get data
val_checkbox_minmaxmarkers = get(handles_gui.checkbox_minmaxmarkers,'Value');
% Set data
setappdata(handles_gui.figure,'val_checkbox_minmaxmarkers',val_checkbox_minmaxmarkers);
% Update
update_axes('update',handles_gui);
end
function callback_edit_transparency(hObject,eventdata) %#ok<INUSD>
% Get data
transparency_prelim = getappdata(handles_gui.figure,'transparency_prelim');
% Get Value
transparency_buffer = str2double(get(handles_gui.edit_transparency,'string'));
if (ncorr_util_isrealbb(transparency_buffer,0,1,'Transparency') == out.success)
transparency_prelim = transparency_buffer;
end
% Set data
setappdata(handles_gui.figure,'transparency_prelim',transparency_prelim);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_lowerbound(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
min_lowerbound = getappdata(handles_gui.figure,'min_lowerbound');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Get Value
lowerbound_buffer = str2double(get(handles_gui.edit_lowerbound,'string'));
if (ncorr_util_isrealbb(lowerbound_buffer,min_lowerbound,slider_buffer(num_cur+1).(lore)(4),'Lowerbound') == out.success)
% Make sure denominator is not close to zero
if (abs(slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4)) <= 1e-10)
slider_buffer(num_cur+1).(lore)(2) = 1;
else
slider_buffer(num_cur+1).(lore)(2) = (lowerbound_buffer-slider_buffer(num_cur+1).(lore)(4))/(slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4));
end
end
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_upperbound(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
max_upperbound = getappdata(handles_gui.figure,'max_upperbound');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Get Value
upperbound_buffer = str2double(get(handles_gui.edit_upperbound,'string'));
if (ncorr_util_isrealbb(upperbound_buffer,slider_buffer(num_cur+1).(lore)(4),max_upperbound,'Upperbound') == out.success)
% Make sure denominator is not close to zero
if (abs(slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4)) <= 1e-10)
slider_buffer(num_cur+1).(lore)(1) = 1;
else
slider_buffer(num_cur+1).(lore)(1) = (upperbound_buffer-slider_buffer(num_cur+1).(lore)(4))/(slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4));
end
end
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_contour(hObject,eventdata) %#ok<INUSD>
% Get data
contourlines_prelim = getappdata(handles_gui.figure,'contourlines_prelim');
max_contourlines = getappdata(handles_gui.figure,'max_contourlines');
% Get Value
contourlines_buffer = str2double(get(handles_gui.edit_contour,'string'));
if (ncorr_util_isintbb(contourlines_buffer,1,max_contourlines,'Number of contour lines') == out.success)
contourlines_prelim = contourlines_buffer;
end
% Set data
setappdata(handles_gui.figure,'contourlines_prelim',contourlines_prelim);
% Update
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_button_applytoall(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Get bounds
upperbound_buffer = (slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(1)+slider_buffer(num_cur+1).(lore)(4);
lowerbound_buffer = (slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(2)+slider_buffer(num_cur+1).(lore)(4);
% Find cutoff for bounds.
cutoff_buffer = vertcat(slider_buffer.(lore));
cutoff_lowerbound = min(cutoff_buffer(:,4));
cutoff_upperbound = max(cutoff_buffer(:,4));
if (upperbound_buffer > cutoff_upperbound && lowerbound_buffer < cutoff_lowerbound)
% Set bounds
for i = 0:length(current)-1
% Set lowerbound
if (abs(slider_buffer(i+1).(lore)(5)-slider_buffer(i+1).(lore)(4)) <= 1e-10)
slider_buffer(i+1).(lore)(2) = 1;
else
slider_buffer(i+1).(lore)(2) = (lowerbound_buffer-slider_buffer(i+1).(lore)(4))/(slider_buffer(i+1).(lore)(5)-slider_buffer(i+1).(lore)(4));
end
% Set upperbound
if (abs(slider_buffer(i+1).(lore)(3)-slider_buffer(i+1).(lore)(4)) <= 1e-10)
slider_buffer(i+1).(lore)(1) = 1;
else
slider_buffer(i+1).(lore)(1) = (upperbound_buffer-slider_buffer(i+1).(lore)(4))/(slider_buffer(i+1).(lore)(3)-slider_buffer(i+1).(lore)(4));
end
end
else
h_error = errordlg(['Lowerbound must be a lower than ' num2str(cutoff_lowerbound) ' and upperbound must be greater than ' num2str(cutoff_upperbound) '.'],'Error','modal');
uiwait(h_error);
end
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_button_resetdefaults(hObject,eventdata) %#ok<INUSD>
% Get data
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
% Set slider buffer
for i = 0:length(current)-1
% Set parameters
data_ref = get_data(type_plot,'lagrangian',i);
slider_buffer(i+1).lagrangian(1) = 0.5; % Initialize to half
slider_buffer(i+1).lagrangian(2) = 0.5; % Initialize to half
slider_buffer(i+1).lagrangian(3:7) = get_sliderparams(data_ref);
data_cur = get_data(type_plot,'eulerian',i);
slider_buffer(i+1).eulerian(1) = 0.5; % Initialize to half
slider_buffer(i+1).eulerian(2) = 0.5; % Initialize to half
slider_buffer(i+1).eulerian(3:7) = get_sliderparams(data_cur);
end
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_resizefunction(hObject,eventdata) %#ok<INUSD>
% This function constrains how the figure resizes its axes, buttons, etc
% on resize. Be careful here because resize function will interrupt
% callbacks even if 'interruptible' is set to 'off'
% Get data
handle_scalebar = getappdata(handles_gui.figure,'handle_scalebar');
handle_axes = getappdata(handles_gui.figure,'handle_axes');
pos_fig = get(handles_gui.figure,'Position');
val_checkbox_scalebar = getappdata(handles_gui.figure,'val_checkbox_scalebar');
val_checkbox_axes = getappdata(handles_gui.figure,'val_checkbox_axes');
% Set offsets
offset_group_menu_y = 21.1;
offset_group_view_y = 26.5;
offset_group_scalebar_y = 33.8;
offset_group_axes_y = 38.7;
offset_group_zoompan_y = 43.7;
offset_axes_x = 1.35;
offset_axes_y = 41.1;
offset_img_x = 24.4;
offset_img_y = 80.8;
offset_left_y = 66;
offset_right_y = 51;
offset_edit_y = 59;
% Update menu panel
pos_group_menu = get(handles_gui.group_menu,'Position');
pos_group_menu(2) = pos_fig(4)-offset_group_menu_y;
set(handles_gui.group_menu,'Position',pos_group_menu);
% Update lore panel
pos_group_view = get(handles_gui.group_viewoptions,'Position');
pos_group_view(2) = pos_fig(4)-offset_group_view_y;
set(handles_gui.group_viewoptions,'Position',pos_group_view);
% Update scalebar panel
pos_group_scalebar = get(handles_gui.group_scalebar,'Position');
pos_group_scalebar(2) = pos_fig(4)-offset_group_scalebar_y;
set(handles_gui.group_scalebar,'Position',pos_group_scalebar);
% Update axes panel
pos_group_axes = get(handles_gui.group_axes,'Position');
pos_group_axes(2) = pos_fig(4)-offset_group_axes_y;
set(handles_gui.group_axes,'Position',pos_group_axes);
% Update zoom/pan panel
pos_group_zoompan = get(handles_gui.group_zoompan,'Position');
pos_group_zoompan(2) = pos_fig(4)-offset_group_zoompan_y;
set(handles_gui.group_zoompan,'Position',pos_group_zoompan);
% Update axes panel - make sure it has positive width and height
if (pos_fig(3)-offset_axes_y > 0 && ...
pos_fig(4)-offset_axes_x > 0)
pos_axes = get(handles_gui.group_formataxes,'Position');
pos_axes(3) = pos_fig(3)-offset_axes_y;
pos_axes(4) = pos_fig(4)-offset_axes_x;
set(handles_gui.group_formataxes,'Position',pos_axes);
end
% Update axes - make sure it has positive width and height
if (pos_fig(3)-offset_img_y > 0 && ...
pos_fig(4)-offset_img_x > 0)
pos_img = get(handles_gui.axes_formatplot,'Position');
pos_img(3) = pos_fig(3)-offset_img_y;
pos_img(4) = pos_fig(4)-offset_img_x;
set(handles_gui.axes_formatplot,'Position',pos_img);
end
% Update buttons
if (pos_fig(3)-offset_left_y > 0)
pos_left = get(handles_gui.button_left,'Position');
pos_left(1) = pos_fig(3)-offset_left_y;
set(handles_gui.button_left,'Position',pos_left);
end
if (pos_fig(3)-offset_right_y > 0)
pos_right = get(handles_gui.button_right,'Position');
pos_right(1) = pos_fig(3)-offset_right_y;
set(handles_gui.button_right,'Position',pos_right);
end
% Update imgnum edit
if (pos_fig(3)-offset_edit_y > 0)
pos_right = get(handles_gui.edit_imgnum,'Position');
pos_right(1) = pos_fig(3)-offset_edit_y;
set(handles_gui.edit_imgnum,'Position',pos_right);
end
% Update handle_scalebar text if it it's enabled.
% Only text is updated because text size is constant during resize;
% patches will resize automatically with handle_axes.
% Note that resize function will interrupt callbacks, so check
% explicitly that the scalebar exists first before resizing it (i.e.
% its possible to interrupt the checkbox callback for the scalebar
% midway).
if (val_checkbox_scalebar && ...
~isempty(handle_scalebar) && ishandle(handle_scalebar))
text_scalebar = findobj(handle_scalebar,'tag','text_scalebar');
pos_img = get(handles_gui.axes_formatplot,'Position');
size_text = max(0.5*min(0.5*pos_img(4),0.14*pos_img(3)),8);
set(text_scalebar,'FontSize',size_text);
end
% Update handle_axes text if it it's enabled.
% Only text is updated because the size is constant during resize;
% patches will resize automatically with handle_axes.
% Note that resize function will interrupt callbacks, so check
% explicitly that the axes exists first before resizing it (i.e.
% its possible to interrupt the checkbox callback for the axes
% midway).
if (val_checkbox_axes && ...
~isempty(handle_axes) && ishandle(handle_axes))
text_x = findobj(handle_axes,'tag','text_x');
text_y = findobj(handle_axes,'tag','text_y');
pos_img = get(handles_gui.axes_formatplot,'Position');
size_text = max(0.5*min(0.5*pos_img(4),0.14*pos_img(3)),8);
set(text_x,'FontSize',size_text);
set(text_y,'FontSize',size_text);
end
end
function callback_moveplot(hObject,eventdata) %#ok<INUSD>
% This function tells the axes what to do if the mouse cursor hovers
% over the plot axes
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
text_info = getappdata(handles_gui.figure,'text_info');
handle_colorbar = getappdata(handles_gui.figure,'handle_colorbar');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
handle_zoom = getappdata(handles_gui.figure,'handle_zoom');
handle_pan = getappdata(handles_gui.figure,'handle_pan');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Get data
plot_data = get_dataplot(type_plot,lore,num_cur);
roi_data = get_roi(type_plot,lore,num_cur);
% Test to see if mouse position is within ROI - uses 1 based
% indexing. Also round it first.
pos_mouse_axes = round(get(handles_gui.axes_formatplot,'CurrentPoint'));
if (pos_mouse_axes(1) >= 1 && pos_mouse_axes(3) >= 1 && pos_mouse_axes(1) <= size(roi_data.mask,2) && pos_mouse_axes(3) <= size(roi_data.mask,1))
if (roi_data.mask(pos_mouse_axes(3),pos_mouse_axes(1)))
% Get Plot info - note that strain is dimensionless
if (strcmp(type_plot,'u'))
text_display = 'U-disp: ';
units = data_dic.dispinfo.units;
elseif (strcmp(type_plot,'v'))
text_display = 'V-disp: ';
units = data_dic.dispinfo.units;
elseif (strcmp(type_plot,'exx'))
text_display = 'Exx-strain: ';
units = '';
elseif (strcmp(type_plot,'exy'))
text_display = 'Exy-strain: ';
units = '';
elseif (strcmp(type_plot,'eyy'))
text_display = 'Eyy-strain: ';
units = '';
end
% Display text
set(text_info,'String',{['x-pos: ' num2str(pos_mouse_axes(1))],['y-pos: ' num2str(pos_mouse_axes(3))],[text_display num2str(plot_data(pos_mouse_axes(3),pos_mouse_axes(1))) ' ' units]}, ...
'Position',[pos_mouse_axes(1) pos_mouse_axes(3) 2],'HorizontalAlignment','left','VerticalAlignment','top');
% If zoom and pan arent being used, then use a cross for the
% cursor
if (strcmp(get(handle_zoom,'Enable'),'off') && strcmp(get(handle_pan,'Enable'),'off'))
set(handles_gui.figure,'Pointer','cross');
end
% Check if text overlaps colorbar or bottom of the axes; if so,
% flip it so the text shows properly
% Set all coordinates to pixels
set(text_info,'units','pixels');
set(handle_colorbar,'units','pixels');
set(handles_gui.group_formataxes,'units','pixels');
set(handles_gui.figure,'units','pixels');
% Get positions
pos_text = get(text_info,'extent');
pos_colorbar = get(handle_colorbar,'Position');
pos_group = get(handles_gui.group_formataxes,'position');
pos_cursor = get(handles_gui.figure,'CurrentPoint');
if (pos_cursor(1)+pos_text(3) > pos_group(1)+pos_colorbar(1) && pos_text(2) < 0)
set(text_info,'HorizontalAlignment','right','VerticalAlignment','bottom');
elseif (pos_cursor(1)+pos_text(3) > pos_group(1)+pos_colorbar(1))
set(text_info,'HorizontalAlignment','right');
elseif (pos_text(2) < 0) % Hangs below bottom
set(text_info,'VerticalAlignment','bottom');
end
% Convert back to original coordinates
set(text_info,'units','data');
set(handle_colorbar,'units','normalized');
set(handles_gui.group_formataxes,'units','characters');
set(handles_gui.figure,'units','characters');
else
% Clear text and set cursor back to arrow if zoom and pan
% aren't enabled
set(text_info,'String','');
if (strcmp(get(handle_zoom,'Enable'),'off') && strcmp(get(handle_pan,'Enable'),'off'))
set(handles_gui.figure,'Pointer','arrow');
end
end
else
% Clear text since cursor is not on top of axes
set(text_info,'String','');
set(handles_gui.figure,'Pointer','arrow');
end
end
function [data] = get_data(type_plot_sub,lore,num_cur)
% This function returns displacement/strain data in vector from the data_dic structure
if (strcmp(lore,'lagrangian'))
rorc = 'ref';
else
rorc = 'cur';
end
if (strcmp(type_plot_sub,'u'))
% U:
data = data_dic.displacements(num_cur+1).(['plot_u_' rorc '_formatted'])(data_dic.displacements(num_cur+1).(['roi_' rorc '_formatted']).mask);
elseif (strcmp(type_plot_sub,'v'))
% V:
data = data_dic.displacements(num_cur+1).(['plot_v_' rorc '_formatted'])(data_dic.displacements(num_cur+1).(['roi_' rorc '_formatted']).mask);
elseif (strcmp(type_plot_sub,'exx'))
% Exx:
data = data_dic.strains(num_cur+1).(['plot_exx_' rorc '_formatted'])(data_dic.strains(num_cur+1).(['roi_' rorc '_formatted']).mask);
elseif (strcmp(type_plot_sub,'exy'))
% Exy:
data = data_dic.strains(num_cur+1).(['plot_exy_' rorc '_formatted'])(data_dic.strains(num_cur+1).(['roi_' rorc '_formatted']).mask);
elseif (strcmp(type_plot_sub,'eyy'))
% Eyy:
data = data_dic.strains(num_cur+1).(['plot_eyy_' rorc '_formatted'])(data_dic.strains(num_cur+1).(['roi_' rorc '_formatted']).mask);
end
end
function [plot_data] = get_dataplot(type_plot_sub,lore,num_cur)
% This function returns plot_data from the data_dic structure
if (strcmp(lore,'lagrangian'))
rorc = 'ref';
else
rorc = 'cur';
end
if (strcmp(type_plot_sub,'u'))
% U:
plot_data = data_dic.displacements(num_cur+1).(['plot_u_' rorc '_formatted']);
elseif (strcmp(type_plot_sub,'v'))
% V:
plot_data = data_dic.displacements(num_cur+1).(['plot_v_' rorc '_formatted']);
elseif (strcmp(type_plot_sub,'exx'))
% Exx:
plot_data = data_dic.strains(num_cur+1).(['plot_exx_' rorc '_formatted']);
elseif (strcmp(type_plot_sub,'exy'))
% Exy:
plot_data = data_dic.strains(num_cur+1).(['plot_exy_' rorc '_formatted']);
elseif (strcmp(type_plot_sub,'eyy'))
% Eyy:
plot_data = data_dic.strains(num_cur+1).(['plot_eyy_' rorc '_formatted']);
end
end
function [roi_data] = get_roi(type_plot_sub,lore,num_cur)
% This function returns the ROI from the data_dic structure
if (strcmp(lore,'lagrangian'))
rorc = 'ref';
else
rorc = 'cur';
end
if (strcmp(type_plot_sub,'u') || strcmp(type_plot_sub,'v'))
% Displacement
roi_data = data_dic.displacements(num_cur+1).(['roi_' rorc '_formatted']);
else
% Strains
roi_data = data_dic.strains(num_cur+1).(['roi_' rorc '_formatted']);
end
end
function sliderparams = get_sliderparams(data)
% Returns slider params based on data input
param_upperbound = prctile(data,99);
param_median = prctile(data,50);
param_lowerbound = prctile(data,1);
sliderparams = [param_upperbound+(param_upperbound-param_median) ...
param_median ...
param_lowerbound-(param_median-param_lowerbound) ...
max(data) ...
min(data)];
end
function handles_gui_savefig = form_savefig(num_cur,includeinfo,params_init)
% Get data - num_cur is specified
transparency_prelim = getappdata(handles_gui.figure,'transparency_prelim');
contourlines_prelim = getappdata(handles_gui.figure,'contourlines_prelim');
scalebarlength = getappdata(handles_gui.figure,'scalebarlength');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
val_checkbox_contour = getappdata(handles_gui.figure,'val_checkbox_contour');
val_checkbox_scalebar = getappdata(handles_gui.figure,'val_checkbox_scalebar');
val_checkbox_axes = getappdata(handles_gui.figure,'val_checkbox_axes');
val_checkbox_minmaxmarkers = getappdata(handles_gui.figure,'val_checkbox_minmaxmarkers');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
handle_point_max = getappdata(handles_gui.figure,'handle_point_max');
handle_point_min = getappdata(handles_gui.figure,'handle_point_min');
if (val_popupmenu == 1)
img_bg = reference;
else
img_bg = current(num_cur+1);
end
% Form figure
handles_gui_savefig.figure = figure( ...
'Units','pixels', ...
'Name', 'Save Preview', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color','white', ...
'handlevisibility','off', ...
'DockControls','off', ...
'Visible','off', ...
'IntegerHandle','off', ...
'Interruptible','off', ...
'WindowStyle','modal');
% Create axes
handles_gui_savefig.axes_formatplot = axes('Parent',handles_gui_savefig.figure,'Units','pixels');
% If the user wants to include info
if (includeinfo)
% Set Info texts
uicontrol( ...
'Parent', handles_gui_savefig.figure, ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 18.5 100 1.3], ...
'String', ['Type: ' type_plot '-plot'], ...
'HorizontalAlignment', 'left', ...
'BackgroundColor','white', ...
'Interruptible','off');
% Now get info text which is below the plot
handles_infotext = set_infotext(handles_gui_savefig.figure,'white');
fields_infotext = fieldnames(handles_infotext);
for i = 0:length(fields_infotext)-1
handles_gui_savefig.(fields_infotext{i+1}) = handles_infotext.(fields_infotext{i+1});
end
% Set data height
height_data = 255;
else
height_data = 0;
end
% Transfer data, except for some handles, so that update_axes can set
% the plot
setappdata(handles_gui_savefig.figure,'num_cur',num_cur);
setappdata(handles_gui_savefig.figure,'transparency_prelim',transparency_prelim);
setappdata(handles_gui_savefig.figure,'contourlines_prelim',contourlines_prelim);
setappdata(handles_gui_savefig.figure,'scalebarlength',scalebarlength);
setappdata(handles_gui_savefig.figure,'slider_buffer',slider_buffer);
setappdata(handles_gui_savefig.figure,'type_plot',type_plot);
setappdata(handles_gui_savefig.figure,'val_checkbox_contour',val_checkbox_contour);
setappdata(handles_gui_savefig.figure,'val_checkbox_scalebar',val_checkbox_scalebar);
setappdata(handles_gui_savefig.figure,'val_checkbox_axes',val_checkbox_axes);
setappdata(handles_gui_savefig.figure,'val_checkbox_minmaxmarkers',val_checkbox_minmaxmarkers);
setappdata(handles_gui_savefig.figure,'val_popupmenu',val_popupmenu);
setappdata(handles_gui_savefig.figure,'handle_preview',[]);
setappdata(handles_gui_savefig.figure,'handle_scalebar',[]);
setappdata(handles_gui_savefig.figure,'handle_axes',[]);
setappdata(handles_gui_savefig.figure,'handle_point_max',handle_point_max);
setappdata(handles_gui_savefig.figure,'handle_point_min',handle_point_min);
% Additional fields
setappdata(handles_gui_savefig.figure,'includeinfo',includeinfo);
% Set plot
update_axes('save',handles_gui_savefig);
% Set default size
if (isempty(params_init))
width_img = floor(img_bg.width/(data_dic.dispinfo.spacing+1));
height_img = floor(img_bg.height/(data_dic.dispinfo.spacing+1));
else
width_img = params_init(1);
height_img = params_init(2);
end
border = 30;
width_cb = 20;
spacing_save_fig = 100;
spacing_width_img = 4*border+width_cb;
spacing_height_img = 2*border+height_data;
% Set data in savefig - these are parameters which are modified by
% gui_savesize
setappdata(handles_gui_savefig.figure,'height_data',height_data);
setappdata(handles_gui_savefig.figure,'width_img',width_img);
setappdata(handles_gui_savefig.figure,'height_img',height_img);
setappdata(handles_gui_savefig.figure,'border',border);
setappdata(handles_gui_savefig.figure,'width_cb',width_cb);
setappdata(handles_gui_savefig.figure,'spacing_save_fig',spacing_save_fig);
setappdata(handles_gui_savefig.figure,'spacing_width_img',spacing_width_img);
setappdata(handles_gui_savefig.figure,'spacing_height_img',spacing_height_img);
% Update savefig
update_savefig(handles_gui_savefig);
% Set plot visible
set(handles_gui_savefig.figure,'Visible','on');
end
function handles_gui = init_gui()
handles_gui.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', ncorr_util_figpos(pos_parent,[44.5 150]), ...
'Name', 'Data Plot', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'IntegerHandle','off', ...
'Interruptible','off', ...
'Visible','off', ...
'CloseRequestFcn','');
% Top Menu
handles_gui.topmenu_file = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_file', ...
'Label', 'File', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_save = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_save', ...
'Label', 'Save Image', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_save_withoutinfo = uimenu( ...
'Parent', handles_gui.topmenu_save, ...
'Tag', 'topmenu_save_withoutinfo', ...
'Label', 'Save Image Without Info', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata)callback_topmenu_save(hObject,eventdata,false),handles_gui.figure), ...
'Interruptible','off');
handles_gui.topmenu_save_withinfo = uimenu( ...
'Parent', handles_gui.topmenu_save, ...
'Tag', 'topmenu_save_withinfo', ...
'Label', 'Save Image With Info', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata)callback_topmenu_save(hObject,eventdata,true),handles_gui.figure), ...
'Interruptible','off');
handles_gui.topmenu_savegif = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_savegif', ...
'Label', 'Save GIF', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata)callback_topmenu_savegif (hObject,eventdata),handles_gui.figure), ...
'Interruptible','off');
% Panels
handles_gui.group_menu = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_menu', ...
'Units', 'characters', ...
'Position', [2 23.4 35.0 20.6], ...
'Title', 'Local Plot Options', ...
'Interruptible','off');
handles_gui.group_viewoptions = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_viewoptions', ...
'Units', 'characters', ...
'Position', [2 18 35.0 4.8], ...
'Title', 'View Options', ...
'Interruptible','off');
handles_gui.group_scalebar = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_scalebar', ...
'Units', 'characters', ...
'Position', [2 10.8 35.0 6.5], ...
'Title', 'Scalebar Options', ...
'Interruptible','off');
handles_gui.group_axes = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_axes', ...
'Units', 'characters', ...
'Position', [2 5.8 35.0 4.4], ...
'Title', 'Axes Options', ...
'Interruptible','off');
handles_gui.group_zoompan = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_zoompan', ...
'Units', 'characters', ...
'Position', [2 0.8 35 4.5], ...
'Title', 'Zoom/Pan', ...
'Interruptible','off');
if (strcmp(type_plot,'u'))
group_title = 'U-displacements';
elseif (strcmp(type_plot,'v'))
group_title = 'V-displacements';
elseif (strcmp(type_plot,'exx'))
group_title = 'Exx-strain';
elseif (strcmp(type_plot,'exy'))
group_title = 'Exy-strain';
elseif (strcmp(type_plot,'eyy'))
group_title = 'Eyy-strain';
end
handles_gui.group_formataxes = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_formataxes', ...
'Units', 'characters', ...
'Position', [39.0 0.8 109 43.2], ...
'Title', group_title, ...
'Interruptible','off');
% Axes
handles_gui.axes_formatplot = axes( ...
'Parent', handles_gui.group_formataxes, ...
'Tag', 'axes_formatplot', ...
'Units', 'characters', ...
'Position', [12.4 19.0 86.2 20], ...
'Interruptible','off');
% Drop-down Menu
handles_gui.popupmenu = uicontrol( ...
'Parent', handles_gui.group_viewoptions, ...
'Tag', 'popupmenu', ...
'Style', 'popupmenu', ...
'Units', 'characters', ...
'Position', [2.4 1.4 29.1 1.3], ...
'BackgroundColor', [1 1 1], ...
'String', {'Lagrangian','Eulerian'}, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_popupmenu,handles_gui.figure), ...
'Interruptible','off');
% Static Texts
handles_gui.text_transparency = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'text_transparency', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.5 13.5 16 1.3], ...
'HorizontalAlignment', 'left', ...
'String', 'Transparency:', ...
'Interruptible','off');
handles_gui.text_upperbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'text_upperbound', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.5 9.9 16 1.3], ...
'HorizontalAlignment', 'left', ...
'String', 'Upperbound:', ...
'Interruptible','off');
handles_gui.text_lowerbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'text_lowerbound', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.5 6.6 16 1.3], ...
'HorizontalAlignment', 'left', ...
'String', 'Lowerbound:', ...
'Interruptible','off');
handles_gui.text_scalebarlength = uicontrol( ...
'Parent', handles_gui.group_scalebar, ...
'Tag', 'text_scalebarlength', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.5 1 16 1.3], ...
'HorizontalAlignment', 'left', ...
'String', 'Scale Bar Len:', ...
'Interruptible','off');
% Now get info text which is below the plot
handles_infotext = set_infotext(handles_gui.group_formataxes,'');
fields_infotext = fieldnames(handles_infotext);
for i = 0:length(fields_infotext)-1
handles_gui.(fields_infotext{i+1}) = handles_infotext.(fields_infotext{i+1});
end
% Sliders
handles_gui.slider_transparency = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'slider_transparency', ...
'Style', 'slider', ...
'Units', 'characters', ...
'Position', [2.5 12.0 28.9 1.3], ...
'BackgroundColor', [0.9 0.9 0.9], ...
'String', 'Slider', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_slider_transparency,handles_gui.figure), ...
'Interruptible','off');
handles_gui.slider_upperbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'slider_upperbound', ...
'Style', 'slider', ...
'Units', 'characters', ...
'Position', [2.5 8.5 28.9 1.3], ...
'BackgroundColor', [0.9 0.9 0.9], ...
'String', 'Slider', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_slider_upperbound,handles_gui.figure), ...
'Interruptible','off');
handles_gui.slider_lowerbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'slider_lowerbound', ...
'Style', 'slider', ...
'Units', 'characters', ...
'Position', [2.5 5.0 28.9 1.3], ...
'BackgroundColor', [0.9 0.9 0.9], ...
'String', 'Slider', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_slider_lowerbound,handles_gui.figure), ...
'Interruptible','off');
% Check Box
handles_gui.checkbox_contour = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'checkbox_contour', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [2.5 17.3 17 1.3], ...
'String', 'Contour Plot: ', ...
'Value', 0, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_contour,handles_gui.figure), ...
'Interruptible','off');
handles_gui.checkbox_minmaxmarkers = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'checkbox_minmaxmarkers', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [2.5 15.5 29.7 1.3], ...
'String', 'Max/min markers', ...
'Value', 0, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_minmaxmarkers,handles_gui.figure), ...
'Interruptible','off');
handles_gui.checkbox_scalebar = uicontrol( ...
'Parent', handles_gui.group_scalebar, ...
'Tag', 'checkbox_scalebar', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [2.5 3 17 1.3], ...
'String', 'Scalebar ', ...
'Value', 1, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_scalebar,handles_gui.figure), ...
'Interruptible','off');
handles_gui.checkbox_axes = uicontrol( ...
'Parent', handles_gui.group_axes, ...
'Tag', 'checkbox_axes', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [2.5 1.0 17 1.3], ...
'String', 'Axes ', ...
'Value', 1, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_axes,handles_gui.figure), ...
'Interruptible','off');
% Edit
handles_gui.edit_transparency = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'edit_transparency', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 13.6 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_transparency,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_upperbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'edit_upperbound', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 10.1 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_upperbound,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_lowerbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'edit_lowerbound', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 6.6 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_lowerbound,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_contour = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'edit_contour', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 17.3 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Enable', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_contour,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_scalebarlength = uicontrol( ...
'Parent', handles_gui.group_scalebar, ...
'Tag', 'edit_scalebarlength', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 1.1 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_scalebarlength,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_imgnum = uicontrol( ...
'Parent', handles_gui.group_formataxes, ...
'Tag', 'edit_imgnum', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [91 1.1 7 1.6], ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_imgnum,handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
% Pushbuttons
handles_gui.button_applytoall = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'button_applytoall', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.5 2.8 28.9 1.5], ...
'String', 'Apply to All', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_applytoall,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_resetdefaults = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'button_resetdefaults', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.5 1 28.9 1.5], ...
'String', 'Reset Defaults', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_resetdefaults,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_zoom = uicontrol( ...
'Parent', handles_gui.group_zoompan, ...
'Tag', 'button_zoom', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.1 1 14.4 1.7], ...
'String', 'Zoom', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_zoom,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_pan = uicontrol( ...
'Parent', handles_gui.group_zoompan, ...
'Tag', 'button_pan', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [17.4 1 14.4 1.7], ...
'String', 'Pan', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_pan,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_left = uicontrol( ...
'Parent', handles_gui.group_formataxes, ...
'Tag', 'button_left', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [84 1.0 6 1.8], ...
'String', '<', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_left,handles_gui.figure), ...
'Interruptible','off', ...
'Enable', 'off');
handles_gui.button_right = uicontrol( ...
'Parent', handles_gui.group_formataxes, ...
'Tag', 'button_right', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [99 1.0 6 1.8], ...
'String', '>', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_right,handles_gui.figure), ...
'Interruptible','off', ...
'Enable', 'off');
end
end
%---------------------------------------------------------------------%
% SAVE GUI -----------------------------------------------------------%
%---------------------------------------------------------------------%
function [size_savefig,timedelay,outstate] = gui_savesize(handles_gui_savefig,isgif,pos_parent)
% This is a GUI for inputting the height and width for the saved figure.
% This gui will update the figure in handles_gui_savefig.
%
% Inputs -----------------------------------------------------------------%
% handles_gui_savefig - handle; handle of the save figure. The position
% of this figure is controlled by this GUI
% isgif - logical; this tells whether or not an animated gif is being
% saved. If a gif is being saved then the time delay can be adjusted
% pos_parent - integer array; this is the position of the parent figure
% which determines where to position this figure
%
% Outputs ----------------------------------------------------------------%
% size_savefig - integer array; contains the size of the save fig
% timedelay - double; this is the time delay between frames
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Data ---------------------------------------------------------------%
% Initialize outputs
outstate = out.cancelled;
size_savefig = [];
timedelay = [];
% Get GUI handles - Part of output
handles_gui = init_gui();
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui.figure));
% Callbacks and functions --------------------------------------------%
function constructor()
% Get save size parameters; the screen size is needed to
% prevent the user from resizing outside the screen, which will
% result in cropping when using getframe()
% Get data
width_img = getappdata(handles_gui_savefig.figure,'width_img');
height_img = getappdata(handles_gui_savefig.figure,'height_img');
spacing_save_fig = getappdata(handles_gui_savefig.figure,'spacing_save_fig');
spacing_width_img = getappdata(handles_gui_savefig.figure,'spacing_width_img');
spacing_height_img = getappdata(handles_gui_savefig.figure,'spacing_height_img');
set(0,'units','pixels'); % Set to pixels first
size_screen = get(0,'Screensize'); % width = size_screen(3); height = size_screen(4)
max_width_img = size_screen(3)-spacing_save_fig-spacing_width_img;
max_height_img = size_screen(4)-spacing_save_fig-spacing_height_img;
if (max_width_img/max_height_img > width_img/height_img)
max_width_img = round(max_height_img*(width_img/height_img));
else
max_height_img = round(max_width_img/(width_img/height_img));
end
if (width_img > max_width_img || height_img > max_height_img)
% Image is too large, resize it to fit within screen
img_reduction = min(max_width_img/width_img,max_height_img/height_img);
width_img = round(width_img*img_reduction);
height_img = round(height_img*img_reduction);
end
timedelay_prelim = 0.04;
% Set data
setappdata(handles_gui.figure,'width_img',width_img);
setappdata(handles_gui.figure,'height_img',height_img);
setappdata(handles_gui.figure,'ratio_img',width_img/height_img);
setappdata(handles_gui.figure,'max_width_img',max_width_img);
setappdata(handles_gui.figure,'max_height_img',max_height_img);
setappdata(handles_gui.figure,'timedelay_prelim',timedelay_prelim);
% Update
update_axes('set');
update_sidemenu();
% Set visible
set(handles_gui.figure,'Visible','on');
end
function callback_edit_timedelay(hObject,eventdata) %#ok<INUSD>
% Get data
timedelay_prelim = getappdata(handles_gui.figure,'timedelay_prelim');
% Max and min values
max_timedelay = 1;
min_timedelay = 1e-5;
% Get width
timedelay_buffer = str2double(get(handles_gui.edit_timedelay,'string'));
if (ncorr_util_isrealbb(timedelay_buffer,min_timedelay,max_timedelay,'Time delay') == out.success)
timedelay_prelim = timedelay_buffer;
end
% Set data
setappdata(handles_gui.figure,'timedelay_prelim',timedelay_prelim);
% Update preview image
update_axes('update');
update_sidemenu();
end
function callback_edit_width(hObject,eventdata) %#ok<INUSD>
% Get data
ratio_img = getappdata(handles_gui.figure,'ratio_img');
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
max_width_img = getappdata(handles_gui.figure,'max_width_img');
max_height_img = getappdata(handles_gui.figure,'max_height_img');
% Get width
width_img_buffer = str2double(get(handles_gui.edit_width,'string'));
if (ncorr_util_isintbb(width_img_buffer,1,max_width_img,'Width') == out.success)
% Calculate new width and height - make sure they do
% not go outside screen size
height_img_buffer = round(width_img_buffer/ratio_img);
if (ncorr_util_isintbb(height_img_buffer,1,max_height_img,'Height') == out.success)
width_img = width_img_buffer;
height_img = height_img_buffer;
end
end
% Set data
setappdata(handles_gui.figure,'width_img',width_img);
setappdata(handles_gui.figure,'height_img',height_img);
% Update preview image
update_axes('update');
update_sidemenu();
end
function callback_edit_height(hObject,eventdata) %#ok<INUSD>
% Get data
ratio_img = getappdata(handles_gui.figure,'ratio_img');
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
max_width_img = getappdata(handles_gui.figure,'max_width_img');
max_height_img = getappdata(handles_gui.figure,'max_height_img');
% Get height
height_img_buffer = str2double(get(handles_gui.edit_height,'string'));
if (ncorr_util_isintbb(height_img_buffer,1,max_height_img,'Height') == out.success)
% Calculate new width and height - make sure they do
% not go outside screen size
width_img_buffer = round(height_img_buffer*ratio_img);
if (ncorr_util_isintbb(width_img_buffer,1,max_width_img,'Width') == out.success)
width_img = width_img_buffer;
height_img = height_img_buffer;
end
end
% Set data
setappdata(handles_gui.figure,'width_img',width_img);
setappdata(handles_gui.figure,'height_img',height_img);
% Update
update_axes('update');
update_sidemenu();
end
function callback_button_finish(hObject,eventdata) %#ok<INUSD>
% Get data
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
timedelay_prelim = getappdata(handles_gui.figure,'timedelay_prelim');
% Set output
size_savefig = [width_img height_img];
timedelay = timedelay_prelim;
outstate = out.success;
% Exit
close(handles_gui.figure);
end
function callback_button_cancel(hObject,eventdata) %#ok<INUSD>
% Close
close(handles_gui.figure);
end
function update_sidemenu()
% Get data
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
timedelay_prelim = getappdata(handles_gui.figure,'timedelay_prelim');
set(handles_gui.edit_width,'String',num2str(width_img));
set(handles_gui.edit_height,'String',num2str(height_img));
if (isgif)
set(handles_gui.edit_timedelay,'String',num2str(timedelay_prelim));
else
set(handles_gui.edit_timedelay,'enable','off');
end
end
function update_axes(action)
% Get data - savefig handles:
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
if (strcmp(action,'set') || strcmp(action,'update'))
% Transfer data then update
setappdata(handles_gui_savefig.figure,'width_img',width_img);
setappdata(handles_gui_savefig.figure,'height_img',height_img);
% Update
update_savefig(handles_gui_savefig);
end
end
function handles_gui = init_gui()
% Form UIs
handles_gui.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', ncorr_util_figpos(pos_parent,[10 30.5]), ...
'Name', 'Set Image Size', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'Resize','off', ...
'WindowStyle','modal', ...
'IntegerHandle','off', ...
'Interruptible','off');
% Adjust position
% Set this UI next to the save fig
pos_savefig_pixels = get(handles_gui_savefig.figure,'OuterPosition');
% Get size of figure in pixels
set(handles_gui.figure,'Units','pixels');
pos_fig_pixels = get(handles_gui.figure,'Position');
pos_fig_pixels(1) = pos_savefig_pixels(3)+1.5*pos_savefig_pixels(1);
pos_fig_pixels(2) = pos_savefig_pixels(2)+pos_savefig_pixels(4)/2-pos_fig_pixels(4)/2;
% Check to make sure position is not out of screen
set(0,'units','pixels');
pos_screen_pixels = get(0,'ScreenSize');
% Check right - no need to check bottom
screen_right = 20; % Use this as padding
if (pos_fig_pixels(1)+pos_fig_pixels(3) > pos_screen_pixels(3)-screen_right)
pos_fig_pixels(1) = pos_screen_pixels(3)-pos_fig_pixels(3)-screen_right;
end
% Set position
set(handles_gui.figure,'Position',pos_fig_pixels);
% Convert back to characters
set(handles_gui.figure,'Units','characters');
% Text
handles_gui.text_timedelay = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_timedelay', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 7.5 15 1.3], ...
'String', 'Time Delay:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_width = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_width', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 5.5 15 1.3], ...
'String', 'Width:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_height = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_height', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 3.5 15 1.3], ...
'String', 'Height:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% Edit box
handles_gui.edit_timedelay = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'edit_timedelay', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [18.2 7.5 9.6 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_timedelay,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_width = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'edit_width', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [18.2 5.5 9.6 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_width,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_height = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'edit_height', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [18.2 3.5 9.6 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_height,handles_gui.figure), ...
'Interruptible','off');
% Buttons
handles_gui.button_finish = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'button_finish', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.1 1 12 1.7], ...
'String', 'Finish', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_finish,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_cancel = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'button_cancel', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [16 1 12 1.7], ...
'String', 'Cancel', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_cancel,handles_gui.figure), ...
'Interruptible','off');
end
% Pause until figure is closed -----------------------------------%
waitfor(handles_gui.figure);
end
function update_savefig(handles_gui_savefig)
% This function is called whenever the savefig needs to be updated. It
% will resize the window and reposition the axes/colorbar.
% Get data
height_data = getappdata(handles_gui_savefig.figure,'height_data');
width_img = getappdata(handles_gui_savefig.figure,'width_img');
height_img = getappdata(handles_gui_savefig.figure,'height_img');
border = getappdata(handles_gui_savefig.figure,'border');
width_cb = getappdata(handles_gui_savefig.figure,'width_cb');
spacing_save_fig = getappdata(handles_gui_savefig.figure,'spacing_save_fig');
spacing_width_img = getappdata(handles_gui_savefig.figure,'spacing_width_img');
spacing_height_img = getappdata(handles_gui_savefig.figure,'spacing_height_img');
handle_colorbar = getappdata(handles_gui_savefig.figure,'handle_colorbar');
handle_scalebar = getappdata(handles_gui_savefig.figure,'handle_scalebar');
handle_axes = getappdata(handles_gui_savefig.figure,'handle_axes');
% Set image
pos_savefig(1) = spacing_save_fig;
pos_savefig(2) = spacing_save_fig;
pos_savefig(3) = spacing_width_img+width_img; % Width
pos_savefig(4) = spacing_height_img+height_img; % Height
set(handles_gui_savefig.figure,'Position',pos_savefig);
% Colorbar:
set(handle_colorbar,'Position',[2*border+width_img border+height_data width_cb height_img]);
% Plot:
set(handles_gui_savefig.axes_formatplot,'Position',[border border+height_data width_img height_img]);
% Update handle_scalebar text if it it's toggled
% Only text is updated because the size is constant during resize;
% patches will resize with handle_axes. Do not need to check with
% 'ishandle' because the scalebar is either set once or not at all.
if (~isempty(handle_scalebar))
set(handles_gui_savefig.axes_formatplot,'units','characters');
text_scalebar = findobj(handles_gui_savefig.axes_formatplot,'tag','text_scalebar');
pos_img = get(handles_gui_savefig.axes_formatplot,'Position');
size_text = max(0.5*max(0.5*pos_img(4),0.14*pos_img(3)),8);
set(text_scalebar,'FontSize',size_text);
set(handles_gui_savefig.axes_formatplot,'units','pixels');
end
% Update handle_axes text if it it's toggled
% Only text is updated because the size is constant during resize;
% patches will resize with handle_axes. Do not need to check with
% 'ishandle' because the axes is either set once or not at all.
if (~isempty(handle_axes))
set(handles_gui_savefig.axes_formatplot,'units','characters');
text_x = findobj(handles_gui_savefig.axes_formatplot,'tag','text_x');
text_y = findobj(handles_gui_savefig.axes_formatplot,'tag','text_y');
pos_img = get(handles_gui_savefig.axes_formatplot,'Position');
size_text = max(0.5*max(0.5*pos_img(4),0.14*pos_img(3)),8);
set(text_x,'FontSize',size_text);
set(text_y,'FontSize',size_text);
set(handles_gui_savefig.axes_formatplot,'units','pixels');
end
% Make sure figure is drawn to ensure getframe works properly.
drawnow;
end
function handles_infotext = set_infotext(parent,bgcolor)
% This function sets information text
handles_infotext.text_ref_name = uicontrol( ...
'Parent', parent, ...
'Tag', 'ref_name', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 17.0 100 1.3], ...
'String', 'Reference Name: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_cur_name = uicontrol( ...
'Parent', parent, ...
'Tag', 'cur_name', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 15.5 100 1.3], ...
'String', 'Current Name: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_type = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_type', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 14.0 100 1.3], ...
'String', 'Analysis Type: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_dicparams = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_dicparams', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 12.5 100 1.3], ...
'String', 'RG-DIC Radius: | Subset Spacing:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_itparams = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_itparams', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 11.0 100 1.3], ...
'String', 'Diffnorm Cutoff: | Iteration Cutoff: | Total Threads: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_stepanalysis = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_stepanalysis', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 9.5 100 1.3], ...
'String', 'Step Analysis: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_subsettrunc = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_subsettrunc', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 8.0 100 1.3], ...
'String', 'Disp Subset Truncation: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_imgcorr = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_imgcorr', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 6.5 100 1.3], ...
'String', 'Image Correspondences: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_pixtounits = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_pixtounits', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 5.0 100 1.3], ...
'String', 'Reference Image FOV width: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_cutoff_corrcoef = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_cutoff_corrcoef', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 3.5 100 1.3], ...
'String', 'Correlation Coefficient Cutoff: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_lenscoef = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_lenscoef', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 2.0 100 1.3], ...
'String', 'Radial Lens Distortion Coefficient: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_minmedianmax = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_max', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 0.5 100 1.3], ...
'String', 'Min: | Median: | Max: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% Check if bgcolor was provided
if (~isempty(bgcolor))
fields_infotext = fieldnames(handles_infotext);
for i = 0:length(fields_infotext)-1
set(handles_infotext.(fields_infotext{i+1}),'BackgroundColor',bgcolor);
end
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr_util_formregionconstraint.m
|
.m
|
choco-packages-master/packages/matlab-coecis/tools/ncorr/ncorr_util_formregionconstraint.m
| 6,122 |
utf_8
|
458de04923bdcb004e97d0415e37da7e
|
function handle_constraintfcn = ncorr_util_formregionconstraint(region)
% This function returns handle_constraintfcn which, given a point, will
% return the closest point inside the region. This is mainly used for the
% constrainfcn for impoints which are restricted to be inside a region.
%
% Inputs -----------------------------------------------------------------%
% region - struct; region info used to determine the position of returned
% point
%
% Outputs ----------------------------------------------------------------%
% handle_constraintfcn - function handle;
%
% Returns error if region is empty.
if (region.totalpoints == 0)
error('Region cannot be empty when forming constraint function.');
end
handle_constraintfcn = @constraintfcn;
function pos_nearest = constraintfcn(pos)
% This function will generally be called within a callback
% automatically which will use 1 based indexing, so pos_nearest is
% returned using 1 based indexing. However, for processing, 0 based
% indexing is used, so convert back and forth as necessary.
% Convert pos to 0 based indexing and round it:
pos = round(pos)-1;
% Find bounding box - must find this since left and right bounds
% are based on the length of the noderange/nodelist which may not
% necessarily be the bounding box.
left = region.rightbound;
right = 0;
firstpoint = false;
for i = 0:size(region.noderange,1)-1
if (region.noderange(i+1) > 0 && ~firstpoint)
firstpoint = true;
left = i + region.leftbound;
end
if (region.noderange(i+1) > 0 && i+region.leftbound > right)
right = i + region.leftbound;
end
end
% Check if above, between, or beneath bounds
if (pos(1) < left)
% Left of bounds - set x to left and then find the nearest node
% for y
pos_nearest(1) = left+1;
pos_nearest(2) = nearestnode(region.nodelist(left-region.leftbound+1,:),region.noderange(left-region.leftbound+1),pos(2))+1;
elseif (pos(1) >= left && pos(1) <= right)
% Between bounds - must check if nodes exist at this x position
if (region.noderange(pos(1)-region.leftbound+1) > 0)
pos_nearest(1) = pos(1)+1;
else
% Initialize
leftfound = false;
leftdist = 0;
rightfound = false;
rightdist = 0;
% Cycle left until finding a positive noderange
for i = pos(1)-1:-1:left
if (region.noderange(i-region.leftbound+1) > 0)
leftdist = pos(1)-i;
leftfound = true;
break;
end
end
% Cycle right until finding a positive noderange
for i = pos(1)+1:right
if (region.noderange(i-region.leftbound+1) > 0)
rightdist = i-pos(1);
rightfound = true;
break;
end
end
% Now set x position
if (leftfound && rightfound)
if (leftdist < rightdist)
pos_nearest(1) = pos(1)-leftdist+1;
else
pos_nearest(1) = pos(1)+rightdist+1;
end
elseif (leftfound)
pos_nearest(1) = pos(1)-leftdist+1;
else
pos_nearest(1) = pos(1)+rightdist+1;
end
end
pos_nearest(2) = nearestnode(region.nodelist((pos_nearest(1)-1)-region.leftbound+1,:),region.noderange((pos_nearest(1)-1)-region.leftbound+1),pos(2))+1;
else
% Right of bounds - set x to left and then find the nearest node
% for y
pos_nearest(1) = right+1;
pos_nearest(2) = nearestnode(region.nodelist(right-region.leftbound+1,:),region.noderange(right-region.leftbound+1),pos(2))+1;
end
end
end
function y_nearest = nearestnode(nodelist,noderange,y_coord)
% Finds the nearest y value given the nodelist, noderange and y_coord. Note
% that nodelist and noderange are a single column for a specific x position.
% Uses zero based indexing.
% Initialize
y_nearest = -1;
for i = 0:2:noderange-1
% Test if node is before, within, or after a node pair
if (y_coord < nodelist(i+1))
if (i == 0)
% Above first node
y_nearest = nodelist(i+1);
break;
else
% Above inner node pair
% Find out if y_coord is closer to bottom node of previous
% pair or top node of current pair
if ((y_coord-nodelist(i)) < (nodelist(i+1)-y_coord))
% y_coord is closer to bottom node of previous pair
y_nearest = nodelist(i);
break;
else
% y_coord is closer to top node of current pair
y_nearest = nodelist(i+1);
break;
end
end
elseif (y_coord >= nodelist(i+1) && y_coord <= nodelist(i+2))
% y_coord is between node pairs, so just return it
y_nearest = y_coord;
break;
else
% y_coord is after noderange - test to see if this is the last
% node pair.
if (i == noderange-2)
% This is last node pair, so y_coord is the below node of
% last node pair
y_nearest = nodelist(i+2);
break;
else
% Skip to next node pair
continue;
end
end
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr_class_roi.m
|
.m
|
choco-packages-master/packages/matlab-ciser/tools/ncorr/ncorr_class_roi.m
| 66,847 |
utf_8
|
b4e72c2e366297dd03223cfb0a283d2d
|
classdef ncorr_class_roi < handle
% This is the class definition for the region of interest.
% Properties ---------------------------------------------------------%
properties(SetAccess = private)
type; % string
mask; % logical array
region; % struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{})
boundary; % struct('add',{},'sub',{})
data; % varying struct
end
% Methods ------------------------------------------------------------%
methods(Access = public)
% Constructor
function obj = ncorr_class_roi
obj.type = '';
obj.mask = false(0);
obj.region = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
obj.boundary = struct('add',{},'sub',{});
obj.data = struct();
end
function set_roi(obj,type_i,data_i)
% This function sets the region of interest.
%
% Inputs ---------------------------------------------------------%
% type_i - string; describes how ROI was made. Supported types
% shown below:
% 'load' - mask was loaded from an image file. data_i is
% struct('mask',{},'cutoff',{}).
% 'draw' - mask was drawn. data_i is
% struct('mask',{}','drawobjects',{},'cutoff',{}).
% 'region' - region and size of the mask are provided.
% data_i is struct('region',{},'size_mask',{}).
% 'boundary' - boundary and size of the mask are provided.
% data_i is struct('boundary',{},'size_mask',{}).
% data_i - struct; contains input data for the type of ROI.
%
% Outputs --------------------------------------------------------%
% None
%
% Returns error if type is wrong.
if (~strcmp(type_i,'load') && ~strcmp(type_i,'draw') && ~strcmp(type_i,'region') && ~strcmp(type_i,'boundary'))
error('Incorrect type provided.');
end
if (strcmp(type_i,'load') || strcmp(type_i,'draw'))
% This is the "load" and "draw" types, which mean a
% mask for the ROI is provided directly.
% Get mask - mask is directly provided for 'load' and 'draw'
mask_prelim = data_i.mask;
% Create region(s) - these are 4-way connected/contiguous
[region_prelim,removed] = ncorr_alg_formregions(mask_prelim,int32(data_i.cutoff),false);
% Get 20 largest contiguous regions. This is to prevent
% boundary routine from running very slowly if there are a
% bunch of small regions
cutoff_regions = 20;
[val_sorted,idx_sorted] = sort([region_prelim.totalpoints],'descend'); %#ok<ASGLU>
idx_sorted = idx_sorted-1; % Convert to zero based
if (length(idx_sorted) > cutoff_regions)
region_prelim = region_prelim(idx_sorted(1:cutoff_regions)+1);
removed = true;
end
% Update mask if regions were removed
if (removed)
mask_prelim(:) = false;
for i = 0:length(region_prelim)-1
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
for k = 0:2:region_prelim(i+1).noderange(j+1)-1
vec_y = region_prelim(i+1).nodelist(j+1,k+1):region_prelim(i+1).nodelist(j+1,k+2);
mask_prelim(vec_y+1,x+1) = true;
end
end
end
end
% Now get the boundaries - Do the "add boundaries"
% first. One per region.
boundary_prelim = struct('add',cell(length(region_prelim),1),'sub',cell(length(region_prelim),1));
for i = 0:length(region_prelim)-1
% Get mask corresponding to region - must do this
% because boundary tracing algorithm is 8-way
% connected, but the region is 4-way connected. I
% used the 8-way connected boundary because it is
% smoother. Note that if two 4-way connected
% regions are just touching at corners they are
% technically considered 8-way connected, which is
% why each 4-way region must be analyzed separately.
regionmask_buffer = false(size(mask_prelim));
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
for k = 0:2:region_prelim(i+1).noderange(j+1)-1
vec_y = region_prelim(i+1).nodelist(j+1,k+1):region_prelim(i+1).nodelist(j+1,k+2);
regionmask_buffer(vec_y+1,x+1) = true;
end
end
% Get add boundary:
% Use the top of the left most point in the region.
% Send this coordinate and the regionmask_buffer
% corresponding to this region to determine the
% boundary
boundary_buffer = ncorr_alg_formboundary(int32([region_prelim(i+1).leftbound region_prelim(i+1).nodelist(1,1)]),int32(0),regionmask_buffer);
% Append boundary
boundary_prelim(i+1).add = boundary_buffer;
% Get inverse of regionmask_buffer, and then do logical
% "and" with the filled in outer boundary. This
% leaves only internal regions
regionmask_inv_buffer = false(size(mask_prelim));
% Get filled-in outter boundary - note that this
% does not fill the boundary exactly since the
% algorithm uses double precision points to
% estimate the boundary.
ncorr_alg_formmask(struct('pos_imroi',boundary_prelim(i+1).add,'type','poly','addorsub','add'),regionmask_inv_buffer);
regionmask_inv_buffer = regionmask_inv_buffer & ~regionmask_buffer;
% Form mask_boundary - this keeps track of the sub
% boundaries already analyzed so we dont count one
% twice.
mask_boundary = false(size(mask_prelim)); % Make a copy to keep track of which points have been used to analyze the boundary
% Get sub boundaries:
boundary_prelim(i+1).sub = cell(0);
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
% Make sure noderange is greater than 2, or
% else this portion doesnt have a hole
if (region_prelim(i+1).noderange(j+1) > 2)
for k = 0:2:region_prelim(i+1).noderange(j+1)-3 % Dont test last node pair
% Only use bottom nodes - only test
% bottom nodes since these are the
% first points adjacent to a hole
y_bottom = region_prelim(i+1).nodelist(j+1,k+2);
% Test one pixel below bottom node. Make
% sure this pixel hasnt already been analyzed,
% and is also within the inverse regionmask
% buffer
if (regionmask_inv_buffer(y_bottom+2,x+1) && ~mask_boundary(y_bottom+2,x+1))
% This is a boundary point which
% hasn't been analyzed yet
boundary_prelim(i+1).sub{end+1} = ncorr_alg_formboundary(int32([x y_bottom+1]),int32(0),regionmask_inv_buffer);
% update mask_boundary
mask_boundary(sub2ind(size(mask_boundary),boundary_prelim(i+1).sub{end}(:,2)+1,boundary_prelim(i+1).sub{end}(:,1)+1)) = true;
end
end
end
end
end
elseif (strcmp(type_i,'region'))
% This is the 'region' option; regions are supplied
% directly. It's possible that analysis yielded regions
% directly (like unioning).
% Form mask
mask_prelim = false(data_i.size_mask);
% Form region
region_prelim = data_i.region;
% Update mask from region:
for i = 0:length(region_prelim)-1
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
for k = 0:2:region_prelim(i+1).noderange(j+1)-1
vec_y = region_prelim(i+1).nodelist(j+1,k+1):region_prelim(i+1).nodelist(j+1,k+2);
mask_prelim(vec_y+1,x+1) = true;
end
end
end
% For the custom case, do not form a real boundary, since
% regions may not longer be contigous. Do form one boundary
% per region though.
for i = 0:length(region_prelim)-1
boundary_prelim(i+1).add = [-1 -1]; %#ok<AGROW>
boundary_prelim(i+1).sub = {}; %#ok<AGROW>
end
elseif (strcmp(type_i,'boundary'))
% This is the 'boundary' option; a boundary is supplied
% directly. This allows Ncorr to update the mask based
% on displacement values at the boundary point. Note
% there will be one region per "add" boundary, this
% preserves the correspondences between a region and
% boundary.
% Form mask
mask_prelim = false(data_i.size_mask);
% Form boundary
boundary_prelim = data_i.boundary;
% Fill a region for each boundary -> Get the region
% corresponding to that mask -> append all
% regions.
% Set drawobjects which are sent to ncorr_alg_formmask
region_prelim = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
for i = 0:length(boundary_prelim)-1
% Initialize counter and draw objects
drawobjects = struct('pos_imroi',{},'type',{},'addorsub',{});
counter = 0;
drawobjects(counter+1).pos_imroi = boundary_prelim(i+1).add;
drawobjects(counter+1).type = 'poly';
drawobjects(counter+1).addorsub = 'add';
counter = counter+1;
for j = 0:length(boundary_prelim(i+1).sub)-1
drawobjects(counter+1).pos_imroi = boundary_prelim(i+1).sub{j+1};
drawobjects(counter+1).type = 'poly';
drawobjects(counter+1).addorsub = 'sub';
counter = counter+1;
end
% Get mask corresponding to this boundary
ncorr_alg_formmask(drawobjects,mask_prelim);
% Get region
[region_buffer,removed] = ncorr_alg_formregions(mask_prelim,int32(0),false); %#ok<NASGU>
% There must be one region per boundary to preserve
% their correspondence. It's possible for the region
% for a boundary to "pinch" or form more than one.
if (isempty(region_buffer))
% Form an empty ROI list if region_buffer is
% empty - this keeps the correspondence between
% the boundary and region
region_buffer = struct('nodelist',[-1 -1],'noderange',0,'leftbound',0,'rightbound',0,'upperbound',0,'lowerbound',0,'totalpoints',0);
elseif (length(region_buffer) > 1)
% Select biggest ROI if there are more than
% one. This could possibly happen if a boundary
% is "pinched" or closes. Unlikely- but may
% happen.
idx_max = find([region_buffer.totalpoints] == max([region_buffer.totalpoints]),1,'first');
region_buffer = region_buffer(idx_max);
end
% Merge
region_prelim(i+1) = region_buffer;
end
% Update mask from region:
for i = 0:length(region_prelim)-1
for j = 0:size(region_prelim(i+1).noderange,1)-1
x = j + region_prelim(i+1).leftbound;
for k = 0:2:region_prelim(i+1).noderange(j+1)-1
vec_y = region_prelim(i+1).nodelist(j+1,k+1):region_prelim(i+1).nodelist(j+1,k+2);
mask_prelim(vec_y+1,x+1) = true;
end
end
end
end
% Set properties
obj.type = type_i;
obj.mask = mask_prelim;
obj.region = region_prelim;
obj.boundary = boundary_prelim;
obj.data = data_i;
end
function roi_reduced = reduce(obj,spacing)
% This function reduces the ROI. Its possible some regions will
% be deleted after the reduction; a placeholder is still used to
% preserve the number of regions.
%
% Inputs ---------------------------------------------------------%
% spacing - integer; spacing parameter
%
% Outputs --------------------------------------------------------%
% roi_reduced - ncorr_class_roi; reduced ROI
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
% Initialize output
roi_reduced = ncorr_class_roi.empty;
if (spacing == 0)
% Don't do anything, the ROI is not actually being reduced.
% Just make a deep copy of this ROI and return;
roi_reduced(1) = ncorr_class_roi;
p = properties(obj);
for i = 0:length(p)-1
roi_reduced.(p{i+1}) = obj.(p{i+1});
end
else
% Form reduced region and its template
region_reduced = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
region_reduced_template = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
for i = 0:length(obj.region)-1
% Find new bounds - left and right bounds are the
% upper limit.
region_reduced_template(1).leftbound = ceil(obj.region(i+1).leftbound/(spacing+1));
region_reduced_template.rightbound = floor(obj.region(i+1).rightbound/(spacing+1));
region_reduced_template.upperbound = inf; % Initialize to infinitely high so it can updated
region_reduced_template.lowerbound = -inf; % Initialize to infinitely low so it can updated
% Initialize nodelist, noderange, and totalpoints
region_reduced_template.nodelist = -ones(max(1,region_reduced_template.rightbound-region_reduced_template.leftbound+1),size(obj.region(i+1).nodelist,2));
region_reduced_template.noderange = zeros(max(1,region_reduced_template.rightbound-region_reduced_template.leftbound+1),1);
region_reduced_template.totalpoints = 0;
% Scan columns - calculate nodelist, noderange,
% and totalpoints
for j = region_reduced_template.leftbound*(spacing+1)-obj.region(i+1).leftbound:spacing+1:region_reduced_template.rightbound*(spacing+1)-obj.region(i+1).leftbound
% This is the column which lies on the grid;
% Form the reduced nodelist and noderange for
% this column
x_reduced = (j-(region_reduced_template.leftbound*(spacing+1)-obj.region(i+1).leftbound))/(spacing+1);
for k = 0:2:obj.region(i+1).noderange(j+1)-1
% Find upper and lower bounds for each node pair -
% it is possible that entire node pair is skipped
% over by the spacing
node_top_reduced = ceil(obj.region(i+1).nodelist(j+1,k+1)/(spacing+1));
node_bottom_reduced = floor(obj.region(i+1).nodelist(j+1,k+2)/(spacing+1));
if (node_bottom_reduced >= node_top_reduced)
% Add this node pair
region_reduced_template.nodelist(x_reduced+1,region_reduced_template.noderange(x_reduced+1)+1) = node_top_reduced;
region_reduced_template.nodelist(x_reduced+1,region_reduced_template.noderange(x_reduced+1)+2) = node_bottom_reduced;
% Update node range
region_reduced_template.noderange(x_reduced+1) = region_reduced_template.noderange((j-(region_reduced_template.leftbound*(spacing+1)-obj.region(i+1).leftbound))/(spacing+1)+1)+2;
% Update totalpoints
region_reduced_template.totalpoints = region_reduced_template.totalpoints + (node_bottom_reduced-node_top_reduced+1);
% Update upper and lower bounds
if (node_top_reduced < region_reduced_template.upperbound)
region_reduced_template.upperbound = node_top_reduced;
end
if (node_bottom_reduced > region_reduced_template.lowerbound)
region_reduced_template.lowerbound = node_bottom_reduced;
end
end
end
end
% See if region is empty - if so use a placeholder.
if (region_reduced_template.totalpoints == 0)
region_reduced_template.nodelist = [-1 -1];
region_reduced_template.noderange = 0;
region_reduced_template.leftbound = 0;
region_reduced_template.rightbound = 0;
region_reduced_template.upperbound = 0;
region_reduced_template.lowerbound = 0;
end
% Insert template into reduced region
region_reduced(i+1) = region_reduced_template;
end
% Create new ROI
roi_reduced(1) = ncorr_class_roi;
roi_reduced.set_roi('region',struct('region',region_reduced,'size_mask',size(obj.mask(1:spacing+1:end,1:spacing+1:end))));
end
end
function roi_union = get_union(obj,mask_i,spacing)
% This function returns the union of the current ROI and the
% inputted mask (which may be reduced).
%
% Inputs ---------------------------------------------------------%
% mask_i - logical array; mask used to union
% spacing - integer; indicates how much mask_i has been reduced.
%
% Outputs --------------------------------------------------------%
% roi_union - ncorr_class_roi; union of this ROI with mask_i.
%
% Returns error if ROI has not been set yet or if the sizes dont
% match.
if (isempty(obj.type))
error('ROI has not been set yet');
elseif (~isequal(size(obj.mask(1:spacing+1:end,1:spacing+1:end)),size(mask_i)))
error('Reduced mask and input mask are not the same size');
end
% Initialize output
roi_union = ncorr_class_roi;
% Get reduced ROI
roi_reduced = obj.reduce(spacing);
% Get unioned mask
mask_union = obj.mask(1:spacing+1:end,1:spacing+1:end) & mask_i;
% Get unioned region, this will not necessarily be contiguous anymore
region_union = ncorr_alg_formunion(roi_reduced.formatted(),mask_union);
% Create new ROI
roi_union.set_roi('region',struct('region',region_union,'size_mask',size(mask_union)));
end
function roi_update = update_roi(obj,plot_u,plot_v,roi_plot,size_mask_update,spacing,radius)
% This function returns an updated ROI, based on the inputted
% displacement fields. This works by updating the boundary and
% redrawing the mask. This assumes boundary can be subpixel, so it
% interpolates a new position based on the displacement field.
% Furthermore, displacement fields are reduced by a spacing factor,
% so it's required as an input.
%
% Inputs ---------------------------------------------------------%
% plot_u - double array; u displacement plot
% plot_v - double array; v displacement plot
% roi_plot - ncorr_class_roi; ROI corresponding to displacement
% plots
% size_mask_update - integer array; size of the updated mask. Can
% be a different size than obj.mask if different sized image are
% used
% spacing - integer; spacing parameter
% radius - integer; subset radius
%
% Outputs --------------------------------------------------------%
% roi_update - ncorr_class_roi; updated ROI.
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
% Extrapolate displacement plots to improve interpolation near the
% boundary points.
% border_interp is the border added to the displacements when they are
% extrapolated.
border_interp = 20; % MUST BE GREATER THAN OR EQUAL TO 2!!!!
plot_u_interp = ncorr_alg_extrapdata(plot_u,roi_plot.formatted(),int32(border_interp));
plot_v_interp = ncorr_alg_extrapdata(plot_v,roi_plot.formatted(),int32(border_interp));
% Convert displacement plots to B-spline coefficients; these are used
% for interpolation. Make sure to do this for each region.
for i = 0:length(roi_plot.region)-1
plot_u_interp{i+1} = ncorr_class_img.form_bcoef(plot_u_interp{i+1});
plot_v_interp{i+1} = ncorr_class_img.form_bcoef(plot_v_interp{i+1});
end
% Initialize new boundary - preserve the number and
% correspondences of the "add" boundaries, even if a
% boundary is empty
boundary_update = struct('add',{},'sub',{});
for i = 0:length(obj.boundary)-1
boundary_update(i+1).add = interp_border(obj.boundary(i+1).add, ...
plot_u_interp{i+1}, ...
plot_v_interp{i+1}, ...
roi_plot, ...
i, ...
size_mask_update, ...
border_interp, ...
spacing, ...
radius);
for j = 0:length(obj.boundary(i+1).sub)-1
boundary_update(i+1).sub{j+1} = interp_border(obj.boundary(i+1).sub{j+1}, ...
plot_u_interp{i+1}, ...
plot_v_interp{i+1}, ...
roi_plot, ...
i, ...
size_mask_update, ...
border_interp, ...
spacing, ...
radius);
end
end
% Set new ROI - note that size_mask_update must be used
% instead of the size of the current mask. This is because
% different sized current images can be used.
roi_update = ncorr_class_roi;
roi_update.set_roi('boundary',struct('boundary',boundary_update,'size_mask',size_mask_update));
end
function roi_f = formatted(obj)
% This function returns the formatted ROI, which can be inputted to a
% mex function. Mex functions can receive ncorr_class_roi as either
% a class or structure.
%
% Inputs ---------------------------------------------------------%
% none;
%
% Outputs --------------------------------------------------------%
% roi_f - ncorr_class_roi; formatted ROI.
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
% Must make deep copy first
roi_f = ncorr_class_roi;
p = properties(obj);
for i = 0:length(p)-1
roi_f.(p{i+1}) = obj.(p{i+1});
end
% Now format properties
for i = 0:length(obj.region)-1
roi_f.region(i+1).nodelist = int32(roi_f.region(i+1).nodelist);
roi_f.region(i+1).noderange = int32(roi_f.region(i+1).noderange);
roi_f.region(i+1).leftbound = int32(roi_f.region(i+1).leftbound);
roi_f.region(i+1).rightbound = int32(roi_f.region(i+1).rightbound);
roi_f.region(i+1).upperbound = int32(roi_f.region(i+1).upperbound);
roi_f.region(i+1).lowerbound = int32(roi_f.region(i+1).lowerbound);
roi_f.region(i+1).totalpoints = int32(roi_f.region(i+1).totalpoints);
end
end
% ----------------------------------------------------------------%
% Get functions --------------------------------------------------%
% ----------------------------------------------------------------%
function [num_region,idx_nodelist] = get_num_region(obj,x,y,list_region)
% This function determines which region x and y lie in, excluding
% the regions indicated by list_region
%
% Inputs ---------------------------------------------------------%
% x - integer; x_coordinate
% y - integer; y_coordinate
% list_region - logical array; indices of regions to search
% if x and y are contained within it. If list_region(i) == true,
% then skip over region(i).
%
% Output ---------------------------------------------------------%
% num_region - integer; index of region that contains x
% and y. Returns -1 if x and y are not within the regions
% specified by region.
% idx_nodelist - integer; index of node pair that contains y
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
% Initialize outputs
num_region = -1;
idx_nodelist = 0;
% Initialize withinroi to false
withinroi = false;
for i = 0:length(obj.region)-1
if (list_region(i+1)) % Skip this ROI
continue;
else
if (x >= obj.region(i+1).leftbound && x <= obj.region(i+1).rightbound) % Check to make sure x coordinate is within bounds
idx_region = x-obj.region(i+1).leftbound;
for j = 0:2:obj.region(i+1).noderange(idx_region+1)-1 % Check to see if point is within node pairs
if (y >= obj.region(i+1).nodelist(idx_region+1,j+1) && y <= obj.region(i+1).nodelist(idx_region+1,j+2))
withinroi = true;
idx_nodelist = j;
num_region = i;
break;
end
end
end
if (withinroi)
break;
end
end
end
end
function regionmask = get_regionmask(obj,num_region)
% This function returns a mask corresponding only to the region
% indicated by num_region.
%
% Inputs ---------------------------------------------------------%
% num_region - integer; number of region to use to form mask.
%
% Outputs --------------------------------------------------------%
% regionmask - logical array; mask corresponding to num_region
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
regionmask = false(size(obj.mask));
for i = 0:size(obj.region(num_region+1).noderange,1)-1
x = i + obj.region(num_region+1).leftbound;
for j = 0:2:obj.region(num_region+1).noderange(i+1)-1
vec_y = obj.region(num_region+1).nodelist(i+1,j+1):obj.region(num_region+1).nodelist(i+1,j+2);
regionmask(vec_y+1,x+1) = true;
end
end
end
function total_fullregions = get_fullregions(obj)
% This function returns the number of regions which are
% nonempty. Generally used to see if ROI is empty or not.
%
% Inputs ---------------------------------------------------------%
% none;
%
% Outputs --------------------------------------------------------%
% total_fullregions - integer; number of nonemtpy regions
%
% Returns error if ROI has not been set yet.
if (isempty(obj.type))
error('ROI has not been set yet');
end
total_fullregions = 0;
for i = 0:length(obj.region)-1
if (obj.region(i+1).totalpoints > 0)
total_fullregions = total_fullregions+1;
end
end
end
function cirroi = get_cirroi(obj,x,y,radius,subsettrunc)
% This function returns a contiguous circular region for the subset
% located at x and y.
%
% Inputs ---------------------------------------------------------%
% x - integer; x_coordinate of subset
% y - integer; y_coordinate of subset
% radius - integer; radius of subset
% subsettrunc - logical; indicates whether to enable subset
% truncation or not
%
% Outputs --------------------------------------------------------%
% cirroi - circular subset; this is the circular subset
% corresponding to the points specified at x and y. Contains
% struct('mask',{},'region',{},'boundary',{},'x',{},'y',{},'radius',{})
%
% Returns error if ROI has not been set yet or if x and y are not
% within the ROI. Note that the boundary field in cirroi is
% currently not being used.
% Find idx_nodelist and num_region
[num_region,idx_nodelist] = obj.get_num_region(x,y,false(size(obj.region)));
if (isempty(obj.type))
error('ROI has not been set yet');
elseif (num_region == -1)
error('x and y coordinates are not within the ROI');
end
% Initialize cirroi structure
cirroi = struct('mask',{},'region',{},'boundary',{},'x',{},'y',{},'radius',{});
cirroi_template = struct('mask',{},'region',{},'boundary',{},'x',{},'y',{},'radius',{});
% Store x,y, and radius
cirroi_template(1).mask = false(2*radius+1);
cirroi_template.region = struct('nodelist',{},'noderange',{},'leftbound',{},'rightbound',{},'upperbound',{},'lowerbound',{},'totalpoints',{});
cirroi_template.boundary = [];
cirroi_template.x = x;
cirroi_template.y = y;
cirroi_template.radius = radius;
% Find max_nodewidth_buffer - this is the maximum width
% of the nodelist.
max_nodewidth_buffer = 0;
for i = 0:length(obj.region)-1
if (size(obj.region(i+1).nodelist,2) > max_nodewidth_buffer)
max_nodewidth_buffer = size(obj.region(i+1).nodelist,2);
end
end
% Initialize cirroi nodelist and noderange
cirroi_template.region(1).nodelist = -ones(cirroi_template.radius*2+1,max_nodewidth_buffer);
cirroi_template.region.noderange = zeros(cirroi_template.radius*2+1,1);
% Initialize totalpoints
cirroi_template.region.totalpoints = 0;
% Now find circle nodes
% Fill must be contiguous and begins at the centerpoint
queue_nodelist = -ones(size(cirroi_template.region.nodelist,1)*size(cirroi_template.region.nodelist,2),1); % Initialize to max size to prevent resizing
queue_nodeindex = zeros(size(cirroi_template.region.nodelist,1)*size(cirroi_template.region.nodelist,2)/2,1); % Index of nodepair with respect to cirroi;
length_queue = 0; %#ok<NASGU> % length of the queue_nodelist
queue_nodelist_buffer = -ones(1,2);
queue_nodeindex_buffer = 0; %#ok<NASGU>
% Initialize parameter which indicates whether the subset
% has been truncated
circ_untrunc = true;
% Node pair which contains the center point is added to queue first; this
% guarantees the circular region is contiguous WRT the centerpoint
if (obj.region(num_region+1).nodelist(cirroi_template.x-obj.region(num_region+1).leftbound+1,idx_nodelist+1) < cirroi_template.y-cirroi_template.radius) % make sure top node is within the circle
node_top = cirroi_template.y-cirroi_template.radius;
else
node_top = obj.region(num_region+1).nodelist(cirroi_template.x-obj.region(num_region+1).leftbound+1,idx_nodelist+1);
circ_untrunc = false;
end
if (obj.region(num_region+1).nodelist(cirroi_template.x-obj.region(num_region+1).leftbound+1,idx_nodelist+2) > cirroi_template.y+cirroi_template.radius) % make sure bottom node is within the circle
node_bottom = cirroi_template.y+cirroi_template.radius;
else
node_bottom = obj.region(num_region+1).nodelist(cirroi_template.x-obj.region(num_region+1).leftbound+1,idx_nodelist+2);
circ_untrunc = false;
end
% Update mask
cirroi_template.mask(node_top-(cirroi_template.y-cirroi_template.radius)+1:node_bottom-(cirroi_template.y-cirroi_template.radius)+1,cirroi_template.radius+1) = true;
% Update queue
queue_nodelist(1:2) = [node_top node_bottom];
queue_nodeindex(1) = cirroi_template.radius;
length_queue = 2;
% Form activelines and then inactivate nodepair from nodelist
% Activelines keeps track of which node pairs have been
% analyzed
activelines = true(size(obj.region(num_region+1).nodelist,1),size(obj.region(num_region+1).nodelist,2)/2);
activelines((cirroi_template.x-obj.region(num_region+1).leftbound)+1,idx_nodelist/2+1) = false;
% Enter while loop. Exit when queue is empty
while (length_queue ~= 0)
% STEPS:
% 1) Load nodepair from queue
% 2) Update queue
% 3) Add nodepair to cirroi, sort, and then update
% 4) Compare nodepair to nodepairs left and right and add nodes to queue
% 5) Update totalpoints
% Step 1) Pop queue
queue_nodelist_buffer(1:2) = queue_nodelist(length_queue-1:length_queue);
queue_nodeindex_buffer = queue_nodeindex(length_queue/2);
% Step 2)
length_queue = length_queue-2;
% Step 3)
if (cirroi_template.region.noderange(queue_nodeindex_buffer+1) == 0)
% Just place directly
cirroi_template.region.nodelist(queue_nodeindex_buffer+1,1:2) = queue_nodelist_buffer(1:2);
else
% Merge nodes
inserted = false;
for i = 0:2:cirroi_template.region.noderange(queue_nodeindex_buffer+1)-1
if (queue_nodelist_buffer(2) < cirroi_template.region.nodelist(queue_nodeindex_buffer+1,i+1))
nodelist_buffer = cirroi_template.region.nodelist(queue_nodeindex_buffer+1,i+1:cirroi_template.region.noderange(queue_nodeindex_buffer+1));
cirroi_template.region.nodelist(queue_nodeindex_buffer+1,i+1:i+2) = queue_nodelist_buffer;
cirroi_template.region.nodelist(queue_nodeindex_buffer+1,i+3:cirroi_template.region.noderange(queue_nodeindex_buffer+1)+2) = nodelist_buffer;
inserted = true;
break
end
end
if (~inserted)
% Append at the end
cirroi_template.region.nodelist(queue_nodeindex_buffer+1,cirroi_template.region.noderange(queue_nodeindex_buffer+1)+1:cirroi_template.region.noderange(queue_nodeindex_buffer+1)+2) = queue_nodelist_buffer;
end
end
cirroi_template.region.noderange(queue_nodeindex_buffer+1) = cirroi_template.region.noderange(queue_nodeindex_buffer+1)+2;
% Step 4)
idx_froi = queue_nodeindex_buffer+(cirroi_template.x-cirroi_template.radius)-obj.region(num_region+1).leftbound;
% Compare to node pairs LEFT
if (queue_nodeindex_buffer > 0 && idx_froi > 0) % makes sure previous node is within cirroi
for i = 0:2:obj.region(num_region+1).noderange(idx_froi)-1
if (activelines(idx_froi,i/2+1) == 0) % Nodes are inactive
continue
end
upperlim = ceil(-sqrt(cirroi_template.radius^2-(((queue_nodeindex_buffer-1)+(cirroi_template.x-cirroi_template.radius))-cirroi_template.x)^2)+cirroi_template.y);
lowerlim = floor(sqrt(cirroi_template.radius^2-(((queue_nodeindex_buffer-1)+(cirroi_template.x-cirroi_template.radius))-cirroi_template.x)^2)+cirroi_template.y);
if (obj.region(num_region+1).nodelist(idx_froi,i+2) < queue_nodelist_buffer(1)) % lower node comes before upper node of buffer
continue;
elseif (obj.region(num_region+1).nodelist(idx_froi,i+1) <= queue_nodelist_buffer(2) && obj.region(num_region+1).nodelist(idx_froi,i+2) >= queue_nodelist_buffer(1)) % nodes interact
if (obj.region(num_region+1).nodelist(idx_froi,i+1) < upperlim) % make sure upper node is within the circle
node_top = upperlim;
else
node_top = obj.region(num_region+1).nodelist(idx_froi,i+1);
circ_untrunc = false;
end
if (obj.region(num_region+1).nodelist(idx_froi,i+2) > lowerlim) % make sure lower node is within the circle
node_bottom = lowerlim;
else
node_bottom = obj.region(num_region+1).nodelist(idx_froi,i+2);
circ_untrunc = false;
end
if (node_top > node_bottom || node_top > queue_nodelist_buffer(2) || node_bottom < queue_nodelist_buffer(1)) % This can occur along diagonal boundaries by virtue of how the four way direction contiguous algorithm works. If this happens, break, because it is no longer contiugous
continue;
end
% Add to queue
queue_nodelist(length_queue+1:length_queue+2) = [node_top node_bottom]; % add to queue
queue_nodeindex(length_queue/2+1) = queue_nodeindex_buffer-1;
length_queue = length_queue + 2;
% Make node pair inactive
activelines((idx_froi-1)+1,i/2+1) = false;
% Update mask
cirroi_template.mask(node_top-(cirroi_template.y-cirroi_template.radius)+1:node_bottom-(cirroi_template.y-cirroi_template.radius)+1,queue_nodeindex_buffer) = true;
else
break;
end
end
end
% Compare to node pairs RIGHT
if (queue_nodeindex_buffer < 2*cirroi_template.radius && idx_froi < obj.region(num_region+1).rightbound-obj.region(num_region+1).leftbound) % makes sure next node is within cirroiint
for i = 0:2:obj.region(num_region+1).noderange(idx_froi+2)-1
if (activelines(idx_froi+2,i/2+1) == 0)
continue
end
upperlim = ceil(-sqrt(cirroi_template.radius^2-(((queue_nodeindex_buffer+1)+(cirroi_template.x-cirroi_template.radius))-cirroi_template.x)^2)+cirroi_template.y);
lowerlim = floor(sqrt(cirroi_template.radius^2-(((queue_nodeindex_buffer+1)+(cirroi_template.x-cirroi_template.radius))-cirroi_template.x)^2)+cirroi_template.y);
if (obj.region(num_region+1).nodelist(idx_froi+2,i+2) < queue_nodelist_buffer(1)) % lower node comes before upper node of buffer
continue;
elseif (obj.region(num_region+1).nodelist(idx_froi+2,i+1) <= queue_nodelist_buffer(2) && obj.region(num_region+1).nodelist(idx_froi+2,i+2) >= queue_nodelist_buffer(1)) % nodes interact
if (obj.region(num_region+1).nodelist(idx_froi+2,i+1) < upperlim) % make sure upper node is within the circle
node_top = upperlim;
else
node_top = obj.region(num_region+1).nodelist(idx_froi+2,i+1);
circ_untrunc = false;
end
if (obj.region(num_region+1).nodelist(idx_froi+2,i+2) > lowerlim) % make sure lower node is within the circle
node_bottom = lowerlim;
else
node_bottom = obj.region(num_region+1).nodelist(idx_froi+2,i+2);
circ_untrunc = false;
end
if (node_top > node_bottom || node_top > queue_nodelist_buffer(2) || node_bottom < queue_nodelist_buffer(1)) % This can occur along diagonal boundaries by virtue of how the four way direction contiguous algorithm works. If this happens, break, because it is no longer contiugous
continue;
end
% Add to queue
queue_nodelist(length_queue+1:length_queue+2) = [node_top node_bottom]; % add to queue
queue_nodeindex(length_queue/2+1) = queue_nodeindex_buffer+1; %
length_queue = length_queue + 2;
% Make node pair inactive
activelines((idx_froi+1)+1,i/2+1) = false;
% Update mask
cirroi_template.mask(node_top-(cirroi_template.y-cirroi_template.radius)+1:node_bottom-(cirroi_template.y-cirroi_template.radius)+1,queue_nodeindex_buffer+2) = true;
else
break;
end
end
end
% Update totalpoints
cirroi_template.region.totalpoints = cirroi_template.region.totalpoints + (queue_nodelist_buffer(2)-queue_nodelist_buffer(1)+1);
end
% Set Bounds - since noderange length is always
% 2*radius+1, set left and right bounds to:
cirroi_template.region.leftbound = cirroi_template.x - cirroi_template.radius;
cirroi_template.region.rightbound = cirroi_template.x + cirroi_template.radius;
% Find upper and lower bounds:
cirroi_template.region.upperbound = size(obj.mask,1);
cirroi_template.region.lowerbound = 0;
for i = 0:size(cirroi_template.region.noderange,1)-1 % Find max and min x-values of cirroi
if (cirroi_template.region.noderange(i+1) > 0)
if (cirroi_template.region.upperbound > cirroi_template.region.nodelist(i+1,1))
cirroi_template.region.upperbound = cirroi_template.region.nodelist(i+1,1);
end
if (cirroi_template.region.lowerbound < cirroi_template.region.nodelist(i+1,cirroi_template.region.noderange(i+1)))
cirroi_template.region.lowerbound = cirroi_template.region.nodelist(i+1,cirroi_template.region.noderange(i+1));
end
end
end
% If subset is truncated, do some special analysis to construct
% the cirroi. At this point, it's only contiguous. I've added
% this portion to truncate a part of the subset if this option
% is enabled. This is helpful for analyzing cracks so the subset
% does not wrap around the crack tip. Also make sure to check
% if any of the noderanges are zero, as this will not trigger a
% truncation.
if (subsettrunc && (~circ_untrunc || any(cirroi_template.region.noderange == 0)))
% Get boundary
point_topleft = [-1 -1]; % Initialize
for i = 0:size(cirroi_template.mask,2)-1
for j = 0:size(cirroi_template.mask,1)-1
if (cirroi_template.mask(j+1,i+1))
point_topleft = [i j]; % This is the first point.
break;
end
end
if (cirroi_template.mask(j+1,i+1))
break;
end
end
boundary_cirroi = ncorr_alg_formboundary(int32(point_topleft),int32(7),cirroi_template.mask);
% Find closest point -> Find line equation -> Find
% number of points to the left and right of the
% line; the side with the least amount of points
% will be discarded
dists = (boundary_cirroi(:,1)-cirroi_template.radius).^2 + (boundary_cirroi(:,2)-cirroi_template.radius).^2;
[val_min,idx_min] = min(dists);
idx_min = idx_min-1; % Zero based indexing
% Make sure closest point is not on the boundary,
% which can happen since the boundary isnt
% perfectly circular
if (ceil(sqrt(val_min)) < cirroi_template.radius)
% Nonlinear solver
idx_space = 3;
idx_plus = mod(idx_min+idx_space,size(boundary_cirroi,1));
idx_minus = mod(idx_min-idx_space,size(boundary_cirroi,1));
% Initialize points to calculate derivatives with
x_plus_f = 0;
x_min_f = 0;
x_minus_f = 0;
y_plus_f = 0;
y_min_f = 0;
y_minus_f = 0;
% Set filt length
length_filt = 2;
for i = -length_filt:length_filt
x_plus_f = x_plus_f + boundary_cirroi(mod(idx_plus+i,size(boundary_cirroi,1))+1,1);
x_min_f = x_min_f + boundary_cirroi(mod(idx_min+i,size(boundary_cirroi,1))+1,1);
x_minus_f = x_minus_f + boundary_cirroi(mod(idx_minus+i,size(boundary_cirroi,1))+1,1);
y_plus_f = y_plus_f + boundary_cirroi(mod(idx_plus+i,size(boundary_cirroi,1))+1,2);
y_min_f = y_min_f + boundary_cirroi(mod(idx_min+i,size(boundary_cirroi,1))+1,2);
y_minus_f = y_minus_f + boundary_cirroi(mod(idx_minus+i,size(boundary_cirroi,1))+1,2);
end
% Divide by length
x_plus_f = x_plus_f/(2*length_filt+1);
x_min_f = x_min_f/(2*length_filt+1);
x_minus_f = x_minus_f/(2*length_filt+1);
y_plus_f = y_plus_f/(2*length_filt+1);
y_min_f = y_min_f/(2*length_filt+1);
y_minus_f = y_minus_f/(2*length_filt+1);
% Get derivatives
dx_di_f = (x_plus_f - x_minus_f)/(2*idx_space);
d2x_di2_f = (x_plus_f-2*x_min_f+x_minus_f)/(idx_space^2);
dy_di_f = (y_plus_f - y_minus_f)/(2*idx_space);
d2y_di2_f = (y_plus_f-2*y_min_f+y_minus_f)/(idx_space^2);
% Do one iteration to find change in index
deltai = ((-x_min_f*dx_di_f+cirroi_template.radius*dx_di_f) + (-y_min_f*dy_di_f+cirroi_template.radius*dy_di_f))/((dx_di_f^2+x_min_f*d2x_di2_f-cirroi_template.radius*d2x_di2_f)+(dy_di_f^2+y_min_f*d2y_di2_f-cirroi_template.radius*d2y_di2_f));
% Test deltai, make sure its between subsequent spacings; If
% not then set the points minus and plus points
if (abs(deltai) < idx_space)
% Calculate two points based on dx_di_i and dy_di_i
x_i = x_min_f + dx_di_f*deltai + (1/2)*d2x_di2_f*deltai^2;
y_i = y_min_f + dy_di_f*deltai + (1/2)*d2y_di2_f*deltai^2;
dx_di_i = dx_di_f + d2x_di2_f*deltai;
dy_di_i = dy_di_f + d2y_di2_f*deltai;
% Set stepsize - the magnitude doesnt matter
stepsize = 0.5;
% Get points
p0 = [x_i-dx_di_i*stepsize y_i-dy_di_i*stepsize];
p1 = [x_i+dx_di_i*stepsize y_i+dy_di_i*stepsize];
else
% Set points to averaged points on either side
p0 = [x_minus_f y_minus_f];
p1 = [x_plus_f y_plus_f];
end
% Find which side to clear: p_subset is a point defined
% to be part of the subset, so the side opposite of
% p_subset needs to be cleared. If the center of the
% subset does not lie on boundary, then find displacement
% from closest point to p0. Add this displacement to
% the center, and then determine which side the center
% is on.
p_subset = [0 0]; % Initialize
if (isequal(boundary_cirroi(idx_min+1,:),[cirroi_template.radius cirroi_template.radius]))
% Center is the closest point. Find valid points
% around the boundary and get the centroid of
% these points.
width_win = 1; % This determines window of points collected
counter = 0; % Counts number of points added so a proper average can be taken
for i = -width_win:width_win
x_mask = boundary_cirroi(idx_min+1,1)+i;
for j = -width_win:width_win
y_mask = boundary_cirroi(idx_min+1,2)+j;
% Make sure points are within mask and
% that the mask is valid here.
if (x_mask >= 0 && x_mask <= 2*cirroi_template.radius && y_mask >= 0 && y_mask <= 2*cirroi_template.radius && ...
cirroi_template.mask(y_mask+1,x_mask+1))
p_subset = p_subset + [x_mask y_mask];
counter = counter+1;
end
end
end
% Divide by counter to get the average
p_subset = p_subset/counter;
% Debug ------%
%{
figure(1); imshow(cirroi_template.mask); hold on;
plot(p0(1,1),p0(1,2),'rx');
plot(p1(1,1),p1(1,2),'rx');
plot(p_subset(1,1),p_subset(1,2),'gx');
hold off;
%}
% ------------%
else
% Set the center point
p_subset = [cirroi_template.radius cirroi_template.radius];
% Debug ------%
%{
figure(1); imshow(cirroi_template.mask); hold on;
plot(p0(1,1),p0(1,2),'rx');
plot(p1(1,1),p1(1,2),'rx');
plot(p_subset(1,1),p_subset(1,2),'gx');
hold off;
%}
% ------------%
end
% Normalize point against line since it can shift
disp_p0 = p0 - boundary_cirroi(idx_min+1,:);
p_subset = p_subset + disp_p0;
% Now determine which side p_subset lies and
% clear the other side
sign_clear = -sign((p1(1)-p0(1))*(p_subset(2)-p0(2))-(p_subset(1)-p0(1))*(p1(2)-p0(2)));
mask_cirroi_prelim = cirroi_template.mask; % Make a copy
for i = 0:size(cirroi_template.region.noderange,1)-1
for j = 0:2:cirroi_template.region.noderange(i+1)-1
for k = cirroi_template.region.nodelist(i+1,j+1):cirroi_template.region.nodelist(i+1,j+2)
p2 = [i k-(cirroi_template.y-cirroi_template.radius)];
if (sign((p1(1)-p0(1))*(p2(2)-p0(2))-(p2(1)-p0(1))*(p1(2)-p0(2))) == sign_clear)
% Clear points on this side
mask_cirroi_prelim(p2(2)+1,p2(1)+1) = false;
end
end
end
end
% Get region again from the mask, then select the
% biggest region. This is required because subset
% truncation does not preserve the cirroi's contiguous
% nature. Setting the last parameter to true for
% formregion will make the length of the noderange the
% same as the width of the mask
[region_cirroi_prelim,removed] = ncorr_alg_formregions(mask_cirroi_prelim,int32(0),true); %#ok<NASGU>
% Its possible for region to be empty. Must check it. If
% its empty, then abandon subset truncation.
if (~isempty(region_cirroi_prelim))
% Only keep the region with the max number of
% totalpoints
region_cirroi_prelim = region_cirroi_prelim([region_cirroi_prelim.totalpoints] == max([region_cirroi_prelim.totalpoints]));
% Update mask then store it
mask_cirroi_prelim(:) = false;
for i = 0:size(cirroi_template.region.noderange,1)-1
for j = 0:2:region_cirroi_prelim.noderange(i+1)-1
for k = region_cirroi_prelim.nodelist(i+1,j+1):region_cirroi_prelim.nodelist(i+1,j+2)
mask_cirroi_prelim(k+1,i+1) = true;
end
end
end
% Store mask
cirroi_template.mask = mask_cirroi_prelim;
% Store region with greatest number of nodes
cirroi_template.region = region_cirroi_prelim;
% Bring back to regular coords
for i = 0:size(cirroi_template.region.noderange,1)-1
if (cirroi_template.region.noderange(i+1) > 0)
cirroi_template.region.nodelist(i+1,1:cirroi_template.region.noderange(i+1)) = cirroi_template.region.nodelist(i+1,1:cirroi_template.region.noderange(i+1)) + (cirroi_template.y-cirroi_template.radius);
end
end
cirroi_template.region.leftbound = cirroi_template.region.leftbound + (cirroi_template.x-cirroi_template.radius);
cirroi_template.region.rightbound = cirroi_template.region.rightbound + (cirroi_template.x-cirroi_template.radius);
cirroi_template.region.upperbound = cirroi_template.region.upperbound + (cirroi_template.y-cirroi_template.radius);
cirroi_template.region.lowerbound = cirroi_template.region.lowerbound + (cirroi_template.y-cirroi_template.radius);
end
% Debug
%{
figure(2), imshow(cirroi_template.mask);
hold on;
plot(boundary_cirroi(idx_min+1,1)+1,boundary_cirroi(idx_min+1,2)+1,'bx');
plot(p0(1)+1,p0(2)+1,'gs');
plot(p1(1)+1,p1(2)+1,'gs');
hold off;
%}
end
end
%-----------------------------------------------------%
%-----------------------------------------------------%
%-----------------------------------------------------%
% Assign outputs
cirroi(1) = cirroi_template;
end
%-----------------------------------------------------------------%
% For debugging --------------------------------------------------%
%-----------------------------------------------------------------%
function debug_region(obj)
if (isempty(obj.type))
error('ROI has not been set yet');
end
mask_debug = false(size(obj.mask));
for i = 0:length(obj.region)-1
regionmask_debug = false(size(obj.mask));
for j = 0:size(obj.region(i+1).noderange,1)-1
x = j + obj.region(i+1).leftbound;
for k = 0:2:obj.region(i+1).noderange(j+1)-1
vec_y = obj.region(i+1).nodelist(j+1,k+1):obj.region(i+1).nodelist(j+1,k+2);
mask_debug(vec_y+1,x+1) = true;
regionmask_debug(vec_y+1,x+1) = true;
end
end
% figure, imshow(regionmask_debug); - This can potential be a lot of figures
end
figure, imshow(mask_debug);
if (isequal(mask_debug,obj.mask))
disp('SUCCESS - mask matches region');
else
error('FAILURE - for some reason mask and region are different');
end
end
function debug_boundary(obj)
if (isempty(obj.type))
error('ROI has not been set yet');
end
figure, imshow(obj.mask);
hold on;
for i = 0:length(obj.boundary)-1
plot(obj.boundary(i+1).add(:,1)+1,obj.boundary(i+1).add(:,2)+1,'go');
for j = 0:length(obj.boundary(i+1).sub)-1
plot(obj.boundary(i+1).sub{j+1}(:,1)+1,obj.boundary(i+1).sub{j+1}(:,2)+1,'rx');
end
end
hold off;
end
end
end
function boundary_update = interp_border(boundary,plot_u_interp,plot_v_interp,roi,num_region,size_mask_update,border_interp,spacing,radius)
% Updates boundary based on old boundary and displacement plots.
% Does not preserve length of the boundary. If points are found to travel
% outside a radius length around the size_mask_update, they are discarded.
%
% Inputs -----------------------------------------------------------------%
% boundary - double array; boundary we're trying to update - uses pixel
% units.
% plot_u_interp - double array; b-spline coefficients of u displacement
% field
% plot_v_interp - double array; b-spline coefficients of v displacement
% field
% roi - ncorr_class_roi; ROI corresponding to displacement fields. Note
% that roi is reduced.
% num_region - integer; number corresponding to region
% size_mask_update - integer array; size of the new mask (can be different
% from the mask in ROI if different sized current images are used).
% border_interp - integer; border around b-spline coefficients
% spacing - integer; spacing parameter
% radius - integer; subset radius
%
% Outputs ----------------------------------------------------------------%
% boundary_update - double array; updated boundary coordinates
%
% Note, if boundary_update is found to be empty after analysis, it will
% return [-1 -1] so it is not empty. This is a temporary workaround because
% the ncorr_alg_formmask function does not support empty polygons.
% Get scaled coordinates since displacement plots are reduced.
boundary_scaled = boundary/(spacing+1);
% Get interpolated u displacements - can return NaN if out of range
interp_u = ncorr_alg_interpqbs(boundary_scaled,plot_u_interp,roi.region(num_region+1).leftbound,roi.region(num_region+1).upperbound,border_interp);
% Get interpolated v displacements - can return NaN if out of range
interp_v = ncorr_alg_interpqbs(boundary_scaled,plot_v_interp,roi.region(num_region+1).leftbound,roi.region(num_region+1).upperbound,border_interp);
% Update boundary
boundary_update = boundary;
boundary_update(:,1) = boundary_update(:,1) + interp_u;
boundary_update(:,2) = boundary_update(:,2) + interp_v;
% Set points near boundary to NaN;
for i = 0:size(boundary_update,1)-1
if (boundary_update(i+1,1) < radius || boundary_update(i+1,1) > size_mask_update(2)-radius || ...
boundary_update(i+1,2) < radius || boundary_update(i+1,2) > size_mask_update(1)-radius)
boundary_update(i+1,:) = NaN;
end
end
% Remove all coordinates that have NaN
counter = 0;
while (counter < size(boundary_update,1))
if (any(isnan(boundary_update(counter+1,:))))
boundary_update(counter+1,:) = [];
counter = counter-1;
end
counter = counter+1;
end
% Check to see if boundary is empty
if (isempty(boundary_update))
boundary_update = [-1 -1];
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr.m
|
.m
|
choco-packages-master/packages/matlab-ciser/tools/ncorr/ncorr.m
| 215,473 |
utf_8
|
0869c73f18c3ca178d6efe7202e0fe69
|
classdef ncorr < handle
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% Version: 1.2.2
% Date: 6/13/2017
% Programmed by: Justin Blaber
% Principle Investigator: Antonia Antoniou
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% Start Ncorr with:
%
% handles_ncorr = ncorr;
%
% NOTE: Images/masks can be set using the GUI menu or by using
% "handles_ncorr.set_ref(data)", "handles_ncorr.set_cur(data)",
% "handles_ncorr.set_roi_ref(data)", or "handles_ncorr.set_roi_cur(data)".
% These will manually set the reference image, current image(s), or
% region of interest if these have been calculated or
% modified using MATLAB and exist in the main workspace. Sometimes the
% reference and current images can be obtained using an average of a
% series of images. The region of interest can also be calculated using
% various thresholding and edge detecting algorithms. Displacement and
% strain data can be obtained through handles_ncorr.data_dic in case the
% user is interested in doing further calculations on the deformation
% data. In addition, if the menu freezes for some reason due to an error,
% it can be unfrozen with "handles_ncorr.refresh()". Lastly, calling
% "delete(handles_ncorr)" will force close Ncorr.
%
%
% MAIN CONSIDERATIONS:
%
% 1) All program data and appdata in the ncorr object are SET by callbacks directly.
% 2) "Downstream" program data (i.e. dependent data) and appdata are
% CLEARED with the "clear_downstream()" function before setting the
% new data.
% 3) UI objects are modified by the update* functions through the wrapper
% function "util_wrapcallbackall" and not within callback directly.
%
% The point of doing this was to make each callback as clear and
% uncluttered as possible. The clearing of "downstream" data and updating
% of UI controls are mainly for upkeep.
%
%
% MAIN FLOW OF CALLBACK:
%
% 1) Update UI controls. Generally, if a menu option updates information,
% it will freeze the top menu to prevent users from calling other
% options while the first one is running.
% 2) Check if data will be overwritten with: "overwrite = clear_downstream('callback')"
% This returns a logical value which is true if the user chooses
% to proceed and also clears the downstream data.
% 3) Perform calculations
% 4) If calculations succeed, store the data directly in the callback
% 5) Update UI controls. This unfreezes the top menu and updates it,
% as well as sets any images (such as the reference/current image)
% if they were loaded.
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% NCORR_GUI* FUNCTIONS:
%
% These functions contain GUIs which are called by the callbacks within
% this "ncorr" object. These are, unlike "ncorr," functions that
% utilize "uiwait" and nested functions instead of an object. Thus, when
% the function returns, all workspace data within those functions get
% cleared. Some of these ncorr_gui* functions have an input called
% "params_init" which contains initialization data if the function has
% been called before. Most of these functions use a modal window because
% they must be set before proceeding. These figure are generally not
% resizeable, and their size is checked with "ncorr_util_formatwindow" to
% ensure the top right edges of the window are within the screen.
%
% The initialization of the ncorr_gui_functions generally proceeds as:
%
% 1) Initialize outputs
% 2) Create GUI handles
% 3) Run the constructor function
%
% The callbacks have the general flow:
%
% 1) Possibly freeze menu if it exists
% 2) Get data with "getappdata()"
% 3) Perform calculations
% 4) Set data with "setappdata()"
% 5) Possibly unfreeze menu if it exists and update UI controls
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% NCORR_ALG* FUNCTIONS:
%
% These functions contain source-code for algorithms used with the ncorr
% object callbacks and ncorr_gui* functions. Most of these algorithms are
% mex files written in C++ and must be compiled with "compile_func_cpp_mex()"
% or mex before using ncorr.
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
%
% NCORR_UTIL* FUNCTIONS:
%
% These functions contain certain utilities used by ncorr, such as
% checking whether the window is within the screen, formatting a colobar,
% etc.
%
%-------------------------------------------------------------------------%
%-------------------------------------------------------------------------%
properties (SetAccess = private)
% GUI handles:
handles_gui;
% DIC data:
reference;
current;
data_dic;
% Installation data:
support_openmp;
total_cores;
end
% Constructor
methods(Access = public)
function obj = ncorr
% Set default UI control font size here before UI opens. Larger
% font sizes can make the GUI too large. This seems to be an
% error in earlier versions of Matlab
set(0,'defaultuicontrolfontsize',7);
% Initialize GUI and get GUI handles
obj.handles_gui = init_gui(obj);
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@obj.constructor,obj.handles_gui.figure));
end
% Constructor ----------------------------------------------------%
function constructor(obj)
% Check MATLAB version and toolbox compatibility -------------%
if (obj.check_matlabcompat() ~= out.success)
% Force close
obj.callback_close_function([],[],true);
return;
end
% Check MEX installation and load/set ncorr_installinfo.txt --%
if (obj.check_mexinstall() ~= out.success)
% Force close
obj.callback_close_function([],[],true);
return;
end
% Set path ---------------------------------------------------%
% Path to ncorr install directory must be set or else program
% can freeze when loading images from a different directory -
% not sure why this happens.
% Note that if ncorr.m is not in the current directory, then
% path has already been set.
listing = dir;
if (isempty(strfind(lower(path),lower(pwd))) && any(strcmp('ncorr.m',{listing.name})))
% Ask user if its okay to add path
contbutton = questdlg('Path has not been set. Path must be set before running program. Press yes to add path.','Continue Operation','Yes','No','Yes');
if (strcmp(contbutton,'Yes'))
% Add Path
path(path,pwd);
else
% Force close, ncorr may not to work if path is not set
obj.callback_close_function([],[],true);
return;
end
end
% Initialize opengl ------------------------------------------%
% In earlier versions of Matlab this will fix inverted plots
% Plotting tools are also run based on opengl
if (ispc)
data_opengl = opengl('data');
if (~data_opengl.Software)
% Set opengl to software
opengl('software');
end
end
% Start timer to fetch name of the handle that points to ncorr.
% Use a timer because, to my knowledge, there isn't a callback
% option if the handle pointing to ncorr gets cleared.
timer_ncorr = timer('executionMode', 'fixedRate', ...
'Period', 1/5, ...
'TimerFcn', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_update_title(obj,hObject,eventdata),obj.handles_gui.figure));
start(timer_ncorr);
% Program Data -----------------------------------------------%
% Reference image info
obj.reference = struct('imginfo',{},'roi',{});
% Current image(s) info
obj.current = struct('imginfo',{},'roi',{});
% DIC data
obj.data_dic = struct('displacements',struct('plot_u_dic',{}, ... % U plot after DIC (can be regular or eulerian)
'plot_v_dic',{}, ... % V plot after DIC (can be regular or eulerian)
'plot_corrcoef_dic',{}, ... % Correlaton coef plot after DIC (can be regular or eulerian)
'roi_dic',{}, ... % ROI after DIC
'plot_u_ref_formatted',{}, ... % formatted U plot WRT reference image used for displaying displacements
'plot_v_ref_formatted',{}, ... % formatted V plot WRT reference image used for displaying displacements
'roi_ref_formatted',{}, ... % ROI after formatting used for plotting displacements
'plot_u_cur_formatted',{}, ... % formatted U plot WRT current image used for displaying displacements
'plot_v_cur_formatted',{}, ... % formatted V plot WRT current image used for displaying displacements
'roi_cur_formatted',{}), ... % ROI after formatting used for plotting displacements
'dispinfo',struct('type',{}, ... % Type of DIC: either regular or backward
'radius',{}, ... % Radius for DIC
'spacing',{}, ... % Spacing for DIC
'cutoff_diffnorm',{}, ... % Cutoff for norm of the difference vector
'cutoff_iteration',{}, ... % Cutoff for the number of iterations
'total_threads',{}, ... % Number of threads for computation
'stepanalysis',struct('enabled',{},'type',{},'auto',{},'step',{}), ... % Indicates whether or not to implement step analysis for high strain
'subsettrunc',{}, ... % Indicates whether or not to implement subset truncation for DIC analysis
'imgcorr',struct('idx_ref',{},'idx_cur',{}), ... % Image correspondences
'pixtounits',{}, ... % Ratio of "units" to pixels. Assumes pixels are square
'units',{}, ... % String to display units
'cutoff_corrcoef',{}, ... % Correlation coefficient cutoff for each formatted displacement plot
'lenscoef',{}), ... % Radial lens distortion coefficient
'strains',struct('plot_exx_ref_formatted',{}, ... % Exx Green-Lagragian strain plot
'plot_exy_ref_formatted',{}, ... % Exy Green-Lagragian strain plot
'plot_eyy_ref_formatted',{}, ... % Exy Green-Lagragian strain plot
'roi_ref_formatted',{}, ... % ROI used for plotting strains
'plot_exx_cur_formatted',{}, ... % Exx Eulerian-Almansi strain plot
'plot_exy_cur_formatted',{}, ... % Exy Eulerian-Almansi strain plot
'plot_eyy_cur_formatted',{}, ... % Exy Eulerian-Almansi strain plot
'roi_cur_formatted',{}), ... % ROI used for plotting strains
'straininfo',struct('radius',{}, ... % Strain radius used for calculating strains
'subsettrunc',{})); % Indicates whether or not to implement subset truncation for strain analysis
% Appdata - setting these to '[]' technically does nothing, but
% it is included here to show what appdata are/will be present in the
% figure
% handles_plot are the handles for the data plots:
setappdata(obj.handles_gui.figure,'handles_plot',[]);
% num_cur is the current image which is currently being displayed:
setappdata(obj.handles_gui.figure,'num_cur',[]);
% timer_ncorr is the timer for this instantiation of ncorr;
% it is used for fetching the name of the handle points to
% ncorr in the current workspace
setappdata(obj.handles_gui.figure,'timer',timer_ncorr);
% Set visible
set(obj.handles_gui.figure,'Visible','on');
end
% Destructor -----------------------------------------------------%
% This ensures data is deleted if delete is called directly on the
% ncorr handle.
function delete(obj)
if (ishandle(obj.handles_gui.figure))
% Setting 3rd argument to true results in a force close.
obj.callback_close_function([],[],true);
end
end
% Public methods -------------------------------------------------%
% These are used for setting the reference image, current image, or
% ROI manually.
function set_ref(obj,ref_prelim)
% Form wrapped function
handle_set_ref = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(ref_prelim)set_ref_source(obj,ref_prelim),obj.handles_gui.figure));
% Call wrapped function
handle_set_ref(ref_prelim);
end
function set_cur(obj,cur_prelim)
% Form wrapped function
handle_set_cur = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(cur_prelim)set_cur_source(obj,cur_prelim),obj.handles_gui.figure));
% Call wrapped function
handle_set_cur(cur_prelim);
end
function set_roi_ref(obj,mask_prelim)
% Form wrapped function
handle_set_roi_ref = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(mask_prelim)set_roi_ref_source(obj,mask_prelim),obj.handles_gui.figure));
% Call wrapped function
handle_set_roi_ref(mask_prelim);
end
function set_roi_cur(obj,mask_prelim)
% Form wrapped function
handle_set_roi_cur = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(mask_prelim)set_roi_cur_source(obj,mask_prelim),obj.handles_gui.figure));
% Call wrapped function
handle_set_roi_cur(mask_prelim);
end
function refresh(obj)
% Form wrapped function
handle_refresh = obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@()refresh_source(obj),obj.handles_gui.figure));
% Call wrapped function
handle_refresh();
end
end
methods(Access = private)
% ----------------------------------------------------------------%
% Local Utility Function(s) --------------------------------------%
% ----------------------------------------------------------------%
function handle_wrapcallback = util_wrapcallbackall(obj,handle_callback)
% This function wraps the callback with the update* UI functions. It
% also checks to see if an error was generated, and if it was, it
% will rethrow it and recomplete the finishing update* UI functions
% to ensure the menu unfreezes. Note that the error will not be
% rethrown if the figure is closed.
%
% Inputs ---------------------------------------------------------%
% handle_callback - function handle;
%
% Outputs --------------------------------------------------------%
% handle_wrapcallback - function handle;
handle_wrapcallback = @updatestatecallback;
function updatestatecallback(varargin)
try
% Beginning of callback - freeze menu;
obj.freeze_menu();
% Run callback
handle_callback(varargin{:});
% End of callback;
% Update axes
obj.update_axes('set');
% Update UI menu
obj.update_topmenu();
% Update state text
obj.update_dicstatetext();
% Unfreeze top layer of menu
obj.unfreeze_menu();
catch err
% If figure still exists, update UI and then rethrow
% error
if (isvalid(obj) && ishandle(obj.handles_gui.figure))
% Error is generated in callback
obj.update_axes('set');
% Update UI menu
obj.update_topmenu();
% Update state text
obj.update_dicstatetext();
% Unfreeze top layer of menu
obj.unfreeze_menu();
% Rethrow error
rethrow(err);
end
end
end
end
function name = util_get_name(obj)
% This function will obtain the name of the variable in the main
% workspace that points to this ncorr object
% Initialize output
name = '';
% Get all variables in base workspace
basevars = evalin('base','whos');
% Grab variables of class ncorr
ncorrvars = basevars(strcmp({basevars.class},class(obj)));
% Cycle through variables and find which one is equivalent to
% this object
for i = 1:length(ncorrvars)
if (eq(evalin('base',ncorrvars(i).name),obj))
% Its possible there are more than one handle that
% point to this object, if that's the case just return
% the first one
name = ncorrvars(i).name;
break;
end
end
end
%-----------------------------------------------------------------%
% Handle Functions Source ----------------------------------------%
%-----------------------------------------------------------------%
function set_ref_source(obj,ref_prelim)
% This function allows the manual uploading of a reference image;
% only a single image is permitted.
% Check to make sure input is of the correct form
if (ncorr_util_properimgfmt(ref_prelim,'Reference image') == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_ref');
if (overwrite)
% Set data
obj.reference(1).imginfo = ncorr_class_img;
obj.reference(1).imginfo.set_img('load',struct('img',ref_prelim,'name','reference','path',''));
obj.reference(1).roi = ncorr_class_roi.empty;
end
end
end
function set_cur_source(obj,cur_prelim)
% This function allows the manual uploading of a current image -
% if a single image is uploaded it must be a double array. If multiple
% images are uploaded, they must be in a cell array.
% Check to make sure input is a cell
if (~iscell(cur_prelim))
% Wrap cur_prelim in a cell
cur_prelim = {cur_prelim};
end
% Make sure each image has the correct format
cursameformat = true;
for i = 0:length(cur_prelim)-1
if (ncorr_util_properimgfmt(cur_prelim{i+1},'Current image') ~= out.success)
cursameformat = false;
break;
end
end
if (cursameformat)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_cur');
if (overwrite)
% It's possible to run out of memory here, so put this
% in a try-catch block
try
% Set data
for i = 0:length(cur_prelim)-1
obj.current(i+1).imginfo = ncorr_class_img;
obj.current(i+1).imginfo.set_img('load',struct('img',cur_prelim{i+1},'name',['current_' num2str(i+1)],'path',''));
obj.current(i+1).roi = ncorr_class_roi.empty;
end
setappdata(obj.handles_gui.figure,'num_cur',length(cur_prelim)-1);
catch %#ok<CTCH>
h_error = errordlg('Loading current images failed, most likely because Ncorr ran out of memory.','Error','modal');
uiwait(h_error);
% Clear all current images because exception could have
% been thrown midway through setting current images
obj.current(:) = [];
setappdata(obj.handles_gui.figure,'num_cur',[]);
end
end
else
h_error = errordlg('Loading current images failed because the image data format was incorrect.','Error','modal');
uiwait(h_error);
end
end
function set_roi_ref_source(obj,mask_prelim)
% This function allows the manual uploading of a region of
% interest.
% Check to make sure reference image has been loaded first -
% for menu callbacks this isn't necessary since these options
% will only become callable if "upstream" data has been loaded
if (~isempty(obj.reference))
% Make sure ROI is the same size as the reference image and
% is of class logical.
if (isequal(size(mask_prelim),[obj.reference.imginfo.height obj.reference.imginfo.width]) && islogical(mask_prelim))
% Form roi_prelim
roi_prelim = ncorr_class_roi;
roi_prelim.set_roi('load',struct('mask',mask_prelim,'cutoff',2000));
% Make sure ROI is not empty
if (roi_prelim.get_fullregions > 0)
% At this point, roi_prelim fits the critera for a ROI. Show ROI
% overlayed and ask user if ROI is appropriate:
outstate = ncorr_gui_loadroi(obj.reference.imginfo, ...
roi_prelim, ...
get(obj.handles_gui.figure,'OuterPosition'));
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_roi');
if (overwrite)
% At this point, ROI is acceptable, has been
% approved by the user, and will now be set.
% Package data:
dispinfo_template.type = 'regular';
dispinfo_template.radius = [];
dispinfo_template.spacing = [];
dispinfo_template.cutoff_diffnorm = [];
dispinfo_template.cutoff_iteration = [];
dispinfo_template.total_threads = [];
dispinfo_template.stepanalysis = struct('enabled',{},'type',{},'auto',{},'step',{});
dispinfo_template.subsettrunc = [];
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
obj.reference(1).roi = roi_prelim;
end
end
else
h_error = errordlg('ROI must contain a large contiguous region.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Input must be of class logical and the same size as the reference image','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Reference image has not been loaded yet','Error','modal');
uiwait(h_error);
end
end
function set_roi_cur_source(obj,mask_prelim)
% This function allows the manual uploading of a region of
% interest. This ROI corresponds to the LAST current image.
% Check to make sure current image(s) have been loaded first -
% for menu callbacks this isn't necessary since these options
% will only become callable if "upstream" data has been loaded
if (~isempty(obj.current))
% Make sure ROI is the same size as the last current image
if (isequal(size(mask_prelim),[obj.current(end).imginfo.height obj.current(end).imginfo.width]) && islogical(mask_prelim))
% Form roi_prelim
roi_prelim = ncorr_class_roi;
roi_prelim.set_roi('load',struct('mask',mask_prelim,'cutoff',2000));
% Make sure ROI is not empty
if (roi_prelim.get_fullregions > 0)
% At this point, roi_prelim fits the critera for a ROI. Show ROI
% overlayed and ask user if ROI is appropriate:
outstate = ncorr_gui_loadroi(obj.current(end).imginfo, ...
roi_prelim, ...
get(obj.handles_gui.figure,'OuterPosition'));
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_roi');
if (overwrite)
% At this point, ROI is acceptable, has been
% approved by the user, and will now be set.
% Package data:
dispinfo_template.type = 'backward';
dispinfo_template.radius = [];
dispinfo_template.spacing = [];
dispinfo_template.cutoff_diffnorm = [];
dispinfo_template.cutoff_iteration = [];
dispinfo_template.total_threads = [];
dispinfo_template.stepanalysis = struct('enabled',{},'type',{},'auto',{},'step',{});
dispinfo_template.subsettrunc = [];
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
obj.current(end).roi = roi_prelim;
end
end
else
h_error = errordlg('ROI must contain a large contiguous region.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Input must be of class logical and the same size as the last current image','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Current image(s) have not been loaded yet.','Error','modal');
uiwait(h_error);
end
end
function refresh_source(obj) %#ok<MANU>
% Call this function if there's an error and the menu needs to be
% unfrozen.
end
%-----------------------------------------------------------------%
% Menu Callbacks -------------------------------------------------%
%-----------------------------------------------------------------%
function callback_topmenu_loadref(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for loading a reference image from the
% GUI.
% false means lazy loading isnt used
[ref_prelim,outstate] = ncorr_util_loadimgs(false);
if (outstate == out.success && length(ref_prelim) == 1)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_ref');
if (overwrite)
% Set Image
obj.reference(1).imginfo = ref_prelim;
obj.reference(1).roi = ncorr_class_roi.empty;
end
elseif (outstate == out.success && length(ref_prelim) > 1)
h_error = errordlg('Please select only one reference image.','Error','modal');
uiwait(h_error);
end
end
function callback_topmenu_loadcur(obj,hObject,eventdata,lazyparam) %#ok<INUSL>
% This is the callback for loading current image(s) from the GUI.
[cur_prelim,outstate] = ncorr_util_loadimgs(lazyparam);
if (outstate == out.success)
overwrite = obj.clear_downstream('set_cur');
if (overwrite)
% Set Image
for i = 0:length(cur_prelim)-1
obj.current(i+1).imginfo = cur_prelim(i+1);
obj.current(i+1).roi = ncorr_class_roi.empty;
end
% Display last current image
setappdata(obj.handles_gui.figure,'num_cur',length(cur_prelim)-1);
end
end
end
function callback_topmenu_loaddata(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for loading data from a previous analysis.
% Get data filename
[filename,pathname] = uigetfile({'*.mat'},'Select the previous DIC data (must be .dat)');
if (~isequal(filename,0) && ~isequal(pathname,0));
try
% Load data
struct_load = load(fullfile(pathname,filename));
loadsuccess = true;
catch %#ok<CTCH>
% Probably out of memory
loadsuccess = false;
end
if (loadsuccess)
if (isfield(struct_load,'reference_save') && isfield(struct_load,'current_save') && isfield(struct_load,'data_dic_save'))
% The data has the correct fields
if (isa(struct_load.reference_save,'struct') && ...
isa(struct_load.current_save,'struct') && ...
isa(struct_load.data_dic_save,'struct'))
% Make sure data_dic has the correct
% fields. Easiest way to do this is to assign
% the saved data to a structure with the
% correct fields, an error will result if the
% fields are wrong
data_dic_prelim = obj.data_dic; % This will copy fields - only used temporarily
try
data_dic_prelim(1) = struct_load.data_dic_save; %#ok<NASGU>
loaddatasuccess = true;
catch %#ok<CTCH>
% Some fields are not correct
loaddatasuccess = false;
end
if (loaddatasuccess)
% See if data will be overwritten
overwrite = obj.clear_downstream('all');
if (overwrite)
% Put in try block - its possible to run
% out of memory here.
try
% Do reference image first
[ref_prelim,outstate_ref] = ncorr_util_loadsavedimg(struct_load.reference_save);
% Do current images next
cur_prelim = ncorr_class_img.empty;
for i = 0:length(struct_load.current_save)-1
[cur_buffer,outstate_cur] = ncorr_util_loadsavedimg(struct_load.current_save(i+1));
if (outstate_cur == out.success)
cur_prelim(i+1) = cur_buffer;
else
break;
end
end
if (outstate_ref == out.success && outstate_cur == out.success)
% Store data:
% Set reference:
obj.reference(1).imginfo = ref_prelim;
obj.reference(1).roi = struct_load.reference_save.roi;
% Set current:
for i = 0:length(struct_load.current_save)-1
obj.current(i+1).imginfo = cur_prelim(i+1);
obj.current(i+1).roi = struct_load.current_save(i+1).roi;
end
setappdata(obj.handles_gui.figure,'num_cur',length(struct_load.current_save)-1);
% Set dic data:
obj.data_dic(1) = struct_load.data_dic_save;
else
% Images could not be found
% Form error message
msg_error{1} = 'Images could not be located. Make sure they are in the current directory or were not moved from the locations listed here:';
msg_error{2} = fullfile(struct_load.reference_save.path,struct_load.reference_save.name);
max_display = 10;
for i = 0:min(length(struct_load.current_save),max_display)-1
msg_error{end+1} = fullfile(struct_load.current_save(i+1).path,struct_load.current_save(i+1).name); %#ok<AGROW>
end
if (length(struct_load.current_save) > max_display)
msg_error{end+1} = '...';
end
h_error = errordlg(msg_error,'Error','modal');
uiwait(h_error);
end
catch %#ok<CTCH>
h_error = errordlg('Loading failed, most likely because Ncorr ran out of memory.','Error','modal');
uiwait(h_error);
% Clear everything - its possible
% exception was caught while
% loading data midway.
obj.reference(:) = [];
obj.current(:) = [];
setappdata(obj.handles_gui.figure,'num_cur',[]);
fields_data_dic = fieldnames(obj.data_dic);
for i = 0:length(fields_data_dic)-1
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
end
else
h_error = errordlg('The data is not valid, please load data saved specifically from ncorr.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('The data is not valid, please load data saved specifically from ncorr.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('The data is not valid, please load data saved specifically from ncorr.','Error','modal');
uiwait(h_error);
end
else
h_error = errordlg('Loading failed, most likely because Ncorr ran out of memory.','Error','modal');
uiwait(h_error);
end
end
end
function callback_topmenu_savedata(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for saving data.
% Get save data filename
[filename,pathname] = uiputfile({'*.mat'},'Save DIC data (must be .dat)');
if (~isequal(filename,0) && ~isequal(pathname,0));
% Check if data will be overwritten in directory
overwrite = true;
if (exist(fullfile(pathname,filename),'file'))
contbutton = questdlg('File already exists. Do you want to overwrite?','Continue Operation','Yes','No','Yes');
if (strcmp(contbutton,'No'))
overwrite = false;
end
end
if (overwrite)
% Must deal with image data, ROI data, and data_dic.
% 1) Images: Save the file names if they are 'file' or 'lazy'
% If they were set through the workspace (i.e. 'load') then save the
% image as double precision.
% 2) ROIs: For the ROIs, save each directly.
% 3) Data: Save data_dic directly.
reference_save = struct('type',{},'gs',{},'name',{},'path',{},'roi',{});
current_save = struct('type',{},'gs',{},'name',{},'path',{},'roi',{});
% Images ---------------------------------------------%
% Reference image:
reference_save(1).type = obj.reference.imginfo.type;
reference_save.gs = [];
if (strcmp(obj.reference.imginfo.type,'load'))
% Must save gs data directly
reference_save.gs = obj.reference.imginfo.get_gs();
end
reference_save.name = obj.reference.imginfo.name;
reference_save.path = obj.reference.imginfo.path;
reference_save.roi = obj.reference.roi; %#ok<STRNU>
% Current image(s):
for i = 0:length(obj.current)-1
current_save(i+1).type = obj.current(i+1).imginfo.type;
current_save(i+1).gs = [];
if (strcmp(obj.current(i+1).imginfo.type,'load'))
% Must save gs data directly
current_save(i+1).gs = obj.current(i+1).imginfo.get_gs();
end
current_save(i+1).name = obj.current(i+1).imginfo.name;
current_save(i+1).path = obj.current(i+1).imginfo.path;
current_save(i+1).roi = obj.current(i+1).roi;
end
% Data -----------------------------------------------%
data_dic_save = obj.data_dic; %#ok<NASGU>
% Save -----------------------------------------------%
try
% The v7.3 flag helps save larger files
save(fullfile(pathname,filename),'reference_save','current_save','data_dic_save','-v7.3');
catch %#ok<CTCH>
% If saving fails, its generally because the files
% are too large.
h_error = errordlg('Saving failed, probably because the amount of data being saved is too large.','Error','modal');
uiwait(h_error);
end
end
end
end
function callback_topmenu_clear(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for the clearing all the data.
obj.clear_downstream('all');
end
function callback_topmenu_sethandle(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for setting the handle to ncorr in the case
% that it gets cleared from the workspace
% Get Name
name = util_get_name(obj);
if (isempty(name))
% Prompt user for what handle he/she wants to use
[handle_name,outstate] = gui_sethandle(get(obj.handles_gui.figure,'OuterPosition'));
if (outstate == out.success)
% Assign handles to base workspace
assignin('base',handle_name,obj);
end
else
% Handle already exists
e = msgbox(['Handle already exists and is called: ' name],'WindowStyle','modal');
uiwait(e);
end
end
function callback_topmenu_reinstall(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for reinstalling the mex files.
% Check if ncorr.m is in current directory
listing = dir;
if (any(strcmp('ncorr.m',{listing.name})))
% Ask user if its okay to reinstall
contbutton = questdlg('Are you sure you want to reinstall? All data will be lost if proceeding.','Continue Operation','Yes','No','Yes');
if (strcmp(contbutton,'Yes'))
% Clear ncorr_installinfo.txt file - this is the standard
% way to reinstall
filename = 'ncorr_installinfo.txt';
fid = fopen(filename,'w'); % This will clear file
if (fid ~= -1)
fclose(fid); % Close file
% Force close
obj.callback_close_function([],[],true);
% Reopen ncorr - this will cause reinstallation since
% ncorr_installinfo.txt has been cleared
handles_ncorr = ncorr;
% Get name
name = util_get_name(obj);
if (~isempty(name))
% If there is a name then assign the name to the
% ncorr object.
assignin('base',name,handles_ncorr);
end
else
% Error
h_error = errordlg('For some reason ncorr was not able to clear "ncorr_installinfo.txt" file, reinstall cannot take place.','Error','modal');
uiwait(h_error);
end
end
else
% Error
h_error = errordlg('Please navigate to folder containing ncorr.m first before reinstalling.','Error','modal');
uiwait(h_error);
end
end
function callback_exit_callback(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for exiting the program.
% 3rd argument is set to false, which queries user about
% closing if DIC data has been computed.
obj.callback_close_function([],[],false);
end
function callback_topmenu_set_roi_ref(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for loading the region of interest from the
% GUI
% Get ROIs ---------------------------------------------------%
% Check if ROI has been set before - must be from the regular
% analysis, as backward DIC analysis will also set a reference ROI
params_init = ncorr_class_roi.empty;
if (~isempty(obj.reference) && ~isempty(obj.reference.roi) && ...
~isempty(obj.data_dic.dispinfo) && strcmp(obj.data_dic.dispinfo.type,'regular'))
params_init(1) = obj.reference.roi;
end
[roi_prelim,outstate] = ncorr_gui_setrois(obj.reference.imginfo, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_roi');
if (overwrite)
% Package data:
dispinfo_template.type = 'regular';
dispinfo_template.radius = [];
dispinfo_template.spacing = [];
dispinfo_template.cutoff_diffnorm = [];
dispinfo_template.cutoff_iteration = [];
dispinfo_template.total_threads = [];
dispinfo_template.stepanalysis = struct('enabled',{},'type',{},'auto',{},'step',{});
dispinfo_template.subsettrunc = [];
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
obj.reference(1).roi = roi_prelim;
end
end
end
function callback_topmenu_set_roi_cur(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for loading the region of interest from
% the GUI
% Get ROIs ---------------------------------------------------%
% Check if ROI has been set before - must be from the backward
% analysis, as backward dic analysis will also set a current ROI
params_init = ncorr_class_roi.empty;
if (~isempty(obj.current) && ~isempty(obj.current(end).roi) && ...
~isempty(obj.data_dic.dispinfo) && strcmp(obj.data_dic.dispinfo.type,'backward'))
params_init(1) = obj.current(end).roi;
end
[roi_prelim,outstate] = ncorr_gui_setrois(obj.current(end).imginfo, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_roi');
if (overwrite)
% Package data:
dispinfo_template.type = 'backward';
dispinfo_template.radius = [];
dispinfo_template.spacing = [];
dispinfo_template.cutoff_diffnorm = [];
dispinfo_template.cutoff_iteration = [];
dispinfo_template.total_threads = [];
dispinfo_template.stepanalysis = struct('enabled',{},'type',{},'auto',{},'step',{});
dispinfo_template.subsettrunc = [];
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
obj.current(end).roi = roi_prelim;
end
end
end
function callback_topmenu_setdicparameters(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for setting DIC parameters
% Check if DIC parameters were set before - if dic parameters
% are being set, the data_dic.dispinfo field is gauranteed
% nonempty, so you don't need to check this first.
params_init = {};
if (~isempty(obj.data_dic.dispinfo.radius) && ...
~isempty(obj.data_dic.dispinfo.spacing) && ...
~isempty(obj.data_dic.dispinfo.cutoff_diffnorm) && ...
~isempty(obj.data_dic.dispinfo.cutoff_iteration) && ...
~isempty(obj.data_dic.dispinfo.total_threads) && ...
~isempty(obj.data_dic.dispinfo.stepanalysis) && ...
~isempty(obj.data_dic.dispinfo.subsettrunc))
params_init = {obj.data_dic.dispinfo.radius, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.cutoff_diffnorm, ...
obj.data_dic.dispinfo.cutoff_iteration, ...
obj.data_dic.dispinfo.total_threads, ...
obj.data_dic.dispinfo.stepanalysis, ...
obj.data_dic.dispinfo.subsettrunc};
end
% Get Params -------------------------------------------------%
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
% Show reference image for regular analysis
[radius_prelim,spacing_prelim,cutoff_diffnorm_prelim,cutoff_iteration_prelim,total_threads_prelim,stepanalysis_prelim,subsettrunc_prelim,outstate] = ncorr_gui_setdicparams(obj.reference.imginfo, ...
obj.reference.roi, ...
obj.support_openmp, ...
obj.total_cores, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
else
% Show last current image for backward analysis
[radius_prelim,spacing_prelim,cutoff_diffnorm_prelim,cutoff_iteration_prelim,total_threads_prelim,stepanalysis_prelim,subsettrunc_prelim,outstate] = ncorr_gui_setdicparams(obj.current(end).imginfo, ...
obj.current(end).roi, ...
obj.support_openmp, ...
obj.total_cores, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
end
if (outstate == out.success)
% See if data will be overwritten
overwrite = obj.clear_downstream('set_dicparameters');
if (overwrite)
% Package data:
dispinfo_template.type = obj.data_dic.dispinfo.type;
dispinfo_template.radius = radius_prelim;
dispinfo_template.spacing = spacing_prelim;
dispinfo_template.cutoff_diffnorm = cutoff_diffnorm_prelim;
dispinfo_template.cutoff_iteration = cutoff_iteration_prelim;
dispinfo_template.total_threads = total_threads_prelim;
dispinfo_template.stepanalysis = stepanalysis_prelim;
dispinfo_template.subsettrunc = subsettrunc_prelim;
dispinfo_template.imgcorr = struct('idx_ref',{},'idx_cur',{});
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
obj.data_dic.dispinfo(1) = dispinfo_template;
end
end
end
function callback_topmenu_dic(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for performing DIC.
% Merge images. This makes it convenient for the idx
% tracker if step analysis is used
imgs = [obj.reference obj.current];
% Initialize
rois_dic_prelim = ncorr_class_roi.empty;
displacements_prelim = struct('plot_u',{},'plot_v',{},'plot_corrcoef',{},'plot_validpoints',{});
imgcorr_prelim = struct('idx_ref',{},'idx_cur',{});
seedinfo_buffer = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
% Imgcorr starts out empty so this guarantees at least one
% iteration. Make sure to exit when all images have been
% analyzed.
while (isempty(imgcorr_prelim) || imgcorr_prelim(end).idx_cur < length(imgs)-1)
% Update idx_ref
if (isempty(imgcorr_prelim))
imgcorr_prelim(1).idx_ref = 0;
else
% Use previous last current image as the new
% reference image
imgcorr_prelim(end+1).idx_ref = imgcorr_prelim(end).idx_cur; %#ok<AGROW>
end
% Update idx_cur
if (obj.data_dic.dispinfo.stepanalysis.enabled && strcmp(obj.data_dic.dispinfo.stepanalysis.type,'leapfrog'))
% If leapfrog is used, then set current image to a
% preset increment
imgcorr_prelim(end).idx_cur = min(imgcorr_prelim(end).idx_ref+obj.data_dic.dispinfo.stepanalysis.step,length(imgs)-1);
else
% If this is not leapfrog, set the current image to
% the last image. This number will get updated
% depending on how many images are successfully
% analyzed and seeded
imgcorr_prelim(end).idx_cur = length(imgs)-1;
end
% Do DIC analysis - only send initial parameters if
% stepanalysis is enabled with automatic seed
% propagation and an interation has already been done.
params_init = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});
if (obj.data_dic.dispinfo.stepanalysis.enabled && ...
obj.data_dic.dispinfo.stepanalysis.auto && ...
~isempty(seedinfo_buffer))
% Get previous seeds as initial parameters if step
% analysis and automatic seed propagation are enabled.
% If these are provided then the seeds are automatically
% updated
params_init = seedinfo_buffer;
end
% Returns failed if exception is thrown; for both
% failed and cancel just return.
[displacements_buffer,rois_dic_buffer,seedinfo_buffer,outstate_dic] = ncorr_alg_dicanalysis(imgs(imgcorr_prelim(end).idx_ref+1:imgcorr_prelim(end).idx_cur+1), ...
obj.data_dic.dispinfo.radius, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.cutoff_diffnorm, ...
obj.data_dic.dispinfo.cutoff_iteration, ...
obj.data_dic.dispinfo.total_threads, ...
obj.data_dic.dispinfo.stepanalysis.enabled, ...
obj.data_dic.dispinfo.subsettrunc, ...
imgcorr_prelim(end).idx_ref, ...
length(obj.current), ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
if (outstate_dic ~= out.success)
% DIC analysis was cancelled or failed by throwing
% an exception, for both cases return
return;
end
% Update ROIs
for i = 0:length(displacements_buffer)-1
imgs(i+imgcorr_prelim(end).idx_ref+2).roi = imgs(imgcorr_prelim(end).idx_ref+1).roi.update_roi(displacements_buffer(i+1).plot_u, ...
displacements_buffer(i+1).plot_v, ...
rois_dic_buffer(i+1), ...
[imgs(i+imgcorr_prelim(end).idx_ref+2).imginfo.height imgs(i+imgcorr_prelim(end).idx_ref+2).imginfo.width], ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.radius);
end
% Store outputs
for i = 0:length(displacements_buffer)-1
displacements_prelim(i+imgcorr_prelim(end).idx_ref+1) = displacements_buffer(i+1);
rois_dic_prelim(i+imgcorr_prelim(end).idx_ref+1) = rois_dic_buffer(i+1);
end
% Update imgcorr_prelim if stepanalysis is enabled
% - this is necessary since not all images are
% necessarily analyzed.
if (obj.data_dic.dispinfo.stepanalysis.enabled)
imgcorr_prelim(end).idx_cur = imgcorr_prelim(end).idx_ref + length(displacements_buffer);
end
end
else
% Imgcorr starts out empty so this guarantees at least one
% iteration. Make sure to exit when all images have been
% analyzed.
while (isempty(imgcorr_prelim) || imgcorr_prelim(end).idx_cur > 0)
% Update idx_ref
if (isempty(imgcorr_prelim))
imgcorr_prelim(1).idx_ref = length(imgs)-1;
else
% Use previous last current image as the new
% reference image
imgcorr_prelim(end+1).idx_ref = imgcorr_prelim(end).idx_cur; %#ok<AGROW>
end
% Update idx_cur
if (obj.data_dic.dispinfo.stepanalysis.enabled && strcmp(obj.data_dic.dispinfo.stepanalysis.type,'leapfrog'))
% If leapfrog is used, then set current image to a
% preset increment
imgcorr_prelim(end).idx_cur = max(imgcorr_prelim(end).idx_ref-obj.data_dic.dispinfo.stepanalysis.step,0);
else
% If this is not leapfrog, set the current image to
% the last image. This number will get updated
% depending on how many images are successfully
% analyzed and seeded
imgcorr_prelim(end).idx_cur = 0;
end
% Do DIC analysis - only send initial parameters if
% stepanalysis is enabled with automatic seed
% propagation and an interation has already been done.
params_init = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});
if (obj.data_dic.dispinfo.stepanalysis.enabled && ...
obj.data_dic.dispinfo.stepanalysis.auto && ...
~isempty(seedinfo_buffer))
% Get previous seeds as initial parameters if step
% analysis and automatic seed propagation are enabled.
% If these are provided then the seeds are automatically
% updated
params_init = seedinfo_buffer;
end
% Returns failed if exception is thrown; for both
% failed and cancel just return.
[displacements_buffer,rois_dic_buffer,seedinfo_buffer,outstate_dic] = ncorr_alg_dicanalysis(imgs(imgcorr_prelim(end).idx_ref+1:-1:imgcorr_prelim(end).idx_cur+1), ...
obj.data_dic.dispinfo.radius, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.cutoff_diffnorm, ...
obj.data_dic.dispinfo.cutoff_iteration, ...
obj.data_dic.dispinfo.total_threads, ...
obj.data_dic.dispinfo.stepanalysis.enabled, ...
obj.data_dic.dispinfo.subsettrunc, ...
length(obj.current)-imgcorr_prelim(end).idx_ref, ...
length(obj.current), ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
if (outstate_dic ~= out.success)
% DIC analysis was cancelled or failed by throwing
% an exception, for both cases return
return;
end
% Update ROIs
for i = 0:length(displacements_buffer)-1
imgs(imgcorr_prelim(end).idx_ref-i).roi = imgs(imgcorr_prelim(end).idx_ref+1).roi.update_roi(displacements_buffer(i+1).plot_u, ...
displacements_buffer(i+1).plot_v, ...
rois_dic_buffer(i+1), ...
[imgs(imgcorr_prelim(end).idx_ref-i).imginfo.height imgs(imgcorr_prelim(end).idx_ref-i).imginfo.width], ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.radius);
end
% Update displacements
for i = 0:length(displacements_buffer)-1
% Displacements must be updated if more than two
% images were analyzed. Also, leave the last
% displacement field in the buffer alone since
% it's already WRT the correct configuration
if (i > 0)
% Update displacement fields
params_init = struct('paramvector',{},'num_region',{},'num_thread',{},'computepoints',{});
if (obj.data_dic.dispinfo.stepanalysis.auto)
params_init = seedinfo_buffer(:,:,end-i);
end
% Returns failed if exception is thrown; for both
% failed and cancel just return.
[displacement_buffer_update,roi_dic_buffer_update,seedinfo_buffer_update,outstate_dic] = ncorr_alg_dicanalysis([imgs(imgcorr_prelim(end).idx_ref-length(displacements_buffer)+i+1) imgs(imgcorr_prelim(end).idx_ref-length(displacements_buffer)+1)], ...
obj.data_dic.dispinfo.radius, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.cutoff_diffnorm, ...
obj.data_dic.dispinfo.cutoff_iteration, ...
obj.data_dic.dispinfo.total_threads, ...
obj.data_dic.dispinfo.stepanalysis.enabled, ...
obj.data_dic.dispinfo.subsettrunc, ...
length(obj.current)-imgcorr_prelim(end).idx_ref+i, ...
length(obj.current), ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init); %#ok<ASGLU>
if (outstate_dic ~= out.success)
% DIC analysis was cancelled or failed by throwing
% an exception, for both cases return
return;
end
% Store Displacements
displacements_prelim(imgcorr_prelim(end).idx_ref-length(displacements_buffer)+i) = displacement_buffer_update;
rois_dic_prelim(imgcorr_prelim(end).idx_ref-length(displacements_buffer)+i) = roi_dic_buffer_update;
else
% Directly store displacements
displacements_prelim(imgcorr_prelim(end).idx_ref) = displacements_buffer(end);
rois_dic_prelim(imgcorr_prelim(end).idx_ref) = rois_dic_buffer(end);
end
end
% Update imgcorr_prelim - this is necessary since
% not all images are necessarily analyzed.
if (obj.data_dic.dispinfo.stepanalysis.enabled)
imgcorr_prelim(end).idx_cur = imgcorr_prelim(end).idx_ref - length(displacements_buffer);
end
end
end
% Save the data
% See if data will be overwritten
overwrite = obj.clear_downstream('dicanalysis');
if (overwrite)
% Package the data:
for i = 0:length(obj.current)-1
displacements_template(i+1).plot_u_dic = displacements_prelim(i+1).plot_u; %#ok<AGROW>
displacements_template(i+1).plot_v_dic = displacements_prelim(i+1).plot_v; %#ok<AGROW>
displacements_template(i+1).plot_corrcoef_dic = displacements_prelim(i+1).plot_corrcoef; %#ok<AGROW>
displacements_template(i+1).roi_dic = rois_dic_prelim(i+1); %#ok<AGROW>
displacements_template(i+1).plot_u_ref_formatted = []; %#ok<AGROW>
displacements_template(i+1).plot_v_ref_formatted = []; %#ok<AGROW>
displacements_template(i+1).roi_ref_formatted = []; %#ok<AGROW>
displacements_template(i+1).plot_u_cur_formatted = []; %#ok<AGROW>
displacements_template(i+1).plot_v_cur_formatted = []; %#ok<AGROW>
displacements_template(i+1).roi_cur_formatted = []; %#ok<AGROW>
end
dispinfo_template.type = obj.data_dic.dispinfo.type;
dispinfo_template.radius = obj.data_dic.dispinfo.radius;
dispinfo_template.spacing = obj.data_dic.dispinfo.spacing;
dispinfo_template.cutoff_diffnorm = obj.data_dic.dispinfo.cutoff_diffnorm;
dispinfo_template.cutoff_iteration = obj.data_dic.dispinfo.cutoff_iteration;
dispinfo_template.total_threads = obj.data_dic.dispinfo.total_threads;
dispinfo_template.stepanalysis = obj.data_dic.dispinfo.stepanalysis;
dispinfo_template.subsettrunc = obj.data_dic.dispinfo.subsettrunc;
dispinfo_template.imgcorr = imgcorr_prelim;
dispinfo_template.pixtounits = [];
dispinfo_template.units = '';
dispinfo_template.cutoff_corrcoef = [];
dispinfo_template.lenscoef = [];
% Store the data:
% Updated ROIs
obj.reference.roi = imgs(1).roi;
for i = 0:length(obj.current)-1
obj.current(i+1).roi = imgs(i+2).roi;
end
% Displacement info
obj.data_dic.dispinfo(1) = dispinfo_template;
for i = 0:length(obj.current)-1
% Store displacements
obj.data_dic.displacements(i+1) = displacements_template(i+1);
end
% Tell user analysis is done
msgbox('DIC Analysis completed successfully. Press ok to finish.','WindowStyle','modal');
end
end
function callback_topmenu_formatdisp(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for formatting the displacements.
% Merge images. This makes it convenient for the idx
% tracker
imgs = [obj.reference.imginfo obj.current.imginfo];
% Check if format has been done before
params_init = cell(0);
if (~isempty(obj.data_dic.dispinfo.pixtounits) && ...
~isempty(obj.data_dic.dispinfo.units) && ...
~isempty(obj.data_dic.dispinfo.cutoff_corrcoef) && ...
~isempty(obj.data_dic.dispinfo.lenscoef))
params_init = {obj.data_dic.dispinfo.pixtounits, ...
obj.data_dic.dispinfo.units, ...
obj.data_dic.dispinfo.cutoff_corrcoef, ...
obj.data_dic.dispinfo.lenscoef};
end
% Initialize
plots_disp_f_prelim = struct('plot_u_ref_formatted',{},'plot_v_ref_formatted',{},'plot_u_cur_formatted',{},'plot_v_cur_formatted',{});
rois_f_ref_prelim = ncorr_class_roi.empty;
rois_f_cur_prelim = ncorr_class_roi.empty;
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
% Gather reference and current images in the correct order
imgs_ref = ncorr_class_img.empty;
imgs_cur = ncorr_class_img.empty;
for i = 0:length(obj.data_dic.dispinfo.imgcorr)-1
imgs_ref = horzcat(imgs_ref,repmat(imgs(obj.data_dic.dispinfo.imgcorr(i+1).idx_ref+1),1,obj.data_dic.dispinfo.imgcorr(i+1).idx_cur-obj.data_dic.dispinfo.imgcorr(i+1).idx_ref)); %#ok<AGROW>
imgs_cur = horzcat(imgs_cur,imgs(obj.data_dic.dispinfo.imgcorr(i+1).idx_ref+2:obj.data_dic.dispinfo.imgcorr(i+1).idx_cur+1)); %#ok<AGROW>
end
% Format step displacements ------------------------------%
[plots_disp_f_step_prelim,rois_f_step_prelim,pixtounits_prelim,units_prelim,cutoff_corrcoef_prelim,lenscoef_prelim,outstate_formatdisp_step] = ncorr_gui_formatdisp(imgs_ref, ...
imgs_cur, ...
[obj.data_dic.displacements.roi_dic], ...
{obj.data_dic.displacements.plot_u_dic}, ...
{obj.data_dic.displacements.plot_v_dic}, ...
{obj.data_dic.displacements.plot_corrcoef_dic}, ...
obj.data_dic.dispinfo.spacing, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
% Check if analysis was cancelled
if (outstate_formatdisp_step ~= out.success)
return;
end
% Convert plots back to pixel displacements
for i = 0:length(obj.current)-1
plots_disp_f_step_prelim(i+1).plot_u_formatted = plots_disp_f_step_prelim(i+1).plot_u_formatted./pixtounits_prelim;
plots_disp_f_step_prelim(i+1).plot_v_formatted = plots_disp_f_step_prelim(i+1).plot_v_formatted./pixtounits_prelim;
end
% Add plots ----------------------------------------------%
% Gather images that dont need to be added
for i = obj.data_dic.dispinfo.imgcorr(1).idx_ref:obj.data_dic.dispinfo.imgcorr(1).idx_cur-1
plots_disp_f_prelim(i+1).plot_u_ref_formatted = plots_disp_f_step_prelim(i+1).plot_u_formatted;
plots_disp_f_prelim(i+1).plot_v_ref_formatted = plots_disp_f_step_prelim(i+1).plot_v_formatted;
rois_f_ref_prelim(i+1) = rois_f_step_prelim(i+1);
end
% Reduce reference ROI
roi_ref_reduced = obj.reference.roi.reduce(obj.data_dic.dispinfo.spacing);
% Add other plots
plot_added_buffer = cell(0);
% Cycle over imgcorr - skip first index in imgcorr
for i = 1:length(obj.data_dic.dispinfo.imgcorr)-1
for j = obj.data_dic.dispinfo.imgcorr(i+1).idx_ref:obj.data_dic.dispinfo.imgcorr(i+1).idx_cur-1
% Get idxs of displacement fields used to add
idx_dispadd = [[obj.data_dic.dispinfo.imgcorr(1:i).idx_cur]-1 j];
% Get added plots
[plot_added_buffer{1},outstate_add] = ncorr_alg_addanalysis({plots_disp_f_step_prelim(idx_dispadd+1).plot_u_formatted}, ...
{plots_disp_f_step_prelim(idx_dispadd+1).plot_v_formatted}, ...
rois_f_step_prelim(idx_dispadd+1), ...
obj.data_dic.dispinfo.spacing, ...
j+1, ...
length(obj.current));
% See if analysis was cancelled
if (outstate_add ~= out.success)
return;
end
% Store "added" plots
plots_disp_f_prelim(j+1).plot_u_ref_formatted = plot_added_buffer{1}.plot_u_added;
plots_disp_f_prelim(j+1).plot_v_ref_formatted = plot_added_buffer{1}.plot_v_added;
rois_f_ref_prelim(j+1) = roi_ref_reduced.get_union(plot_added_buffer{1}.plot_validpoints,0);
end
end
% Convert plots to Eulerian ------------------------------%
% Get Eulerian displacements
plot_eulerian_buffer = cell(0);
roi_eulerian_buffer = cell(0);
for i = 0:length(obj.current)-1
% Convert displacements from Lagrangian to Eulerian perspective
[plot_eulerian_buffer{1},roi_eulerian_buffer{1},outstate_convert] = ncorr_alg_convertanalysis(obj.current(i+1), ...
obj.reference, ...
{plots_disp_f_prelim(i+1).plot_u_ref_formatted}, ...
{plots_disp_f_prelim(i+1).plot_v_ref_formatted}, ...
rois_f_ref_prelim(i+1), ...
obj.data_dic.dispinfo.spacing, ...
i, ...
length(obj.current));
% See if analysis was cancelled or failed. Return for
% both.
if (outstate_convert ~= out.success)
return;
end
% Store
plots_disp_f_prelim(i+1).plot_u_cur_formatted = plot_eulerian_buffer{1}.plot_u_new;
plots_disp_f_prelim(i+1).plot_v_cur_formatted = plot_eulerian_buffer{1}.plot_v_new;
rois_f_cur_prelim(i+1) = roi_eulerian_buffer{1};
end
% Make sure to convert displacements back to real units from
% pixels. Also multiply Eulerian displacements by -1 to
% make them truly Eulerian
for i = 0:length(obj.current)-1
% Lagrangian
plots_disp_f_prelim(i+1).plot_u_ref_formatted = plots_disp_f_prelim(i+1).plot_u_ref_formatted.*pixtounits_prelim;
plots_disp_f_prelim(i+1).plot_v_ref_formatted = plots_disp_f_prelim(i+1).plot_v_ref_formatted.*pixtounits_prelim;
% Eulerian
plots_disp_f_prelim(i+1).plot_u_cur_formatted = -plots_disp_f_prelim(i+1).plot_u_cur_formatted.*pixtounits_prelim;
plots_disp_f_prelim(i+1).plot_v_cur_formatted = -plots_disp_f_prelim(i+1).plot_v_cur_formatted.*pixtounits_prelim;
end
else
% Gather reference and current images in the correct order
imgs_ref = imgs(2:end);
imgs_cur = ncorr_class_img.empty;
for i = length(obj.data_dic.dispinfo.imgcorr)-1:-1:0
imgs_cur = horzcat(imgs_cur,repmat(imgs(obj.data_dic.dispinfo.imgcorr(i+1).idx_cur+1),1,obj.data_dic.dispinfo.imgcorr(i+1).idx_ref-obj.data_dic.dispinfo.imgcorr(i+1).idx_cur)); %#ok<AGROW>
end
% Format step displacements ------------------------------%
[plots_disp_f_step_prelim,rois_f_step_prelim,pixtounits_prelim,units_prelim,cutoff_corrcoef_prelim,lenscoef_prelim,outstate_formatdisp_step] = ncorr_gui_formatdisp(imgs_ref, ...
imgs_cur, ...
[obj.data_dic.displacements.roi_dic], ...
{obj.data_dic.displacements.plot_u_dic}, ...
{obj.data_dic.displacements.plot_v_dic}, ...
{obj.data_dic.displacements.plot_corrcoef_dic}, ...
obj.data_dic.dispinfo.spacing, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
% Check if analysis was cancelled
if (outstate_formatdisp_step ~= out.success)
return;
end
% Convert plots to pixel displacements
for i = 0:length(obj.current)-1
plots_disp_f_step_prelim(i+1).plot_u_formatted = plots_disp_f_step_prelim(i+1).plot_u_formatted./pixtounits_prelim;
plots_disp_f_step_prelim(i+1).plot_v_formatted = plots_disp_f_step_prelim(i+1).plot_v_formatted./pixtounits_prelim;
end
% Add plots ------------------------------------------%
% Gather images that dont need to be added
for i = obj.data_dic.dispinfo.imgcorr(end).idx_cur:obj.data_dic.dispinfo.imgcorr(end).idx_ref-1
plots_disp_f_prelim(i+1).plot_u_cur_formatted = plots_disp_f_step_prelim(i+1).plot_u_formatted;
plots_disp_f_prelim(i+1).plot_v_cur_formatted = plots_disp_f_step_prelim(i+1).plot_v_formatted;
rois_f_cur_prelim(i+1) = rois_f_step_prelim(i+1);
end
% Add other plots
plot_added_buffer = cell(0);
counter = obj.data_dic.dispinfo.imgcorr(end).idx_ref+1;
% Cycle over imgcorr - skip over last index
for i = 0:length(obj.data_dic.dispinfo.imgcorr)-2
for j = obj.data_dic.dispinfo.imgcorr(i+1).idx_ref-1:-1:obj.data_dic.dispinfo.imgcorr(i+1).idx_cur
% Get idxs of displacement fields used to add
idx_dispadd = [j [obj.data_dic.dispinfo.imgcorr(i+2:end).idx_ref]-1];
% Get added plots
[plot_added_buffer{1},outstate_add] = ncorr_alg_addanalysis({plots_disp_f_step_prelim(idx_dispadd+1).plot_u_formatted}, ...
{plots_disp_f_step_prelim(idx_dispadd+1).plot_v_formatted}, ...
rois_f_step_prelim(idx_dispadd+1), ...
obj.data_dic.dispinfo.spacing, ...
counter, ...
length(obj.current));
% See if analysis was cancelled
if (outstate_add ~= out.success)
return;
end
% Reduce current ROI
roi_cur_reduced = obj.current(j+1).roi.reduce(obj.data_dic.dispinfo.spacing);
% Store "added" plots
plots_disp_f_prelim(j+1).plot_u_cur_formatted = plot_added_buffer{1}.plot_u_added;
plots_disp_f_prelim(j+1).plot_v_cur_formatted = plot_added_buffer{1}.plot_v_added;
rois_f_cur_prelim(j+1) = roi_cur_reduced.get_union(plot_added_buffer{1}.plot_validpoints,0);
% Update counter
counter = counter+1;
end
end
% Convert plots to Lagrangian ----------------------------%
% Get Lagrangian Displacements
plot_lagrangian_buffer = cell(0);
roi_lagrangian_buffer = cell(0);
[plot_lagrangian_buffer{1},roi_lagrangian_buffer{1},outstate_convert] = ncorr_alg_convertanalysis(obj.reference, ...
obj.current, ...
{plots_disp_f_prelim.plot_u_cur_formatted}, ...
{plots_disp_f_prelim.plot_v_cur_formatted}, ...
rois_f_cur_prelim, ...
obj.data_dic.dispinfo.spacing, ...
0, ...
length(obj.current));
% See if analysis was cancelled or failed. Return for
% both.
if (outstate_convert ~= out.success)
return;
end
% Make sure to convert displacements back to real units from
% pixels. Also multiply Eulerian displacements by -1 to
% make them truly
% Eulerian
for i = 0:length(obj.current)-1
% Lagrangian
plots_disp_f_prelim(i+1).plot_u_ref_formatted = plot_lagrangian_buffer{1}(i+1).plot_u_new.*pixtounits_prelim;
plots_disp_f_prelim(i+1).plot_v_ref_formatted = plot_lagrangian_buffer{1}(i+1).plot_v_new.*pixtounits_prelim;
rois_f_ref_prelim(i+1) = roi_lagrangian_buffer{1}(i+1);
% Eulerian
plots_disp_f_prelim(i+1).plot_u_cur_formatted = -plots_disp_f_prelim(i+1).plot_u_cur_formatted.*pixtounits_prelim;
plots_disp_f_prelim(i+1).plot_v_cur_formatted = -plots_disp_f_prelim(i+1).plot_v_cur_formatted.*pixtounits_prelim;
end
end
% Dont query overwrite, just do it since formatting
% displacement data and calculating strain maps is quick
obj.clear_downstream('formatdisp');
% For regular analysis just store formatted rois
% Package data:
for i = 0:length(obj.current)-1
displacements_template(i+1).plot_u_dic = obj.data_dic.displacements(i+1).plot_u_dic; %#ok<AGROW>
displacements_template(i+1).plot_v_dic = obj.data_dic.displacements(i+1).plot_v_dic; %#ok<AGROW>
displacements_template(i+1).plot_corrcoef_dic = obj.data_dic.displacements(i+1).plot_corrcoef_dic; %#ok<AGROW>
displacements_template(i+1).roi_dic = obj.data_dic.displacements(i+1).roi_dic; %#ok<AGROW>
displacements_template(i+1).plot_u_ref_formatted = plots_disp_f_prelim(i+1).plot_u_ref_formatted; %#ok<AGROW>
displacements_template(i+1).plot_v_ref_formatted = plots_disp_f_prelim(i+1).plot_v_ref_formatted; %#ok<AGROW>
displacements_template(i+1).roi_ref_formatted = rois_f_ref_prelim(i+1); %#ok<AGROW>
displacements_template(i+1).plot_u_cur_formatted = plots_disp_f_prelim(i+1).plot_u_cur_formatted; %#ok<AGROW>
displacements_template(i+1).plot_v_cur_formatted = plots_disp_f_prelim(i+1).plot_v_cur_formatted; %#ok<AGROW>
displacements_template(i+1).roi_cur_formatted = rois_f_cur_prelim(i+1); %#ok<AGROW>
end
dispinfo_template.type = obj.data_dic.dispinfo.type;
dispinfo_template.radius = obj.data_dic.dispinfo.radius;
dispinfo_template.spacing = obj.data_dic.dispinfo.spacing;
dispinfo_template.cutoff_diffnorm = obj.data_dic.dispinfo.cutoff_diffnorm;
dispinfo_template.cutoff_iteration = obj.data_dic.dispinfo.cutoff_iteration;
dispinfo_template.total_threads = obj.data_dic.dispinfo.total_threads;
dispinfo_template.stepanalysis = obj.data_dic.dispinfo.stepanalysis;
dispinfo_template.subsettrunc = obj.data_dic.dispinfo.subsettrunc;
dispinfo_template.imgcorr = obj.data_dic.dispinfo.imgcorr;
dispinfo_template.pixtounits = pixtounits_prelim;
dispinfo_template.units = units_prelim;
dispinfo_template.cutoff_corrcoef = cutoff_corrcoef_prelim;
dispinfo_template.lenscoef = lenscoef_prelim;
% Store data:
for i = 0:length(obj.current)-1
obj.data_dic.displacements(i+1) = displacements_template(i+1);
end
obj.data_dic.dispinfo(1) = dispinfo_template;
end
function callback_topmenu_calcstrain(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for computing the strains after the
% displacements have been formatted.
% Get strain radius ------------------------------------------%
% Check if strain has been calculated before
params_init = [];
if (~isempty(obj.data_dic.straininfo) && ~isempty(obj.data_dic.straininfo.radius) && ~isempty(obj.data_dic.straininfo.subsettrunc))
params_init(1) = obj.data_dic.straininfo.radius;
params_init(2) = obj.data_dic.straininfo.subsettrunc;
end
% Get strain parameters
[radius_strain_prelim,subsettrunc_prelim,outstate_radius_strain] = ncorr_gui_setstrainradius(obj.reference.imginfo, ...
[obj.current.imginfo], ...
[obj.data_dic.displacements.roi_ref_formatted], ...
[obj.data_dic.displacements.roi_cur_formatted], ...
{obj.data_dic.displacements.plot_u_ref_formatted}, ...
{obj.data_dic.displacements.plot_v_ref_formatted}, ...
{obj.data_dic.displacements.plot_u_cur_formatted}, ...
{obj.data_dic.displacements.plot_v_cur_formatted}, ...
obj.data_dic.dispinfo.spacing, ...
obj.data_dic.dispinfo.pixtounits, ...
obj.data_dic.dispinfo.units, ...
get(obj.handles_gui.figure,'OuterPosition'), ...
params_init);
% See if analysis was cancelled
if (outstate_radius_strain ~= out.success)
return;
end
% Calculate strains --------------------------------------%
% Calculate displacement gradients through least squares
% plane fit first
% Lagrangian
plots_dispgrad_ref_prelim = struct('plot_dudx',{},'plot_dudy',{},'plot_dvdx',{},'plot_dvdy',{},'plot_validpoints',{});
plots_dispgrad_cur_prelim = struct('plot_dudx',{},'plot_dudy',{},'plot_dvdx',{},'plot_dvdy',{},'plot_validpoints',{});
% Lagrangian
for i = 0:length(obj.current)-1
[plots_dispgrad_ref_prelim(i+1),outstate_dispgrad_ref] = ncorr_alg_dispgrad(obj.data_dic.displacements(i+1).plot_u_ref_formatted, ...
obj.data_dic.displacements(i+1).plot_v_ref_formatted, ...
obj.data_dic.displacements(i+1).roi_ref_formatted.formatted(), ...
int32(radius_strain_prelim), ...
obj.data_dic.dispinfo.pixtounits, ...
int32(obj.data_dic.dispinfo.spacing), ...
logical(subsettrunc_prelim), ...
int32(i), ...
int32(length(obj.current)));
% See if analysis was cancelled
if (outstate_dispgrad_ref ~= out.success)
return;
end
end
% Eulerian
for i = 0:length(obj.current)-1
% Eulerian
[plots_dispgrad_cur_prelim(i+1),outstate_dispgrad_cur] = ncorr_alg_dispgrad(obj.data_dic.displacements(i+1).plot_u_cur_formatted, ...
obj.data_dic.displacements(i+1).plot_v_cur_formatted, ...
obj.data_dic.displacements(i+1).roi_cur_formatted.formatted(), ...
int32(radius_strain_prelim), ...
obj.data_dic.dispinfo.pixtounits, ...
int32(obj.data_dic.dispinfo.spacing), ...
logical(subsettrunc_prelim), ...
int32(i), ...
int32(length(obj.current)));
% See if analysis was cancelled
if (outstate_dispgrad_cur ~= out.success)
return;
end
end
% Store
% Dont query overwrite, just do it since calculating strain maps is quick
obj.clear_downstream('strains');
% Package info:
for i = 0:length(obj.current)-1
% Green Lagrangian
strains_template(i+1).plot_exx_ref_formatted = (1/2)*(2*plots_dispgrad_ref_prelim(i+1).plot_dudx+plots_dispgrad_ref_prelim(i+1).plot_dudx.^2+plots_dispgrad_ref_prelim(i+1).plot_dvdx.^2); %#ok<AGROW>
strains_template(i+1).plot_exy_ref_formatted = (1/2)*(plots_dispgrad_ref_prelim(i+1).plot_dudy+plots_dispgrad_ref_prelim(i+1).plot_dvdx+plots_dispgrad_ref_prelim(i+1).plot_dudx.*plots_dispgrad_ref_prelim(i+1).plot_dudy+plots_dispgrad_ref_prelim(i+1).plot_dvdx.*plots_dispgrad_ref_prelim(i+1).plot_dvdy); %#ok<AGROW>
strains_template(i+1).plot_eyy_ref_formatted = (1/2)*(2*plots_dispgrad_ref_prelim(i+1).plot_dvdy+plots_dispgrad_ref_prelim(i+1).plot_dudy.^2+plots_dispgrad_ref_prelim(i+1).plot_dvdy.^2); %#ok<AGROW>
strains_template(i+1).roi_ref_formatted = obj.data_dic.displacements(i+1).roi_ref_formatted.get_union(plots_dispgrad_ref_prelim(i+1).plot_validpoints,0); %#ok<AGROW>
% Eulerian-Almansi
strains_template(i+1).plot_exx_cur_formatted = (1/2)*(2*plots_dispgrad_cur_prelim(i+1).plot_dudx-plots_dispgrad_cur_prelim(i+1).plot_dudx.^2-plots_dispgrad_cur_prelim(i+1).plot_dvdx.^2); %#ok<AGROW>
strains_template(i+1).plot_exy_cur_formatted = (1/2)*(plots_dispgrad_cur_prelim(i+1).plot_dudy+plots_dispgrad_cur_prelim(i+1).plot_dvdx-plots_dispgrad_cur_prelim(i+1).plot_dudx.*plots_dispgrad_cur_prelim(i+1).plot_dudy-plots_dispgrad_cur_prelim(i+1).plot_dvdx.*plots_dispgrad_cur_prelim(i+1).plot_dvdy); %#ok<AGROW>
strains_template(i+1).plot_eyy_cur_formatted = (1/2)*(2*plots_dispgrad_cur_prelim(i+1).plot_dvdy-plots_dispgrad_cur_prelim(i+1).plot_dudy.^2-plots_dispgrad_cur_prelim(i+1).plot_dvdy.^2); %#ok<AGROW>
strains_template(i+1).roi_cur_formatted = obj.data_dic.displacements(i+1).roi_cur_formatted.get_union(plots_dispgrad_cur_prelim(i+1).plot_validpoints,0); %#ok<AGROW>
end
% Store info:
for i = 0:length(obj.current)-1
obj.data_dic.strains(i+1) = strains_template(i+1);
end
obj.data_dic.straininfo(1).radius = radius_strain_prelim;
obj.data_dic.straininfo(1).subsettrunc = subsettrunc_prelim;
% Tell user calculating strains was successful
msgbox('Strains calculation complete. Press ok to finish.','WindowStyle','modal');
end
function callback_topmenu_viewplot(obj,hObject,eventdata,type_fig) %#ok<INUSL>
% This is the callback for viewing the plots after the
% displacements have been formatted and after the strains
% have been computed.
% Get Data
handles_plot = getappdata(obj.handles_gui.figure,'handles_plot');
% Deactivate closerequestfcn - this prevents any closing of
% figures when handles_plot is being updated
for i = 0:length(handles_plot)-1
set(handles_plot(i+1),'CloseRequestFcn','');
end
% Cycle over figures (it's possible type fig has more than one
% type).
for i = 0:length(type_fig)-1
% Check if plot already exists
plotexists = false;
for j = 0:length(handles_plot)-1
if (strcmp(getappdata(handles_plot(j+1),'type_plot'),type_fig{i+1}))
% Plot already exists, bring it back to focus
figure(handles_plot(j+1));
plotexists = true;
break;
end
end
if (~plotexists)
% Get params_init;
params_init = cell(0);
if (~isempty(handles_plot))
% All windows will have the same paramters so just
% grab the info from the first window
params_init{1} = getappdata(handles_plot(1),'num_cur'); % {1} = num_cur
% Get data
params_init{2} = getappdata(handles_plot(1),'scalebarlength'); % {2} = scalebarlength
params_init{3} = getappdata(handles_plot(1),'val_checkbox_scalebar'); % {3} = scalebar;
params_init{4} = getappdata(handles_plot(1),'val_checkbox_axes'); % {4} = axes;
params_init{5} = getappdata(handles_plot(1),'val_popupmenu'); % {5} = lagrangian or eulerian
params_init{6} = strcmp(get(getappdata(handles_plot(1),'handle_zoom'),'Enable'),'on'); % {6} = zoomed
params_init{7} = strcmp(get(getappdata(handles_plot(1),'handle_pan'),'Enable'),'on'); % {7} = panned
end
% Go over friends list; find the right most figure and
% make this the figure whose coordinates are used for
% pos_parent.
if (isempty(handles_plot))
% Use coordinates of ncorr
pos_parent = get(obj.handles_gui.figure,'OuterPosition');
else
% Plots already exist, fight right most plot
pos_parent = get(handles_plot(1),'OuterPosition');
for j = 1:length(handles_plot)-1
pos_buf = get(handles_plot(j+1),'OuterPosition');
if (pos_buf(1) + pos_buf(3) > pos_parent(1) + pos_parent(3))
pos_parent = pos_buf;
elseif (pos_buf(1) + pos_buf(3) == pos_parent(1) + pos_parent(3))
% If they are equal, get the one that is
% lower
if (pos_buf(2) < pos_parent(2))
pos_parent = pos_buf;
end
end
end
end
% Create new plot - This function will return all
% gui handles. Store these as "friends" so plots can
% remain consistent. The figure has already has its
% closereqestfcn disabled
handles_gui_new = ncorr_gui_viewplots(obj.reference.imginfo, ...
[obj.current.imginfo], ...
obj.data_dic, ...
type_fig{i+1}, ...
pos_parent, ...
params_init);
% Figure can be invalid if the ROI is empty
if (ishandle(handles_gui_new.figure))
% Set delete functions
set(handles_gui_new.figure,'DeleteFcn',ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata)callback_update_handles_plot(obj,hObject,eventdata),obj.handles_gui.figure));
% Update friends list - this allows the things to
% sync
if (isempty(handles_plot))
% Check if a plot already exists - if it does then get
% the old friends list from the first plot
friends_old = [];
else
friends_old = getappdata(handles_plot(1),'friends');
end
friends_new = horzcat(friends_old,{handles_gui_new});
% Link the axes
vec_friends = [friends_new{:}];
linkaxes([vec_friends.axes_formatplot],'xy');
% Set Data
% First update handles_gui_new
setappdata(handles_gui_new.figure,'friends',friends_new);
% Now update the preexisting handles
for j = 0:length(handles_plot)-1
setappdata(handles_plot(j+1),'friends',friends_new);
end
% Now store figure handle
handles_plot = horzcat(handles_plot,handles_gui_new.figure); %#ok<AGROW>
end
end
end
% Reactivate closerequestfcns
for i = 0:length(handles_plot)-1
set(handles_plot(i+1),'CloseRequestFcn','closereq');
end
% Store Data
setappdata(obj.handles_gui.figure,'handles_plot',handles_plot);
end
function callback_topmenu_closeplots(obj,hObject,eventdata) %#ok<INUSD>
% This callback closes all the open plots.
obj.close_dicplots('all');
end
%-----------------------------------------------------------------%
% Other Callbacks ------------------------------------------------%
%-----------------------------------------------------------------%
function callback_update_title(obj,hObject,eventdata) %#ok<INUSD>
% This function will update the title of ncorr to display the
% handle pointing to ncorr
% Get Name
name = util_get_name(obj);
if (isempty(name))
% No handle exists
set(obj.handles_gui.figure,'Name','Ncorr');
else
% Handle exists
set(obj.handles_gui.figure,'Name',['Ncorr - ' name]);
end
end
function callback_edit_imgnum(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for setting the image number directly
% Get data
num_cur = getappdata(obj.handles_gui.figure,'num_cur');
% Get img num
num_cur_prelim = str2double(get(obj.handles_gui.edit_imgnum,'string'));
if (ncorr_util_isintbb(num_cur_prelim,1,length(obj.current),'Current image number') == out.success)
% convert num_cur_prelim to zero based indexed
num_cur = num_cur_prelim-1;
end
% Set data
setappdata(obj.handles_gui.figure,'num_cur',num_cur);
end
function callback_button_left(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for the left button to display different
% current images
% Get data
num_cur = getappdata(obj.handles_gui.figure,'num_cur');
% Check for overshoot
if (num_cur > 0)
num_cur = num_cur-1;
end
% Set data
setappdata(obj.handles_gui.figure,'num_cur',num_cur);
end
function callback_button_right(obj,hObject,eventdata) %#ok<INUSD>
% This is the callback for the right button to display different
% current images
% Get data
num_cur = getappdata(obj.handles_gui.figure,'num_cur');
% Check for overshoot
if (num_cur < length(obj.current)-1)
num_cur = num_cur+1;
end
% Set data
setappdata(obj.handles_gui.figure,'num_cur',num_cur);
end
function callback_update_handles_plot(obj,hObject,eventdata) %#ok<INUSD>
% This function is called when a plot figure is closed; this
% function removes the figure handle from handles_plot.
% Get data
handles_plot = getappdata(obj.handles_gui.figure,'handles_plot');
% Disable closerequestfcns - ensure other plots aren't closed
% while the handle is being updated.
for i = 0:length(handles_plot)-1
set(handles_plot(i+1),'CloseRequestFcn','');
end
% Determine index of closing figure
closingfig = gcbf;
idx_closingfig = -1;
for i = 0:length(handles_plot)-1
if (handles_plot(i+1) == closingfig) % update handle array
idx_closingfig = i;
break;
end
end
% Delete closing figure from handles_plot
handles_plot(idx_closingfig+1) = [];
% Update Friends
for i = 0:length(handles_plot)-1
% Get friends list for each plot handle. Delete the friend
% that contains closing fig
% Get data
friends = getappdata(handles_plot(i+1),'friends');
for j = 0:length(friends)-1
if (friends{j+1}.figure == closingfig)
friends(j+1) = [];
break;
end
end
% Set data
setappdata(handles_plot(i+1),'friends',friends);
end
% Reenable CloseRequestfFcns
for i = 0:length(handles_plot)-1
set(handles_plot(i+1),'CloseRequestFcn','closereq');
end
% Set data
setappdata(obj.handles_gui.figure,'handles_plot',handles_plot);
end
function callback_close_function(obj,hObject,eventdata,force) %#ok<INUSL>
% Force will cause a force close if it's true - this situation
% occurs when the user manually deletes the GUI handle
closencorr = false;
if (~force && ~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements))
contbutton = questdlg('Prior DIC data has been detected. If you continue without saving, this data will be deleted. Do you want to proceed?','Continue Operation','Yes','No','Yes');
if (strcmp(contbutton,'Yes'))
closencorr = true;
end
else
% Force close if user calls "delete(handles_ncorr)" or if
% dic analysis has not been run yet.
closencorr = true;
end
if (closencorr)
% Close plot figures
obj.close_dicplots('all');
% Delete timer
timer_ncorr = getappdata(obj.handles_gui.figure,'timer');
if (isa(timer_ncorr,'timer') && isvalid(timer_ncorr))
stop(timer_ncorr);
delete(timer_ncorr);
end
% Close GUI
delete(obj.handles_gui.figure);
% Delete data
delete(obj);
end
end
%-----------------------------------------------------------------%
% Other Functions ------------------------------------------------%
%-----------------------------------------------------------------%
function close_dicplots(obj,closetype)
% This is the function for closing either the displacement plots,
% strain plots, or all the plots.
% Displacement plots
if (strcmp(closetype,'displacements') || strcmp(closetype,'all'));
% Get data
handles_plot = getappdata(obj.handles_gui.figure,'handles_plot');
handles_plot_close = [];
for i = 0:length(handles_plot)-1
type_plot = getappdata(handles_plot(i+1),'type_plot');
if (strcmp(type_plot,'u') || strcmp(type_plot,'v'))
handles_plot_close = horzcat(handles_plot_close,handles_plot(i+1)); %#ok<AGROW>
end
end
% Close figures
close(handles_plot_close); % handles_plot updates after this
end
% Strain plots
if (strcmp(closetype,'strains') || strcmp(closetype,'all'));
% Get Data
handles_plot = getappdata(obj.handles_gui.figure,'handles_plot');
handles_plot_close = [];
for i = 0:length(handles_plot)-1
type_plot = getappdata(handles_plot(i+1),'type_plot');
if (strcmp(type_plot,'exx') || strcmp(type_plot,'exy') || strcmp(type_plot,'eyy'))
handles_plot_close = horzcat(handles_plot_close,handles_plot(i+1)); %#ok<AGROW>
end
end
% Close figures
close(handles_plot_close); % handles_plot updates after this
end
end
function overwrite = clear_downstream(obj,action)
% Middle of callback - alert user if data is going to be
% overwritten and then clear downstream data.
% Initialize - set default to true.
overwrite = true;
% See whether to query overwrite
if (strcmp(action,'all') || strcmp(action,'set_ref') || strcmp(action,'set_cur') || strcmp(action,'set_roi') || strcmp(action,'set_dicparameters') || strcmp(action,'dicanalysis'))
% Only query if displacements have been set, since this is
% usually the most time consuming process
if (~isempty(obj.data_dic.displacements))
contbutton = questdlg('Prior DIC data has been detected. If you continue without saving, this data will be deleted. Do you want to proceed?','Continue Operation','Yes','No','Yes');
if (~strcmp(contbutton,'Yes'))
overwrite = false;
end
end
end
% If overwrite is permitted, then clear downstream data.
if (overwrite)
% Get field names since they are used a lot
fields_data_dic = fieldnames(obj.data_dic);
fields_dic_data_dispinfo = fieldnames(obj.data_dic.dispinfo);
% Handle each step accordingly
if (strcmp(action,'all'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% All info needs to be deleted
obj.reference(:) = [];
obj.current(:) = [];
setappdata(obj.handles_gui.figure,'num_cur',[]);
for i = 0:length(fields_data_dic)-1
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
elseif (strcmp(action,'set_ref'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% Clear all reference info
obj.reference(:) = [];
% For current images, clear all ROIs if analysis
% was regular. If it was backward, then clear all
% ROIs except for the last one
if (~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo))
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
for i = 0:length(obj.current)-1
obj.current(i+1).roi = ncorr_class_roi.empty;
end
else
for i = 0:length(obj.current)-2
obj.current(i+1).roi = ncorr_class_roi.empty;
end
end
end
% Clear everything in data_dic except for dispinfo
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete everything except for the type in
% dispinfo. If the type was regular, then delete
% that too
if (~isempty(obj.data_dic.dispinfo))
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
obj.data_dic.dispinfo(:) = [];
else
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
end
end
elseif (strcmp(action,'set_cur'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% Delete reference ROI if type is backward
if (~isempty(obj.reference) && ~isempty(obj.data_dic.dispinfo))
if (strcmp(obj.data_dic.dispinfo.type,'backward'))
obj.reference.roi = ncorr_class_roi.empty;
end
end
% Clear all current images
obj.current(:) = [];
setappdata(obj.handles_gui.figure,'num_cur',[]);
% Clear everything in data_dic except for dispinfo
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete everything except for the type in
% dispinfo. If the type was backward, then delete
% that too
if (~isempty(obj.data_dic.dispinfo))
if (strcmp(obj.data_dic.dispinfo.type,'backward'))
obj.data_dic.dispinfo(:) = [];
else
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
end
end
elseif (strcmp(action,'set_roi'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% Clear all ROIs in reference image
if (~isempty(obj.reference))
obj.reference.roi = ncorr_class_roi.empty;
end
% Clear all ROIS in current image
if (~isempty(obj.current))
for i = 0:length(obj.current)-1
obj.current(i+1).roi = ncorr_class_roi.empty;
end
end
% Clear all data_dic
for i = 0:length(fields_data_dic)-1
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
elseif (strcmp(action,'set_dicparameters'))
% Close DIC figs if they exist -----------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% If type is regular, delete all current ROIS.
% If type is backward, delete all ROIS except for
% last current ROI
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
for i = 0:length(obj.current)-1
obj.current(i+1).roi = ncorr_class_roi.empty;
end
else
obj.reference.roi = ncorr_class_roi.empty;
for i = 0:length(obj.current)-2
obj.current(i+1).roi = ncorr_class_roi.empty;
end
end
% Clear everything in data_dic except for dispinfo
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete everything in dispinfo except for the type
fields_dic_data_dispinfo = fieldnames(obj.data_dic.dispinfo);
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
elseif (strcmp(action,'dicanalysis'))
% Close all DIC figs if they exist -------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% If type is regular, delete all current ROIs.
% If type is backward, delete all ROIs except for
% last current ROI
if (strcmp(obj.data_dic.dispinfo.type,'regular'))
for i = 0:length(obj.current)-1
obj.current(i+1).roi = ncorr_class_roi.empty;
end
else
obj.reference.roi = ncorr_class_roi.empty;
for i = 0:length(obj.current)-2
obj.current(i+1).roi = ncorr_class_roi.empty;
end
end
% Delete all info except dispinfo
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete downstream data in data_dic.dispinfo:
fields_dic_data_dispinfo = fieldnames(obj.data_dic.dispinfo);
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'radius') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'spacing') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'cutoff_diffnorm') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'cutoff_iteration') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'total_threads') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'stepanalysis') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'subsettrunc'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
elseif (strcmp(action,'formatdisp'))
% Close DIC figs if they exist -----------------------%
obj.close_dicplots('all');
% Clear downstream data ------------------------------%
% Delete all info except for displacements and
% dispinfo;
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'displacements') && ...
~strcmp(fields_data_dic{i+1},'dispinfo'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
% Delete downstream data in data_dic.dispinfo:
fields_dic_data_dispinfo = fieldnames(obj.data_dic.dispinfo);
for i = 0:length(fields_dic_data_dispinfo)-1
if (~strcmp(fields_dic_data_dispinfo{i+1},'type') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'radius') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'spacing') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'cutoff_diffnorm') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'cutoff_iteration') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'total_threads') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'stepanalysis') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'subsettrunc') && ...
~strcmp(fields_dic_data_dispinfo{i+1},'imgcorr'))
obj.data_dic.dispinfo.(fields_dic_data_dispinfo{i+1})(:) = [];
end
end
% Delete downstream data in data_dic.displacements:
dic_data_disp_fields = fieldnames(obj.data_dic.displacements);
for i = 0:length(dic_data_disp_fields)-1
if (~strcmp(dic_data_disp_fields{i+1},'plot_u_dic') && ...
~strcmp(dic_data_disp_fields{i+1},'plot_v_dic') && ...
~strcmp(dic_data_disp_fields{i+1},'plot_corrcoef_dic') && ...
~strcmp(dic_data_disp_fields{i+1},'roi_dic'))
for j = 0:length(obj.data_dic.displacements)-1
obj.data_dic.displacements(j+1).(dic_data_disp_fields{i+1})(:) = [];
end
end
end
elseif (strcmp(action,'strains'))
% Close strain figs if they exist --------------------%
obj.close_dicplots('strains');
% Clear downstream data ------------------------------%
% Delete all info except dispinfo and displacements
for i = 0:length(fields_data_dic)-1
if (~strcmp(fields_data_dic{i+1},'dispinfo') && ...
~strcmp(fields_data_dic{i+1},'displacements'))
obj.data_dic.(fields_data_dic{i+1})(:) = [];
end
end
end
end
end
function freeze_menu(obj)
% This function disables the menu when callbacks are executing
set(obj.handles_gui.topmenu_file,'Enable','off');
set(obj.handles_gui.topmenu_regionofinterest,'Enable','off');
set(obj.handles_gui.topmenu_analysis,'Enable','off');
set(obj.handles_gui.topmenu_plot,'Enable','off');
end
function unfreeze_menu(obj)
% This function enables the menu when callbacks are done
set(obj.handles_gui.topmenu_file,'Enable','on');
set(obj.handles_gui.topmenu_regionofinterest,'Enable','on');
set(obj.handles_gui.topmenu_analysis,'Enable','on');
set(obj.handles_gui.topmenu_plot,'Enable','on');
end
function update_topmenu(obj)
% This function updates menu items depending on what is loaded
% Reference image is loaded:
if (~isempty(obj.reference))
set(obj.handles_gui.topmenu_setroi_ref,'Enable','on');
else
set(obj.handles_gui.topmenu_setroi_ref,'Enable','off');
end
% Current image is loaded:
if (~isempty(obj.current))
set(obj.handles_gui.topmenu_setroi_cur,'Enable','on');
else
set(obj.handles_gui.topmenu_setroi_cur,'Enable','off');
end
% Reference image, current image, and ROI are loaded:
% Must check if analysis is regular or backward because ROIs
% can be set through the DIC analysis
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo) && ...
((strcmp(obj.data_dic.dispinfo.type,'regular') && ~isempty(obj.reference.roi)) || ...
((strcmp(obj.data_dic.dispinfo.type,'backward') && ~isempty(obj.current(end).roi)))))
set(obj.handles_gui.topmenu_setdicparameters,'Enable','on');
else
set(obj.handles_gui.topmenu_setdicparameters,'Enable','off');
end
% Reference image, current image, and DIC parameters are loaded:
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo) && ...
~isempty(obj.data_dic.dispinfo.radius) && ...
~isempty(obj.data_dic.dispinfo.spacing) && ...
~isempty(obj.data_dic.dispinfo.cutoff_diffnorm) && ...
~isempty(obj.data_dic.dispinfo.cutoff_iteration) && ...
~isempty(obj.data_dic.dispinfo.total_threads) && ...
~isempty(obj.data_dic.dispinfo.stepanalysis) && ...
~isempty(obj.data_dic.dispinfo.subsettrunc))
set(obj.handles_gui.topmenu_perfdic,'Enable','on');
else
set(obj.handles_gui.topmenu_perfdic,'Enable','off');
end
% Reference image, current image, and DIC analysis are loaded:
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements))
set(obj.handles_gui.topmenu_savedata,'Enable','on');
set(obj.handles_gui.topmenu_formatdisp,'Enable','on');
else
set(obj.handles_gui.topmenu_savedata,'Enable','off');
set(obj.handles_gui.topmenu_formatdisp,'Enable','off');
end
% Reference image, current image, DIC data, and formatted
% displacements are loaded:
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements) && ...
~isempty(obj.data_dic.dispinfo.pixtounits) && ...
~isempty(obj.data_dic.dispinfo.units) && ...
~isempty(obj.data_dic.dispinfo.cutoff_corrcoef) && ...
~isempty(obj.data_dic.dispinfo.lenscoef))
set(obj.handles_gui.topmenu_calcstrain,'Enable','on');
set(obj.handles_gui.topmenu_viewdispplot_u,'Enable','on');
set(obj.handles_gui.topmenu_viewdispplot_v,'Enable','on');
set(obj.handles_gui.topmenu_viewdispplot_all,'Enable','on');
set(obj.handles_gui.topmenu_closeplots,'Enable','on');
else
set(obj.handles_gui.topmenu_calcstrain,'Enable','off');
set(obj.handles_gui.topmenu_viewdispplot_u,'Enable','off');
set(obj.handles_gui.topmenu_viewdispplot_v,'Enable','off');
set(obj.handles_gui.topmenu_viewdispplot_all,'Enable','off');
set(obj.handles_gui.topmenu_closeplots,'Enable','off');
end
% Reference image, current image, DIC data, and strains are
% loaded
if (~isempty(obj.reference) && ~isempty(obj.current) && ~isempty(obj.data_dic.dispinfo)&& ~isempty(obj.data_dic.displacements) && ...
~isempty(obj.data_dic.straininfo) && ~isempty(obj.data_dic.strains))
set(obj.handles_gui.topmenu_viewstrainplot_exx,'Enable','on');
set(obj.handles_gui.topmenu_viewstrainplot_exy,'Enable','on');
set(obj.handles_gui.topmenu_viewstrainplot_eyy,'Enable','on');
set(obj.handles_gui.topmenu_viewstrainplot_all,'Enable','on');
else
set(obj.handles_gui.topmenu_viewstrainplot_exx,'Enable','off');
set(obj.handles_gui.topmenu_viewstrainplot_exy,'Enable','off');
set(obj.handles_gui.topmenu_viewstrainplot_eyy,'Enable','off');
set(obj.handles_gui.topmenu_viewstrainplot_all,'Enable','off');
end
end
function update_dicstatetext(obj)
% This function updates state text depending on what is loaded
% Reference image:
if (~isempty(obj.reference))
set(obj.handles_gui.text_refloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_refloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% Current image:
if (~isempty(obj.current))
set(obj.handles_gui.text_curloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_curloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% ROI: Must check if analysis is regular or backward because ROIs
% can be set through the DIC analysis
if (~isempty(obj.data_dic.dispinfo)&& ...
((strcmp(obj.data_dic.dispinfo.type,'regular') && ~isempty(obj.reference.roi)) || ...
((strcmp(obj.data_dic.dispinfo.type,'backward') && ~isempty(obj.current(end).roi)))))
set(obj.handles_gui.text_roiloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_roiloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% DIC parameters:
if (~isempty(obj.data_dic.dispinfo) && ...
~isempty(obj.data_dic.dispinfo.radius) && ...
~isempty(obj.data_dic.dispinfo.spacing) && ...
~isempty(obj.data_dic.dispinfo.cutoff_diffnorm) && ...
~isempty(obj.data_dic.dispinfo.cutoff_iteration) && ...
~isempty(obj.data_dic.dispinfo.total_threads) && ...
~isempty(obj.data_dic.dispinfo.stepanalysis) && ...
~isempty(obj.data_dic.dispinfo.subsettrunc))
set(obj.handles_gui.text_dicparametersloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_dicparametersloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% DIC analysis:
if (~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements))
set(obj.handles_gui.text_dicloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_dicloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% Displacements formatted:
if (~isempty(obj.data_dic.dispinfo) && ~isempty(obj.data_dic.displacements) && ...
~isempty(obj.data_dic.dispinfo.pixtounits) && ...
~isempty(obj.data_dic.dispinfo.units) && ...
~isempty(obj.data_dic.dispinfo.cutoff_corrcoef) && ...
~isempty(obj.data_dic.dispinfo.lenscoef))
set(obj.handles_gui.text_disploaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_disploaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
% Strains:
if (~isempty(obj.data_dic.straininfo) && ~isempty(obj.data_dic.strains))
set(obj.handles_gui.text_strainloaded_s,'String','SET','ForegroundColor','g','FontWeight','bold');
else
set(obj.handles_gui.text_strainloaded_s,'String','NOT SET','ForegroundColor','r','FontWeight','normal');
end
end
function update_axes(obj,action)
% Get data
num_cur = getappdata(obj.handles_gui.figure,'num_cur');
% Updates axes, axes buttons, and axes texts below:
if (strcmp(action,'set'))
% Reference axes
if (isempty(obj.reference))
% Clear reference image
cla(obj.handles_gui.axes_ref);
set(obj.handles_gui.text_refname,'String','Name: ');
set(obj.handles_gui.text_refresolution,'String','Resolution: ');
else
% Set reference image and format axes
imshow(obj.reference.imginfo.get_img(),[obj.reference.imginfo.min_gs obj.reference.imginfo.max_gs],'Parent',obj.handles_gui.axes_ref);
set(obj.handles_gui.axes_ref ,'Visible','off');
% Show image text
set(obj.handles_gui.text_refname,'String',['Name: ' obj.reference.imginfo.name]);
set(obj.handles_gui.text_refresolution,'String',['Resolution: ' num2str(obj.reference.imginfo.width) ' x ' num2str(obj.reference.imginfo.height)]);
end
% Current axes
if (isempty(obj.current))
% Disable buttons
set(obj.handles_gui.button_right,'Enable','off');
set(obj.handles_gui.button_left,'Enable','off');
set(obj.handles_gui.edit_imgnum,'Enable','off');
set(obj.handles_gui.edit_imgnum,'String',num2str(num_cur));
% Reset current image:
cla(obj.handles_gui.axes_cur);
% Update current image name and resolution:
set(obj.handles_gui.text_curname,'String','Name: ');
set(obj.handles_gui.text_curresolution,'String','Resolution: ');
else
% Set current image and format axes
imshow(obj.current(num_cur+1).imginfo.get_img(),[obj.current(num_cur+1).imginfo.min_gs obj.current(num_cur+1).imginfo.max_gs],'Parent',obj.handles_gui.axes_cur);
set(obj.handles_gui.axes_cur ,'Visible','off');
% Format/show text
set(obj.handles_gui.text_curname,'String',['Name: ' obj.current(num_cur+1).imginfo.name]);
set(obj.handles_gui.text_curresolution,'String',['Resolution: ' num2str(obj.current(num_cur+1).imginfo.width) ' x ' num2str(obj.current(num_cur+1).imginfo.height)]);
% Set left/right buttons and editbox
set(obj.handles_gui.edit_imgnum,'String',num2str(num_cur+1));
if (length(obj.current) == 1)
set(obj.handles_gui.button_right,'Enable','off');
set(obj.handles_gui.button_left,'Enable','off');
set(obj.handles_gui.edit_imgnum,'Enable','off');
elseif (num_cur == 0)
set(obj.handles_gui.button_right,'Enable','on');
set(obj.handles_gui.button_left,'Enable','off');
set(obj.handles_gui.edit_imgnum,'Enable','on');
elseif (num_cur == length(obj.current)-1)
set(obj.handles_gui.button_right,'Enable','off');
set(obj.handles_gui.button_left,'Enable','on');
set(obj.handles_gui.edit_imgnum,'Enable','on');
else
set(obj.handles_gui.button_right,'Enable','on');
set(obj.handles_gui.button_left,'Enable','on');
set(obj.handles_gui.edit_imgnum,'Enable','on');
end
end
% ROI axes
if (~isempty(obj.data_dic.dispinfo) && strcmp(obj.data_dic.dispinfo.type,'regular'))
% Set reference ROI
imshow(obj.reference.roi.mask,'Parent',obj.handles_gui.axes_roi);
set(obj.handles_gui.axes_roi,'Visible','off');
elseif (~isempty(obj.data_dic.dispinfo) && strcmp(obj.data_dic.dispinfo.type,'backward'))
% Set last current ROI
imshow(obj.current(end).roi.mask,'Parent',obj.handles_gui.axes_roi);
set(obj.handles_gui.axes_roi,'Visible','off');
else
% Clear ROI
cla(obj.handles_gui.axes_roi);
end
end
end
function outstate = check_matlabcompat(obj) %#ok<MANU>
% This function checks the matlab compatibility.
% Initialize output
outstate = out.failed;
vm = datevec(version('-date'));
if (vm(1) < 2009)
% Pop error message but allow user to continue
h_error = errordlg('Developed using MATLAB 2009; may not work for versions before this date. Ncorr will continue.','Error','modal');
uiwait(h_error);
end
% Check to make sure correct toolboxes are installed ---------%
% Requires the image processing toolbox and the statistics
% toolbox
% Note that Matlab combined their statistics and machine
% learning toolboxes so just search for "Statistics" to work
% for both cases.
v = ver;
if (isempty(strfind([v.Name],'Image Processing Toolbox')) || isempty(strfind([v.Name],'Statistics')))
h_error = errordlg('Requires the image processing and statistics toolbox.','Error','modal');
uiwait(h_error);
return;
end
% Set output
outstate = out.success;
end
function outstate = check_mexinstall(obj)
% Check to see if mex files exist and loads ncorr_installinfo ----%
% Initialize output
outstate = out.cancelled;
% Files to compile:
% These are stand alone .cpp files compiled with '-c' flag:
lib_ncorr_cpp = {'standard_datatypes','ncorr_datatypes','ncorr_lib'};
% These are .cpp mex functions compiled with libraries
func_ncorr_cpp = {'ncorr_alg_formmask', ...
'ncorr_alg_formregions', ...
'ncorr_alg_formboundary', ...
'ncorr_alg_formthreaddiagram', ...
'ncorr_alg_formunion', ...
'ncorr_alg_extrapdata', ...
'ncorr_alg_adddisp', ...
'ncorr_alg_convert', ...
'ncorr_alg_dispgrad'};
% These are .cpp mex functions compiled with libraries and possibly openmp:
func_ncorr_openmp_cpp = {'ncorr_alg_testopenmp','ncorr_alg_calcseeds','ncorr_alg_rgdic'};
% Get object extension:
if (ispc) % pc
objext = 'obj';
elseif (isunix) % unix
objext = 'o';
end
% See if these files have already been compiled:
compile = false;
% Check libraries first
for i = 0:length(lib_ncorr_cpp)-1
if (~exist([lib_ncorr_cpp{i+1} '.' objext],'file'))
compile = true;
break;
end
end
% Check ncorr functions next
for i = 0:length(func_ncorr_cpp)-1
if (~exist([func_ncorr_cpp{i+1} '.' mexext],'file'))
compile = true;
break;
end
end
% Check ncorr functions with openmp
for i = 0:length(func_ncorr_openmp_cpp)-1
if (~exist([func_ncorr_openmp_cpp{i+1} '.' mexext],'file'))
compile = true;
break;
end
end
if (compile)
% One of the compiled files is missing - tell user that ncorr
% will recompile files.
e = msgbox('One of the compiled files is missing. If using automatic installation, then mex files will compile; if using manual installation, please close Ncorr and make sure all the files compiled properly.','WindowStyle','modal');
uiwait(e);
end
if (~compile)
% Functions have already been compiled - check
% "ncorr_installinfo.txt" file to verify openmp support.
% If "ncorr_installinfo.txt" has incorrect formatting, then
% files will be recompiled. If "ncorr_installinfo.txt" is
% empty, ncorr will take this as the standard way to
% reinstall mex files.
try
% ncorr_installinfo should have the format of:
% [support_openmp_prelim total_cores]
ncorr_installinfo = dlmread('ncorr_installinfo.txt');
if (size(ncorr_installinfo,1) == 1 && size(ncorr_installinfo,2) == 2)
% ncorr_installinfo.txt has the correct number of
% elements
if ((ncorr_installinfo(1) == 0 || ncorr_installinfo(1) == 1) && ...
ncorr_installinfo(2) >= 1)
% Assuming contents have not been modified
% by user, set them:
obj.support_openmp = logical(ncorr_installinfo(1));
obj.total_cores = ncorr_installinfo(2);
else
% ncorr_installinfo.txt has incorrect values
h_error = errordlg('For some reason "ncorr_installinfo.txt" has incorrect values. Program will recompile if using automatic installing. If manually installing Ncorr, please close it and make sure the "ncorr_installinfo.txt" was created correctly.','Error','modal');
uiwait(h_error);
% recompile files
compile = true;
end
elseif (isempty(ncorr_installinfo))
% ncorr_installinfo is empty, this is the stanard
% way to reinstall Ncorr.
h_error = msgbox('"ncorr_installinfo.txt" file is empty. Program will recompile if using automatic installing. If manually installing Ncorr, please close it and make sure the "ncorr_installinfo.txt" was created correctly.','WindowStyle','modal');
uiwait(h_error);
% recompile files
compile = true;
else
% ncorr_installinfo.txt has extra values which
% aren't supposed to be there
h_error = errordlg('For some reason the "ncorr_installinfo.txt" file has extra or missing values. Program will recompile if using automatic installing. If manually installing Ncorr, please close it and make sure the "ncorr_installinfo.txt" was created correctly.','Error','modal');
uiwait(h_error);
% recompile files
compile = true;
end
catch %#ok<CTCH>
% Returns error if file does not exist or format is
% wrong
h_error = msgbox('For some reason the "ncorr_installinfo.txt" file is missing or has improper format. Program will recompile if using automatic installing. If manually installing Ncorr, please close it and make sure the "ncorr_installinfo.txt" was created correctly.','WindowStyle','modal');
uiwait(h_error);
% recompile files
compile = true;
end
end
if (~compile)
% Check if previous installation was corrupted by OpenMP
% support which does not actually exist
if (obj.support_openmp)
if (~ncorr_alg_testopenmp())
% recompile files
compile = true;
end
end
end
%-------------------------------------------------------------%
% BEGIN COMPILE SECTION %
%-------------------------------------------------------------%
% COMMENT THIS SECTION OUT AND MANUALLY COMPILE IF AUTOMATIC %
% COMPILATION FAILS!!! %
% ------------------------------------------------------------%
try
if (compile)
% Check if ncorr.m is in current directory
listing = dir;
if (any(strcmp('ncorr.m',{listing.name})))
% Ask user about openmp support
[support_openmp_prelim,total_cores_prelim,outstate_install] = gui_install(get(obj.handles_gui.figure,'OuterPosition'));
% See if openmp GUI was cancelled
if (outstate_install ~= out.success)
return;
end
% Get compiler flags for openmp support. Depends
% on both OS and compiler.
flags_f = {};
if (support_openmp_prelim)
% Get compiler information
info_comp = mex.getCompilerConfigurations('cpp');
if ((isfield(struct(info_comp),'Details') && isfield(struct(info_comp.Details),'CompilerExecutable')))
% Get compiler
compiler = info_comp.Details.CompilerExecutable;
if (~isempty(strfind(compiler,'cl')))
% This is Microsoft visual studio
% Openmp flag is /openmp
flags_f = horzcat(flags_f{:},{'COMPFLAGS="$COMPFLAGS'},{'/openmp'},{'/DNCORR_OPENMP"'});
elseif (~isempty(strfind(compiler,'g++')))
% This is the GNU compiler; this is
% assumed to be Linux.
% NOTE: GCC must manually link
% against -lgomp. -lgomp also has
% to be placed as the very last
% library or else it will not compile
% correctly.
% Openmp flag is -fopenmp
flags_f = horzcat(flags_f{:},{'CXXFLAGS="$CXXFLAGS'},{'-fopenmp'},{'-DNCORR_OPENMP"'},{'CXXLIBS="$CXXLIBS'},{'-lgomp"'});
else
% C++ compiler is set up, but was not
% recognized as either gcc or cl
h_error = errordlg('C++ compiler is set up in mex, but was not recognized as G++ or Visual Studio. Either comment out the compile section in ncorr and manually compile the mex functions, or restart ncorr and disable openmp support.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
else
% C++ compiler not installed in mex.
h_error = errordlg('C++ compiler was not found. If a C++ compiler was manually installed that supports openmp, then either comment out the compile section in ncorr and manually compile the functions or restart ncorr and disable openmp.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
end
% Compile libraries:
compile_lib_cpp_mex(lib_ncorr_cpp);
% Compile functions:
compile_func_cpp_mex(func_ncorr_cpp,lib_ncorr_cpp,{});
% Compile function with openmp:
compile_func_cpp_mex(func_ncorr_openmp_cpp,lib_ncorr_cpp,flags_f);
% Write to ncorr_installinfo.txt file, this file will be
% used next time ncorr is started up to avoid
% having to reinput this information.
filename = 'ncorr_installinfo.txt';
fid = fopen(filename,'w');
if (fid ~= -1)
fclose(fid);
% Write info to file:
dlmwrite(filename,[support_openmp_prelim total_cores_prelim]);
% Set support variables:
obj.support_openmp = support_openmp_prelim;
obj.total_cores = total_cores_prelim;
else
% Error
h_error = errordlg('For some reason ncorr was not able to create "ncorr_installinfo.txt" file.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
else
% Error
h_error = errordlg('Please navigate to folder containing ncorr.m first before reinstalling.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
end
catch %#ok<CTCH>
h_error = errordlg('Files did not compile properly. Make sure mex has a c++ compiler set and that the file names have not been altered or moved. If this is the case, then try reopening and installing ncorr without openmp. If problems persist, then try commenting out the compile section in ncorr and manually compiling the functions. Instructions for compilation are available in the manual at ncorr.com','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
%-------------------------------------------------------------%
% END OF COMPILE SECTION %
%-------------------------------------------------------------%
% Check if openmp is actually enabled by calling
% ncorr_alg_testopenmp
if (obj.support_openmp)
if (~ncorr_alg_testopenmp())
% openmp was enabled and files were compiled, but openmp
% isn't actually supported.
h_error = errordlg('Files compiled, but it was determined that OpenMP is not actually supported. Please reinstall Ncorr in single threaded mode or use a compiler which supports OpenMP.','Error','modal');
uiwait(h_error);
outstate = out.failed;
return;
end
end
% Set output
outstate = out.success;
end
%-----------------------------------------------------------------%
% Create UI Controls for GUI and Assign Callbacks ----------------%
%-----------------------------------------------------------------%
function handles_gui = init_gui(obj)
% Initialize GUI Figure --------------------------------------%
% Start Ncorr in the middle of the screen
set(0,'units','characters'); % Set this every time incase user changes units of root
pos_screen = get(0,'screensize');
height_ncorr = 25;
width_ncorr= 167;
left_ncorr = (pos_screen(3)-width_ncorr)/2;
bottom_ncorr = (pos_screen(4)-height_ncorr)/2;
handles_gui.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', [left_ncorr bottom_ncorr width_ncorr height_ncorr], ...
'Name', 'Ncorr', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'Visible','off', ...
'IntegerHandle','off', ...
'Interruptible','off');
% Set closerequestfcn
set(handles_gui.figure,'CloseRequestFcn',obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_close_function(obj,hObject,eventdata,false),handles_gui.figure)));
% Menu Items -------------------------------------------------%
% Under File
handles_gui.topmenu_file = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_file', ...
'Label', 'File', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_loadref = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_loadref', ...
'Label', 'Load Reference Image', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_loadref(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_loadcur = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_loadcur', ...
'Label', 'Load Current Image(s)', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_loadcur_all = uimenu( ...
'Parent', handles_gui.topmenu_loadcur, ...
'Tag', 'topmenu_loadcur_all', ...
'Label', 'Load All (memory heavy)', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_loadcur(obj,hObject,eventdata,false),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_loadcur_lazy = uimenu( ...
'Parent', handles_gui.topmenu_loadcur, ...
'Tag', 'topmenu_loadcur_lazy', ...
'Label', 'Load Lazy (slower but less memory)', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_loadcur(obj,hObject,eventdata,true),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_loaddata = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_loaddata', ...
'Label', 'Load Data', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_loaddata(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_savedata = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_savedata', ...
'Label', 'Save Data', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_savedata(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_clear = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_clear', ...
'Label', 'Clear Data', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_clear(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_sethandle = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_sethandle', ...
'Label', 'Set Handle', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_sethandle(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_reinstall = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_reinstall', ...
'Label', 'Reinstall', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_reinstall(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
handles_gui.topmenu_exit = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_exit', ...
'Label', 'Exit', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_exit_callback(obj,hObject,eventdata),handles_gui.figure)), ...
'Interruptible','off');
% Under region of interest
handles_gui.topmenu_regionofinterest = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_regionofinterest', ...
'Label', 'Region of Interest', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_setroi_ref = uimenu( ...
'Parent', handles_gui.topmenu_regionofinterest, ...
'Tag', 'topmenu_setroi_ref', ...
'Label', 'Set Reference ROI', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_set_roi_ref(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_setroi_cur = uimenu( ...
'Parent', handles_gui.topmenu_regionofinterest, ...
'Tag', 'topmenu_setroi_cur', ...
'Label', 'Set Current ROI (For "Backward" Analysis)', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_set_roi_cur(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
% Under Analysis
handles_gui.topmenu_analysis = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_analysis', ...
'Label', 'Analysis', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_setdicparameters = uimenu( ...
'Parent', handles_gui.topmenu_analysis, ...
'Tag', 'topmenu_setdicparameters', ...
'Label', 'Set DIC Parameters', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_setdicparameters(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_perfdic = uimenu( ...
'Parent', handles_gui.topmenu_analysis, ...
'Tag', 'topmenu_perfdic', ...
'Label', 'Perform DIC Analysis', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_dic(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_formatdisp = uimenu( ...
'Parent', handles_gui.topmenu_analysis, ...
'Tag', 'topmenu_formatdisp', ...
'Label', 'Format Displacements', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_formatdisp(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_calcstrain = uimenu( ...
'Parent', handles_gui.topmenu_analysis, ...
'Tag', 'topmenu_calcstrain', ...
'Label', 'Calculate Strains', ...
'Checked', 'off', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_calcstrain(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
% Under plot - Do not wrap with wrapcallbackall
handles_gui.topmenu_plot = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_plot', ...
'Label', 'Plot', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewdispplot = uimenu( ...
'Parent', handles_gui.topmenu_plot, ...
'Tag', 'topmenu_viewdispplot', ...
'Label', 'View Displacement Plots', ...
'Checked', 'off', ...
'Enable', 'on', ...
'Interruptible','off');
handles_gui.topmenu_viewdispplot_u = uimenu( ...
'Parent', handles_gui.topmenu_viewdispplot, ...
'Tag', 'topmenu_viewdispplot_u', ...
'Label', 'U', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'u'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewdispplot_v = uimenu( ...
'Parent', handles_gui.topmenu_viewdispplot, ...
'Tag', 'topmenu_viewdispplot_v', ...
'Label', 'V', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'v'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewdispplot_all = uimenu( ...
'Parent', handles_gui.topmenu_viewdispplot, ...
'Tag', 'topmenu_viewdispplot_all', ...
'Label', 'All', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'u','v'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot = uimenu( ...
'Parent', handles_gui.topmenu_plot, ...
'Tag', 'topmenu_viewstrainpplot', ...
'Label', 'View Strains Plots', ...
'Checked', 'off', ...
'Enable', 'on', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot_exx = uimenu( ...
'Parent', handles_gui.topmenu_viewstrainplot, ...
'Tag', 'topmenu_viewstrainpplot_exx', ...
'Label', 'Exx', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'exx'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot_exy = uimenu( ...
'Parent', handles_gui.topmenu_viewstrainplot, ...
'Tag', 'topmenu_viewstrainpplot_exy', ...
'Label', 'Exy', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'exy'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot_eyy = uimenu( ...
'Parent', handles_gui.topmenu_viewstrainplot, ...
'Tag', 'topmenu_viewstrainpplot_eyy', ...
'Label', 'Eyy', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'eyy'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_viewstrainplot_all = uimenu( ...
'Parent', handles_gui.topmenu_viewstrainplot, ...
'Tag', 'topmenu_viewstrainpplot_all', ...
'Label', 'All', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_viewplot(obj,hObject,eventdata,{'exx','exy','eyy'}),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.topmenu_closeplots = uimenu( ...
'Parent', handles_gui.topmenu_plot, ...
'Tag', 'topmenu_viewstrainpplot_all', ...
'Label', 'Close All Plots', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_topmenu_closeplots(obj,hObject,eventdata),handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
% Panels -----------------------------------------------------%
handles_gui.group_state = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_state', ...
'Units', 'characters', ...
'Position', [2 13.8 35 10.7], ...
'Title', 'Program State', ...
'Interruptible','off');
handles_gui.group_ref = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_ref', ...
'Units', 'characters', ...
'Position', [39.0 0.75 62 23.75], ...
'Title', 'Reference Image', ...
'Interruptible','off');
handles_gui.group_cur = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_cur', ...
'Units', 'characters', ...
'Position', [103 0.75 62 23.75], ...
'Title', 'Current Image(s)', ...
'Interruptible','off');
handles_gui.group_roi = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_roi', ...
'Units', 'characters', ...
'Position', [2 0.75 35 12.3], ...
'Title', 'Region of Interest', ...
'Interruptible','off');
% Axes -------------------------------------------------------%
handles_gui.axes_ref = axes( ...
'Parent', handles_gui.group_ref, ...
'Tag', 'axes_ref', ...
'Units', 'characters', ...
'Position', [2 4 57 18], ...
'Visible', 'off', ...
'handlevisibility','off', ...
'Interruptible','off');
handles_gui.axes_cur = axes( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'axes_cur', ...
'Units', 'characters', ...
'Position', [2 4 57 18], ...
'Visible', 'off', ...
'handlevisibility','off', ...
'Interruptible','off');
handles_gui.axes_roi = axes( ...
'Parent', handles_gui.group_roi, ...
'Tag', 'axes_roi', ...
'Units', 'characters', ...
'Position', [2 1 29.5 9.6],...
'Visible', 'off', ...
'handlevisibility','off', ...
'Interruptible','off');
% Image texts ------------------------------------------------%
handles_gui.text_refname = uicontrol( ...
'Parent', handles_gui.group_ref, ...
'Tag', 'text_refname', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 2 56.9 1.3], ...
'String', 'Name: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_refresolution = uicontrol( ...
'Parent', handles_gui.group_ref, ...
'Tag', 'text_refresolution', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 .5 56.9 1.3], ...
'String', 'Resolution: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_curname = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'text_curname', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 2 56.9 1.3], ...
'String', 'Name: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_curresolution = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'text_curresolution', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 .5 56.9 1.3], ...
'String', 'Resolution: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% State texts ------------------------------------------------%
handles_gui.text_refloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_refloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 7.7 21 1.3], ...
'String', 'Reference Image', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_curloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_curloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 6.5 21 1.3], ...
'String', 'Current Image(s)', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_roiloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_roiloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 5.3 21 1.3], ...
'String', 'Region of Interest', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_dicparamsloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_dicparamsloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 4.1 21 1.3], ...
'String', 'DIC Parameters', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_dicloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_dicloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 2.9 21 1.3], ...
'String', 'DIC Analysis', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_disploaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_disploaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 1.7 21 1.3], ...
'String', 'Displacements', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_strainloaded = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_strainloaded', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 .5 21 1.3], ...
'String', 'Strains', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% More state texts -------------------------------------------%
handles_gui.text_refloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_refloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 7.7 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_curloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_curloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 6.5 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_roiloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_roiloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 5.3 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_dicparametersloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_dicparametersloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 4.1 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_dicloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_dicloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 2.9 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_disploaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_disploaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 1.7 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
handles_gui.text_strainloaded_s = uicontrol( ...
'Parent', handles_gui.group_state, ...
'Tag', 'text_strainloaded_s', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [23 0.5 10 1.3], ...
'String', 'NOT SET', ...
'HorizontalAlignment', 'left', ...
'ForegroundColor', 'r', ...
'Interruptible','off');
% Editbox ----------------------------------------------------%
handles_gui.edit_imgnum = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'edit_imgnum', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [44 1.3 7 1.6], ...
'String', '', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_edit_imgnum(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
% Pushbuttons ------------------------------------------------%
handles_gui.button_left = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'button_left', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [37 1.2 6 1.8], ...
'String', '<', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_button_left(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
handles_gui.button_right = uicontrol( ...
'Parent', handles_gui.group_cur, ...
'Tag', 'button_right', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [52 1.2 6 1.8], ...
'String', '>', ...
'Callback', obj.util_wrapcallbackall(ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata) callback_button_right(obj,hObject,eventdata),handles_gui.figure)), ...
'Enable', 'off', ...
'Interruptible','off');
end
end
end
%-------------------------------------------------------------------------%
% Other functions --------------------------------------------------------%
%-------------------------------------------------------------------------%
function [handle_name,outstate] = gui_sethandle(pos_parent)
% This is a GUI for setting the name of the variable that points to ncorr.
%
% Inputs -----------------------------------------------------------------%
% pos_parent - integer array; this is the position of the parent figure
% which determines where to position this figure
%
% Outputs ----------------------------------------------------------------%
% handle_name - string; name of new handle
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Data ---------------------------------------------------------------%
% Initialize outputs
outstate = out.cancelled;
handle_name = '';
% Get GUI handles - Part of output
handles_gui_sethandle = init_gui();
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui_sethandle.figure));
% Callbacks and functions --------------------------------------------%
function constructor()
% Set Data
setappdata(handles_gui_sethandle.figure,'handle_name_prelim','');
% Set Visible
set(handles_gui_sethandle.figure,'Visible','on');
end
function callback_edit_string_handle(hObject,eventdata) %#ok<INUSD>
% Get data
handle_name_prelim = getappdata(handles_gui_sethandle.figure,'handle_name_prelim');
% Get Name
handle_name_buffer = get(handles_gui_sethandle.edit_string_handle,'string');
if (isvarname(handle_name_buffer))
handle_name_prelim = handle_name_buffer;
else
h_error = errordlg('Not a valid variable name.','Error','modal');
uiwait(h_error);
end
% Set Data
setappdata(handles_gui_sethandle.figure,'handle_name_prelim',handle_name_prelim);
update_sidemenu();
end
function callback_button_finish(hObject,eventdata) %#ok<INUSD>
% Get data
handle_name_prelim = getappdata(handles_gui_sethandle.figure,'handle_name_prelim');
% Set output
handle_name = handle_name_prelim;
outstate = out.success;
% Exit
close(handles_gui_sethandle.figure);
end
function callback_button_cancel(hObject,eventdata) %#ok<INUSD>
% Close
close(handles_gui_sethandle.figure);
end
function update_sidemenu(hObject,eventdata) %#ok<INUSD>
% Get data
handle_name_prelim = getappdata(handles_gui_sethandle.figure,'handle_name_prelim');
set(handles_gui_sethandle.edit_string_handle,'String',handle_name_prelim);
end
function handles_gui_sethandle = init_gui()
% Form UIs
handles_gui_sethandle.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', ncorr_util_figpos(pos_parent,[6 40.5]), ...
'Name', 'Set Image Size', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'WindowStyle','modal', ...
'Visible','off', ...
'IntegerHandle','off', ...
'Interruptible','off');
% Text
handles_gui_sethandle.text_string_handle = uicontrol( ...
'Parent', handles_gui_sethandle.figure, ...
'Tag', 'text_string_handle', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 3.5 15 1.3], ...
'String', 'Handle Name:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% Edit box
handles_gui_sethandle.edit_string_handle = uicontrol( ...
'Parent', handles_gui_sethandle.figure, ...
'Tag', 'edit_string_handle', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [17.2 3.6 20.6 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_string_handle,handles_gui_sethandle.figure), ...
'Interruptible','off');
% Buttons
handles_gui_sethandle.button_finish = uicontrol( ...
'Parent', handles_gui_sethandle.figure, ...
'Tag', 'button_finish', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.1 1 12 1.7], ...
'String', 'Finish', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_finish,handles_gui_sethandle.figure), ...
'Interruptible','off');
handles_gui_sethandle.button_cancel = uicontrol( ...
'Parent', handles_gui_sethandle.figure, ...
'Tag', 'button_cancel', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [16 1 12 1.7], ...
'String', 'Cancel', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_cancel,handles_gui_sethandle.figure), ...
'Interruptible','off');
end
% Pause until figure is closed ---------------------------------------%
waitfor(handles_gui_sethandle.figure);
end
function [support_openmp,total_cores,outstate] = gui_install(pos_parent)
% This is a GUI to prompt user if openmp support exists.
%
% Inputs -----------------------------------------------------------------%
% pos_parent - integer array; this is the position of the parent figure
% which determines where to position this figure
%
% Outputs ----------------------------------------------------------------%
% support_openmp - logical; tells whether openmp support exists
% total_cores - integer; tells the number of cores that exist in the case
% that openmp is supported
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Data ---------------------------------------------------------------%
% Initialize outputs
outstate = out.cancelled;
support_openmp = false;
total_cores = 1;
% Get GUI handles
handles_gui = init_gui();
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui.figure));
% Callbacks and functions --------------------------------------------%
function constructor
% Set data
setappdata(handles_gui.figure,'total_cores_prelim',1);
setappdata(handles_gui.figure,'total_cores_min',1);
setappdata(handles_gui.figure,'total_cores_max',64);
setappdata(handles_gui.figure,'val_checkbox_openmp',false);
% Update
update_sidemenu();
% Format window
set(handles_gui.figure,'Visible','on');
end
% Callbacks and functions --------------------------------------------%
function callback_checkbox_openmp(hObject,eventdata) %#ok<INUSD>
% Get data
total_cores_prelim = getappdata(handles_gui.figure,'total_cores_prelim');
val_checkbox_openmp = get(handles_gui.checkbox_openmp,'Value');
if (~val_checkbox_openmp)
% Reset total cores to 1
total_cores_prelim = 1;
end
% Set data
setappdata(handles_gui.figure,'val_checkbox_openmp',val_checkbox_openmp);
setappdata(handles_gui.figure,'total_cores_prelim',total_cores_prelim);
update_sidemenu();
end
function callback_edit_total_cores(hObject,eventdata) %#ok<INUSD>
% Get Data
total_cores_prelim = getappdata(handles_gui.figure,'total_cores_prelim');
total_cores_min = getappdata(handles_gui.figure,'total_cores_min');
total_cores_max = getappdata(handles_gui.figure,'total_cores_max');
% Get buffer
total_cores_buffer = str2double(get(handles_gui.edit_total_cores,'string'));
if (ncorr_util_isintbb(total_cores_buffer,total_cores_min,total_cores_max,'Number of cores') == out.success)
total_cores_prelim = total_cores_buffer;
end
% Set data
setappdata(handles_gui.figure,'total_cores_prelim',total_cores_prelim);
update_sidemenu();
end
function callback_button_finish(hObject,eventdata) %#ok<INUSD>
% Get data
total_cores_prelim = getappdata(handles_gui.figure,'total_cores_prelim');
support_openmp_prelim = getappdata(handles_gui.figure,'val_checkbox_openmp');
% Store
total_cores = total_cores_prelim;
support_openmp = support_openmp_prelim;
outstate = out.success;
% Return
close(handles_gui.figure);
end
function callback_button_cancel(hObject,eventdata) %#ok<INUSD>
close(handles_gui.figure);
end
function update_sidemenu(hObject,eventdata) %#ok<INUSD>
% Get data
val_checkbox_openmp = getappdata(handles_gui.figure,'val_checkbox_openmp');
total_cores_prelim = getappdata(handles_gui.figure,'total_cores_prelim');
set(handles_gui.checkbox_openmp,'Value',val_checkbox_openmp);
if (val_checkbox_openmp)
set(handles_gui.edit_total_cores,'enable','on');
else
set(handles_gui.edit_total_cores,'enable','off');
end
set(handles_gui.edit_total_cores,'String',num2str(total_cores_prelim));
end
function handles_gui = init_gui()
handles_gui.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', ncorr_util_figpos(pos_parent,[9.5 70]), ...
'Name', 'OpenMP support', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'Visible','off', ...
'IntegerHandle','off', ...
'WindowStyle','modal', ...
'Interruptible','off');
handles_gui.text_openmp = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_openmp', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [1.5 5.1 66.7 2.2], ...
'HorizontalAlignment','left', ...
'String', 'Requires multicore CPU and compiler which supports OpenMP installed through mex.', ...
'Value', 0, ...
'Interruptible','off');
handles_gui.text_cores_total = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_core_total', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [10 3.2 18 1.2], ...
'HorizontalAlignment','left', ...
'String', 'Cores:', ...
'Value', 0, ...
'Interruptible','off');
handles_gui.checkbox_openmp = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'checkbox_openmp', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [1.5 7.5 66.7 1.3], ...
'String', 'OpenMP Multithreading', ...
'Value', 0, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_openmp,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_total_cores = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'edit_total_cores', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [22 3.3 8 1.2], ...
'HorizontalAlignment','left', ...
'String', '1', ...
'Enable', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_total_cores,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_finish = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'button_finish', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [42.3 0.7 12 1.8], ...
'String', 'Finish', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_finish,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_cancel = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'button_cancel', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [56 0.7 12 1.8], ...
'String', 'Cancel', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_cancel,handles_gui.figure), ...
'Interruptible','off');
end
% Pause until figure is closed ---------------------------------------%
waitfor(handles_gui.figure);
end
function compile_lib_cpp_mex(lib_cpp)
% This function compiles cpp_function_lib as object files.
%
% Inputs -----------------------------------------------------------------%
% lib_cpp - cell of strings; names of libraries to be compiled as object
% files
%
% Returns error if files are not found.
% Cycle over libraries and compile
for i = 0:length(lib_cpp)-1
% First check if the cpp and header files exist
if (exist([lib_cpp{i+1} '.cpp'],'file') && exist([lib_cpp{i+1} '.h'],'file'))
disp(['Installing ' lib_cpp{i+1} '... Please wait']);
% Generate compiler string
string_compile = horzcat({'-c'},{[lib_cpp{i+1} '.cpp']});
% Compile file
mex(string_compile{:});
else
h_error = errordlg(['Files ' lib_cpp{i+1} '.cpp and ' lib_cpp{i+1} '.h were not found. Please find them and place them in the current directory before proceeding.'],'Error','modal');
uiwait(h_error);
% Spit error to invoke exception
error('Compilation failed because file was not found.');
end
end
end
function compile_func_cpp_mex(func_cpp,lib_cpp,flags_f)
% This function compiles func_cpp and linkes them with the lib_cpp object
% files. If flags are provided then they will be appended when compiling.
%
% Inputs -----------------------------------------------------------------%
% func_cpp - cell of strings; names of .cpp files to be
% compiled
% lib_cpp - cell of strings; names of object files to be linked
% flags_f - cell of strings; formatted compiler flags.
%
% Returns error if library object files or source code files are not found.
% Get the OS to find object extension
if (ispc) % pc
objext = 'obj';
elseif (isunix) % unix
objext = 'o';
end
% Check if lib files have been compiled first
for i = 0:length(lib_cpp)-1
if (~exist([lib_cpp{i+1} '.' objext],'file'))
% Object file doesnt exist, return error
h_error = errordlg(['Library ' lib_cpp{i+1} ' has not yet been compiled. Please compile first and make sure the object file is located in the current directory before proceeding.'],'Error','modal');
uiwait(h_error);
% Spit error to invoke exception
error('Library not compiled yet');
end
end
% Cycle over mex files and compile
for i = 0:length(func_cpp)-1
% First check if the cpp file exists
if (exist([func_cpp{i+1} '.cpp'],'file'))
disp(['Installing ' func_cpp{i+1} '... Please wait']);
% Generate compiler string
string_compile = {[func_cpp{i+1} '.cpp']};
% Append libraries
for j = 0:length(lib_cpp)-1
string_compile = horzcat(string_compile,{[lib_cpp{j+1} '.' objext]}); %#ok<AGROW>
end
% Append flags
string_compile = horzcat(string_compile,flags_f{:}); %#ok<AGROW>
% Compile
mex(string_compile{:});
else
h_error = errordlg(['File ' filename '.cpp was not found. Please find it and place it in the current directory before proceeding'],'Error','modal');
uiwait(h_error);
% Spit error to invoke exception
error('Compilation failed because file was not found.');
end
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr_alg_convertseeds.m
|
.m
|
choco-packages-master/packages/matlab-ciser/tools/ncorr/ncorr_alg_convertseeds.m
| 27,822 |
utf_8
|
126e3f6e6db2afe68f675dff24040d5b
|
function [convertseedinfo,outstate] = ncorr_alg_convertseeds(plot_u_old,plot_v_old,plot_u_interp_old,plot_v_interp_old,roi_old,roi_new,seedwindow,spacing,border_interp)
% This function obtains the "convert" seeds. It will try to seed as many
% "new" regions as possible (one seed per region). It is possible that no
% seeds are returned.
%
% Inputs -----------------------------------------------------------------%
% plot_u_old - double array; u displacements WRT the "old" configuration.
% Units are pixels.
% plot_v_old - double array; v displacements WRT the "old" configuration.
% Units are pixels.
% plot_u_interp_old - cell; array of b-spline coefficients; one per
% region.
% plot_v_interp_old - cell; array of b-spline coefficients; one per
% region;
% roi_old - ncorr_class_roi; ROI corresponding to "old" displacements.
% Note that ROI is already reduced by default.
% roi_new - ncorr_class_roi; ROI corresponding to "new" displacements.
% Note that ROI is already reduced by default.
% seedwindow - integer; half width of window around seed that must contain
% valid points before its processed. This prevents edge points from being
% seeded.
% spacing - integer; this is the spacing parameter.
% border_interp - integer; the amount of padding used around the borders in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% convertseedinfo - struct; contains
% struct('paramvector',{},'num_region_new',{},'num_region_old',{}). The x
% and y coords stored in convertseedinfo will be reduced while the
% displacement values are in pixels.
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
%
% Note that the ordering of plot_u_interp_old and plot_v_interp_old must
% form a correspondence with the regions in roi_old. This means
% plot_u_interp_old{i} must correspond to roi_old.region(i). Regions in
% roi_old and roi_new do not need to form a direct correspondence, but they
% are assumed to be one-to-one. Returns failed if no seeds are found
% Initialize outputs
outstate = out.failed;
convertseedinfo = struct('paramvector',{},'num_region_new',{},'num_region_old',{}); % paramvector = [x_new y_new x_old y_old u_old v_old distance]
% Form convertseedinfo prelim
convertseedinfo_prelim = struct('paramvector',{},'num_region_new',{},'num_region_old',{});
% Keep track of the regions in roi_old that have already been analyzed.
list_region_old = false(length(roi_old.region),1);
% Cycle over every "new" region and attempt to seed.
for i = 0:length(roi_new.region)-1
% Regions are not gauranteed contiguous at this point, so get the
% region corresponding to the largest contiguous area to make sure
% small areas arent seeded.
regionmask_new_buffer = roi_new.get_regionmask(i);
[region_new_buffer,removed] = ncorr_alg_formregions(regionmask_new_buffer,int32(0),false); %#ok<NASGU>
% Check if contiguous region(s) are empty or if there are more than one
if (isempty(region_new_buffer))
% Continue onto next region in roi_new if region_new_buffer is empty
continue;
elseif (length(region_new_buffer) > 1)
% Select biggest region if there are more than one. This could
% possibly happen if a boundary is "pinched" or closes during
% deformation. Unlikely- but may happen.
idx_max = find([region_new_buffer.totalpoints] == max([region_new_buffer.totalpoints]),1,'first');
region_new_buffer = region_new_buffer(idx_max);
end
% Form convertseedinfo buffer
convertseedinfo_buffer = struct('paramvector',{},'num_region_new',{},'num_region_old',{});
% Set num_region_new
convertseedinfo_buffer(1).num_region_new = i;
% Initialize
successregion = false;
for j = 0:size(region_new_buffer.noderange,1)-1
x_new = j + region_new_buffer.leftbound;
% Cycle over each point
for k = 0:2:region_new_buffer.noderange(j+1)-1
for l = region_new_buffer.nodelist(j+1,k+1):region_new_buffer.nodelist(j+1,k+2);
y_new = l;
% Make sure area of half-width seedwindow is valid
% around the seed before attempting to process.
if (all(all(regionmask_new_buffer(max(y_new-seedwindow+1,1):min(y_new+seedwindow+1,end), ...
max(x_new-seedwindow+1,1):min(x_new+seedwindow+1,end)))))
% Analyze point - outstate_calcpoint will either be
% success or failed
[convertseedinfo_buffer.paramvector,convertseedinfo_buffer.num_region_old,outstate_calcpoint] = calcpoint(x_new, ...
y_new, ...
plot_u_old, ...
plot_v_old, ...
plot_u_interp_old, ...
plot_v_interp_old, ...
roi_old, ...
list_region_old, ...
spacing, ...
border_interp);
% Check if nonlinear solver was successful
if (outstate_calcpoint == out.success)
% Check distance; make sure its less than a
% threshold and also make sure that x_old and
% y_old are in valid area
x_old = round(convertseedinfo_buffer.paramvector(3));
y_old = round(convertseedinfo_buffer.paramvector(4));
if (convertseedinfo_buffer.paramvector(7) < 0.005 && ...
x_old >= 0 && x_old < size(roi_old.mask,2) && ...
y_old >= 0 && y_old < size(roi_old.mask,1) && ...
roi_old.mask(y_old+1,x_old+1)) % Should really check regionmask, but for ease just check the whole mask
% Append
convertseedinfo_prelim = horzcat(convertseedinfo_prelim,convertseedinfo_buffer); %#ok<AGROW>
list_region_old(convertseedinfo_buffer.num_region_old+1) = true;
% Break from this region
successregion = true;
end
end
end
% Break if seed was successful or all regions in the
% old configuration have been analyzed
if (successregion || all(list_region_old))
break;
end
end
% Break if seed was successful or all regions in the
% old configuration have been analyzed
if (successregion || all(list_region_old))
break;
end
end
% Break if seed was successful or all regions in the
% old configuration have been analyzed
if (successregion || all(list_region_old))
break;
end
end
end
% Assign Outputs
if (~isempty(convertseedinfo_prelim))
for i = 0:length(convertseedinfo_prelim)-1
convertseedinfo(i+1) = convertseedinfo_prelim(i+1);
end
outstate = out.success;
end
end
%-------------------------------------------------------------------------%
% Nonlinear solver equations ---------------------------------------------%
%-------------------------------------------------------------------------%
function [paramvector,num_region_old,outstate] = calcpoint(x_new,y_new,plot_u_old,plot_v_old,plot_u_interp_old,plot_v_interp_old,roi_old,list_region_old,spacing,border_interp)
% This function obtains the parameters for a "convert" seed.
%
% Inputs -----------------------------------------------------------------%
% x_new - integer; x position WRT the "new" configuration. Note that
% x_new is WRT reduced coordinates.
% y_new - integer; y position WRT the "new" configuration. Note that
% y_new is WRT reduced coordinates.
% plot_u_old - double array; u displacements WRT the "old" configuration.
% Units are pixels.
% plot_v_old - double array; v displacements WRT the "old" configuration.
% Units are pixels.
% plot_u_interp_old - cell; array of b-spline coefficients; one per
% region.
% plot_v_interp_old - cell; array of b-spline coefficients; one per
% region.
% roi_old - ncorr_class_roi; ROI corresponding to "old" displacements.
% Note that ROI is already reduced by default.
% list_region_old - logical array; keeps track of which "old" regions have
% been analyzed
% spacing - integer; this is the spacing parameter.
% border_interp - integer; the amount of padding used around the borders in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% paramvector - double array; [x_new y_new x_old y_old u_old v_old distance]
% num_region_old - integer; The region number which seed resides in for
% the "old" configuration
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize outputs
paramvector = [];
num_region_old = [];
outstate = out.failed;
% Perform global search - note: defvector = [x_old y_old] - reduced
[defvector_init,num_region_old_prelim,outstate_initialguess] = initialguess(x_new, ...
y_new, ...
plot_u_old, ...
plot_v_old, ...
roi_old, ...
list_region_old, ...
spacing);
if (outstate_initialguess == out.success)
% Perform an iterative search
[defvector,u_old,v_old,distance,outstate_iterative] = iterativesearch(x_new, ...
y_new, ...
defvector_init, ...
plot_u_interp_old, ...
plot_v_interp_old, ...
roi_old, ...
num_region_old_prelim, ...
spacing, ...
border_interp);
if (outstate_iterative == out.success)
% Set outputs
paramvector = [x_new y_new defvector u_old v_old distance];
num_region_old = num_region_old_prelim;
outstate = out.success;
end
end
end
function [defvector_init,num_region_old,outstate] = initialguess(x_new,y_new,plot_u_old,plot_v_old,roi_old,list_region_old,spacing)
% This function finds the closest integer displacements as an initial
% guess.
%
% Inputs -----------------------------------------------------------------%
% x_new - integer; x position WRT the "new" configuration. Note that
% x_new is WRT reduced coordinates.
% y_new - integer; y position WRT the "new" configuration. Note that
% y_new is WRT reduced coordinates.
% plot_u_old - double array; u displacements WRT the "old" configuration.
% Units are pixels.
% plot_v_old - double array; v displacements WRT the "old" configuration.
% Units are pixels.
% roi_old - ncorr_class_roi; ROI corresponding to "old" displacements.
% Note that ROI is already reduced by default.
% list_region_old - logical array; keeps track of which "old" regions have
% been analyzed
% spacing - integer; this is the spacing parameter.
%
% Outputs ----------------------------------------------------------------%
% defvector_init - integer array; [x_old y_old] - reduced
% num_region_old - integer; number of region where x_old and y_old were found
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize Outputs
outstate = out.failed;
defvector_init = [];
num_region_old = [];
% Cycle through every point to insure a global minimum
x_old_prelim = -1;
y_old_prelim = -1;
num_region_old_prelim = -1;
distance_prelim = inf; % arbitrarily large number
for i = 0:length(roi_old.region)-1
if (list_region_old(i+1)) % this ROI has been analyzed already
continue;
else
for j = 0:size(roi_old.region(i+1).noderange,1)-1
x_old_buffer = j + roi_old.region(i+1).leftbound;
for k = 0:2:roi_old.region(i+1).noderange(j+1)-1
for l = roi_old.region(i+1).nodelist(j+1,k+1):roi_old.region(i+1).nodelist(j+1,k+2)
y_old_buffer = l;
% Must divide displacement by spacing so
% displacement is WRT reduced coordinates
u_old_buffer = plot_u_old(y_old_buffer+1,x_old_buffer+1)/(spacing+1);
v_old_buffer = plot_v_old(y_old_buffer+1,x_old_buffer+1)/(spacing+1);
distance_buffer = sqrt((x_new-(x_old_buffer+u_old_buffer))^2+(y_new-(y_old_buffer+v_old_buffer))^2);
% Check if this point is better
if (distance_buffer < distance_prelim)
x_old_prelim = x_old_buffer;
y_old_prelim = y_old_buffer;
num_region_old_prelim = i;
distance_prelim = distance_buffer;
end
end
end
end
end
end
if (x_old_prelim ~= -1 && y_old_prelim ~= -1)
defvector_init = [x_old_prelim y_old_prelim];
num_region_old = num_region_old_prelim;
outstate = out.success;
end
end
function [defvector,u_old,v_old,distance,outstate] = iterativesearch(x_new,y_new,defvector_init,plot_u_interp_old,plot_v_interp_old,roi_old,num_region_old,spacing,border_interp)
% This function uses Gauss-Newton iterations to find the subpixel x_old
% and y_old values.
%
% Inputs -----------------------------------------------------------------%
% x_new - integer; x position WRT the "new" configuration. Note that
% x_new is WRT reduced coordinates.
% y_new - integer; y position WRT the "new" configuration. Note that
% y_new is WRT reduced coordinates.
% defvector_init - integer array; of form [x_old y_old]. It's integer
% because these are the initial guesses from the global search.
% plot_u_interp_old - cell; array of b-spline coefficients; one per
% region.
% plot_v_interp_old - cell; array of b-spline coefficients; one per
% region.
% roi_old - ncorr_class_roi; ROI corresponding to "old" displacements.
% Note that ROI is already reduced by default.
% num_region_old - integer; number of region being analyzed
% spacing - integer; this is the spacing parameter.
% border_interp - integer; the amount of padding used around the borders in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% defvector - double array; [x_old y_old] - reduced
% u_old - double; u displacement from x_old to x_new - pixels
% v_old - double; v displacement from y_old to y_new - pixels
% distance - double; distance between [x_new y_new] and [x_old y_old]
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize outputs
outstate = out.failed;
defvector = [];
u_old = [];
v_old = [];
distance = [];
% Gauss Newton optimization - send only b-spline coefficients
% corresponding to the num_region_old
[defvector_prelim,u_old_prelim,v_old_prelim,distance_prelim,gradnorm,outstate_newton] = newton(x_new, ...
y_new, ...
defvector_init, ...
plot_u_interp_old{num_region_old+1}, ...
plot_v_interp_old{num_region_old+1}, ...
roi_old.region(num_region_old+1), ...
spacing, ...
border_interp);
counter = 1;
while (outstate_newton == out.success && gradnorm > 10^-5 && counter < 10)
% Gauss Newton optimization - send only b-spline coefficients
% corresponding to the num_region_old
[defvector_prelim,u_old_prelim,v_old_prelim,distance_prelim,gradnorm,outstate_newton] = newton(x_new, ...
y_new, ...
defvector_prelim, ...
plot_u_interp_old{num_region_old+1}, ...
plot_v_interp_old{num_region_old+1}, ...
roi_old.region(num_region_old+1), ...
spacing, ...
border_interp);
counter = counter + 1;
end
if (outstate_newton == out.success)
% Assign outputs
defvector = defvector_prelim;
u_old = u_old_prelim;
v_old = v_old_prelim;
distance = distance_prelim;
outstate = out.success;
end
end
function [defvector,u_old,v_old,distance,gradnorm,outstate] = newton(x_new,y_new,defvector_init,plot_u_interp_old,plot_v_interp_old,region_old,spacing,border_interp)
% This function actually performs the Gauss-Newton iteration
%
% Inputs -----------------------------------------------------------------%
% x_new - integer; x position WRT the "new" configuration. Note that
% x_new is WRT reduced coordinates.
% y_new - integer; y position WRT the "new" configuration. Note that
% y_new is WRT reduced coordinates.
% defvector_init - double array; of form [x_old y_old]
% plot_u_interp_old - double array; array of b-spline coefficients
% corresponding to region_old
% plot_v_interp_old - double array; array of b-spline coefficients
% corresponding to region_old
% region_old - struct; specific region being analyzed
% spacing - double; this is the spacing parameter.
% border_interp - integer; the amount of padding used around the borders in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% defvector - double array; [x_old y_old] - reduced
% u_old - double; u displacement from x_old to x_new - pixels
% v_old - double; v displacement from y_old to y_new - pixels
% distance - double; distance between [x_new y_new] and [x_old y_old]
% gradnorm - double; norm of the gradient vector - should be close to 0
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize inputs
outstate = out.failed;
defvector = [];
u_old = [];
v_old = [];
gradnorm = [];
distance = [];
% Use interp function local to this m-file since it combines
% interpolation of values and gradients.
[interpvector,outstate_interp] = interpqbs_convert(defvector_init, ...
plot_u_interp_old, ...
plot_v_interp_old, ...
region_old, ...
border_interp);
if (outstate_interp == out.success)
% Determine Gradient - note that interpolation found through
% interpqbs_convert needs to be WRT reduced coordinates; However,
% displacements use pixel units, so they need to be scaled in order
% to be WRT reduced coordinates.
gradient(1) = -2*((x_new-(defvector_init(1)+interpvector(1)/(spacing+1)))*(1+interpvector(3)/(spacing+1))+(y_new-(defvector_init(2)+interpvector(2)/(spacing+1)))*(interpvector(5)/(spacing+1)));
gradient(2) = -2*((x_new-(defvector_init(1)+interpvector(1)/(spacing+1)))*(interpvector(4)/(spacing+1))+(y_new-(defvector_init(2)+interpvector(2)/(spacing+1)))*(1+interpvector(6)/(spacing+1)));
% Determine Hessian
hessian(1,1) = 2*((1+interpvector(3)/(spacing+1))^2+(interpvector(5)/(spacing+1))^2);
hessian(2,1) = 2*((interpvector(4)/(spacing+1))*(1+interpvector(3)/(spacing+1))+(1+interpvector(6)/(spacing+1))*(interpvector(5)/(spacing+1)));
hessian(1,2) = hessian(2,1); % symmetric
hessian(2,2) = 2*((interpvector(4)/(spacing+1))^2+(1+interpvector(6)/(spacing+1))^2);
det_hess = det(hessian);
% Check to make sure hessian is positive definite
% From :http://www.math.northwestern.edu/~clark/285/2006-07/handouts/pos-def.pdf
% Make sure det(hess) > 0 and hess(1,1) > 0
if (det_hess > 0 && hessian(1) > 0)
% Determine new coordinates
defvector_prelim = (defvector_init'-hessian^-1*gradient')';
% Calculate distance - we have to interpolate again with the new
% coordinates
[interpvector,outstate_interp] = interpqbs_convert(defvector_prelim, ...
plot_u_interp_old, ...
plot_v_interp_old, ...
region_old, ...
border_interp);
if (outstate_interp == out.success)
% Store outputs
defvector = defvector_prelim;
u_old = interpvector(1);
v_old = interpvector(2);
distance = sqrt((x_new-(defvector(1)+interpvector(1)/(spacing+1)))^2+(y_new-(defvector(2)+interpvector(2)/(spacing+1)))^2);
gradnorm = norm(gradient);
outstate = out.success;
end
end
end
end
function [interpvector,outstate] = interpqbs_convert(defvector,plot_u_interp_old,plot_v_interp_old,region_old,border_interp)
% This interpolation combines interpolation of values and gradients, so
% it's reimplemented here because it can save some time by combining the
% interpolation.
%
% Inputs -----------------------------------------------------------------%
% defvector - double array; [x_old y_old] - reduced
% plot_u_interp_old - double array; array of b-spline coefficients. Units
% are pixels.
% plot_v_interp_old - double array; array of b-spline coefficients. Units
% are pixels.
% region_old - struct; specific region being analyzed
% border_interp - integer; the amount of padding used around the edges in
% interpdata
%
% Outputs ----------------------------------------------------------------%
% interpvector - double array; [u v du/dx du/dy dv/dx dv/dy]
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Initialize output
outstate = out.failed;
interpvector = [];
% Biquintic Kernel Matrix
QK = [1/120 13/60 11/20 13/60 1/120 0;
-1/24 -5/12 0 5/12 1/24 0;
1/12 1/6 -1/2 1/6 1/12 0;
-1/12 1/6 0 -1/6 1/12 0;
1/24 -1/6 1/4 -1/6 1/24 0;
-1/120 1/24 -1/12 1/12 -1/24 1/120];
% Interpolate if in bounds
x_tilda = defvector(1);
y_tilda = defvector(2);
x_tilda_floor = floor(x_tilda);
y_tilda_floor = floor(y_tilda);
% Make sure top, left, bottom, and right are within the b-spline
% coefficient array. top, left, bottom and right are the bounding
% box of the b-spline coefficients used for interpolation of this
% point;
top = y_tilda_floor-region_old.upperbound+border_interp-2;
left = x_tilda_floor-region_old.leftbound+border_interp-2;
bottom = y_tilda_floor-region_old.upperbound+border_interp+3;
right = x_tilda_floor-region_old.leftbound+border_interp+3;
if (top >= 0 && ...
left >= 0 && ...
bottom < size(plot_u_interp_old,1) && ...
right < size(plot_u_interp_old,2))
% Set coords
x_tilda_delta = x_tilda-x_tilda_floor;
y_tilda_delta = y_tilda-y_tilda_floor;
x_vec(1) = 1.0;
x_vec(2) = x_tilda_delta;
x_vec(3) = x_vec(2)*x_tilda_delta;
x_vec(4) = x_vec(3)*x_tilda_delta;
x_vec(5) = x_vec(4)*x_tilda_delta;
x_vec(6) = x_vec(5)*x_tilda_delta;
y_vec(1) = 1.0;
y_vec(2) = y_tilda_delta;
y_vec(3) = y_vec(2)*y_tilda_delta;
y_vec(4) = y_vec(3)*y_tilda_delta;
y_vec(5) = y_vec(4)*y_tilda_delta;
y_vec(6) = y_vec(5)*y_tilda_delta;
x_vec_dx(1) = 0.0;
x_vec_dx(2) = 1.0;
x_vec_dx(3) = 2.0*x_vec(2);
x_vec_dx(4) = 3.0*x_vec(3);
x_vec_dx(5) = 4.0*x_vec(4);
x_vec_dx(6) = 5.0*x_vec(5);
y_vec_dy(1) = 0.0;
y_vec_dy(2) = 1.0;
y_vec_dy(3) = 2.0*y_vec(2);
y_vec_dy(4) = 3.0*y_vec(3);
y_vec_dy(5) = 4.0*y_vec(4);
y_vec_dy(6) = 5.0*y_vec(5);
% Precompute
QKMAT_u_plot = QK*plot_u_interp_old(top+1:bottom+1,left+1:right+1)*QK';
QKMAT_v_plot = QK*plot_v_interp_old(top+1:bottom+1,left+1:right+1)*QK';
% Get interpolated value
interpvector(1) = y_vec*QKMAT_u_plot*x_vec'; % u
interpvector(2) = y_vec*QKMAT_v_plot*x_vec'; % v
interpvector(3) = y_vec*QKMAT_u_plot*x_vec_dx'; % du/dx
interpvector(4) = y_vec_dy*QKMAT_u_plot*x_vec'; % du/dy
interpvector(5) = y_vec*QKMAT_v_plot*x_vec_dx'; % dv/dx
interpvector(6) = y_vec_dy*QKMAT_v_plot*x_vec'; % dv/dy
outstate = out.success;
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr_gui_viewplots.m
|
.m
|
choco-packages-master/packages/matlab-ciser/tools/ncorr/ncorr_gui_viewplots.m
| 127,861 |
utf_8
|
b5e3358c4dae7e33660ab822d294b67c
|
function handles_gui = ncorr_gui_viewplots(reference,current,data_dic,type_plot,pos_parent,params_init)
% This is a GUI for viewing the displacement/strain plots.
%
% Inputs -----------------------------------------------------------------%
% reference - ncorr_class_img; used for displaying the background image.
% current - ncorr_class_img; used for displaying the background image.
% data_dic - struct; contains displacement and strain info. This is the
% main data structure used in Ncorr.
% type_plot - string; specifies whether plot is u, v, exx, exy, or eyy.
% pos_parent - integer array; this is the position of the parent figure
% which determines where to position this figure
% params_init - cell; {1} = num_cur, {2} = scalebarlength,
% {3} = if handle_scalebar is on, {4} = if handle_axes is on, {5} if
% Lagrangian or Eulerian, {6} if zoomed; {7} if panned. Used to
% coordinate with any existing open plots.
%
% Outputs ----------------------------------------------------------------%
% handles_gui - handles; these are the GUI handles which allow Ncorr to
% manage the closing and synchronization of the open plots
%
% Note that this function checks both roi_ref_formatted and
% roi_cur_formatted to make sure all ROIs are non-empty. This is a very
% unlikely scenario, but if it happens this function will display and error
% dialogue and return.
% Data ---------------------------------------------------------------%
% Get GUI handles
handles_gui = init_gui();
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui.figure));
% Callbacks and functions --------------------------------------------%
function constructor()
% Check to make sure ROIs are full
roifull = true;
if (strcmp(type_plot,'u') || strcmp(type_plot,'v'))
field = 'displacements';
else
field = 'strains';
end
for i = 0:length(current)-1
if (data_dic.(field)(i+1).roi_ref_formatted.get_fullregions == 0 || ...
data_dic.(field)(i+1).roi_cur_formatted.get_fullregions == 0)
roifull = false;
break;
end
end
if (~roifull)
% One of the ROIs is empty, return; CloseRequestFcn is disabled,
% in gui_init(), so reenable it before closing.
set(handles_gui.figure,'CloseRequestFcn','closereq');
h_error = errordlg('Some data plots are empty, please rerun analysis.','Error','modal');
uiwait(h_error);
close(handles_gui.figure);
return;
end
% Set zoom and pan
handle_zoom = zoom(handles_gui.figure);
handle_pan = pan(handles_gui.figure);
% Initialize buffers -----------------------------------------%
if (isempty(params_init))
% Set num_cur - by default show last image in set
num_cur = length(current)-1;
% Set scalebar length - initialize to 3/4 the width of the
% reference image. This uses real units.
scalebarlength_prelim = (3/4)*reference.width*data_dic.dispinfo.pixtounits;
if (floor(scalebarlength_prelim) > 3)
% Use integer
scalebarlength = floor(scalebarlength_prelim);
else
% Use decimal
scalebarlength = scalebarlength_prelim;
end
% handle_scalebar checkbox
val_checkbox_scalebar = true;
% handle_axes checkbox
val_checkbox_axes = true;
% Lagrangian or Eulerian; 1 == Lagrangian
val_popupmenu = 1;
else
% Set num_cur
num_cur = params_init{1};
% Units and handle_scalebar buffer
scalebarlength = params_init{2};
% handle_scalebar checkbox
val_checkbox_scalebar = params_init{3};
% handle_axes checkbox
val_checkbox_axes = params_init{4};
% Lagrangian or Eulerian
val_popupmenu = params_init{5};
% Zoomed
if (params_init{6})
set(handle_zoom,'Enable','on');
end
% Panned
if (params_init{7})
set(handle_pan,'Enable','on');
end
end
% Transparency buffer
transparency_prelim = 0.75;
% Contour lines buffer
contourlines_prelim = 20;
max_contourlines = 100;
% Set slider buffer
slider_buffer = struct('lagrangian',{},'eulerian',{});
for i = 0:length(current)-1
% Set parameters
% Get the data vector corresponding to this plot
data_ref = get_data(type_plot,'lagrangian',i);
slider_buffer(i+1).lagrangian(1) = 0.5; % Initialize to half
slider_buffer(i+1).lagrangian(2) = 0.5; % Initialize to half
slider_buffer(i+1).lagrangian(3:7) = get_sliderparams(data_ref);
% Get the data vector corresponding to this plot
data_cur = get_data(type_plot,'eulerian',i);
slider_buffer(i+1).eulerian(1) = 0.5; % Initialize to half
slider_buffer(i+1).eulerian(2) = 0.5; % Initialize to half
slider_buffer(i+1).eulerian(3:7) = get_sliderparams(data_cur);
end
max_upperbound = 1e10;
min_lowerbound = -1e10;
max_scalebarlength = 1e10;
% Set data
setappdata(handles_gui.figure,'num_cur',num_cur);
setappdata(handles_gui.figure,'transparency_prelim',transparency_prelim);
setappdata(handles_gui.figure,'contourlines_prelim',contourlines_prelim);
setappdata(handles_gui.figure,'max_contourlines',max_contourlines);
setappdata(handles_gui.figure,'scalebarlength',scalebarlength);
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
setappdata(handles_gui.figure,'max_upperbound',max_upperbound);
setappdata(handles_gui.figure,'min_lowerbound',min_lowerbound);
setappdata(handles_gui.figure,'max_scalebarlength',max_scalebarlength);
setappdata(handles_gui.figure,'type_plot',type_plot); % Store this explicitly so type and other parameters can be deduced from 'friends'
setappdata(handles_gui.figure,'friends',[]); % This is used for modifying other viewplots; it stores their figure handles
setappdata(handles_gui.figure,'text_info',[]); % This is the text box that displays when the cursor is over the data plot
setappdata(handles_gui.figure,'val_checkbox_contour',false);
setappdata(handles_gui.figure,'val_checkbox_scalebar',val_checkbox_scalebar);
setappdata(handles_gui.figure,'val_checkbox_axes',val_checkbox_axes);
setappdata(handles_gui.figure,'val_checkbox_minmaxmarkers',false);
setappdata(handles_gui.figure,'val_popupmenu',val_popupmenu);
setappdata(handles_gui.figure,'handle_preview',[]);
setappdata(handles_gui.figure,'handle_scalebar',[]);
setappdata(handles_gui.figure,'handle_axes',[]);
setappdata(handles_gui.figure,'handle_colorbar',[]);
setappdata(handles_gui.figure,'handle_point_max',[]);
setappdata(handles_gui.figure,'handle_point_min',[]);
setappdata(handles_gui.figure,'handle_zoom',handle_zoom);
setappdata(handles_gui.figure,'handle_pan',handle_pan);
% Update - must send the GUI handles; this is because
% update_axes can be used to update other figure handles stored
% in 'friends'.
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
% Set resize and hover function callbacks; This GUI is
% resizable and displays a data cursor when the cursor hovers
% over the data plot.
% Set resize function
set(handles_gui.figure,'ResizeFcn',ncorr_util_wrapcallbacktrycatch(@callback_resizefunction,handles_gui.figure));
% Set hover function
set(handles_gui.figure,'WindowButtonMotionFcn',ncorr_util_wrapcallbacktrycatch(@callback_moveplot,handles_gui.figure));
% Set Visible
set(handles_gui.figure,'Visible','on');
end
function callback_topmenu_save(hObject,eventdata,includeinfo) %#ok<INUSL>
% Get info
num_cur = getappdata(handles_gui.figure,'num_cur');
% Form save figure -----------------------------------------------%
handles_gui_savefig = form_savefig(num_cur,includeinfo,[]);
% Disable close function so figure isnt inadvertently closed.
set(handles_gui_savefig.figure,'CloseRequestFcn','');
% Set size(s) ----------------------------------------------------%
% gui_savesize is a local function with a GUI; it allows the user
% to modify the size of the image
[size_savefig,timedelay,outstate] = gui_savesize(handles_gui_savefig, ...
false, ...
get(handles_gui.figure,'OuterPosition')); %#ok<*ASGLU>
if (outstate == out.success)
% Save image -------------------------------------------------%
[filename,pathname] = uiputfile({'*.jpg';'*.png';'*.bmp';'*.tif'},'Save Image');
if (~isequal(filename,0) && ~isequal(pathname,0))
overwrite = true;
if (exist(fullfile(pathname,filename),'file'))
contbutton = questdlg('File already exists. Do you want to overwrite?','Continue Operation','Yes','No','No');
if strcmp(contbutton,'No')
overwrite = false;
end
end
if (overwrite)
% Get image ------------------------------------------%
img_printscreen = getframe(handles_gui_savefig.figure);
% Save the image
imwrite(img_printscreen.cdata,fullfile(pathname,filename));
end
end
end
% Exit -----------------------------------------------------------%
set(handles_gui_savefig.figure,'CloseRequestFcn','closereq');
close(handles_gui_savefig.figure);
end
function callback_topmenu_savegif(hObject,eventdata) %#ok<INUSD>
% Get data
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
% All current images must have the same size to use this feature
% with the eulerian description
size_cur = size(current(1).get_gs());
samesize_cur = true;
for i = 1:length(current)-1
if (~isequal(size_cur,[current(i+1).height current(i+1).width]))
samesize_cur = false;
break;
end
end
% Save image -----------------------------------------------------%
% Note val_popupmenu equals 1 for the lagrangian perspective, and 2
% for the eulerian perspective
if (val_popupmenu == 1 || (val_popupmenu == 2 && samesize_cur))
% Form initial save figure -----------------------------------%
handles_gui_savefig = form_savefig(0,0,[]);
% Disable close function so figure isnt inadvertently closed
set(handles_gui_savefig.figure,'CloseRequestFcn','');
% Set Size(s) ------------------------------------------------%
% gui_savesize is a local function with a GUI; it allows the user
% to modify the size of the image
[size_savefig,timedelay,outstate] = gui_savesize(handles_gui_savefig, ...
true, ...
get(handles_gui.figure,'OuterPosition'));
if (outstate == out.success)
[filename,pathname] = uiputfile({'*.gif'},'Save Image');
if (~isequal(filename,0) && ~isequal(pathname,0))
overwrite = true;
if (exist(fullfile(pathname,filename),'file'))
contbutton = questdlg('File already exists. Do you want to overwrite?','Continue Operation','Yes','No','No');
if strcmp(contbutton,'No')
overwrite = false;
end
end
if (overwrite)
% Save initial image -----------------------------%
img_printscreen = getframe(handles_gui_savefig.figure);
img_printscreen = frame2im(img_printscreen);
[imind,cm] = rgb2ind(img_printscreen,256);
% Save
imwrite(imind,cm,[pathname filename],'gif','Loopcount',inf);
% Cycle over other images to save
for i = 1:length(current)-1
% Close figure
set(handles_gui_savefig.figure,'CloseRequestFcn','closereq');
close(handles_gui_savefig.figure);
% Form updated save figure -------------------%
handles_gui_savefig = form_savefig(i,0,size_savefig);
% Disable close function for now
set(handles_gui_savefig.figure,'CloseRequestFcn','');
% Get image ----------------------------------%
img_printscreen = getframe(handles_gui_savefig.figure);
img_printscreen = frame2im(img_printscreen);
[imind,cm] = rgb2ind(img_printscreen,256);
% Append
if (i ~= length(current)-1)
imwrite(imind,cm,[pathname filename],'gif','WriteMode','append','DelayTime',timedelay);
else
% This is the last image, make the time
% delay longer so there's a pause at the
% end.
imwrite(imind,cm,[pathname filename],'gif','WriteMode','append','DelayTime',timedelay+0.5);
end
end
end
end
end
% Close last figure
set(handles_gui_savefig.figure,'CloseRequestFcn','closereq');
close(handles_gui_savefig.figure);
else
h_error = errordlg('All current images must have the same size to save gif with the Eulerian description.','Error','modal');
uiwait(h_error);
end
end
%---------------------------------------------------------------------%
% These functions can potentially modify other viewplots -------------%
%---------------------------------------------------------------------%
function callback_popupmenu(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
val_popupmenu = get(handles_gui.popupmenu,'Value');
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'val_popupmenu',val_popupmenu);
% Update
update_axes('set',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'val_popupmenu',val_popupmenu);
% Update this plot
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_checkbox_scalebar(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
val_checkbox_scalebar = get(handles_gui.checkbox_scalebar,'Value');
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'val_checkbox_scalebar',val_checkbox_scalebar);
% Update
update_axes('update',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'val_checkbox_scalebar',val_checkbox_scalebar);
% Update this plot
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_checkbox_axes(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
val_checkbox_axes = get(handles_gui.checkbox_axes,'Value');
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'val_checkbox_axes',val_checkbox_axes);
% Update
update_axes('update',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'val_checkbox_axes',val_checkbox_axes);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_scalebarlength(hObject,eventdata) %#ok<INUSD>
% Get data
scalebarlength = getappdata(handles_gui.figure,'scalebarlength');
max_scalebarlength = getappdata(handles_gui.figure,'max_scalebarlength');
friends = getappdata(handles_gui.figure,'friends');
% Get Value
scalebarlength_buffer = str2double(get(handles_gui.edit_scalebarlength,'string'));
if (ncorr_util_isrealbb(scalebarlength_buffer,0,max_scalebarlength,'Scalebar Length') == out.success)
% Update buffer
scalebarlength = scalebarlength_buffer;
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'scalebarlength',scalebarlength);
% Update
update_axes('update',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
end
% Set data
setappdata(handles_gui.figure,'scalebarlength',scalebarlength);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_imgnum(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
friends = getappdata(handles_gui.figure,'friends');
% Get Value - uses one based indexing
num_cur_prelim = str2double(get(handles_gui.edit_imgnum,'string'));
if (ncorr_util_isintbb(num_cur_prelim,1,length(current),'Current Image number') == out.success)
% Store value - convert back to zero based indexing
num_cur = num_cur_prelim-1;
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'num_cur',num_cur);
% Update
update_axes('set',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
end
% Set data
setappdata(handles_gui.figure,'num_cur',num_cur);
% Update this plot
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_button_zoom(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
handle_zoom = getappdata(handles_gui.figure,'handle_zoom');
if (strcmp(get(handle_zoom,'Enable'),'on'))
% Zoom is already enabled; disable it
val_zoom = false;
set(handle_zoom,'Enable','off');
else
% Zoom not enabled; enable it
val_zoom = true;
set(handle_zoom,'Enable','on');
end
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Get zoom handle from other plot
handle_zoom_sub = getappdata(friends{i+1}.figure,'handle_zoom');
if (val_zoom)
set(handle_zoom_sub,'Enable','on');
else
set(handle_zoom_sub,'Enable','off');
end
% Set data
setappdata(friends{i+1}.figure,'handle_zoom',handle_zoom_sub);
% Update
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'handle_zoom',handle_zoom);
% Update
update_sidemenu(handles_gui);
end
function callback_button_pan(hObject,eventdata) %#ok<INUSD>
% Get data
friends = getappdata(handles_gui.figure,'friends');
handle_pan = getappdata(handles_gui.figure,'handle_pan');
if (strcmp(get(handle_pan,'Enable'),'on'))
% Pan is already enabled; disable it
val_pan = false;
set(handle_pan,'Enable','off');
else
% Pan not enabled; enable it
val_pan = true;
set(handle_pan,'Enable','on');
end
% Update other plots in friend list
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Get Pan handle from other plot
handle_pan_sub = getappdata(friends{i+1}.figure,'handle_pan');
if (val_pan)
set(handle_pan_sub,'Enable','on');
else
set(handle_pan_sub,'Enable','off');
end
% Set data
setappdata(friends{i+1}.figure,'handle_pan',handle_pan_sub);
% Update
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
% Set data
setappdata(handles_gui.figure,'handle_pan',handle_pan);
% Update
update_sidemenu(handles_gui);
end
function callback_button_left(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
friends = getappdata(handles_gui.figure,'friends');
% Check for overshoot
if (num_cur > 0)
% Update other plots in friend list
num_cur = num_cur-1;
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'num_cur',num_cur);
% Update
update_axes('set',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
end
% Set data
setappdata(handles_gui.figure,'num_cur',num_cur);
% Update this plot
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_button_right(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
friends = getappdata(handles_gui.figure,'friends');
% Check for overshoot
if (num_cur < length(current)-1)
% Update other plots in friend list
num_cur = num_cur+1;
for i = 0:length(friends)-1
if (~strcmp(getappdata(friends{i+1}.figure,'type_plot'),type_plot))
% Must check to make sure figure has not been closed during
% callback since protection is only gauranteed for this
% figure.
try
% Set data
setappdata(friends{i+1}.figure,'num_cur',num_cur);
% Update
update_axes('set',friends{i+1});
update_sidemenu(friends{i+1});
catch err
if (ishandle(friends{i+1}.figure))
rethrow(err);
end
end
end
end
end
% Set data
setappdata(handles_gui.figure,'num_cur',num_cur);
% Update this plot
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function update_sidemenu(handles_gui_sub)
% Get data - MUST USE HANDLES_GUI_SUB!!!
num_cur = getappdata(handles_gui_sub.figure,'num_cur');
scalebarlength = getappdata(handles_gui_sub.figure,'scalebarlength');
transparency_prelim = getappdata(handles_gui_sub.figure,'transparency_prelim');
contourlines_prelim = getappdata(handles_gui_sub.figure,'contourlines_prelim');
slider_buffer = getappdata(handles_gui_sub.figure,'slider_buffer');
val_checkbox_scalebar = getappdata(handles_gui_sub.figure,'val_checkbox_scalebar');
val_checkbox_axes = getappdata(handles_gui_sub.figure,'val_checkbox_axes');
val_checkbox_contour = getappdata(handles_gui_sub.figure,'val_checkbox_contour');
val_popupmenu = getappdata(handles_gui_sub.figure,'val_popupmenu');
handle_zoom = getappdata(handles_gui_sub.figure,'handle_zoom');
handle_pan = getappdata(handles_gui_sub.figure,'handle_pan');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Sliders:
set(handles_gui_sub.slider_transparency,'value',transparency_prelim);
set(handles_gui_sub.slider_upperbound,'value',min(1,max(0,slider_buffer(num_cur+1).(lore)(1))));
set(handles_gui_sub.slider_lowerbound,'value',min(1,max(0,slider_buffer(num_cur+1).(lore)(2))));
% Edit:
set(handles_gui_sub.edit_transparency,'String',num2str(transparency_prelim,'%6.4f'));
set(handles_gui_sub.edit_upperbound,'String',num2str((slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(1)+slider_buffer(num_cur+1).(lore)(4),'%6.4f'));
set(handles_gui_sub.edit_lowerbound,'String',num2str((slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(2)+slider_buffer(num_cur+1).(lore)(4),'%6.4f'));
set(handles_gui_sub.edit_contour,'String',num2str(contourlines_prelim));
set(handles_gui_sub.edit_scalebarlength,'String',num2str(scalebarlength,'%6.2f'));
% Popupmenu:
set(handles_gui_sub.popupmenu,'Value',val_popupmenu);
% Enable scalebar
if (val_checkbox_scalebar)
set(handles_gui_sub.edit_scalebarlength,'Enable','on','backgroundcolor',[0.9412 0.9412 0.9412]);
set(handles_gui_sub.checkbox_scalebar,'Value',true);
else
set(handles_gui_sub.edit_scalebarlength,'Enable','off','backgroundcolor',[0.9412 0.9412 0.9412]);
set(handles_gui_sub.checkbox_scalebar,'Value',false);
end
% Enable axes
if (val_checkbox_axes)
set(handles_gui_sub.checkbox_axes,'Value',true);
else
set(handles_gui_sub.checkbox_axes,'Value',false);
end
% Enable contour
if (val_checkbox_contour)
% Disable trans
set(handles_gui_sub.edit_transparency,'Enable','off');
set(handles_gui_sub.slider_transparency,'Enable','off');
% Enable contours
set(handles_gui_sub.edit_contour,'Enable','on','backgroundcolor',[0.9412 0.9412 0.9412]);
else
% Enable trans
set(handles_gui_sub.edit_transparency,'Enable','on','backgroundcolor',[0.9412 0.9412 0.9412]);
set(handles_gui_sub.slider_transparency,'Enable','on');
% Disable contours
set(handles_gui_sub.edit_contour,'Enable','off');
end
if (strcmp(get(handle_pan,'Enable'),'on'))
set(handles_gui_sub.button_pan,'FontWeight','bold');
else
set(handles_gui_sub.button_pan,'FontWeight','normal');
end
if (strcmp(get(handle_zoom,'Enable'),'on'))
set(handles_gui_sub.button_zoom,'FontWeight','bold');
else
set(handles_gui_sub.button_zoom,'FontWeight','normal');
end
end
function update_axes(action,handles_gui_sub)
% Get data - MUST USE HANDLES_GUI_SUB AND TYPE_PLOT_SUB!!!
num_cur = getappdata(handles_gui_sub.figure,'num_cur');
transparency_prelim = getappdata(handles_gui_sub.figure,'transparency_prelim');
contourlines_prelim = getappdata(handles_gui_sub.figure,'contourlines_prelim');
scalebarlength = getappdata(handles_gui_sub.figure,'scalebarlength');
slider_buffer = getappdata(handles_gui_sub.figure,'slider_buffer');
type_plot_sub = getappdata(handles_gui_sub.figure,'type_plot');
text_info = getappdata(handles_gui_sub.figure,'text_info');
val_checkbox_contour = getappdata(handles_gui_sub.figure,'val_checkbox_contour');
val_checkbox_scalebar = getappdata(handles_gui_sub.figure,'val_checkbox_scalebar');
val_checkbox_axes = getappdata(handles_gui_sub.figure,'val_checkbox_axes');
val_checkbox_minmaxmarkers = getappdata(handles_gui_sub.figure,'val_checkbox_minmaxmarkers');
val_popupmenu = getappdata(handles_gui_sub.figure,'val_popupmenu');
handle_preview = getappdata(handles_gui_sub.figure,'handle_preview');
handle_scalebar = getappdata(handles_gui_sub.figure,'handle_scalebar');
handle_axes = getappdata(handles_gui_sub.figure,'handle_axes');
handle_colorbar = getappdata(handles_gui_sub.figure,'handle_colorbar');
handle_point_max = getappdata(handles_gui_sub.figure,'handle_point_max');
handle_point_min = getappdata(handles_gui_sub.figure,'handle_point_min');
if (val_popupmenu == 1)
lore = 'lagrangian';
img_bg = reference;
else
lore = 'eulerian';
img_bg = current(num_cur+1);
end
% Get data
data = get_data(type_plot_sub,lore,num_cur);
plot_data = get_dataplot(type_plot_sub,lore,num_cur);
roi_data = get_roi(type_plot_sub,lore,num_cur);
if (strcmp(action,'set') || strcmp(action,'save'))
% Get reduced img
img_reduced = img_bg.reduce(data_dic.dispinfo.spacing);
% Set Background Image
imshow(img_reduced.get_img(),[img_reduced.min_gs img_reduced.max_gs],'Parent',handles_gui_sub.axes_formatplot);
hold(handles_gui_sub.axes_formatplot,'on');
% Overlay plot - See if it's a contour plot
if (val_checkbox_contour)
% Format plot
[grid_x,grid_y] = meshgrid(1:size(plot_data,2),1:size(plot_data,1));
alphamap_nan = ~roi_data.mask;
plot_data(alphamap_nan) = NaN;
% Form contour plot
[data_contour,handle_preview] = contourf(grid_x,grid_y,plot_data,contourlines_prelim,'Parent',handles_gui_sub.axes_formatplot);
% Overlay image in NaN regions
% This only works properly when opengl is disabled. When opengl
% is enabled, stacking order is determined by projected Z
% value. This is a problem because images and contourf functions
% have z = 0 value, so sometimes the image will not overlay the
% white regions.
handle_trans = imshow(img_reduced.get_img(),[img_reduced.min_gs img_reduced.max_gs],'Parent',handles_gui_sub.axes_formatplot);
set(handle_trans,'AlphaData',imdilate(alphamap_nan,true(3))); % This dilation covers the border
else
% Regular Plot
handle_preview = imshow(plot_data,[],'Parent',handles_gui_sub.axes_formatplot);
end
% Set axes grid off
set(handles_gui_sub.axes_formatplot,'Visible','off');
% Place markers in min/max location
datamax = max(data);
datamin = min(data);
% Max marker
[y_max,x_max] = find(plot_data == datamax,1);
handle_point_max = impoint(handles_gui_sub.axes_formatplot,x_max,y_max);
setColor(handle_point_max,'g');
set(handle_point_max,'UIContextMenu','');
set(handle_point_max,'ButtonDownFcn','');
% Min Marker
[y_min,x_min] = find(plot_data == datamin,1);
handle_point_min = impoint(handles_gui_sub.axes_formatplot,x_min,y_min);
setColor(handle_point_min,'g');
set(handle_point_min,'UIContextMenu','');
set(handle_point_min,'ButtonDownFcn','');
% Set invisible if markers are disabled
if (~val_checkbox_minmaxmarkers)
set(handle_point_max,'Visible','off');
set(handle_point_min,'Visible','off');
end
% Turn hold off
hold(handles_gui_sub.axes_formatplot,'off');
% Set left/right buttons
if (~strcmp(action,'save'))
set(handles_gui_sub.edit_imgnum,'String',num2str(num_cur+1));
if (length(current) == 1)
set(handles_gui_sub.button_right,'Enable','off');
set(handles_gui_sub.button_left,'Enable','off');
set(handles_gui_sub.edit_imgnum,'Enable','off');
elseif (num_cur == 0)
set(handles_gui_sub.button_right,'Enable','on');
set(handles_gui_sub.button_left,'Enable','off');
set(handles_gui_sub.edit_imgnum,'Enable','on');
elseif (num_cur == length(current)-1)
set(handles_gui_sub.button_right,'Enable','off');
set(handles_gui_sub.button_left,'Enable','on');
set(handles_gui_sub.edit_imgnum,'Enable','on');
else
set(handles_gui_sub.button_right,'Enable','on');
set(handles_gui_sub.button_left,'Enable','on');
set(handles_gui_sub.edit_imgnum,'Enable','on');
end
end
% Static Texts:
if (strcmp(action,'set') || (strcmp(action,'save') && getappdata(handles_gui_sub.figure,'includeinfo')))
set(handles_gui_sub.text_ref_name,'String',['Reference Name: ' reference.name(1:min(end,40))]);
set(handles_gui_sub.text_cur_name,'String',['Current Name: ' current(num_cur+1).name(1:min(end,40))]);
set(handles_gui_sub.text_type,'String',['Analysis type: ' data_dic.dispinfo.type]);
if (strcmp(type_plot_sub,'u') || strcmp(type_plot_sub,'v'))
string_dicparams = ['RG-DIC Radius: ' num2str(data_dic.dispinfo.radius) ' | Subset Spacing: ' num2str(data_dic.dispinfo.spacing)];
else
string_dicparams = ['RG-DIC Radius: ' num2str(data_dic.dispinfo.radius) ' | Strain Radius: ' num2str(data_dic.straininfo.radius) ' | Subset Spacing: ' num2str(data_dic.dispinfo.spacing)];
end
set(handles_gui_sub.text_dicparams,'String', string_dicparams);
set(handles_gui_sub.text_itparams,'String', ['Diffnorm Cutoff: ' num2str(data_dic.dispinfo.cutoff_diffnorm) ' | Iteration Cutoff: ' num2str(data_dic.dispinfo.cutoff_iteration) ' | Threads: ' num2str(data_dic.dispinfo.total_threads)]);
if (data_dic.dispinfo.stepanalysis.enabled)
if (strcmp(data_dic.dispinfo.stepanalysis.type,'seed'))
string_stepanalysis = 'Step Analysis: Enabled | Type: Seed Propagation ';
else
string_stepanalysis = ['Step Analysis: Enabled | Type: Leap Frog | Step: ' num2str(data_dic.dispinfo.stepanalysis.step)];
end
else
string_stepanalysis = 'Step Analysis: Disabled';
end
set(handles_gui_sub.text_stepanalysis,'String',string_stepanalysis);
if (data_dic.dispinfo.subsettrunc)
string_subsettrunc = 'RG-DIC Subset Truncation: Enabled';
else
string_subsettrunc = 'RG-DIC Subset Truncation: Disabled';
end
if (strcmp(type_plot_sub,'exx') || strcmp(type_plot_sub,'exy') || strcmp(type_plot_sub,'eyy'))
if (data_dic.straininfo.subsettrunc)
string_subsettrunc = horzcat(string_subsettrunc,' | Strain Subset Truncation: Enabled'); %#ok<AGROW>
else
string_subsettrunc = horzcat(string_subsettrunc,' | Strain Subset Truncation: Disabled'); %#ok<AGROW>
end
end
set(handles_gui_sub.text_subsettrunc,'String',string_subsettrunc);
string_imgcorr = 'Image Correspondences: ';
for i = 0:length(data_dic.dispinfo.imgcorr)-1 % Might be large
string_imgcorr = horzcat(string_imgcorr,['[' num2str(data_dic.dispinfo.imgcorr(i+1).idx_ref) ' ' num2str(data_dic.dispinfo.imgcorr(i+1).idx_cur) '] ']); %#ok<AGROW>
end
set(handles_gui_sub.text_imgcorr,'String',string_imgcorr);
set(handles_gui_sub.text_pixtounits,'String', ['Units/pixels: ' num2str(data_dic.dispinfo.pixtounits) ' ' data_dic.dispinfo.units '/pixels']);
set(handles_gui_sub.text_cutoff_corrcoef,'String', ['Correlation Coefficient Cutoff: ' num2str(data_dic.dispinfo.cutoff_corrcoef(num_cur+1),'%6.4f')]);
set(handles_gui_sub.text_lenscoef,'String',['Radial Lens Distortion Coefficient: ' num2str(data_dic.dispinfo.lenscoef)]);
if (strcmp(type_plot_sub,'u') || strcmp(type_plot_sub,'v'))
set(handles_gui_sub.text_minmedianmax,'String',['Max: ' num2str(slider_buffer(num_cur+1).(lore)(6),'%6.4f') ' ' data_dic.dispinfo.units ' | Median: ' num2str(slider_buffer(num_cur+1).(lore)(4),'%6.4f') ' ' data_dic.dispinfo.units ' | Min: ' num2str(slider_buffer(num_cur+1).(lore)(7),'%6.4f') ' ' data_dic.dispinfo.units]);
elseif (strcmp(type_plot_sub,'exx') || strcmp(type_plot_sub,'exy') || strcmp(type_plot_sub,'eyy'))
set(handles_gui_sub.text_minmedianmax,'String',['Max: ' num2str(slider_buffer(num_cur+1).(lore)(6),'%6.4f') ' | Median: ' num2str(slider_buffer(num_cur+1).(lore)(4),'%6.4f') ' | Min: ' num2str(slider_buffer(num_cur+1).(lore)(7),'%6.4f')]);
end
end
% Set empty text info
text_info = text(0,0,2,'','Parent',handles_gui_sub.axes_formatplot,'HorizontalAlignment','left','VerticalAlignment','top','BackgroundColor',[1 1 1],'EdgeColor',[0.7 0.7 0.7],'tag','text_info','FontSize',8);
% Update panel text if its strain, since it also displays the
% strain tensor name
if (~strcmp(action,'save') && (strcmp(type_plot_sub,'exx') || strcmp(type_plot_sub,'exy') || strcmp(type_plot_sub,'eyy')))
if (strcmp(type_plot_sub,'exx'))
group_title = 'Exx ';
elseif (strcmp(type_plot_sub,'exy'))
group_title = 'Exy ';
elseif (strcmp(type_plot_sub,'eyy'))
group_title = 'Eyy ';
end
if (val_popupmenu == 1)
group_title = [group_title 'Green-Lagrangian'];
else
group_title = [group_title 'Eulerian-Almansi'];
end
% Update title
set(handles_gui_sub.group_formataxes,'Title',group_title)
end
% Set colormap
ncorr_util_colormap(handles_gui_sub.figure);
end
if (strcmp(action,'set') || strcmp(action,'update') || strcmp(action,'save'))
% Get limits
cmax = (slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(1)+slider_buffer(num_cur+1).(lore)(4);
cmin = (slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(2)+slider_buffer(num_cur+1).(lore)(4);
if (abs(cmin-cmax)<1e-4)
cmax = cmax + 1e-5; % add a small increment to ensure they are not the same number
cmin = cmin - 1e-5;
end
% Update Plot
caxis(handles_gui_sub.axes_formatplot,[cmin cmax]);
% Update transparency for regular plot
if (~val_checkbox_contour)
transparency = transparency_prelim;
alphamap_plot = roi_data.mask.*transparency;
set(handle_preview,'AlphaData',alphamap_plot);
end
% Set colorbar
handle_colorbar = colorbar('peer',handles_gui_sub.axes_formatplot);
set(handle_colorbar,'UIContextMenu','');
set(get(handle_colorbar,'child'),'YData',[cmin cmax]);
set(handle_colorbar,'YLim',[cmin cmax]);
set(handle_colorbar,'Units','Pixels');
% Set max/min markers
if (val_checkbox_minmaxmarkers)
set(handle_point_max,'Visible','on');
set(handle_point_min,'Visible','on');
else
set(handle_point_max,'Visible','off');
set(handle_point_min,'Visible','off');
end
% Check for scale bar
if (val_checkbox_scalebar)
% Need to also test if handle is valid, since it is not
% explicitly cleared when switching img_num
if (isempty(handle_scalebar) || ~ishandle(handle_scalebar))
% Scalebar isnt present, so create it
handle_scalebar = form_scalebar(handles_gui_sub);
else
% Scalebar is already present - just update it
% Get display image dimensions
height_img = floor(img_bg.height/(data_dic.dispinfo.spacing+1));
width_img = floor(img_bg.width/(data_dic.dispinfo.spacing+1));
line_scalebar = findobj(handle_scalebar,'tag','line');
width_sb = scalebarlength/(data_dic.dispinfo.pixtounits*(data_dic.dispinfo.spacing+1)); % Convert to pixels
height_sb = 0.015*height_img; % Height is 1.5% of img height
offset_sb_left = 0.05*width_img; % Offset is 5% from left, and 95% from top
offset_sb_top = 0.95*height_img;
set(line_scalebar,'XData',[offset_sb_left offset_sb_left+width_sb offset_sb_left+width_sb offset_sb_left]);
set(line_scalebar,'YData',[offset_sb_top offset_sb_top offset_sb_top+height_sb offset_sb_top+height_sb]);
% Update bg
bg1 = findobj(handle_scalebar,'tag','bg1');
bg2 = findobj(handle_scalebar,'tag','bg2');
width_bg = (width_sb/width_img+0.06)*width_img;
height_bg = 0.12*height_img; % Height is a 12% of height
offset_bg_left = 0.02*width_img; % Offset is 2% from left, and 86% from top
offset_bg_top = 0.86*height_img;
set(bg1,'XData',[offset_bg_left offset_bg_left+width_bg offset_bg_left+width_bg offset_sb_left+width_sb offset_sb_left+width_sb offset_sb_left offset_sb_left offset_bg_left]);
set(bg1,'YData',[offset_bg_top offset_bg_top offset_bg_top+height_bg offset_sb_top+height_sb offset_sb_top offset_sb_top offset_sb_top+height_sb offset_bg_top+height_bg]);
set(bg2,'XData',[offset_sb_left offset_sb_left+width_sb offset_bg_left+width_bg offset_bg_left]);
set(bg2,'YData',[offset_sb_top+height_sb offset_sb_top+height_sb offset_bg_top+height_bg offset_bg_top+height_bg]);
% Update text
text_scalebar = findobj(handle_scalebar,'tag','text_scalebar');
pos_x_text = offset_sb_left+width_sb/2;
pos_y_text = .905*height_img;
set(text_scalebar,'String',[num2str(scalebarlength) ' ' data_dic.dispinfo.units],'Position',[pos_x_text pos_y_text 1]);
end
else
% See if scalebar exists
if (~isempty(handle_scalebar) && ishandle(handle_scalebar))
delete(handle_scalebar);
end
handle_scalebar = [];
if (~strcmp(action,'save'))
% Disable the edit box for editing scalebar length
set(handles_gui_sub.edit_scalebarlength,'Enable','off');
end
end
% Check for the axes
if (val_checkbox_axes)
if (isempty(handle_axes) || ~ishandle(handle_axes))
% Create plot axes
handle_axes = form_plotaxes(handles_gui_sub);
end
else
if (~isempty(handle_axes) && ishandle(handle_axes))
delete(handle_axes);
end
handle_axes = [];
end
end
% Set data
setappdata(handles_gui_sub.figure,'handle_point_max', handle_point_max);
setappdata(handles_gui_sub.figure,'handle_point_min', handle_point_min);
setappdata(handles_gui_sub.figure,'handle_preview',handle_preview);
setappdata(handles_gui_sub.figure,'handle_scalebar',handle_scalebar);
setappdata(handles_gui_sub.figure,'handle_axes',handle_axes);
setappdata(handles_gui_sub.figure,'handle_colorbar',handle_colorbar);
setappdata(handles_gui_sub.figure,'text_info',text_info);
end
function handle_scalebar = form_scalebar(handles_gui_sub)
% This function creates the scalebar
% Get data
num_cur = getappdata(handles_gui_sub.figure,'num_cur');
scalebarlength = getappdata(handles_gui_sub.figure,'scalebarlength');
val_popupmenu = getappdata(handles_gui_sub.figure,'val_popupmenu');
if (val_popupmenu == 1)
img_bg = reference;
else
img_bg = current(num_cur+1);
end
% Get display image dimensions (these are reduced)
height_img = floor(img_bg.height/(data_dic.dispinfo.spacing+1));
width_img = floor(img_bg.width/(data_dic.dispinfo.spacing+1));
% Form hggroup
handle_scalebar = hggroup('parent',handles_gui_sub.axes_formatplot,'tag','handle_scalebar');
% Form dimensions of scalebar - most importantly, width must be
% converted back to pixels (in reduced coordinates). It must also be
% consistent among plots and based on the scalebarlength parameter.
% Any other parameter, like the scalebar height or offsets, can
% depend on this specific image size for display purposes.
width_sb = scalebarlength/(data_dic.dispinfo.pixtounits*(data_dic.dispinfo.spacing+1));
height_sb = 0.015*height_img; % Height is a 1.5% of im height
offset_sb_left = 0.05*width_img; % Offset is 5% from left, and 95% from top
offset_sb_top = 0.95*height_img;
% BG - Form BG with two patches with a hole for the scale bar.
% For some reason alpha is applied to all overlapping patches
width_bg = (width_sb/width_img+0.06)*width_img;
height_bg = 0.12*height_img; % Height is a 12% of height
offset_bg_left = 0.02*width_img; % Offset is 2% from left, and 86% from top
offset_bg_top = 0.86*height_img;
patch([offset_bg_left offset_bg_left+width_bg offset_bg_left+width_bg offset_sb_left+width_sb offset_sb_left+width_sb offset_sb_left offset_sb_left offset_bg_left], ...
[offset_bg_top offset_bg_top offset_bg_top+height_bg offset_sb_top+height_sb offset_sb_top offset_sb_top offset_sb_top+height_sb offset_bg_top+height_bg], ...
[1 1 1 1 1 1 1 1], ...
'k','parent',handle_scalebar,'linestyle','none','FaceAlpha',0.5,'tag','bg1');
patch([offset_sb_left offset_sb_left+width_sb offset_bg_left+width_bg offset_bg_left], ...
[offset_sb_top+height_sb offset_sb_top+height_sb offset_bg_top+height_bg offset_bg_top+height_bg], ...
[1 1 1 1], ...
'k','parent',handle_scalebar,'linestyle','none','FaceAlpha',0.5,'tag','bg2');
% Line - The actual scale bar
patch([offset_sb_left offset_sb_left+width_sb offset_sb_left+width_sb offset_sb_left], ...
[offset_sb_top offset_sb_top offset_sb_top+height_sb offset_sb_top+height_sb], ...
[1 1 1 1], ...
'w','parent',handle_scalebar,'FaceAlpha',1,'tag','line');
% Text
pos_x_text = offset_sb_left+width_sb/2;
pos_y_text = .905*height_img;
pos_img = get(handles_gui_sub.axes_formatplot,'Position');
size_text = max(0.5*min(0.5*pos_img(4),0.14*pos_img(3)),8);
text(pos_x_text,pos_y_text,1,[num2str(scalebarlength) ' ' data_dic.dispinfo.units],'parent',handle_scalebar,'color','w', ...
'HorizontalAlignment','center','VerticalAlignment','middle','FontWeight','bold','FontSize',size_text,'tag','text_scalebar');
end
function handle_axes = form_plotaxes(handles_gui_sub)
% This function forms the axes seen at the top left of the plot
% Get data
num_cur = getappdata(handles_gui_sub.figure,'num_cur');
val_popupmenu = getappdata(handles_gui_sub.figure,'val_popupmenu');
if (val_popupmenu == 1)
img_bg = reference;
else
img_bg = current(num_cur+1);
end
% Do this WRT the display image
height_img = floor(img_bg.height/(data_dic.dispinfo.spacing+1));
width_img = floor(img_bg.width/(data_dic.dispinfo.spacing+1));
% Form hggroup
handle_axes = hggroup('parent',handles_gui_sub.axes_formatplot,'tag','handle_axes');
length_axes = 0.15*max(width_img,height_img);
width_axes = 0.012*max(width_img,height_img);
arrowwidth_axes = 1.0*width_axes;
width_bg = width_axes*0.4;
% BG
patch([0 width_axes+width_bg width_axes+width_bg width_axes+arrowwidth_axes+2*width_bg 0],[0 0 length_axes-width_bg length_axes-width_bg length_axes+width_axes+arrowwidth_axes+width_bg],[1 1 1 1 1], ...
'w','parent',handle_axes,'linestyle','none','tag','bg1');
patch([0 length_axes+width_axes+arrowwidth_axes+width_bg length_axes-width_bg length_axes-width_bg 0],[0 0 width_axes+arrowwidth_axes+2*width_bg width_axes+width_bg width_axes+width_bg],[1 1 1 1 1], ...
'w','parent',handle_axes,'linestyle','none','tag','bg2');
% Lines
patch([0 width_axes width_axes width_axes+arrowwidth_axes 0],[0 0 length_axes length_axes length_axes+width_axes+arrowwidth_axes],[1 1 1 1 1], ...
'k','parent',handle_axes,'linestyle','none','tag','arrow1');
patch([0 length_axes+width_axes+arrowwidth_axes length_axes length_axes 0],[0 0 width_axes+arrowwidth_axes width_axes width_axes],[1 1 1 1 1], ...
'k','parent',handle_axes,'linestyle','none','tag','arrow2');
% Text BG
spacing_textbg = 2.5*width_axes;
offset_text = 3*width_axes;
pos_text = length_axes+width_axes+arrowwidth_axes+width_bg+offset_text;
pos_img = get(handles_gui_sub.axes_formatplot,'Position');
size_text = max(0.5*min(0.5*pos_img(4),0.14*pos_img(3)),8);
patch([offset_text-spacing_textbg offset_text+spacing_textbg offset_text+spacing_textbg offset_text-spacing_textbg],[pos_text-spacing_textbg pos_text-spacing_textbg pos_text+spacing_textbg pos_text+spacing_textbg],[1 1 1 1], ...
'k','parent',handle_axes,'linestyle','none','FaceAlpha',0.5,'tag','text_bg1');
patch([pos_text-spacing_textbg pos_text+spacing_textbg pos_text+spacing_textbg pos_text-spacing_textbg],[offset_text-spacing_textbg offset_text-spacing_textbg offset_text+spacing_textbg offset_text+spacing_textbg],[1 1 1 1], ...
'k','parent',handle_axes,'linestyle','none','FaceAlpha',0.5,'tag','text_bg2');
% Text
text(offset_text,pos_text,1,'Y','parent',handle_axes,'color','w', ...
'HorizontalAlignment','center','VerticalAlignment','middle','FontWeight','bold','FontSize',size_text,'tag','text_x');
text(pos_text,offset_text,1,'X','parent',handle_axes,'color','w', ...
'HorizontalAlignment','center','VerticalAlignment','middle','FontWeight','bold','FontSize',size_text,'tag','text_y');
end
%---------------------------------------------------------------------%
%---------------------------------------------------------------------%
%---------------------------------------------------------------------%
function callback_slider_transparency(hObject,eventdata) %#ok<INUSD>
% Get data
transparency_prelim = get(handles_gui.slider_transparency,'value');
% Set data
setappdata(handles_gui.figure,'transparency_prelim',transparency_prelim);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_slider_upperbound(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Update data
slider_buffer(num_cur+1).(lore)(1) = get(handles_gui.slider_upperbound,'value');
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_slider_lowerbound(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Update data
slider_buffer(num_cur+1).(lore)(2) = get(handles_gui.slider_lowerbound,'value');
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_checkbox_contour(hObject,eventdata) %#ok<INUSD>
% Get data
val_checkbox_contour = get(handles_gui.checkbox_contour,'Value');
% Set data
setappdata(handles_gui.figure,'val_checkbox_contour',val_checkbox_contour);
% Update
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_checkbox_minmaxmarkers(hObject,eventdata) %#ok<INUSD>
% Get data
val_checkbox_minmaxmarkers = get(handles_gui.checkbox_minmaxmarkers,'Value');
% Set data
setappdata(handles_gui.figure,'val_checkbox_minmaxmarkers',val_checkbox_minmaxmarkers);
% Update
update_axes('update',handles_gui);
end
function callback_edit_transparency(hObject,eventdata) %#ok<INUSD>
% Get data
transparency_prelim = getappdata(handles_gui.figure,'transparency_prelim');
% Get Value
transparency_buffer = str2double(get(handles_gui.edit_transparency,'string'));
if (ncorr_util_isrealbb(transparency_buffer,0,1,'Transparency') == out.success)
transparency_prelim = transparency_buffer;
end
% Set data
setappdata(handles_gui.figure,'transparency_prelim',transparency_prelim);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_lowerbound(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
min_lowerbound = getappdata(handles_gui.figure,'min_lowerbound');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Get Value
lowerbound_buffer = str2double(get(handles_gui.edit_lowerbound,'string'));
if (ncorr_util_isrealbb(lowerbound_buffer,min_lowerbound,slider_buffer(num_cur+1).(lore)(4),'Lowerbound') == out.success)
% Make sure denominator is not close to zero
if (abs(slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4)) <= 1e-10)
slider_buffer(num_cur+1).(lore)(2) = 1;
else
slider_buffer(num_cur+1).(lore)(2) = (lowerbound_buffer-slider_buffer(num_cur+1).(lore)(4))/(slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4));
end
end
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_upperbound(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
max_upperbound = getappdata(handles_gui.figure,'max_upperbound');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Get Value
upperbound_buffer = str2double(get(handles_gui.edit_upperbound,'string'));
if (ncorr_util_isrealbb(upperbound_buffer,slider_buffer(num_cur+1).(lore)(4),max_upperbound,'Upperbound') == out.success)
% Make sure denominator is not close to zero
if (abs(slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4)) <= 1e-10)
slider_buffer(num_cur+1).(lore)(1) = 1;
else
slider_buffer(num_cur+1).(lore)(1) = (upperbound_buffer-slider_buffer(num_cur+1).(lore)(4))/(slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4));
end
end
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_edit_contour(hObject,eventdata) %#ok<INUSD>
% Get data
contourlines_prelim = getappdata(handles_gui.figure,'contourlines_prelim');
max_contourlines = getappdata(handles_gui.figure,'max_contourlines');
% Get Value
contourlines_buffer = str2double(get(handles_gui.edit_contour,'string'));
if (ncorr_util_isintbb(contourlines_buffer,1,max_contourlines,'Number of contour lines') == out.success)
contourlines_prelim = contourlines_buffer;
end
% Set data
setappdata(handles_gui.figure,'contourlines_prelim',contourlines_prelim);
% Update
update_axes('set',handles_gui);
update_sidemenu(handles_gui);
end
function callback_button_applytoall(hObject,eventdata) %#ok<INUSD>
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Get bounds
upperbound_buffer = (slider_buffer(num_cur+1).(lore)(3)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(1)+slider_buffer(num_cur+1).(lore)(4);
lowerbound_buffer = (slider_buffer(num_cur+1).(lore)(5)-slider_buffer(num_cur+1).(lore)(4))*slider_buffer(num_cur+1).(lore)(2)+slider_buffer(num_cur+1).(lore)(4);
% Find cutoff for bounds.
cutoff_buffer = vertcat(slider_buffer.(lore));
cutoff_lowerbound = min(cutoff_buffer(:,4));
cutoff_upperbound = max(cutoff_buffer(:,4));
if (upperbound_buffer > cutoff_upperbound && lowerbound_buffer < cutoff_lowerbound)
% Set bounds
for i = 0:length(current)-1
% Set lowerbound
if (abs(slider_buffer(i+1).(lore)(5)-slider_buffer(i+1).(lore)(4)) <= 1e-10)
slider_buffer(i+1).(lore)(2) = 1;
else
slider_buffer(i+1).(lore)(2) = (lowerbound_buffer-slider_buffer(i+1).(lore)(4))/(slider_buffer(i+1).(lore)(5)-slider_buffer(i+1).(lore)(4));
end
% Set upperbound
if (abs(slider_buffer(i+1).(lore)(3)-slider_buffer(i+1).(lore)(4)) <= 1e-10)
slider_buffer(i+1).(lore)(1) = 1;
else
slider_buffer(i+1).(lore)(1) = (upperbound_buffer-slider_buffer(i+1).(lore)(4))/(slider_buffer(i+1).(lore)(3)-slider_buffer(i+1).(lore)(4));
end
end
else
h_error = errordlg(['Lowerbound must be a lower than ' num2str(cutoff_lowerbound) ' and upperbound must be greater than ' num2str(cutoff_upperbound) '.'],'Error','modal');
uiwait(h_error);
end
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_button_resetdefaults(hObject,eventdata) %#ok<INUSD>
% Get data
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
% Set slider buffer
for i = 0:length(current)-1
% Set parameters
data_ref = get_data(type_plot,'lagrangian',i);
slider_buffer(i+1).lagrangian(1) = 0.5; % Initialize to half
slider_buffer(i+1).lagrangian(2) = 0.5; % Initialize to half
slider_buffer(i+1).lagrangian(3:7) = get_sliderparams(data_ref);
data_cur = get_data(type_plot,'eulerian',i);
slider_buffer(i+1).eulerian(1) = 0.5; % Initialize to half
slider_buffer(i+1).eulerian(2) = 0.5; % Initialize to half
slider_buffer(i+1).eulerian(3:7) = get_sliderparams(data_cur);
end
% Set data
setappdata(handles_gui.figure,'slider_buffer',slider_buffer);
% Update
update_axes('update',handles_gui);
update_sidemenu(handles_gui);
end
function callback_resizefunction(hObject,eventdata) %#ok<INUSD>
% This function constrains how the figure resizes its axes, buttons, etc
% on resize. Be careful here because resize function will interrupt
% callbacks even if 'interruptible' is set to 'off'
% Get data
handle_scalebar = getappdata(handles_gui.figure,'handle_scalebar');
handle_axes = getappdata(handles_gui.figure,'handle_axes');
pos_fig = get(handles_gui.figure,'Position');
val_checkbox_scalebar = getappdata(handles_gui.figure,'val_checkbox_scalebar');
val_checkbox_axes = getappdata(handles_gui.figure,'val_checkbox_axes');
% Set offsets
offset_group_menu_y = 21.1;
offset_group_view_y = 26.5;
offset_group_scalebar_y = 33.8;
offset_group_axes_y = 38.7;
offset_group_zoompan_y = 43.7;
offset_axes_x = 1.35;
offset_axes_y = 41.1;
offset_img_x = 24.4;
offset_img_y = 80.8;
offset_left_y = 66;
offset_right_y = 51;
offset_edit_y = 59;
% Update menu panel
pos_group_menu = get(handles_gui.group_menu,'Position');
pos_group_menu(2) = pos_fig(4)-offset_group_menu_y;
set(handles_gui.group_menu,'Position',pos_group_menu);
% Update lore panel
pos_group_view = get(handles_gui.group_viewoptions,'Position');
pos_group_view(2) = pos_fig(4)-offset_group_view_y;
set(handles_gui.group_viewoptions,'Position',pos_group_view);
% Update scalebar panel
pos_group_scalebar = get(handles_gui.group_scalebar,'Position');
pos_group_scalebar(2) = pos_fig(4)-offset_group_scalebar_y;
set(handles_gui.group_scalebar,'Position',pos_group_scalebar);
% Update axes panel
pos_group_axes = get(handles_gui.group_axes,'Position');
pos_group_axes(2) = pos_fig(4)-offset_group_axes_y;
set(handles_gui.group_axes,'Position',pos_group_axes);
% Update zoom/pan panel
pos_group_zoompan = get(handles_gui.group_zoompan,'Position');
pos_group_zoompan(2) = pos_fig(4)-offset_group_zoompan_y;
set(handles_gui.group_zoompan,'Position',pos_group_zoompan);
% Update axes panel - make sure it has positive width and height
if (pos_fig(3)-offset_axes_y > 0 && ...
pos_fig(4)-offset_axes_x > 0)
pos_axes = get(handles_gui.group_formataxes,'Position');
pos_axes(3) = pos_fig(3)-offset_axes_y;
pos_axes(4) = pos_fig(4)-offset_axes_x;
set(handles_gui.group_formataxes,'Position',pos_axes);
end
% Update axes - make sure it has positive width and height
if (pos_fig(3)-offset_img_y > 0 && ...
pos_fig(4)-offset_img_x > 0)
pos_img = get(handles_gui.axes_formatplot,'Position');
pos_img(3) = pos_fig(3)-offset_img_y;
pos_img(4) = pos_fig(4)-offset_img_x;
set(handles_gui.axes_formatplot,'Position',pos_img);
end
% Update buttons
if (pos_fig(3)-offset_left_y > 0)
pos_left = get(handles_gui.button_left,'Position');
pos_left(1) = pos_fig(3)-offset_left_y;
set(handles_gui.button_left,'Position',pos_left);
end
if (pos_fig(3)-offset_right_y > 0)
pos_right = get(handles_gui.button_right,'Position');
pos_right(1) = pos_fig(3)-offset_right_y;
set(handles_gui.button_right,'Position',pos_right);
end
% Update imgnum edit
if (pos_fig(3)-offset_edit_y > 0)
pos_right = get(handles_gui.edit_imgnum,'Position');
pos_right(1) = pos_fig(3)-offset_edit_y;
set(handles_gui.edit_imgnum,'Position',pos_right);
end
% Update handle_scalebar text if it it's enabled.
% Only text is updated because text size is constant during resize;
% patches will resize automatically with handle_axes.
% Note that resize function will interrupt callbacks, so check
% explicitly that the scalebar exists first before resizing it (i.e.
% its possible to interrupt the checkbox callback for the scalebar
% midway).
if (val_checkbox_scalebar && ...
~isempty(handle_scalebar) && ishandle(handle_scalebar))
text_scalebar = findobj(handle_scalebar,'tag','text_scalebar');
pos_img = get(handles_gui.axes_formatplot,'Position');
size_text = max(0.5*min(0.5*pos_img(4),0.14*pos_img(3)),8);
set(text_scalebar,'FontSize',size_text);
end
% Update handle_axes text if it it's enabled.
% Only text is updated because the size is constant during resize;
% patches will resize automatically with handle_axes.
% Note that resize function will interrupt callbacks, so check
% explicitly that the axes exists first before resizing it (i.e.
% its possible to interrupt the checkbox callback for the axes
% midway).
if (val_checkbox_axes && ...
~isempty(handle_axes) && ishandle(handle_axes))
text_x = findobj(handle_axes,'tag','text_x');
text_y = findobj(handle_axes,'tag','text_y');
pos_img = get(handles_gui.axes_formatplot,'Position');
size_text = max(0.5*min(0.5*pos_img(4),0.14*pos_img(3)),8);
set(text_x,'FontSize',size_text);
set(text_y,'FontSize',size_text);
end
end
function callback_moveplot(hObject,eventdata) %#ok<INUSD>
% This function tells the axes what to do if the mouse cursor hovers
% over the plot axes
% Get data
num_cur = getappdata(handles_gui.figure,'num_cur');
text_info = getappdata(handles_gui.figure,'text_info');
handle_colorbar = getappdata(handles_gui.figure,'handle_colorbar');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
handle_zoom = getappdata(handles_gui.figure,'handle_zoom');
handle_pan = getappdata(handles_gui.figure,'handle_pan');
if (val_popupmenu == 1)
lore = 'lagrangian';
else
lore = 'eulerian';
end
% Get data
plot_data = get_dataplot(type_plot,lore,num_cur);
roi_data = get_roi(type_plot,lore,num_cur);
% Test to see if mouse position is within ROI - uses 1 based
% indexing. Also round it first.
pos_mouse_axes = round(get(handles_gui.axes_formatplot,'CurrentPoint'));
if (pos_mouse_axes(1) >= 1 && pos_mouse_axes(3) >= 1 && pos_mouse_axes(1) <= size(roi_data.mask,2) && pos_mouse_axes(3) <= size(roi_data.mask,1))
if (roi_data.mask(pos_mouse_axes(3),pos_mouse_axes(1)))
% Get Plot info - note that strain is dimensionless
if (strcmp(type_plot,'u'))
text_display = 'U-disp: ';
units = data_dic.dispinfo.units;
elseif (strcmp(type_plot,'v'))
text_display = 'V-disp: ';
units = data_dic.dispinfo.units;
elseif (strcmp(type_plot,'exx'))
text_display = 'Exx-strain: ';
units = '';
elseif (strcmp(type_plot,'exy'))
text_display = 'Exy-strain: ';
units = '';
elseif (strcmp(type_plot,'eyy'))
text_display = 'Eyy-strain: ';
units = '';
end
% Display text
set(text_info,'String',{['x-pos: ' num2str(pos_mouse_axes(1))],['y-pos: ' num2str(pos_mouse_axes(3))],[text_display num2str(plot_data(pos_mouse_axes(3),pos_mouse_axes(1))) ' ' units]}, ...
'Position',[pos_mouse_axes(1) pos_mouse_axes(3) 2],'HorizontalAlignment','left','VerticalAlignment','top');
% If zoom and pan arent being used, then use a cross for the
% cursor
if (strcmp(get(handle_zoom,'Enable'),'off') && strcmp(get(handle_pan,'Enable'),'off'))
set(handles_gui.figure,'Pointer','cross');
end
% Check if text overlaps colorbar or bottom of the axes; if so,
% flip it so the text shows properly
% Set all coordinates to pixels
set(text_info,'units','pixels');
set(handle_colorbar,'units','pixels');
set(handles_gui.group_formataxes,'units','pixels');
set(handles_gui.figure,'units','pixels');
% Get positions
pos_text = get(text_info,'extent');
pos_colorbar = get(handle_colorbar,'Position');
pos_group = get(handles_gui.group_formataxes,'position');
pos_cursor = get(handles_gui.figure,'CurrentPoint');
if (pos_cursor(1)+pos_text(3) > pos_group(1)+pos_colorbar(1) && pos_text(2) < 0)
set(text_info,'HorizontalAlignment','right','VerticalAlignment','bottom');
elseif (pos_cursor(1)+pos_text(3) > pos_group(1)+pos_colorbar(1))
set(text_info,'HorizontalAlignment','right');
elseif (pos_text(2) < 0) % Hangs below bottom
set(text_info,'VerticalAlignment','bottom');
end
% Convert back to original coordinates
set(text_info,'units','data');
set(handle_colorbar,'units','normalized');
set(handles_gui.group_formataxes,'units','characters');
set(handles_gui.figure,'units','characters');
else
% Clear text and set cursor back to arrow if zoom and pan
% aren't enabled
set(text_info,'String','');
if (strcmp(get(handle_zoom,'Enable'),'off') && strcmp(get(handle_pan,'Enable'),'off'))
set(handles_gui.figure,'Pointer','arrow');
end
end
else
% Clear text since cursor is not on top of axes
set(text_info,'String','');
set(handles_gui.figure,'Pointer','arrow');
end
end
function [data] = get_data(type_plot_sub,lore,num_cur)
% This function returns displacement/strain data in vector from the data_dic structure
if (strcmp(lore,'lagrangian'))
rorc = 'ref';
else
rorc = 'cur';
end
if (strcmp(type_plot_sub,'u'))
% U:
data = data_dic.displacements(num_cur+1).(['plot_u_' rorc '_formatted'])(data_dic.displacements(num_cur+1).(['roi_' rorc '_formatted']).mask);
elseif (strcmp(type_plot_sub,'v'))
% V:
data = data_dic.displacements(num_cur+1).(['plot_v_' rorc '_formatted'])(data_dic.displacements(num_cur+1).(['roi_' rorc '_formatted']).mask);
elseif (strcmp(type_plot_sub,'exx'))
% Exx:
data = data_dic.strains(num_cur+1).(['plot_exx_' rorc '_formatted'])(data_dic.strains(num_cur+1).(['roi_' rorc '_formatted']).mask);
elseif (strcmp(type_plot_sub,'exy'))
% Exy:
data = data_dic.strains(num_cur+1).(['plot_exy_' rorc '_formatted'])(data_dic.strains(num_cur+1).(['roi_' rorc '_formatted']).mask);
elseif (strcmp(type_plot_sub,'eyy'))
% Eyy:
data = data_dic.strains(num_cur+1).(['plot_eyy_' rorc '_formatted'])(data_dic.strains(num_cur+1).(['roi_' rorc '_formatted']).mask);
end
end
function [plot_data] = get_dataplot(type_plot_sub,lore,num_cur)
% This function returns plot_data from the data_dic structure
if (strcmp(lore,'lagrangian'))
rorc = 'ref';
else
rorc = 'cur';
end
if (strcmp(type_plot_sub,'u'))
% U:
plot_data = data_dic.displacements(num_cur+1).(['plot_u_' rorc '_formatted']);
elseif (strcmp(type_plot_sub,'v'))
% V:
plot_data = data_dic.displacements(num_cur+1).(['plot_v_' rorc '_formatted']);
elseif (strcmp(type_plot_sub,'exx'))
% Exx:
plot_data = data_dic.strains(num_cur+1).(['plot_exx_' rorc '_formatted']);
elseif (strcmp(type_plot_sub,'exy'))
% Exy:
plot_data = data_dic.strains(num_cur+1).(['plot_exy_' rorc '_formatted']);
elseif (strcmp(type_plot_sub,'eyy'))
% Eyy:
plot_data = data_dic.strains(num_cur+1).(['plot_eyy_' rorc '_formatted']);
end
end
function [roi_data] = get_roi(type_plot_sub,lore,num_cur)
% This function returns the ROI from the data_dic structure
if (strcmp(lore,'lagrangian'))
rorc = 'ref';
else
rorc = 'cur';
end
if (strcmp(type_plot_sub,'u') || strcmp(type_plot_sub,'v'))
% Displacement
roi_data = data_dic.displacements(num_cur+1).(['roi_' rorc '_formatted']);
else
% Strains
roi_data = data_dic.strains(num_cur+1).(['roi_' rorc '_formatted']);
end
end
function sliderparams = get_sliderparams(data)
% Returns slider params based on data input
param_upperbound = prctile(data,99);
param_median = prctile(data,50);
param_lowerbound = prctile(data,1);
sliderparams = [param_upperbound+(param_upperbound-param_median) ...
param_median ...
param_lowerbound-(param_median-param_lowerbound) ...
max(data) ...
min(data)];
end
function handles_gui_savefig = form_savefig(num_cur,includeinfo,params_init)
% Get data - num_cur is specified
transparency_prelim = getappdata(handles_gui.figure,'transparency_prelim');
contourlines_prelim = getappdata(handles_gui.figure,'contourlines_prelim');
scalebarlength = getappdata(handles_gui.figure,'scalebarlength');
slider_buffer = getappdata(handles_gui.figure,'slider_buffer');
val_checkbox_contour = getappdata(handles_gui.figure,'val_checkbox_contour');
val_checkbox_scalebar = getappdata(handles_gui.figure,'val_checkbox_scalebar');
val_checkbox_axes = getappdata(handles_gui.figure,'val_checkbox_axes');
val_checkbox_minmaxmarkers = getappdata(handles_gui.figure,'val_checkbox_minmaxmarkers');
val_popupmenu = getappdata(handles_gui.figure,'val_popupmenu');
handle_point_max = getappdata(handles_gui.figure,'handle_point_max');
handle_point_min = getappdata(handles_gui.figure,'handle_point_min');
if (val_popupmenu == 1)
img_bg = reference;
else
img_bg = current(num_cur+1);
end
% Form figure
handles_gui_savefig.figure = figure( ...
'Units','pixels', ...
'Name', 'Save Preview', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color','white', ...
'handlevisibility','off', ...
'DockControls','off', ...
'Visible','off', ...
'IntegerHandle','off', ...
'Interruptible','off', ...
'WindowStyle','modal');
% Create axes
handles_gui_savefig.axes_formatplot = axes('Parent',handles_gui_savefig.figure,'Units','pixels');
% If the user wants to include info
if (includeinfo)
% Set Info texts
uicontrol( ...
'Parent', handles_gui_savefig.figure, ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 18.5 100 1.3], ...
'String', ['Type: ' type_plot '-plot'], ...
'HorizontalAlignment', 'left', ...
'BackgroundColor','white', ...
'Interruptible','off');
% Now get info text which is below the plot
handles_infotext = set_infotext(handles_gui_savefig.figure,'white');
fields_infotext = fieldnames(handles_infotext);
for i = 0:length(fields_infotext)-1
handles_gui_savefig.(fields_infotext{i+1}) = handles_infotext.(fields_infotext{i+1});
end
% Set data height
height_data = 255;
else
height_data = 0;
end
% Transfer data, except for some handles, so that update_axes can set
% the plot
setappdata(handles_gui_savefig.figure,'num_cur',num_cur);
setappdata(handles_gui_savefig.figure,'transparency_prelim',transparency_prelim);
setappdata(handles_gui_savefig.figure,'contourlines_prelim',contourlines_prelim);
setappdata(handles_gui_savefig.figure,'scalebarlength',scalebarlength);
setappdata(handles_gui_savefig.figure,'slider_buffer',slider_buffer);
setappdata(handles_gui_savefig.figure,'type_plot',type_plot);
setappdata(handles_gui_savefig.figure,'val_checkbox_contour',val_checkbox_contour);
setappdata(handles_gui_savefig.figure,'val_checkbox_scalebar',val_checkbox_scalebar);
setappdata(handles_gui_savefig.figure,'val_checkbox_axes',val_checkbox_axes);
setappdata(handles_gui_savefig.figure,'val_checkbox_minmaxmarkers',val_checkbox_minmaxmarkers);
setappdata(handles_gui_savefig.figure,'val_popupmenu',val_popupmenu);
setappdata(handles_gui_savefig.figure,'handle_preview',[]);
setappdata(handles_gui_savefig.figure,'handle_scalebar',[]);
setappdata(handles_gui_savefig.figure,'handle_axes',[]);
setappdata(handles_gui_savefig.figure,'handle_point_max',handle_point_max);
setappdata(handles_gui_savefig.figure,'handle_point_min',handle_point_min);
% Additional fields
setappdata(handles_gui_savefig.figure,'includeinfo',includeinfo);
% Set plot
update_axes('save',handles_gui_savefig);
% Set default size
if (isempty(params_init))
width_img = floor(img_bg.width/(data_dic.dispinfo.spacing+1));
height_img = floor(img_bg.height/(data_dic.dispinfo.spacing+1));
else
width_img = params_init(1);
height_img = params_init(2);
end
border = 30;
width_cb = 20;
spacing_save_fig = 100;
spacing_width_img = 4*border+width_cb;
spacing_height_img = 2*border+height_data;
% Set data in savefig - these are parameters which are modified by
% gui_savesize
setappdata(handles_gui_savefig.figure,'height_data',height_data);
setappdata(handles_gui_savefig.figure,'width_img',width_img);
setappdata(handles_gui_savefig.figure,'height_img',height_img);
setappdata(handles_gui_savefig.figure,'border',border);
setappdata(handles_gui_savefig.figure,'width_cb',width_cb);
setappdata(handles_gui_savefig.figure,'spacing_save_fig',spacing_save_fig);
setappdata(handles_gui_savefig.figure,'spacing_width_img',spacing_width_img);
setappdata(handles_gui_savefig.figure,'spacing_height_img',spacing_height_img);
% Update savefig
update_savefig(handles_gui_savefig);
% Set plot visible
set(handles_gui_savefig.figure,'Visible','on');
end
function handles_gui = init_gui()
handles_gui.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', ncorr_util_figpos(pos_parent,[44.5 150]), ...
'Name', 'Data Plot', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'IntegerHandle','off', ...
'Interruptible','off', ...
'Visible','off', ...
'CloseRequestFcn','');
% Top Menu
handles_gui.topmenu_file = uimenu( ...
'Parent', handles_gui.figure, ...
'Tag', 'topmenu_file', ...
'Label', 'File', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_save = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_save', ...
'Label', 'Save Image', ...
'Checked', 'off', ...
'Interruptible','off');
handles_gui.topmenu_save_withoutinfo = uimenu( ...
'Parent', handles_gui.topmenu_save, ...
'Tag', 'topmenu_save_withoutinfo', ...
'Label', 'Save Image Without Info', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata)callback_topmenu_save(hObject,eventdata,false),handles_gui.figure), ...
'Interruptible','off');
handles_gui.topmenu_save_withinfo = uimenu( ...
'Parent', handles_gui.topmenu_save, ...
'Tag', 'topmenu_save_withinfo', ...
'Label', 'Save Image With Info', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata)callback_topmenu_save(hObject,eventdata,true),handles_gui.figure), ...
'Interruptible','off');
handles_gui.topmenu_savegif = uimenu( ...
'Parent', handles_gui.topmenu_file, ...
'Tag', 'topmenu_savegif', ...
'Label', 'Save GIF', ...
'Checked', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@(hObject,eventdata)callback_topmenu_savegif (hObject,eventdata),handles_gui.figure), ...
'Interruptible','off');
% Panels
handles_gui.group_menu = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_menu', ...
'Units', 'characters', ...
'Position', [2 23.4 35.0 20.6], ...
'Title', 'Local Plot Options', ...
'Interruptible','off');
handles_gui.group_viewoptions = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_viewoptions', ...
'Units', 'characters', ...
'Position', [2 18 35.0 4.8], ...
'Title', 'View Options', ...
'Interruptible','off');
handles_gui.group_scalebar = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_scalebar', ...
'Units', 'characters', ...
'Position', [2 10.8 35.0 6.5], ...
'Title', 'Scalebar Options', ...
'Interruptible','off');
handles_gui.group_axes = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_axes', ...
'Units', 'characters', ...
'Position', [2 5.8 35.0 4.4], ...
'Title', 'Axes Options', ...
'Interruptible','off');
handles_gui.group_zoompan = uibuttongroup( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_zoompan', ...
'Units', 'characters', ...
'Position', [2 0.8 35 4.5], ...
'Title', 'Zoom/Pan', ...
'Interruptible','off');
if (strcmp(type_plot,'u'))
group_title = 'U-displacements';
elseif (strcmp(type_plot,'v'))
group_title = 'V-displacements';
elseif (strcmp(type_plot,'exx'))
group_title = 'Exx-strain';
elseif (strcmp(type_plot,'exy'))
group_title = 'Exy-strain';
elseif (strcmp(type_plot,'eyy'))
group_title = 'Eyy-strain';
end
handles_gui.group_formataxes = uipanel( ...
'Parent', handles_gui.figure, ...
'Tag', 'group_formataxes', ...
'Units', 'characters', ...
'Position', [39.0 0.8 109 43.2], ...
'Title', group_title, ...
'Interruptible','off');
% Axes
handles_gui.axes_formatplot = axes( ...
'Parent', handles_gui.group_formataxes, ...
'Tag', 'axes_formatplot', ...
'Units', 'characters', ...
'Position', [12.4 19.0 86.2 20], ...
'Interruptible','off');
% Drop-down Menu
handles_gui.popupmenu = uicontrol( ...
'Parent', handles_gui.group_viewoptions, ...
'Tag', 'popupmenu', ...
'Style', 'popupmenu', ...
'Units', 'characters', ...
'Position', [2.4 1.4 29.1 1.3], ...
'BackgroundColor', [1 1 1], ...
'String', {'Lagrangian','Eulerian'}, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_popupmenu,handles_gui.figure), ...
'Interruptible','off');
% Static Texts
handles_gui.text_transparency = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'text_transparency', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.5 13.5 16 1.3], ...
'HorizontalAlignment', 'left', ...
'String', 'Transparency:', ...
'Interruptible','off');
handles_gui.text_upperbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'text_upperbound', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.5 9.9 16 1.3], ...
'HorizontalAlignment', 'left', ...
'String', 'Upperbound:', ...
'Interruptible','off');
handles_gui.text_lowerbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'text_lowerbound', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.5 6.6 16 1.3], ...
'HorizontalAlignment', 'left', ...
'String', 'Lowerbound:', ...
'Interruptible','off');
handles_gui.text_scalebarlength = uicontrol( ...
'Parent', handles_gui.group_scalebar, ...
'Tag', 'text_scalebarlength', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.5 1 16 1.3], ...
'HorizontalAlignment', 'left', ...
'String', 'Scale Bar Len:', ...
'Interruptible','off');
% Now get info text which is below the plot
handles_infotext = set_infotext(handles_gui.group_formataxes,'');
fields_infotext = fieldnames(handles_infotext);
for i = 0:length(fields_infotext)-1
handles_gui.(fields_infotext{i+1}) = handles_infotext.(fields_infotext{i+1});
end
% Sliders
handles_gui.slider_transparency = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'slider_transparency', ...
'Style', 'slider', ...
'Units', 'characters', ...
'Position', [2.5 12.0 28.9 1.3], ...
'BackgroundColor', [0.9 0.9 0.9], ...
'String', 'Slider', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_slider_transparency,handles_gui.figure), ...
'Interruptible','off');
handles_gui.slider_upperbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'slider_upperbound', ...
'Style', 'slider', ...
'Units', 'characters', ...
'Position', [2.5 8.5 28.9 1.3], ...
'BackgroundColor', [0.9 0.9 0.9], ...
'String', 'Slider', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_slider_upperbound,handles_gui.figure), ...
'Interruptible','off');
handles_gui.slider_lowerbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'slider_lowerbound', ...
'Style', 'slider', ...
'Units', 'characters', ...
'Position', [2.5 5.0 28.9 1.3], ...
'BackgroundColor', [0.9 0.9 0.9], ...
'String', 'Slider', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_slider_lowerbound,handles_gui.figure), ...
'Interruptible','off');
% Check Box
handles_gui.checkbox_contour = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'checkbox_contour', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [2.5 17.3 17 1.3], ...
'String', 'Contour Plot: ', ...
'Value', 0, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_contour,handles_gui.figure), ...
'Interruptible','off');
handles_gui.checkbox_minmaxmarkers = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'checkbox_minmaxmarkers', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [2.5 15.5 29.7 1.3], ...
'String', 'Max/min markers', ...
'Value', 0, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_minmaxmarkers,handles_gui.figure), ...
'Interruptible','off');
handles_gui.checkbox_scalebar = uicontrol( ...
'Parent', handles_gui.group_scalebar, ...
'Tag', 'checkbox_scalebar', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [2.5 3 17 1.3], ...
'String', 'Scalebar ', ...
'Value', 1, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_scalebar,handles_gui.figure), ...
'Interruptible','off');
handles_gui.checkbox_axes = uicontrol( ...
'Parent', handles_gui.group_axes, ...
'Tag', 'checkbox_axes', ...
'Style', 'checkbox', ...
'Units', 'characters', ...
'Position', [2.5 1.0 17 1.3], ...
'String', 'Axes ', ...
'Value', 1, ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_checkbox_axes,handles_gui.figure), ...
'Interruptible','off');
% Edit
handles_gui.edit_transparency = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'edit_transparency', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 13.6 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_transparency,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_upperbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'edit_upperbound', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 10.1 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_upperbound,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_lowerbound = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'edit_lowerbound', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 6.6 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_lowerbound,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_contour = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'edit_contour', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 17.3 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Enable', 'off', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_contour,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_scalebarlength = uicontrol( ...
'Parent', handles_gui.group_scalebar, ...
'Tag', 'edit_scalebarlength', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [20.2 1.1 11.1 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_scalebarlength,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_imgnum = uicontrol( ...
'Parent', handles_gui.group_formataxes, ...
'Tag', 'edit_imgnum', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [91 1.1 7 1.6], ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_imgnum,handles_gui.figure), ...
'Enable', 'off', ...
'Interruptible','off');
% Pushbuttons
handles_gui.button_applytoall = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'button_applytoall', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.5 2.8 28.9 1.5], ...
'String', 'Apply to All', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_applytoall,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_resetdefaults = uicontrol( ...
'Parent', handles_gui.group_menu, ...
'Tag', 'button_resetdefaults', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.5 1 28.9 1.5], ...
'String', 'Reset Defaults', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_resetdefaults,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_zoom = uicontrol( ...
'Parent', handles_gui.group_zoompan, ...
'Tag', 'button_zoom', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.1 1 14.4 1.7], ...
'String', 'Zoom', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_zoom,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_pan = uicontrol( ...
'Parent', handles_gui.group_zoompan, ...
'Tag', 'button_pan', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [17.4 1 14.4 1.7], ...
'String', 'Pan', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_pan,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_left = uicontrol( ...
'Parent', handles_gui.group_formataxes, ...
'Tag', 'button_left', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [84 1.0 6 1.8], ...
'String', '<', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_left,handles_gui.figure), ...
'Interruptible','off', ...
'Enable', 'off');
handles_gui.button_right = uicontrol( ...
'Parent', handles_gui.group_formataxes, ...
'Tag', 'button_right', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [99 1.0 6 1.8], ...
'String', '>', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_right,handles_gui.figure), ...
'Interruptible','off', ...
'Enable', 'off');
end
end
%---------------------------------------------------------------------%
% SAVE GUI -----------------------------------------------------------%
%---------------------------------------------------------------------%
function [size_savefig,timedelay,outstate] = gui_savesize(handles_gui_savefig,isgif,pos_parent)
% This is a GUI for inputting the height and width for the saved figure.
% This gui will update the figure in handles_gui_savefig.
%
% Inputs -----------------------------------------------------------------%
% handles_gui_savefig - handle; handle of the save figure. The position
% of this figure is controlled by this GUI
% isgif - logical; this tells whether or not an animated gif is being
% saved. If a gif is being saved then the time delay can be adjusted
% pos_parent - integer array; this is the position of the parent figure
% which determines where to position this figure
%
% Outputs ----------------------------------------------------------------%
% size_savefig - integer array; contains the size of the save fig
% timedelay - double; this is the time delay between frames
% outstate - integer; returns either out.cancelled, out.failed, or
% out.success.
% Data ---------------------------------------------------------------%
% Initialize outputs
outstate = out.cancelled;
size_savefig = [];
timedelay = [];
% Get GUI handles - Part of output
handles_gui = init_gui();
% Run c-tor
feval(ncorr_util_wrapcallbacktrycatch(@constructor,handles_gui.figure));
% Callbacks and functions --------------------------------------------%
function constructor()
% Get save size parameters; the screen size is needed to
% prevent the user from resizing outside the screen, which will
% result in cropping when using getframe()
% Get data
width_img = getappdata(handles_gui_savefig.figure,'width_img');
height_img = getappdata(handles_gui_savefig.figure,'height_img');
spacing_save_fig = getappdata(handles_gui_savefig.figure,'spacing_save_fig');
spacing_width_img = getappdata(handles_gui_savefig.figure,'spacing_width_img');
spacing_height_img = getappdata(handles_gui_savefig.figure,'spacing_height_img');
set(0,'units','pixels'); % Set to pixels first
size_screen = get(0,'Screensize'); % width = size_screen(3); height = size_screen(4)
max_width_img = size_screen(3)-spacing_save_fig-spacing_width_img;
max_height_img = size_screen(4)-spacing_save_fig-spacing_height_img;
if (max_width_img/max_height_img > width_img/height_img)
max_width_img = round(max_height_img*(width_img/height_img));
else
max_height_img = round(max_width_img/(width_img/height_img));
end
if (width_img > max_width_img || height_img > max_height_img)
% Image is too large, resize it to fit within screen
img_reduction = min(max_width_img/width_img,max_height_img/height_img);
width_img = round(width_img*img_reduction);
height_img = round(height_img*img_reduction);
end
timedelay_prelim = 0.04;
% Set data
setappdata(handles_gui.figure,'width_img',width_img);
setappdata(handles_gui.figure,'height_img',height_img);
setappdata(handles_gui.figure,'ratio_img',width_img/height_img);
setappdata(handles_gui.figure,'max_width_img',max_width_img);
setappdata(handles_gui.figure,'max_height_img',max_height_img);
setappdata(handles_gui.figure,'timedelay_prelim',timedelay_prelim);
% Update
update_axes('set');
update_sidemenu();
% Set visible
set(handles_gui.figure,'Visible','on');
end
function callback_edit_timedelay(hObject,eventdata) %#ok<INUSD>
% Get data
timedelay_prelim = getappdata(handles_gui.figure,'timedelay_prelim');
% Max and min values
max_timedelay = 1;
min_timedelay = 1e-5;
% Get width
timedelay_buffer = str2double(get(handles_gui.edit_timedelay,'string'));
if (ncorr_util_isrealbb(timedelay_buffer,min_timedelay,max_timedelay,'Time delay') == out.success)
timedelay_prelim = timedelay_buffer;
end
% Set data
setappdata(handles_gui.figure,'timedelay_prelim',timedelay_prelim);
% Update preview image
update_axes('update');
update_sidemenu();
end
function callback_edit_width(hObject,eventdata) %#ok<INUSD>
% Get data
ratio_img = getappdata(handles_gui.figure,'ratio_img');
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
max_width_img = getappdata(handles_gui.figure,'max_width_img');
max_height_img = getappdata(handles_gui.figure,'max_height_img');
% Get width
width_img_buffer = str2double(get(handles_gui.edit_width,'string'));
if (ncorr_util_isintbb(width_img_buffer,1,max_width_img,'Width') == out.success)
% Calculate new width and height - make sure they do
% not go outside screen size
height_img_buffer = round(width_img_buffer/ratio_img);
if (ncorr_util_isintbb(height_img_buffer,1,max_height_img,'Height') == out.success)
width_img = width_img_buffer;
height_img = height_img_buffer;
end
end
% Set data
setappdata(handles_gui.figure,'width_img',width_img);
setappdata(handles_gui.figure,'height_img',height_img);
% Update preview image
update_axes('update');
update_sidemenu();
end
function callback_edit_height(hObject,eventdata) %#ok<INUSD>
% Get data
ratio_img = getappdata(handles_gui.figure,'ratio_img');
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
max_width_img = getappdata(handles_gui.figure,'max_width_img');
max_height_img = getappdata(handles_gui.figure,'max_height_img');
% Get height
height_img_buffer = str2double(get(handles_gui.edit_height,'string'));
if (ncorr_util_isintbb(height_img_buffer,1,max_height_img,'Height') == out.success)
% Calculate new width and height - make sure they do
% not go outside screen size
width_img_buffer = round(height_img_buffer*ratio_img);
if (ncorr_util_isintbb(width_img_buffer,1,max_width_img,'Width') == out.success)
width_img = width_img_buffer;
height_img = height_img_buffer;
end
end
% Set data
setappdata(handles_gui.figure,'width_img',width_img);
setappdata(handles_gui.figure,'height_img',height_img);
% Update
update_axes('update');
update_sidemenu();
end
function callback_button_finish(hObject,eventdata) %#ok<INUSD>
% Get data
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
timedelay_prelim = getappdata(handles_gui.figure,'timedelay_prelim');
% Set output
size_savefig = [width_img height_img];
timedelay = timedelay_prelim;
outstate = out.success;
% Exit
close(handles_gui.figure);
end
function callback_button_cancel(hObject,eventdata) %#ok<INUSD>
% Close
close(handles_gui.figure);
end
function update_sidemenu()
% Get data
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
timedelay_prelim = getappdata(handles_gui.figure,'timedelay_prelim');
set(handles_gui.edit_width,'String',num2str(width_img));
set(handles_gui.edit_height,'String',num2str(height_img));
if (isgif)
set(handles_gui.edit_timedelay,'String',num2str(timedelay_prelim));
else
set(handles_gui.edit_timedelay,'enable','off');
end
end
function update_axes(action)
% Get data - savefig handles:
width_img = getappdata(handles_gui.figure,'width_img');
height_img = getappdata(handles_gui.figure,'height_img');
if (strcmp(action,'set') || strcmp(action,'update'))
% Transfer data then update
setappdata(handles_gui_savefig.figure,'width_img',width_img);
setappdata(handles_gui_savefig.figure,'height_img',height_img);
% Update
update_savefig(handles_gui_savefig);
end
end
function handles_gui = init_gui()
% Form UIs
handles_gui.figure = figure( ...
'Tag', 'figure', ...
'Units', 'characters', ...
'Position', ncorr_util_figpos(pos_parent,[10 30.5]), ...
'Name', 'Set Image Size', ...
'MenuBar', 'none', ...
'NumberTitle', 'off', ...
'Color', get(0,'DefaultUicontrolBackgroundColor'), ...
'handlevisibility','off', ...
'DockControls','off', ...
'Resize','off', ...
'WindowStyle','modal', ...
'IntegerHandle','off', ...
'Interruptible','off');
% Adjust position
% Set this UI next to the save fig
pos_savefig_pixels = get(handles_gui_savefig.figure,'OuterPosition');
% Get size of figure in pixels
set(handles_gui.figure,'Units','pixels');
pos_fig_pixels = get(handles_gui.figure,'Position');
pos_fig_pixels(1) = pos_savefig_pixels(3)+1.5*pos_savefig_pixels(1);
pos_fig_pixels(2) = pos_savefig_pixels(2)+pos_savefig_pixels(4)/2-pos_fig_pixels(4)/2;
% Check to make sure position is not out of screen
set(0,'units','pixels');
pos_screen_pixels = get(0,'ScreenSize');
% Check right - no need to check bottom
screen_right = 20; % Use this as padding
if (pos_fig_pixels(1)+pos_fig_pixels(3) > pos_screen_pixels(3)-screen_right)
pos_fig_pixels(1) = pos_screen_pixels(3)-pos_fig_pixels(3)-screen_right;
end
% Set position
set(handles_gui.figure,'Position',pos_fig_pixels);
% Convert back to characters
set(handles_gui.figure,'Units','characters');
% Text
handles_gui.text_timedelay = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_timedelay', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 7.5 15 1.3], ...
'String', 'Time Delay:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_width = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_width', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 5.5 15 1.3], ...
'String', 'Width:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_gui.text_height = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'text_height', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 3.5 15 1.3], ...
'String', 'Height:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% Edit box
handles_gui.edit_timedelay = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'edit_timedelay', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [18.2 7.5 9.6 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_timedelay,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_width = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'edit_width', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [18.2 5.5 9.6 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_width,handles_gui.figure), ...
'Interruptible','off');
handles_gui.edit_height = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'edit_height', ...
'Style', 'edit', ...
'Units', 'characters', ...
'Position', [18.2 3.5 9.6 1.3], ...
'HorizontalAlignment', 'left', ...
'String', '', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_edit_height,handles_gui.figure), ...
'Interruptible','off');
% Buttons
handles_gui.button_finish = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'button_finish', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [2.1 1 12 1.7], ...
'String', 'Finish', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_finish,handles_gui.figure), ...
'Interruptible','off');
handles_gui.button_cancel = uicontrol( ...
'Parent', handles_gui.figure, ...
'Tag', 'button_cancel', ...
'Style', 'pushbutton', ...
'Units', 'characters', ...
'Position', [16 1 12 1.7], ...
'String', 'Cancel', ...
'Callback', ncorr_util_wrapcallbacktrycatch(@callback_button_cancel,handles_gui.figure), ...
'Interruptible','off');
end
% Pause until figure is closed -----------------------------------%
waitfor(handles_gui.figure);
end
function update_savefig(handles_gui_savefig)
% This function is called whenever the savefig needs to be updated. It
% will resize the window and reposition the axes/colorbar.
% Get data
height_data = getappdata(handles_gui_savefig.figure,'height_data');
width_img = getappdata(handles_gui_savefig.figure,'width_img');
height_img = getappdata(handles_gui_savefig.figure,'height_img');
border = getappdata(handles_gui_savefig.figure,'border');
width_cb = getappdata(handles_gui_savefig.figure,'width_cb');
spacing_save_fig = getappdata(handles_gui_savefig.figure,'spacing_save_fig');
spacing_width_img = getappdata(handles_gui_savefig.figure,'spacing_width_img');
spacing_height_img = getappdata(handles_gui_savefig.figure,'spacing_height_img');
handle_colorbar = getappdata(handles_gui_savefig.figure,'handle_colorbar');
handle_scalebar = getappdata(handles_gui_savefig.figure,'handle_scalebar');
handle_axes = getappdata(handles_gui_savefig.figure,'handle_axes');
% Set image
pos_savefig(1) = spacing_save_fig;
pos_savefig(2) = spacing_save_fig;
pos_savefig(3) = spacing_width_img+width_img; % Width
pos_savefig(4) = spacing_height_img+height_img; % Height
set(handles_gui_savefig.figure,'Position',pos_savefig);
% Colorbar:
set(handle_colorbar,'Position',[2*border+width_img border+height_data width_cb height_img]);
% Plot:
set(handles_gui_savefig.axes_formatplot,'Position',[border border+height_data width_img height_img]);
% Update handle_scalebar text if it it's toggled
% Only text is updated because the size is constant during resize;
% patches will resize with handle_axes. Do not need to check with
% 'ishandle' because the scalebar is either set once or not at all.
if (~isempty(handle_scalebar))
set(handles_gui_savefig.axes_formatplot,'units','characters');
text_scalebar = findobj(handles_gui_savefig.axes_formatplot,'tag','text_scalebar');
pos_img = get(handles_gui_savefig.axes_formatplot,'Position');
size_text = max(0.5*max(0.5*pos_img(4),0.14*pos_img(3)),8);
set(text_scalebar,'FontSize',size_text);
set(handles_gui_savefig.axes_formatplot,'units','pixels');
end
% Update handle_axes text if it it's toggled
% Only text is updated because the size is constant during resize;
% patches will resize with handle_axes. Do not need to check with
% 'ishandle' because the axes is either set once or not at all.
if (~isempty(handle_axes))
set(handles_gui_savefig.axes_formatplot,'units','characters');
text_x = findobj(handles_gui_savefig.axes_formatplot,'tag','text_x');
text_y = findobj(handles_gui_savefig.axes_formatplot,'tag','text_y');
pos_img = get(handles_gui_savefig.axes_formatplot,'Position');
size_text = max(0.5*max(0.5*pos_img(4),0.14*pos_img(3)),8);
set(text_x,'FontSize',size_text);
set(text_y,'FontSize',size_text);
set(handles_gui_savefig.axes_formatplot,'units','pixels');
end
% Make sure figure is drawn to ensure getframe works properly.
drawnow;
end
function handles_infotext = set_infotext(parent,bgcolor)
% This function sets information text
handles_infotext.text_ref_name = uicontrol( ...
'Parent', parent, ...
'Tag', 'ref_name', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 17.0 100 1.3], ...
'String', 'Reference Name: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_cur_name = uicontrol( ...
'Parent', parent, ...
'Tag', 'cur_name', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 15.5 100 1.3], ...
'String', 'Current Name: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_type = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_type', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 14.0 100 1.3], ...
'String', 'Analysis Type: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_dicparams = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_dicparams', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 12.5 100 1.3], ...
'String', 'RG-DIC Radius: | Subset Spacing:', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_itparams = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_itparams', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 11.0 100 1.3], ...
'String', 'Diffnorm Cutoff: | Iteration Cutoff: | Total Threads: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_stepanalysis = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_stepanalysis', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 9.5 100 1.3], ...
'String', 'Step Analysis: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_subsettrunc = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_subsettrunc', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 8.0 100 1.3], ...
'String', 'Disp Subset Truncation: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_imgcorr = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_imgcorr', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 6.5 100 1.3], ...
'String', 'Image Correspondences: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_pixtounits = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_pixtounits', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 5.0 100 1.3], ...
'String', 'Reference Image FOV width: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_cutoff_corrcoef = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_cutoff_corrcoef', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 3.5 100 1.3], ...
'String', 'Correlation Coefficient Cutoff: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_lenscoef = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_lenscoef', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 2.0 100 1.3], ...
'String', 'Radial Lens Distortion Coefficient: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
handles_infotext.text_minmedianmax = uicontrol( ...
'Parent', parent, ...
'Tag', 'text_max', ...
'Style', 'text', ...
'Units', 'characters', ...
'Position', [2.1 0.5 100 1.3], ...
'String', 'Min: | Median: | Max: ', ...
'HorizontalAlignment', 'left', ...
'Interruptible','off');
% Check if bgcolor was provided
if (~isempty(bgcolor))
fields_infotext = fieldnames(handles_infotext);
for i = 0:length(fields_infotext)-1
set(handles_infotext.(fields_infotext{i+1}),'BackgroundColor',bgcolor);
end
end
end
|
github
|
CU-CommunityApps/choco-packages-master
|
ncorr_util_formregionconstraint.m
|
.m
|
choco-packages-master/packages/matlab-ciser/tools/ncorr/ncorr_util_formregionconstraint.m
| 6,122 |
utf_8
|
458de04923bdcb004e97d0415e37da7e
|
function handle_constraintfcn = ncorr_util_formregionconstraint(region)
% This function returns handle_constraintfcn which, given a point, will
% return the closest point inside the region. This is mainly used for the
% constrainfcn for impoints which are restricted to be inside a region.
%
% Inputs -----------------------------------------------------------------%
% region - struct; region info used to determine the position of returned
% point
%
% Outputs ----------------------------------------------------------------%
% handle_constraintfcn - function handle;
%
% Returns error if region is empty.
if (region.totalpoints == 0)
error('Region cannot be empty when forming constraint function.');
end
handle_constraintfcn = @constraintfcn;
function pos_nearest = constraintfcn(pos)
% This function will generally be called within a callback
% automatically which will use 1 based indexing, so pos_nearest is
% returned using 1 based indexing. However, for processing, 0 based
% indexing is used, so convert back and forth as necessary.
% Convert pos to 0 based indexing and round it:
pos = round(pos)-1;
% Find bounding box - must find this since left and right bounds
% are based on the length of the noderange/nodelist which may not
% necessarily be the bounding box.
left = region.rightbound;
right = 0;
firstpoint = false;
for i = 0:size(region.noderange,1)-1
if (region.noderange(i+1) > 0 && ~firstpoint)
firstpoint = true;
left = i + region.leftbound;
end
if (region.noderange(i+1) > 0 && i+region.leftbound > right)
right = i + region.leftbound;
end
end
% Check if above, between, or beneath bounds
if (pos(1) < left)
% Left of bounds - set x to left and then find the nearest node
% for y
pos_nearest(1) = left+1;
pos_nearest(2) = nearestnode(region.nodelist(left-region.leftbound+1,:),region.noderange(left-region.leftbound+1),pos(2))+1;
elseif (pos(1) >= left && pos(1) <= right)
% Between bounds - must check if nodes exist at this x position
if (region.noderange(pos(1)-region.leftbound+1) > 0)
pos_nearest(1) = pos(1)+1;
else
% Initialize
leftfound = false;
leftdist = 0;
rightfound = false;
rightdist = 0;
% Cycle left until finding a positive noderange
for i = pos(1)-1:-1:left
if (region.noderange(i-region.leftbound+1) > 0)
leftdist = pos(1)-i;
leftfound = true;
break;
end
end
% Cycle right until finding a positive noderange
for i = pos(1)+1:right
if (region.noderange(i-region.leftbound+1) > 0)
rightdist = i-pos(1);
rightfound = true;
break;
end
end
% Now set x position
if (leftfound && rightfound)
if (leftdist < rightdist)
pos_nearest(1) = pos(1)-leftdist+1;
else
pos_nearest(1) = pos(1)+rightdist+1;
end
elseif (leftfound)
pos_nearest(1) = pos(1)-leftdist+1;
else
pos_nearest(1) = pos(1)+rightdist+1;
end
end
pos_nearest(2) = nearestnode(region.nodelist((pos_nearest(1)-1)-region.leftbound+1,:),region.noderange((pos_nearest(1)-1)-region.leftbound+1),pos(2))+1;
else
% Right of bounds - set x to left and then find the nearest node
% for y
pos_nearest(1) = right+1;
pos_nearest(2) = nearestnode(region.nodelist(right-region.leftbound+1,:),region.noderange(right-region.leftbound+1),pos(2))+1;
end
end
end
function y_nearest = nearestnode(nodelist,noderange,y_coord)
% Finds the nearest y value given the nodelist, noderange and y_coord. Note
% that nodelist and noderange are a single column for a specific x position.
% Uses zero based indexing.
% Initialize
y_nearest = -1;
for i = 0:2:noderange-1
% Test if node is before, within, or after a node pair
if (y_coord < nodelist(i+1))
if (i == 0)
% Above first node
y_nearest = nodelist(i+1);
break;
else
% Above inner node pair
% Find out if y_coord is closer to bottom node of previous
% pair or top node of current pair
if ((y_coord-nodelist(i)) < (nodelist(i+1)-y_coord))
% y_coord is closer to bottom node of previous pair
y_nearest = nodelist(i);
break;
else
% y_coord is closer to top node of current pair
y_nearest = nodelist(i+1);
break;
end
end
elseif (y_coord >= nodelist(i+1) && y_coord <= nodelist(i+2))
% y_coord is between node pairs, so just return it
y_nearest = y_coord;
break;
else
% y_coord is after noderange - test to see if this is the last
% node pair.
if (i == noderange-2)
% This is last node pair, so y_coord is the below node of
% last node pair
y_nearest = nodelist(i+2);
break;
else
% Skip to next node pair
continue;
end
end
end
end
|
github
|
ganlubbq/StatisticalSignalProcessing-master
|
spet_plo.m
|
.m
|
StatisticalSignalProcessing-master/spet_plo.m
| 787 |
utf_8
|
2c37b27f7a781ce1fa1f6c056b7a1520
|
% funzione che plotta lo spettro in modulo e fase rappresentato dai valori
% della trasformata Z di un filtro con zeri e poli rappresentati dai
% polinomi da passare in ingresso Az(zeri) Bp(poli), calcolata sul cerchio
% unitario
function [Spettro,f]=spet_plo(Az,Bp,fc)
%Potrei a questo punto valutare la fdt per frequenze continue, z=exp(j*2*pi*(f/fc))
%Traccio la funzione di trasferimento corrispondente ad un filtro con
%trasformata Z che ha questi zeri
M=2^11; %numero di pulsazioni normalizzate nelle quali valuto la FDT
f=-fc/2+fc/M:fc/M:fc/2;
for k=1:length(f)
A=1;
for i=1:length(Az)
A=A*(1-Az(i)*exp(-1i*2*pi*(f(k)./fc)));
end
Num(k)=A;
B=1;
for i=1:length(Bp)
B=B*(1-Bp(i)*exp(-1i*2*pi*(f(k)./fc)));
end
Den(k)=B;
clear A;
clear B;
end
Spettro=Num./Den;
|
github
|
ganlubbq/StatisticalSignalProcessing-master
|
zero.m
|
.m
|
StatisticalSignalProcessing-master/zero.m
| 186 |
utf_8
|
37d559f73a9a57ddf53cf7db273976ae
|
%funzione che genera la sequenza complessa pertinente ad una certa
%trasformata Z contenente solo zeri
function [A]=zero(z)
A=[1 -z(1)];
for i=2:length(z)
A=conv(A,[1 -z(i)]);
end
|
github
|
ganlubbq/StatisticalSignalProcessing-master
|
dft.m
|
.m
|
StatisticalSignalProcessing-master/dft.m
| 515 |
utf_8
|
0ab8bf1fed495d9258e3dbb5ac8e4cd9
|
%funzione che calcola la DFT in forma matriciale
% x= sequenza in ingresso
% m= numero di campioni dft da calcolare
function [X,fk]=dft(x,m,fc)
n=length(x);
%zero padding
if(n<m)
x=[x zeros(1,m-n)];
end
W=zeros(m); %matrice DFT
for k=1:m
for i=1:m
W(k,i)=exp(-j*((2*pi)/m)*k*i);
end
end
X=x*W.';
if(mod(m,2)==0)
fk=-(m/2-1)*fc/m:fc/m:(m/2)*fc/m;
X=[X(m/2+2:m) X(1:m/2+1)];
else
fk=-((m-1)/2)*fc/m:fc/m:((m-1)/2)*fc/m;
X=[X(((m-1)/2)+2:m) X(1:((m-1)/2)+1)];
end
|
github
|
ganlubbq/StatisticalSignalProcessing-master
|
LMS.m
|
.m
|
StatisticalSignalProcessing-master/LMS.m
| 1,262 |
utf_8
|
26a64a5e3f9a20c4fb081974a0b4594a
|
%INPUT
%
%
% U= matrice di convoluzione per identificazione
% h_sti= stima iniziale del filtro
% y= osservazioni con rumore
% mu= passo di aggiornamento
% h=filtro vero
%
%
%OUTPUT:
%
%
% fstim=filtro stimato
% MSE=errore quadratico medio della stima ad ogni iterazione
function [fstim,MSE]=LMS(U,h_sti,y,mu,h)
P=length(h_sti);
i=1;
while(i==1 || i==2 || J(i-1)<J(i-2) || (abs(J(i-1)/J(i-2))>(1-1e-2) && abs(J(i-1)-J(i-2))>1e-3))
%stima dell'out
the(i)=U(i,:)*h_sti(:,i); %scalare, stima dell'OUT al passo i
%calcolo del funzionale di costo
%stima campionaria della crosscorrelaz istantanea
p=(y(i)'*U(i,:)); %riga
%stima campionaria della matrice di covarianza istantanea
R=zeros(P);
R=(U(i,:)'*U(i,:));
J(i)=(y(i)'*y(i))-2*p*h_sti(:,i)+h_sti(:,i)'*R*h_sti(:,i);
%aggiornamento filtro
err(i)=y(i)-U(i,:)*h_sti(:,i); %errore istantaneo di stima
h_sti(:,i+1)=h_sti(:,i)+mu*(err(i)*U(i,:)');
i=i+1;
end
fstim=h_sti(:,end); %stima del filtro a convergenza
%errore quadratico medio di stima ad ogni iterazione
err=h_sti-repmat(h',1,size(h_sti,2));
for i=1:size(err,2)
MSE(i)=err(:,i)'*err(:,i); %calcolo MSE tra filtro vero e filtro stimato alle varie iterazioni
end
|
github
|
ganlubbq/StatisticalSignalProcessing-master
|
trigiv.m
|
.m
|
StatisticalSignalProcessing-master/trigiv.m
| 574 |
utf_8
|
3cb4deef9841237812f4f32fd682b430
|
%% Triangolarizzazione di una matrice via rotazioni di Givens
function [A_tri,Qtot1]=trigiv(A)
N=size(A,1);
M=size(A,2);
A_tri=A;
%rango (a meno di colonne o righe linearmente dipendenti)
rang=min(N,M);
k=1;
for j=1:1:(rang-1)
for i=rang:-1:(j+1)
Q=eye(rang);
the=atan(A_tri(i,j)/A_tri(j,j));
c=cos(the);
s=sin(the);
Q(j,j)=c;
Q(i,j)=-s;
Q(j,i)=s;
Q(i,i)=c;
Qt(:,:,k)=Q;
A_tri=Q*A_tri;
k=k+1;
end
end
Qtot1=eye(rang);
for k=size(Qt,3):-1:1
Qtot1=Qtot1*Qt(:,:,k);
end
|
github
|
ganlubbq/StatisticalSignalProcessing-master
|
fermat.m
|
.m
|
StatisticalSignalProcessing-master/fermat.m
| 523 |
utf_8
|
e5ac674353476e8e222b16a22e73cca5
|
%Funzione che calcola i percorsi intermedi BS-superficie e superficie-MS
%con raggio di Fermat --> l1 ed l2 rispettivamente
% d = distanza in piano BS-MS
% hBS =altezza BS in metri
% hMS = altezza MS in metri
function [l1,l2]=fermat(hBS,hMS,d)
df1=((-d*(hBS^2))+(hMS*hBS*d))/(hMS^2-hBS^2);
df2=((-d*(hBS^2))-(hMS*hBS*d))/(hMS^2-hBS^2);
if (df1>0)
df=df1;
elseif (df2>0)
df=df2;
else
df=min(df1,df2);
end
l1=sqrt(hBS^2 + df^2);
l2=sqrt((d-df)^2 + hMS^2);
|
github
|
ganlubbq/StatisticalSignalProcessing-master
|
RLS.m
|
.m
|
StatisticalSignalProcessing-master/RLS.m
| 735 |
utf_8
|
333b21ebfc99340285205afb22f2cf1f
|
%Algoritmo RLS per la stima dei coefficienti del filtro
function [fil,MSE]=RLS(U,y,h)
P=length(h);
delta=0.3;
R_s= eye(P)*delta; %inizializzazione della matrice di covarianza
f_s=zeros(P,1); %inizializzazione della stima
Ri=(R_s)^-1;
i=1;
while(i<=P+20*P)
Ri=Ri - (Ri*U(i,:)'*U(i,:)*Ri)/(1+ U(i,:)*Ri*U(i,:)'); %aggiornamento dell'inversa
g=Ri*U(i,:)'; %guadagno al passo i
f_s(:,i+1)= f_s(:,i) + g* (y(i)-U(i,:)*f_s(:,i)); %aggiornamento filtro
i=i+1;
end
fil=f_s(:,end);
%errore quadratico medio di stima ad ogni iterazione
err= f_s - repmat(h',1,size(f_s,2));
for i=1:size(err,2)
MSE(i)=err(:,i)'*err(:,i); %calcolo MSE tra filtro vero e filtro stimato alle varie iterazioni
end
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
multi_qrsdetect.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/multi_qrsdetect.m
| 9,442 |
utf_8
|
a96e2aff02717a96d3c94dcf4187a983
|
function [qrs,feats]=multi_qrsdetect(signal,fs,fname)
% This function detects QRS peaks on ECG signals by taking the consensus of multiple algorithms, namely:
% - gqrs (WFDB Toolbox)
% - Pan-Tompkins (FECGSYN)
% - Maxima Search (OSET/FECGSYN)
% - matched filtering
%
% --
% ECG classification from single-lead segments using Deep Convolutional Neural
% Networks and Feature-Based Approaches - December 2017
%
% Released under the GNU General Public License
%
% Copyright (C) 2017 Fernando Andreotti, Oliver Carr
% University of Oxford, Insitute of Biomedical Engineering, CIBIM Lab - Oxford 2017
% [email protected]
%
%
% For more information visit: https://github.com/fernandoandreotti/cinc-challenge2017
%
% Referencing this work
%
% Andreotti, F., Carr, O., Pimentel, M.A.F., Mahdi, A., & De Vos, M. (2017).
% Comparing Feature Based Classifiers and Convolutional Neural Networks to Detect
% Arrhythmia from Short Segments of ECG. In Computing in Cardiology. Rennes (France).
%
% Last updated : December 2017
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
qrs = cell(1,5); % CHANGE ME! Using 6 levels of detection
WIN_ALG = round(0.08*fs); % 100ms allow re-alignment of 80ms for gqrs
REF_WIN = round(0.17*fs); % refractory window PT algorithm, no detection should occur here.
WIN_BLOCK = round(5*fs); % window for PT algorithm
OLAP = round(1*fs);
MIRR = round(2*fs); % length to mirror signal at beginning and end to avoid border effects
LEN = length(signal);
signal = [signal(1:MIRR); signal ; signal(LEN-MIRR+1:LEN)];
LEN = LEN + 2*MIRR;
%% gQRS
try
recordName = ['gd_' fname];
tm = 1/fs:1/fs:LEN/fs;
wrsamp(tm',signal,recordName,fs,1)
disp(['Running gqrs ' fname '...'])
if isunix
system(['gqrs -r ' recordName ' -f 0 -s 0']);
disp(['gqrs ran ' fname '...'])
else
gqrs(recordName)
end
qrs{1} = rdann(recordName,'qrs');
disp(['read gqrs output ' fname '...'])
[~,lag]=arrayfun(@(x) max(abs(signal(x-WIN_ALG:x+WIN_ALG))),qrs{1}(2:end-1));
qrs{1}(2:end-1) = qrs{1}(2:end-1) + lag - WIN_ALG - 1;
delete([recordName '.*'])
catch
warning('gqrs failed.')
delete([recordName '.*'])
qrs{1} = [];
end
clear lag tm recordName
%% P&T algorithm (in windows of 5 seconds - 1 sec overlap)
try
disp(['Running jqrs ' fname '...'])
qrs{2} = jqrs(signal,REF_WIN,[],fs,[],[],0);
catch
warning('Pan Tompkins failed.')
qrs{2} = [];
end
clear qrs_tmp startp endp count
%% MaxSearch (mQRS)
qrsmax=qrs{double(length(qrs{2})>length(qrs{1}))+1}; % selecting as reference detector with most detections
try
disp(['Running maxsearch ' fname '...'])
if length(qrsmax)<5
HR_PARAM = 1.3; % default value
else
HR_PARAM = fs./nanmedian(diff(qrsmax))+0.1; % estimate rate (in Hz) for MaxSearch
end
qrs{3} = OSET_MaxSearch(signal,HR_PARAM/fs)';
catch
warning('MaxSearch failed.')
qrs{3} = [];
end
% Put all detectors on same sign (max or min) - shift by median lag
x = decimate(signal,5); % just to reduce calculus
y = sort(x);
flag = mean(abs(y(round(end-0.05*length(y)):end)))>mean(abs(y(1:round(0.05*length(y)))));
for i = 1:length(qrs)
if flag
[~,lag]=arrayfun(@(x) max(signal(x-WIN_ALG:x+WIN_ALG)),qrs{i}(3:end-2));
else
[~,lag]=arrayfun(@(x) min(signal(x-WIN_ALG:x+WIN_ALG)),qrs{i}(3:end-2));
end
qrs{i}(3:end-2) = qrs{i}(3:end-2) + lag - WIN_ALG - 1;
end
clear HR_PARAM qrsmax
%% Matched filtering QRS detection
try
disp(['Running matchedfilter ' fname '...'])
[btype,templates,tempuncut] = beat_class(signal,qrs{3},round(WIN_ALG));
[qrs{4},ect_qrs]=matchedQRS(signal,templates,qrs{3},btype);
matchedf = 1; % status signal used as feature
catch
warning('Matched filter failed.')
disp('Matched filter failed.')
qrs{4} = [];
ect_qrs = [];
matchedf = 0;
end
%% Consensus detection
try
consqrs = kde_fusion(cell2mat(qrs(1:4)'),fs,length(signal)); % 2x gqrs
consqrs(diff(consqrs)<REF_WIN) = []; % removing double detections
[~,lag]=arrayfun(@(x) max(abs(signal(x-WIN_ALG:x+WIN_ALG))),consqrs(2:end-2));
consqrs(2:end-2) = consqrs(2:end-2) + lag - WIN_ALG - 1;
% Put all detectors on same sign (max or min) - shift by median lag
if flag
[~,lag]=arrayfun(@(x) max(signal(x-WIN_ALG:x+WIN_ALG)),consqrs(3:end-2));
else
[~,lag]=arrayfun(@(x) min(signal(x-WIN_ALG:x+WIN_ALG)),consqrs(3:end-2));
end
qrs{5} = consqrs(3:end-2) + lag - WIN_ALG - 1;
catch
disp('Consensus failed.')
qrs{5} = qrs{3};
end
% Remove border detections
qrs = cellfun(@(x) x(x>MIRR&x<LEN-MIRR)-MIRR,qrs,'UniformOutput',false);
signal = signal(MIRR+1:end-MIRR); % just for plotting
ect_qrs = ect_qrs(ect_qrs>MIRR&ect_qrs<(LEN-MIRR)) - MIRR;
clear lag flag consqrs
%% In case ectopic beats are present (consensus QRS locations is ignored, matched filter assumes)
% try
% if ~isempty(ect_qrs)
% % Remove ectopic beats
% cons = qrs{4};
% [~,dist] = dsearchn(cons,ect_qrs);
% insbeats = ect_qrs(dist>REF_WIN); % inserting these beats
%
% cons = sort([cons; insbeats]);
% cons(arrayfun(@(x) find(cons==x),insbeats)) = NaN; % insert NaN on missing beats
% cons = round(inpaint_nans(cons)); % Interpolate with simple spline over missing beats
% cons(cons<1|cons>length(signal)) = [];
% cons = sort(cons);
% cons(diff(cons)<REF_WIN) = [];
% qrs{6} = cons;
%
% % % visualise
% % plot(signal)
% % hold on
% % plot(qrs{4},2.*ones(size(qrs{4})),'ob')
% % plot(ect_qrs,2.*ones(size(ect_qrs)),'xr')
% % plot(qrs{6},3.*ones(size(qrs{6})),'md')
% % legend('signal','matchedf','ectopic','interpolated')
% % close
%
% else
% qrs{6} = qrs{5};
% end
% catch
% warning('Figuring out ectopic failed.')
% qrs{6} = qrs{5};
% ect_qrs = [];
% end
%% Generating some features
% Amplitude around QRS complex
normsig = signal./median(signal(qrs{end})); % normalized amplitude
feat_amp = var(normsig(qrs{end})); % QRS variations in amplitude
feat_amp2 = std(normsig(qrs{end})); % QRS variations in amplitude
feat_amp3 = mean(diff(normsig(qrs{end}))); % QRS variations in amplitude
feats = [feat_amp feat_amp2 feat_amp3];
%% Plots for sanity check
% subplot(2,1,1)
% plot(signal,'color',[0.7 0.7 0.7])
% hold on
% plot(qrs{1},signal(qrs{1}),'sg')
% plot(qrs{2},signal(qrs{2}),'xb')
% plot(qrs{3},signal(qrs{3}),'or')
% plot(qrs{4},signal(qrs{4}),'dy')
% plot(qrs{5},1.3*median(signal(qrs{5}))*ones(size(qrs{5})),'dm')
% legend('signal','gqrs','jqrs','maxsearch','matchedfilt','kde consensus')
% subplot(2,1,2)
% plot(qrs{6}(2:end),diff(qrs{6})*1000/fs)
% ylabel('RR intervals (ms)')
% ylim([250 1300])
% close
end
function det=kde_fusion(qrs,fs,dlength)
% Function uses Kernel density estimation on fusing multiple detections
%
% Input
% qrs Array with all detections
% fs Sampling frequency
% dlength Signal length
%
%
qrs = sort(qrs);
w_std = 0.10*fs; % standard deviation of gaussian kernels [ms]
pt_kernel = round(fs/2); % half window for kernel function [samples]
%% Calculating Kernel Density Estimation
% preparing annotations
peaks = hist(qrs,1:dlength);
% kde (adding gaussian kernels around detections)
kernel = exp(-(-pt_kernel:pt_kernel).^2./(2*w_std^2));
% calculating kernel density estimate
kde = conv(peaks,kernel,'same');
%% Decision
% Parameters
min_dist = round(0.2*fs); % minimal distance between consecutive peaks [ms]
th = max(kde)/3; % threshold for true positives (good measure is number_of_channels/3)
% Finding candidate peaks
wpoints = 1+min_dist:min_dist:dlength; % start points of windows (50% overlap)
wpoints(wpoints>dlength-2*min_dist) = []; % cutting edges
M = arrayfun(@(x) kde(x:x+2*min_dist-1)',wpoints(1:end), ...
'UniformOutput',false); % windowing signal (50% overlap)
M = cell2mat(M);
% adding first segment
head = [kde(1:min_dist) zeros(1,min_dist)]';
M = [head M];
% adding last segment
tail = kde((wpoints(end)+2*min_dist):dlength)';
tail = [tail; zeros(2*min_dist-length(tail),1)];
M = [M tail];
[~,idx] = max(M); % finding maxima
idx = idx+[1 wpoints wpoints(end)+2*min_dist]; % absolute locations
idx(idx < 0) = [];
idx(idx > length(kde)) = [];
i = 1;
while i<=length(idx)
doubled = (abs(idx-idx(i))<min_dist);
if sum(doubled) > 1
[~,idxmax]=max(kde(idx(doubled)));
idxmax = idx(idxmax + find(doubled,1,'first') - 1);
idx(doubled) = [];
idx = [idxmax idx];
clear doubled idxmax
end
i = i+1;
end
% threshold check
idx(kde(idx)<th) = [];
det = sort(idx)';
end
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
residualfeats.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/residualfeats.m
| 4,225 |
utf_8
|
caec19d3a2f1a68388f57735d2d29752
|
function feats = residualfeats(signal,fs,qrs)
% This function derives features out of QRS cancelled ECG signals, aiming at the atrial information.
%
% --
% ECG classification from single-lead segments using Deep Convolutional Neural
% Networks and Feature-Based Approaches - December 2017
%
% Released under the GNU General Public License
%
% Copyright (C) 2017 Fernando Andreotti, Oliver Carr
% University of Oxford, Insitute of Biomedical Engineering, CIBIM Lab - Oxford 2017
% [email protected]
%
%
% For more information visit: https://github.com/fernandoandreotti/cinc-challenge2017
%
% Referencing this work
%
% Andreotti, F., Carr, O., Pimentel, M.A.F., Mahdi, A., & De Vos, M. (2017).
% Comparing Feature Based Classifiers and Convolutional Neural Networks to Detect
% Arrhythmia from Short Segments of ECG. In Computing in Cardiology. Rennes (France).
%
% Last updated : December 2017
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
feats = zeros(1,5);
signal = signal';
if length(qrs) > 5
residual = FECGSYN_ts_extraction(qrs,signal,'TS-CERUTTI',0,5,2,fs);
else
return
end
try
% Cross-correlation
R=corrcoef(signal,residual);
feats(1) = 1 - R(1,2);
% Spectral coherence
[Pmf,f]=mscohere(signal,residual,[],[],1024,fs);
feats(2)=1-mean(Pmf(f>3&f<30));
feats(3) = psqi(residual',fs);
% Fundamental frequency on spectrum against rest
feats(4)=mpsqi1(residual',fs);
% Test for randomness
[h,p,R] = white_test(residual', 1, rand(1e3,1));
feats(5) = 1-p;
catch
disp('Residuals failed!')
end
end
function [h, p_value, R] = white_test(x, maxlag, alpha)
% tests against the null hyptothesis of whiteness
% see http://dsp.stackexchange.com/questions/7678/determining-the-whiteness-of-noise for details
% demo:
% % white:
% >> [h,p,R]=white_test(((filter([1], [1], rand(1e3,1)))))
% >> h = 0, p =1, R = 455
% % non white:
% >> [h,p,R]=white_test(((filter([1 .3], [.4 0.3], rand(1e3,1)))))
% >> h = 1, p = 0, R = 2e3
%
% Copyright (c) 2013, Hanan Shteingart
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
N = length(x);
x = x-mean(x);
if ~exist('m','var')
maxlag = N-1;
end
if ~exist('alpha','var')
alpha = 0.05;
end
[r, lag] = xcorr(x, maxlag, 'biased');
R = N/r(lag==0)^2*sum(r(lag > 0).^2);
p_value = 1-chi2cdf(R, maxlag);
T = chi2inv(1-alpha, maxlag);
h = R > T;
end
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
morphofeatures.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/morphofeatures.m
| 7,107 |
utf_8
|
cce0ae9aa3c7c26ee530c9260c8b53f2
|
function feats = morphofeatures(signal,fs,qrs,recordName)
% This function obtains morphological features from raw ECG data.
%
% --
% ECG classification from single-lead segments using Deep Convolutional Neural
% Networks and Feature-Based Approaches - December 2017
%
% Released under the GNU General Public License
%
% Copyright (C) 2017 Fernando Andreotti, Oliver Carr
% University of Oxford, Insitute of Biomedical Engineering, CIBIM Lab - Oxford 2017
% [email protected]
%
%
% For more information visit: https://github.com/fernandoandreotti/cinc-challenge2017
%
% Referencing this work
%
% Andreotti, F., Carr, O., Pimentel, M.A.F., Mahdi, A., & De Vos, M. (2017).
% Comparing Feature Based Classifiers and Convolutional Neural Networks to Detect
% Arrhythmia from Short Segments of ECG. In Computing in Cardiology. Rennes (France).
%
% Last updated : December 2017
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
fsnew = 250;
gain = 3000;
T_LENGTH = 200; % about a second
NB_BINS = 250;
Nfeats = 17;
% Bandpass filter for morphological analysis
Fhigh = 1; % highpass frequency [Hz]
Flow = 100; % low pass frequency [Hz]
Nbut = 12; % order of Butterworth filter
d_bp= design(fdesign.bandpass('N,F3dB1,F3dB2',Nbut,Fhigh,Flow,fs),'butter');
[b_bp2,a_bp2] = tf(d_bp);
clear Fhigh Flow Nbut d_bp
signal = filtfilt(b_bp2,a_bp2,signal); % filtering
signal = detrend(signal);
recordName = ['pu' recordName];
% Resampling for ECGPUWAVE
sigres=resample(signal,fsnew,fs);
qrsfinal = round(qrs{end}*fsnew/fs);
% Morphological features
%% Running ECGPUWAVE for normal beats
% == Using average normal beat
try
[M,RES] = stackbeats(sigres,qrsfinal,T_LENGTH,NB_BINS);
template = mean(M,2);
template = resample(template,RES,NB_BINS);
template = detrend(template);
fake_sig = repmat(template,1,20);
smoothvec = [0:0.1:0.9, ones(1,size(fake_sig,1)-20),0.9:-0.1:0]';
fake_sig = bsxfun(@times,fake_sig,smoothvec); % smoothing edges
fake_sig = reshape(fake_sig,[],1);
fake_sig = detrend(fake_sig);
tm = 1/fsnew:1/fsnew:length(fake_sig)/fsnew;
tm = tm'-1/fsnew;
[~,I] = max(abs(fake_sig));
wsign = sign(fake_sig(I)); % looking for signal sign
qrsfake = cumsum([0 repmat(RES,1,19)]) + floor(RES/2);
fake_sig = 2*gain*wsign(1)*fake_sig/max(abs(fake_sig));
wrsamp(tm,fake_sig,recordName,fsnew,gain,'')
wrann(recordName,'qrs',qrsfake-1,repmat('N',length(qrsfake),1));
if isunix
system(['ecgpuwave -r ' recordName '.hea' ' -a ecgpu -i qrs']);
else
ecgpuwave(recordName,'ecgpu',[],[],'qrs'); % important to specify the QRS because it seems that ecgpuwave is crashing sometimes otherwise
end
[allref,alltypes_r] = rdann(recordName,'ecgpu');
fake_sig = fake_sig./gain;
featavgnorm = FECGSYN_QTcalc(alltypes_r,allref,fake_sig,fsnew);
feats = struct2array(featavgnorm);
feats(isnan(feats)) = 0;
catch
warning('ecgpuwave NORMAL average has failed.')
feats = zeros(1,Nfeats);
end
delete([recordName '.*'])
end
function feats = FECGSYN_QTcalc(ann_types,ann_stamp,signal,fs)
temp_types = ann_types; % allows exclusion of unsuitable annotations
temp_stamp = ann_stamp;zeros(1,10);
feats = struct('QRSheight',0,'QRSwidth',0,'QRSpow',0,...
'noPwave',0,'Pheight',0,'Pwidth',0,'Ppow',0,...
'Theight',0,'Twidth',0,'Tpow',0,...
'Theightnorm',0,'Pheightnorm',0,'Prelpow',0,...
'PTrelpow',0,'Trelpow',0,'QTlen',0,'PRlen',0);
%== Treat biphasic T-waves
annstr = strcat({temp_types'});
idxbi=cell2mat(regexp(annstr,'tt')); % biphasic
nonbi2= cell2mat(regexp(annstr,'\)t\(')) +1; % weird t
nonbi3= cell2mat(regexp(annstr,'\)t\)')) +1; % weird t2
if sum(idxbi) > 0 % case biphasic waves occured
posmax = [idxbi' idxbi'+1];
[~,bindx]=max(abs(signal(ann_stamp(posmax))),[],2); % max abs value between tt
clearidx = [idxbi+double(bindx'==1) nonbi2 nonbi3];
%idxbi = idxbi + bindx -1; % new index to consider
temp_types(clearidx) = []; % clearing biphasic cases
temp_stamp(clearidx) = [];
end
clear biphasic teesfollowed nonbi1 nonbi2 nonbi3 bindx clearidx posmax idxbi
%== Remove incomplete beats
comp=cell2mat(regexp(cellstr(temp_types'),'\(p\)\(N\)\(t\)')); % regular
beats = temp_stamp(cell2mat(arrayfun(@(x) x:x+8,comp','uniformoutput',0)));
skipP = false;
if isempty(beats)
comp=cell2mat(regexp(cellstr(temp_types'),'\(t\)\(N\)\(t\)')); % missing P-wave
if isempty(comp), return, end % if ECGPUWAVE does not really work then output zeros
beats = temp_stamp(cell2mat(arrayfun(@(x) x:x+8,comp','uniformoutput',0)));
skipP = true;
feats.noPwave = 1;
else
feats.noPwave = 0;
end
if size(beats,2)==1; beats = beats';end % case single beat is available
Pstart = beats(:,1);
validP = beats(:,2);
Pend = beats(:,3);
Rstart = beats(:,4);
validR = beats(:,5);
Rend = beats(:,6);
Tstart = beats(:,7);
validT = beats(:,8);
Tend = beats(:,9);
%% Calculating features
feats.QRSheight = abs(median(min([signal(Rstart) signal(Rend)],[],2) - signal(validR))); % T-wave height
feats.QRSwidth = median(Rend - Rstart)/fs; % T-wave width
feats.QRSpow = sum(signal(Rstart:Rend).^2);
if ~skipP
feats.Pheight = abs(median(median([signal(Pstart) signal(Pend)],2) - signal(validP))); % P-wave height
feats.Pwidth = median(Pend - Pstart)/fs; % P-wave width
feats.Ppow = sum(signal(Pstart:Pend).^2);
end
feats.Theight = abs(median(median([signal(Tstart) signal(Tend)],2) - signal(validT))); % T-wave height
feats.Twidth = median(Tend - Tstart)/fs; % T-wave width
feats.Tpow = sum(signal(Tstart:Tend).^2);
feats.Theightnorm = feats.Theight/feats.QRSheight;
feats.Trelpow = feats.Tpow/feats.QRSpow;
if ~skipP
feats.Pheightnorm = feats.Pheight/feats.QRSheight;
feats.Prelpow = feats.Ppow/feats.QRSpow;
feats.PTrelpow = feats.Ppow/feats.Tpow;
end
QT_MAX = 0.5*fs; % Maximal QT length (in s) MAY VARY DEPENDING ON APPLICATION!
QT_MIN = 0.1*fs; % Minimal QT length (in s) MAY VARY DEPENDING ON APPLICATION!
[~,dist] = dsearchn(Rstart,Tend); % closest ref for each point in test qrs
feats.QTlen = median(dist(dist<QT_MAX&dist>QT_MIN))/fs;
if ~skipP
PR_MAX = 0.3*fs; % Maximal QT length (in s) MAY VARY DEPENDING ON APPLICATION!
PR_MIN = 0.05*fs; % Minimal QT length (in s) MAY VARY DEPENDING ON APPLICATION!
[~,dist] = dsearchn(validP,validR); % closest ref for each point in test qrs
feats.PRlen = median(dist(dist<PR_MAX&dist>PR_MIN))/fs;
end
end
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
OSET_MaxSearch.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/OSET/OSET_MaxSearch.m
| 3,010 |
utf_8
|
ea7b0805ed40c38f18668f76d549e9ed
|
% peaks = OSET_MaxSearch(x,f,flag),
% R-peak detector based on max search
%
% inputs:
% signal: vector of input data
% ff: approximate signal beat-rate in Hertz, normalized by the sampling frequency
% flag: search for positive (flag=1) or negative (flag=0) peaks. By default
% the maximum absolute value of the signal, determines the peak sign.
%
% output:
% peaks: vector of R-peak impulse train
%
% Notes:
% - The R-peaks are found from a peak search in windows of length N; where
% N corresponds to the R-peak period calculated from the given f. R-peaks
% with periods smaller than N/2 or greater than N are not detected.
% - The signal baseline wander is recommended to be removed before the
% R-peak detection
%
%
% Open Source signal Toolbox, version 1.0, November 2006
% Released under the GNU General Public License
% Copyright (C) 2006 Reza Sameni
% Sharif University of Technology, Tehran, Iran -- GIPSA-Lab, INPG, Grenoble, France
% [email protected]
% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the
% Free Software Foundation; either version 2 of the License, or (at your
% option) any later version.
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
% Public License for more details.
%
% (minor modifications by Fernando Andreotti, October 2013)
% log: - Allowed multi-channel detection by looping through channels
% - Made selection of maxima/minima more robust
function peaks = OSET_MaxSearch(signal,ff,varargin)
if size(signal,1) > size(signal,2)
signal = signal';
end
th = .5;
rng = floor(th/ff);
% By choosing median of 5% of the data length makes flag choice more robust.
% modification by Andreotti
segs = reshape(signal(1:end-mod(length(signal),rng)),rng,[]);
segs = sort(segs,'ascend');
ymax = median(median(segs((end-floor(0.05*rng):end),:)));
ymin = median(median(segs(1:floor(0.05*rng),:)));
flag = ymax > abs(ymin); % check if 5% data positive or negative
if ~flag
signal = -signal;
clear ymin x y flag
end % always search for maxima
% loops through every channel
x = signal;
N = length(x);
peaks = zeros(1,N);
for j = 1:N,
% index = max(j-rng,1):min(j+rng,N);
if(j>rng && j<N-rng)
index = j-rng:j+rng;
elseif(j>rng)
index = N-2*rng:N;
else
index = 1:2*rng;
end
if(max(x(index))==x(j))
peaks(j) = 1;
end
end
% remove fake peaks
I = find(peaks);
d = diff(I);
% z = find(d<rng);
peaks(I(d<rng))=0;
peaks = find(peaks);
% Getting read of peaks with too low amplitude
segs = reshape(abs(signal(1:end-mod(length(signal),rng))),rng,[]);
segs = sort(segs,'ascend');
ymin = median(median(segs(1:floor(0.5*rng),:))); % if lower than the half
peaks(abs(signal(peaks)) < ymin) = []; % remove peaks with little amplitude
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
DFA_main_a2.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/DFA/DFA_main_a2.m
| 1,843 |
utf_8
|
c9154258387369bda985b073224c1447
|
function [D,Alpha1]=DFA_main_a2(DATA)
% DATA should be a time series of length(DATA) greater than 2000,and of column vector.
%A is the alpha in the paper
%D is the dimension of the time series
%n can be changed to your interest
%
%Copyright (c) 2009, Guan Wenye
%All rights reserved.
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions are
%met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
%AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
%LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
%CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
%ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%POSSIBILITY OF SUCH DAMAGE.
n=4:1:10;
N1=length(n);
F_n=zeros(N1,1);
for i=1:N1
F_n(i)=DFA(DATA,n(i),1);
end
n=n';
% plot(log(n),log(F_n));
% xlabel('n')
% ylabel('F(n)')
A=polyfit(log(n(1:end)),log(F_n(1:end)),1);
Alpha1=A(1);
D=3-A(1);
return
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
DFA_main_a1.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/DFA/DFA_main_a1.m
| 1,846 |
utf_8
|
be6d67571fecfe7d895b457d320335ef
|
function [D,Alpha1]=DFA_main_a1(DATA)
% DATA should be a time series of length(DATA) greater than 2000,and of column vector.
%A is the alpha in the paper
%D is the dimension of the time series
%n can be changed to your interest
%
%Copyright (c) 2009, Guan Wenye
%All rights reserved.
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions are
%met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
%AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
%LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
%CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
%ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%POSSIBILITY OF SUCH DAMAGE.
n=10:10:100;
N1=length(n);
F_n=zeros(N1,1);
for i=1:N1
F_n(i)=DFA(DATA,n(i),1);
end
n=n';
% plot(log(n),log(F_n));
% xlabel('n')
% ylabel('F(n)')
A=polyfit(log(n(1:end)),log(F_n(1:end)),1);
Alpha1=A(1);
D=3-A(1);
return
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
FECGx_kf_PhaseCalc.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/fernando/FECGx_kf_PhaseCalc.m
| 2,758 |
utf_8
|
a283d62f38cf92cf9a06bd0fd09507a7
|
%% Phase Calculation
% Generates the phase signal for Kalman Filtering
% Inputs
% peaks QRS peak locations
% length Length of data for phase generation
%
%
% Fetal Extraction Toolbox, version 1.0, February 2014
% Released under the GNU General Public License
%
% Copyright (C) 2014 Fernando Andreotti
% Dresden University of Technology, Institute of Biomedical Engineering
% [email protected]
%
% Last updated : 24-07-2014
%
% Based on: Synthetic ECG model error
% Open Source ECG Toolbox, version 2.0, March 2008
% Released under the GNU General Public License
% Copyright (C) 2008 Reza Sameni
% Sharif University of Technology, Tehran, Iran -- LIS-INPG, Grenoble, France
% [email protected]
% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the
% Free Software Foundation; either version 2 of the License, or (at your
% option) any later version.
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
% Public License for more details.
% This program is free software; you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the
% Free Software Foundation; either version 2 of the License, or (at your
% option) any later version.
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
% Public License for more details.
%
function phase = FECGx_kf_PhaseCalc(peaks,lengthx)
% Based on Sameni's method for phase calculation
phase = zeros(1,lengthx);
m = diff(peaks); % gets distance between peaks
% first interval
% dealing with borders (first and last peaks may not be full waves)
% uses second interval as reference
L = peaks(1); %length of first interval
if isempty(m) % only ONE peak was detected
phase(1:lengthx) = linspace(-2*pi,2*pi,lengthx);
else
phase(1:L) = linspace(2*pi-L*2*pi/m(1),2*pi,L);
% beats in the middle
for i = 1:length(peaks)-1; % generate phases between 0 and 2pi for almos all peaks
phase(peaks(i):peaks(i+1)) = linspace(0,2*pi,m(i)+1);
end % 2pi is overlapped by 0 on every loop
% last interval
% uses second last interval as reference
L = length(phase)-peaks(end); %length of last interval
phase(peaks(end):end) = linspace(0,L*2*pi/m(end),L+1);
end
phase = mod(phase,2*pi);
phase(find(phase>pi)) = phase(find(phase>pi))- 2*pi;
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
FECGSYN_ts_extraction.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/fernando/FECGSYN_ts_extraction.m
| 9,690 |
utf_8
|
4d553bba7d7da1625e755a67ee0948ce
|
function residual = FECGSYN_ts_extraction(peaks,ecg,method,debug,varargin)
% Template subtraction for MECG cancellation. Five template subtraction techniques
% are implemented, namely TS,TS-CERUTTI,TS-SUZANNA,TS-LP,TS-PCA. If a more adaptive
% technique is required then an the EKF technique as in (Sameni 2007) is recommended.
%
% inputs
% peaks: MQRS markers in ms. Each marker corresponds to the
% position of a MQRS
% ecg: matrix of abdominal ecg channels
% method: method to use ('TS','TS-CERUTTI','TS-SUZANNA','TS-LP','TS-PCA')
% TS - simple template removal with no adaptation
%
% TS-CERUTTI - simply adapts the template to each beat using
% a scalar gain (Cerutti 1986)
%
% TS-SUZANNA - the scaling procedure was performed for the P, QRS,
% and T waves independently. (Martens 2007)
%
% TS-LP - the template ECG is built by weighing the former cycles in
% order to minimize the mean square error (as opposed to the other TS
% where the weights of the different cycles are equal)(Vullings 2009)
%
% TS-PCA - stacks MECG cycles, selects some of the principal components,
% next a back-propagation step takes place on a beat-to-beat basis, thus
% producing MECG estimates every cycle (Kanjilal 1997)
% varargin:
% nbCycles: number of cycles to use in order to build the mean MECG template
% NbPC: number of principal components to use for PCA
% fs: sampling frequency (NOTE: this code is meant to work at 1kHz)
%
% output
% residual: residual containing the FECG
%
% References:
% (Cerutti 1986) Cerutti S, Baselli G, Civardi S, Ferrazzi E, Marconi A M and Pagani M Pardi G 1986
% Variability analysis of fetal heart rate signals as obtained from abdominal
% electrocardiographic recordings J. Perinatal Med. Off. J. WAPM 14 445–52
% (Kanjilal 1997) Kanjilal P P, Palit S and Saha G 1997 Fetal ECG extraction
% from single-channel maternal ECG using singular value decomposition IEEE
% Trans. Biomed. Eng. 44 51–9
% (Martens 2007) Martens S M M, Rabotti C, Mischi M and Sluijter R J 2007 A
% robust fetal ECG detection method for abdominal recordings Physiol. Meas. 28 373–88
% (Sameni 2007)
% (Vullings 2009) Vullings R, Peters C, Sluijter R, Mischi M, Oei S G and
% Bergmans J W M 2009 Dynamic segmentation linear prediction for maternal ECG removal in antenatal
% abdominal recordings Physiol. Meas. 30 291
%
%
% Examples:
% TODO
%
% See also:
% FECGSYN_kf_extraction
% FECGSYN_bss_extraction
% FECGSYN_adaptfilt_extraction
% FEGSYN_main_extract
%
%
% --
% fecgsyn toolbox, version 1.2, March 2017
% Released under the GNU General Public License
%
% Copyright (C) 2017 Joachim Behar & Fernando Andreotti
% Department of Engineering Science, University of Oxford
% [email protected], [email protected]
%
%
% For more information visit: http://www.fecgsyn.com
%
% Referencing this work
%
% Behar, J., Andreotti, F., Zaunseder, S., Li, Q., Oster, J., & Clifford, G. D. (2014). An ECG Model for Simulating
% Maternal-Foetal Activity Mixtures on Abdominal ECG Recordings. Physiol. Meas., 35(8), 1537–1550.
%
%
% Last updated : 15-03-2017
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
%
% == manage inputs
% set defaults for optional inputs
optargs = {20 2 1000};
newVals = cellfun(@(x) ~isempty(x), varargin);
optargs(newVals) = varargin(newVals);
[nbCycles, NbPC, fs] = optargs{:};
if nargin > 7
error('ts_extraction: wrong number of input arguments \n');
end
% check that we have more peaks than nbCycles
if nbCycles>length(peaks)
error('MECGcancellation Error: more peaks than number of cycles for average ecg');
end
% == constants
NB_CYCLES = nbCycles;
NB_MQRS = length(peaks);
ecg_temp = zeros(1,length(ecg));
Pstart = ceil(0.25*fs)-1;
Tstop = floor(0.45*fs);
ecg_buff = zeros(Tstop+Pstart+1,NB_CYCLES); % ecg stack buffer
try
% == template ecg (TECG)
indMQRSpeaks = find(peaks>Pstart);
for cc=1:NB_CYCLES
peak_nb = peaks(indMQRSpeaks(cc+1)); % +1 to unsure full cycles
ecg_buff(:,cc) = ecg((peak_nb-Pstart):(peak_nb+Tstop))';
end
TECG = median(ecg_buff,2);
if strcmp(method,'TS-PCA'); [U,~,~] = svds(ecg_buff,NbPC); end;
% == MECG cancellation
for qq=1:NB_MQRS
if peaks(qq)>Pstart && length(ecg)-peaks(qq)>Tstop
switch method
case 'TS'
% - simple TS -
ecg_temp(peaks(qq)-Pstart:peaks(qq)+Tstop) = TECG';
case 'TS-SUZANNA'
% - three scaling factors -
M = zeros (round(0.7*fs),3);
M(1:round(0.2*fs),1) = TECG(1:Pstart-round(0.05*fs)+1);
M(round(0.2*fs)+1:0.3*fs,2) = TECG(Pstart-round(0.05*fs)+2:Pstart+round(0.05*fs)+1);
M(round(0.3*fs)+1:end,3) = TECG(Pstart+2+round(0.05*fs):Pstart+1+Tstop);
a = (M'*M)\M'*ecg(peaks(qq)-Pstart:peaks(qq)+Tstop)';
ecg_temp(peaks(qq)-Pstart:peaks(qq)+Tstop) = a(1)*M(:,1)'+a(2)*M(:,2)'+a(3)*M(:,3)';
case 'TS-CERUTTI'
% - only one scaling factor -
M = TECG;
a = (M'*M)\M'*ecg(peaks(qq)-Pstart:peaks(qq)+Tstop)';
ecg_temp(peaks(qq)-Pstart:peaks(qq)+Tstop) = a*M';
case 'TS-LP'
% - Linear prediction method (Ungureanu et al., 2007) -
% NOTE: in Ungureanu nbCycles=7
if qq>NB_CYCLES
M = ecg(peaks(qq)-Pstart:peaks(qq)+Tstop)';
Lambda = (ecg_buff'*ecg_buff)\ecg_buff'*M;
if sum(isnan(Lambda))>0
Lambda = ones(length(Lambda),1)/(length(Lambda));
end
ecg_temp(peaks(qq)-Pstart:peaks(qq)+Tstop) = Lambda'*ecg_buff';
else
M = TECG;
ecg_temp(peaks(qq)-Pstart:peaks(qq)+Tstop) = M';
end
case 'TS-PCA'
if mod(qq,10)==0
% - to allow some adaptation of the PCA basis -
% !!NOTE: this adaption step is slowing down the code!!
[U,~,~] = svds(ecg_buff,NbPC);
end
% - PCA method -
X_out = ecg(peaks(qq)-Pstart:peaks(qq)+Tstop)*(U*U');
ecg_temp(peaks(qq)-Pstart:peaks(qq)+Tstop) = X_out;
otherwise
error('ts_extraction: Method not implemented.')
end
if qq>NB_CYCLES
% adapt template conditional to new cycle being very similar to
% meanECG to avoid catching artifacts. (not used for PCA method).
Match = CompareCycles(TECG', ecg(peaks(qq)-Pstart:peaks(qq)+Tstop)',0.8);
if Match
ecg_buff = circshift(ecg_buff,[0 -1]);
ecg_buff(:,end) = ecg(peaks(qq)-Pstart:peaks(qq)+Tstop)';
TECG = median(ecg_buff,2);
end
end
% == managing borders
elseif peaks(qq)<=Pstart
% - first cycle if not full cycle -
n = length(ecg_temp(1:peaks(qq)+Tstop)); % length of first pseudo cycle
m = length(TECG); % length of a pseudo cycle
ecg_temp(1:peaks(qq)+Tstop+1) = TECG(m-n:end);
elseif length(ecg)-peaks(qq)<Tstop
% - last cycle if not full cycle -
ecg_temp(peaks(qq)-Pstart:end) = TECG(1:length(ecg_temp(peaks(qq)-Pstart:end)));
end
end
% compute residual
residual = ecg - ecg_temp;
catch ME
for enb=1:length(ME.stack); disp(ME.stack(enb)); end;
residual = ecg;
end
% == debug
if debug
FONT_SIZE = 15;
tm = 1/fs:1/fs:length(residual)/fs;
figure('name','MECG cancellation');
plot(tm,ecg,'LineWidth',3);
hold on, plot(tm,ecg-residual,'--k','LineWidth',3);
hold on, plot(tm,residual-1.5,'--r','LineWidth',3);
hold on, plot(tm(peaks),ecg(peaks),'+r','LineWidth',2);
legend('mixture','template','residual','MQRS');
title('Template subtraction for extracting the FECG');
xlabel('Time [sec]'); ylabel('Amplitude [NU]')
set(gca,'FontSize',FONT_SIZE);
set(findall(gcf,'type','text'),'fontSize',FONT_SIZE);
end
end
function match = CompareCycles(cycleA,cycleB,thres)
% cross correlation measure to compare if new ecg cycle match with template.
% If not then it is not taken into account for updating the template.
match = 0;
bins = size(cycleA,2);
coeff = sqrt(abs((cycleA-mean(cycleA))*(cycleB-mean(cycleB)))./(bins*std(cycleA)*std(cycleB)));
if coeff > thres; match = 1; end;
end
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
binary_seq_to_string.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/Lempel Ziv/binary_seq_to_string.m
| 2,118 |
utf_8
|
ea1f9bd7af2d67266212e36a905a2f71
|
%BINARY_SEQ_TO_STRING String representation of a logical vector.
% This function takes a vector of logical values, and returns a string
% representation of the vector. e.g. [0 1 0 1 1] becomes '01011'.
%
% Usage: [s] = binary_seq_to_string(b)
%
% INPUTS:
%
% b:
% A vector of logical values representing a binary sequence.
% Numeric values will be converted to logical values depending on
% whether (0) or not (1) they are equal to 0.
%
%
% OUTPUTS:
%
% s:
% A string representation of b. The nth character in the string
% corresponds with b(k).
%
%
%
%
% Author: Quang Thai ([email protected])
% Copyright (C) Quang Thai 2012
%
% Copyright (c) 2012, Quang Thai
%All rights reserved.
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions are
%met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
%AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
%LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
%CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
%ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%POSSIBILITY OF SUCH DAMAGE.
function [s] = binary_seq_to_string(b)
b = logical(b(:));
lookup_string = '01';
s = lookup_string(b + 1);
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
calc_lz_complexity.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/Lempel Ziv/calc_lz_complexity.m
| 15,770 |
utf_8
|
a02daa7bc1f2f004f72b0dd90a486379
|
%CALC_LZ_COMPLEXITY Lempel-Ziv measure of binary sequence complexity.
% This function calculates the complexity of a finite binary sequence,
% according to the algorithm published by Abraham Lempel and Jacob Ziv in
% the paper "On the Complexity of Finite Sequences", published in
% "IEEE Transactions on Information Theory", Vol. IT-22, no. 1, January
% 1976. From that perspective, the algorithm could be referred to as
% "LZ76".
%
% Usage: [C, H] = calc_lz_complexity(S, type, normalize)
%
% INPUTS:
%
% S:
% A vector consisting of a binary sequence whose complexity is to be
% analyzed and calculated. Numeric values will be converted to logical
% values depending on whether (0) or not (1) they are equal to 0.
%
% type:
% The type of complexity to evaluate as a string, which is one of:
% - 'exhaustive': complexity measurement is based on decomposing S
% into an exhaustive production process.
% - 'primitive': complexity measurement is based on decomposing S
% into a primitive production process.
% Exhaustive complexity can be considered a lower limit of the complexity
% measurement approach proposed in LZ76, and primitive complexity an
% upper limit.
%
% normalize:
% A logical value (true or false), used to specify whether or not the
% complexity value returned is normalized or not.
% Where normalization is applied, the normalized complexity is
% calculated from the un-normalized complexity, C_raw, as:
% C = C_raw / (n / log2(n))
% where n is the length of the sequence S.
%
% OUTPUTS:
%
% C:
% The Lempel-Ziv complexity value of the sequence S.
%
% H:
% A cell array consisting of the history components that were found in
% the sequence S, whilst calculating C. Each element in H consists of a
% vector of logical values (true, false), and represents
% a history component.
%
% gs:
% A vector containing the corresponding eigenfunction that was calculated
% which corresponds with S.
%
%
%
% Author: Quang Thai ([email protected])
% Copyright (C) Quang Thai 2012
%
%
% Copyright (c) 2012, Quang Thai
%All rights reserved.
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions are
%met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
%AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
%IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
%LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
%CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
%SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
%CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
%ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
%POSSIBILITY OF SUCH DAMAGE.
function [C, H, gs] = calc_lz_complexity(S, type, normalize)
%% Some parameter-checking.
% Make sure S is a vector.
if ~isvector(S)
error('''S'' must be a vector');
end
% Make sure 'normalize' is a scalar.
if ~isscalar(normalize)
error('''normalize'' must be a scalar');
end
% Make sure 'type' is valid.
if ~(strcmpi(type, 'exhaustive') || strcmpi(type, 'primitive'))
error(['''type'' parameter is not valid, must be either ' ...
'''exhaustive'' or ''primitive''']);
end
%% Some parameter 'conditioning'.
S = logical(S);
normalize = logical(normalize);
%% ANALYSIS
% NOTE: Many of these comments will refer to the paper "On the Complexity
% of Finite Sequences" by Lempel and Ziv, so to follow this code, it may
% be useful to have the manuscript in front of you!
% Allocate memory for eigenfunction (vector of eigenvalues).
% The first value of this vector corresponds with gs(0), and is always
% equal to 0.
% Please note that, since MATLAB array indices start at 1, gs(n) in MATLAB
% actually holds gs(n-1) as defined in the paper.
n = length(S);
gs = zeros(1, n + 1);
gs(1) = 0; % gs(0) = 0 from the paper
% The approach we will use to find the eigenfunction values at each
% successive prefix of S is as follows:
% - We wish to find gs(n), where 1 <= n <= l(S) (l(S) = length of S)
% - Lemma 4 says:
% k(S(1,n-1)) <= k(S(1,n))
% equivalently
% gs(n-1) <= gs(n)
% In other words, the eigenfunction is a non-decreasing function of n.
% - Theorem 6 provides the expression that defines the eigenvocabulary of
% a sequence:
% e(S(1,n)) = {S(i,n) | 1 <= i <= k(S(1,n))}
% equivalently
% e(S(1,n)) = {S(i,n) | 1 <= i <= gs(n)}
% Note that we do not know what gs(n) is at this point - it's what we're
% trying to find!!!
% - Remember that the definition of the eigenvocabulary of a sequence S(1,n),
% e(S(1,n)), is the subset of the vocabulary of S(1,n) containing words
% that are not in the vocabulary of any proper prefix of S(1,n), and the
% eigenvalue of S(1,n) is the subset's cardinality: gs(n) = |e(S(1,n))|
% (p 76, 79)
% - Given this, a corollary to Theorem 6 is:
% For each S(m,n) | gs(n) < m <= n, S(m,n) is NOT a member of
% the eigenvocabulary e(S(1,n)).
% By definition, this means that S(m,n) is in the vocabulary of at
% least one proper prefix of S(1,n).
% - Also note that from Lemma 1: if a word is in the vocabulary of a
% sequence S, and S is a proper prefix of S+, then the word is also
% in the vocabulary of S+.
%
% As a result of the above discussion, the algorithm can be expressed in
% pseudocode as follows:
%
% For a given n, whose corresponding eigenfunction value, gs(n) we wish to
% find:
% - gs(0) = 0
% - Let m be defined on the interval: gs(n-1) <= m <= n
% - for each m
% check if S(m,n) is in the vocabulary of S(1,n-1)
% if it isn't, then gs(n) = m
% end if
% end for
%
% An observation: searching linearly along the interval
% gs(n-1) <= m <= n will tend to favour either very complex sequences
% (starting from n and working down), or very un-complex sequences
% (starting from gs(n-1) and working up). This implementation will
% attempt to balance these outcomes by alternately searching from either
% end and working inward - a 'meet-in-the-middle' search.
%
% Note that:
% - When searching from the upper end downwards, we are seeking
% the value of m such that S(m,n) IS NOT in the vocabulary of S(1,n-1).
% The eigenfunction value is then m.
% - When searching from the lower end upwards, we are seeking the value
% of m such that S(m,n) IS in the vocabulary of S(1,n-1). The
% eigenfunction value is then m-1, since it is the MAXIMAL value of m
% whereby S(m,n) IS NOT in the vocabulary of S(1,n-1)
%% Calculate eigenfunction, gs(n)
% Convert to string form - aids the searching process!
S_string = binary_seq_to_string(S);
gs(2) = 1; % By definition. Remember: gs(2) in MATLAB is actually gs(1)
% due to the first element of the gs array holding the
% eigenvalue for n = 0.
for n = 2:length(S)
eigenvalue_found = false;
% The search space gs(n-1) <= m <= n.
% Remember: gs(n) in MATLAB is actually gs(n-1).
% Note that we start searching at (gs(n-1) + 1) at the lower end, since
% if it passes the lower-end search criterion, then we subtract 1
% to get the eigenvalue.
idx_list = (gs(n)+1):n;
for k = 1:ceil(length(idx_list)/2);
% Check value at upper end of interval
m_upper = idx_list(end - k + 1);
if ~numel(strfind(S_string(1:(n-1)), S_string(m_upper:n)))
% We've found the eigenvalue!
gs(n+1) = m_upper; % Remember:
% gs(n+1) in MATLAB is actually gs(n)
eigenvalue_found = true;
break;
end
% Check value at lower end of interval.
%
% Note that the search at this end is slightly more complicated,
% in the sense that we have to find the first value of m where the
% substring is FOUND, and then subtract 1. However, this is
% complicated by the 'meet-in-the-middle' search adopted, as
% described below...
m_lower = idx_list(k);
if numel(strfind(S_string(1:(n-1)), S_string(m_lower:n)))
% We've found the eigenvalue!
gs(n+1) = m_lower-1; % Remember:
% gs(n+1) in MATLAB is actually gs(n)
eigenvalue_found = true;
break;
elseif (m_upper == m_lower + 1)
% If we've made it here, then we know that:
% - The search for substring S(m,n) from the upper end had a
% FOUND result
% - The search for substring S(m,n) from the lower end had a
% NOT FOUND result
% - The value of m used in the upper end search is one more
% than the value of m used in this lower end search
%
% However, when searching from the lower end, we need a FOUND
% result and then subtract 1 from the corresponding m.
% The problem with this 'meet-in-the-middle' searching is that
% it's possible that the actual eigenfunction value actually
% does occur in the middle, such that the loop would terminate
% before the lower-end search can reach a FOUND result and the
% upper-end search can reach a NOT FOUND result.
%
% This branch detects precisely this condition, whereby
% the two searches use adjacent values of m in the middle,
% the upper-end search has the FOUND result that the lower-end
% search normally requires, and the lower-end search has the
% NOT FOUND result that the upper-end search normally requires.
% We've found the eigenvalue!
gs(n+1) = m_lower; % Remember:
% gs(n+1) in MATLAB is actually gs(n)
eigenvalue_found = true;
break;
end
end
if ~eigenvalue_found
% Raise an error - something is not right!
error('Internal error: could not find eigenvalue');
end
end
%% Calculate the terminal points for the required production sequence.
% Histories are composed by decomposing the sequence S into the following
% sequence of words:
% H(S) = S(1,h_1)S(h_1 + 1,h_2)S(h_2 + 1,h_3)...S(h_m-1 + 1,h_m)
% The indices {h_1, h_2, h_3, ..., h_m-1, h_m} that characterise a history
% make up the set of 'terminals'.
%
% Alternatively, for consistency, we will specify the history as:
% H(S) = ...
% S(h_0 + 1,h_1)S(h_1 + 1,h_2)S(h_2 + 1,h_3)...S(h_m-1 + 1,h_m)
% Where, by definition, h_0 = 0.
% Efficiency measure: we don't know how long the histories will be (and
% hence, how many terminals we need). As a result, we will allocate an
% array of length equal to the eigenfunction vector length. We will also
% keep a 'length' counter, so that we know how much of this array we are
% actually using. This avoids us using an array that needs to be resized
% iteratively!
% Note that h_i(1) in MATLAB holds h_0, h_i(2) holds h_1, etc., since
% MATLAB array indices must start at 1.
h_i = zeros(1, length(gs));
h_i_length = 1; % Since h_0 is already present as the first value!
if strcmpi(type, 'exhaustive')
% - From Theorem 8, for an exhaustive history, the terminal points h_i,
% 1 <= i <= m-1, are defined by:
% h_i = min{h | gs(h) > h_m-1}
% - We know that h_0 = 0, so this definition basically bootstraps our
% search process, allowing us to find h_1, then h_2, etc.
h_prev = 0; % Points to h_0 initially
k = 1;
while ~isempty(k)
% Remember that gs(1) in MATLAB holds the value of gs(0).
% Therefore, the index h_prev needs to be incremented by 1
% to be used as an index into the gs vector.
k = find(gs((h_prev+1+1):end) > h_prev, 1);
if ~isempty(k)
h_i_length = h_i_length + 1;
% Remember that gs(1) in MATLAB holds the value of gs(0).
% Therefore, the index h_prev needs to be decremented by 1
% to be used as an index into the original sequence S.
h_prev = h_prev + k;
h_i(h_i_length) = h_prev;
end
end
% Once we break out of the above loop, we've found all of the
% exhaustive production components.
else
% Sequence type is 'primitive'
% Find all unique eigenfunction values, where they FIRST occur.
% - From Theorem 8, for a primitive history, the terminal points h_i,
% 1 <= i <= m-1, are defined by:
% h_i = min{h | gs(h) > gs(h_i-1)}
% - From Lemma 4, we know that the eigenfunction, gs(n), is
% monotonically non-decreasing.
% - Therefore, the following call to unique() locates the first
% occurrance of each unique eigenfunction value, as well as the values
% of n where the eigenfunction increases from the previous value.
% Hence, this is also an indicator for the terminal points h_i.
[~, n] = unique(gs, 'first');
% The terminals h_i, 1 <= i <= m-1, is ultimately obtained from n by
% subtracting 1 from each value (since gs(1) in MATLAB actually
% corresponds with gs(0) in the paper)
h_i_length = length(n);
h_i(1:h_i_length) = n - 1;
end
% Now we have to deal with the final production component - which may or
% may not be exhaustive or primitive, but can still be a part of an
% exhaustive or primitive process.
%
% If the last component is not exhaustive or primitive, we add it here
% explicitly.
%
% - From Theorem 8, for a primitive history, this simply enforces
% the requirement that:
% h_m = l(S)
if h_i(h_i_length) ~= length(S)
h_i_length = h_i_length + 1;
h_i(h_i_length) = length(S);
end
% Some final sanity checks - as indicated by Theorem 8.
% Raise an error if these checks fail!
% Also remember that gs(1) in the MATLAB code corresponds with gs(0).
if strcmpi(type, 'exhaustive')
% Theorem 8 - check that gs(h_m - 1) <= h_m-1
if gs(h_i(h_i_length) - 1 + 1) > h_i(h_i_length-1)
error(['Check failed for exhaustive sequence: ' ...
'Require: gs(h_m - 1) <= h_m-1']);
end
else
% Sequence type is 'primitive'
% Theorem 8 - check that gs(h_m - 1) = gs(h_m-1)
if gs(h_i(h_i_length) - 1 + 1) ~= gs(h_i(h_i_length-1) + 1)
error(['Check failed for primitive sequence: ' ...
'Require: gs(h_m - 1) = gs(h_m-1)']);
end
end
%% Use the terminal points to construct the production sequence.
% Note the first value in h_i is h_0, so its length is one more than the
% length of the production history.
H = cell([1 (h_i_length-1)]);
for k = 1:(h_i_length-1)
H{k} = S((h_i(k)+1):h_i(k+1));
end
%% Hence calculate the complexity.
if normalize
% Normalized complexity
C = length(H) / (n / log2(n));
else
% Un-normalized complexity
C = length(H);
end
%% Eigenfunction is returned.
% The (redundant) first value (gs(0) = 0) is removed first.
gs = gs(2:end);
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
metrics.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/sample_entry/metrics.m
| 5,892 |
utf_8
|
c0496681f837dba38f12fff9b12fd0d9
|
% //This software is licensed under the BSD 3 Clause license: http://opensource.org/licenses/BSD-3-Clause
%
%
% //Copyright (c) 2013, University of Oxford
% //All rights reserved.
%
% //Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
%
% //Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
% //Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
% //Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
% //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% The method implemented in this file has been patented by their original
% authors. Commercial use of this code is thus strongly not
% recocomended.
%
% //Authors: Gari D Clifford -
% // Roberta Colloca -
% // Julien Oster -
function [OriginCount,IrrEv,PACEv] = metrics( dRR )
% This function:
% 1) Takes the dRR intervals series and build a 2D
% histogram of {dRR(i),dRR(i-1)};
% 2) The histogram is marked with 13 segments;
% 3) The number of non empty bins ( BinCountX=BPX ) and the
% number of {dRR(i),dRR(i-1)} ( PointCountX=PCX ) are computed,
% for each segment;
% 4) BPX and PCX are used to extract the metrics: IrregularityEvidence(IrrEv)
% and PACEvidence (PACEv)
%
% Detailed explanation
% INPUTS
% dRR: Delta RR series (column vector)
%
% OUTPUTS
% OriginCount: Number of points in the bin containing the Origin
% IrrEv: Irregularity Evidence
% PACEv: PAC Evidence
%
% The 2D histogram of the {dRR(i),dRR(i-1)} values is built using 30*30
% bins corresponding to a binSize=0.04 s:
% x axis variable -> actual dRR interval
% y axis variable -> previous dRR interval
%
% The histogram is marked with 13 segments (0,..,12).
% For each segment:
%
% BinCountX= number of non empty bins in the Xth segment
% PointCountX= number of {dRR(i),dRR(i-1)} in the Xth segment
%
% are computed.
% dRR={dRR(i),dRR(i-1)}
dRR=[dRR(2:length(dRR),1) dRR(1:length(dRR)-1,1)];
% COMPUTE OriginCount
OCmask=0.02;
os=sum(abs(dRR)<=OCmask,2);
OriginCount=sum(os==2);
% DELETE OUTLIERS |dRR|>=1.5
OLmask=1.5;
dRRnew=[];
j=1;
for i=1:size(dRR,1)
if sum(abs(dRR(i,:))>=OLmask)==0
dRRnew(j,:)=dRR(i,:);
j=j+1;
end
end
if size(dRRnew)==0
dRRnew = [0 0];
end
% BUILD HISTOGRAM
% Specify bin centers of the histogram
bin_c=-0.58:0.04:0.58;
% Three dimensional histogram of bivariate data
Z = hist3(dRRnew, {bin_c bin_c});
% COMPUTE POINT COUNT ZERO
%O1=sum(sum(Z(14,15:16)));
%O2=sum(sum(Z(15:16,14:17)));
%O3=sum(sum(Z(17,15:16)));
%PC0=O1+O2+O3;
% Clear SegmentZero
Z(14,15:16)=0;
Z(15:16,14:17)=0;
Z(17,15:16)=0;
% [X,Y]=meshgrid(-0.58:0.04:0.58, -0.58:0.04:0.58);
% surf(X,Y, Z);
% axis tight
% xlabel('dRR(i-1)')
% ylabel('dRR(i)')
%COMPUTE BinCount12
%COMPUTE PointCount12
% Z2 contains all the bins belonging to the II quadrant of Z
Z2=Z(16:30,16:30);
[BC12,PC12,sZ2] = BPcount( Z2 );
Z(16:30,16:30)=sZ2;
%COMPUTE BinCount11
%COMPUTE PointCount11
%Z3 cointains points belonging to the III quadrant of Z
Z3=Z(16:30,1:15);
Z3=fliplr(Z3);
[BC11,PC11,sZ3] = BPcount( Z3 );
Z(16:30,1:15)=fliplr(sZ3);
%COMPUTE BinCount10
%COMPUTE PointCount10
%Z4 cointains points belonging to the IV quadrant of Z
Z4=Z(1:15,1:15);
[BC10,PC10,sZ4] = BPcount( Z4 );
Z(1:15,1:15)=sZ4;
%COMPUTE BinCount9
%COMPUTE PointCount9
%Z1 cointains points belonging to the I quadrant of Z
Z1=Z(1:15,16:30);
Z1=fliplr(Z1);
[BC9,PC9,sZ1] = BPcount( Z1 );
Z(1:15,16:30)=fliplr(sZ1);
%COMPUTE BinCount5
BC5=sum(sum(Z(1:15,14:17)~=0));
%COMPUTE PointCount5
PC5=sum(sum(Z(1:15,14:17)));
%COMPUTE BinCount7
BC7=sum(sum(Z(16:30,14:17)~=0));
%COMPUTE PointCount7
PC7=sum(sum(Z(16:30,14:17)));
%COMPUTE BinCount6
BC6=sum(sum(Z(14:17,1:15)~=0));
%Compute PointCount6
PC6=sum(sum(Z(14:17,1:15)));
%COMPUTE BinCount8
BC8=sum(sum(Z(14:17,16:30)~=0));
%COMPUTE PointCount8
PC8=sum(sum(Z(14:17,16:30)));
% CLEAR SEGMENTS 5, 6, 7, 8
% Clear segments 6 and 8
Z(14:17,:)=0;
%Clear segments 5 and 7
Z(:,14:17)=0;
% COMPUTE BinCount2
BC2=sum(sum(Z(1:13,1:13)~=0));
% COMPUTE PointCount2
PC2=sum(sum(Z(1:13,1:13)));
% COMPUTE BinCount1
BC1=sum(sum(Z(1:13,18:30)~=0));
% COMPUTE PointCount1
PC1=sum(sum(Z(1:13,18:30)));
% COMPUTE BinCount3
BC3=sum(sum(Z(18:30,1:13)~=0));
%COMPUTE PointCount3
PC3=sum(sum(Z(18:30,1:13)));
% COMPUTE BinCount4
BC4=sum(sum(Z(18:30,18:30)~=0));
% COMPUTE PointCount4
PC4=sum(sum(Z(18:30,18:30)));
% COMPUTE IrregularityEvidence
IrrEv=BC1+BC2+BC3+BC4+...
BC5+BC6+BC7+BC8+...
BC9+BC10+BC11+BC12;
% COMPUTE PACEvidence
PACEv=(PC1-BC1)+(PC2-BC2)+(PC3-BC3)+(PC4-BC4)+...
(PC5-BC5)+(PC6-BC6)+(PC10-BC10)-...
(PC7-BC7)-(PC8-BC8)-(PC12-BC12);
end
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
BPcount.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/sample_entry/BPcount.m
| 2,459 |
utf_8
|
587edb21d3cebe075fa99c07a8390363
|
% //This software is licensed under the BSD 3 Clause license: http://opensource.org/licenses/BSD-3-Clause
%
%
% //Copyright (c) 2013, University of Oxford
% //All rights reserved.
%
% //Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
%
% //Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
% //Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
% //Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
% //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% The method implemented in this file has been patented by their original
% authors. Commercial use of this code is thus strongly not
% recocomended.
%
% //Authors: Gari D Clifford -
% // Roberta Colloca -
% // Julien Oster -
function [BC,PC,sZ] = BPcount( sZ )
% BPcount counts the number of non empty bins (BC) in the matrix Z and
% the number of {dRR(i),dRR(i-1)} in the same region (PC) and deletes
% the counted points from the matrix Z
%bdc is the BIN diagonal count: number of non empty bins contained in
%the i-th diagonal of Z
bdc=0;
BC=0;
%pdc is the POINTS diagonal count: number of {dRR(i),dRR(i-1)} contained in
%the i-th diagonal of Z
pdc=0;
PC=0;
for i=-2:2
bdc=sum(diag(sZ,i)~=0);
pdc=sum(diag(sZ,i));
BC=BC+bdc;
PC=PC+pdc;
sZ=sZ-diag(diag(sZ,i),i);
end
end
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
comp_dRR.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/sample_entry/comp_dRR.m
| 2,386 |
utf_8
|
f89ecc65ebc8d408b0e33413b7c15127
|
% //This software is licensed under the BSD 3 Clause license: http://opensource.org/licenses/BSD-3-Clause
%
%
% //Copyright (c) 2013, University of Oxford
% //All rights reserved.
%
% //Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
%
% //Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
% //Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
% //Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
% //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% The method implemented in this file has been patented by their original
% authors. Commercial use of this code is thus strongly not
% recocomended.
%
% //Authors: Gari D Clifford -
% // Roberta Colloca -
% // Julien Oster -
function [ dRR_s ] = comp_dRR( data )
% RR_s(:,1)=RR(i) and RR_s(:,2)=RR(i-1)
RR_s=[data(2:length(data),1) data(1:length(data)-1,1)];
dRR_s=zeros(length(data)-1, 1);
% Normalization factors (normalize according to the heart rate)
k1=2;
k2=0.5;
for i=1:length(RR_s)
if sum(RR_s(i,:)<0.500)>=1
dRR_s(i,1)=k1*(RR_s(i,1)-RR_s(i,2));
else if sum(RR_s(i,:)>1)>=1
dRR_s(i,1)=k2*(RR_s(i,1)-RR_s(i,2));
else
dRR_s(i,1)=RR_s(i,1)-RR_s(i,2);
end
end
end
end
|
github
|
fernandoandreotti/cinc-challenge2017-master
|
comput_AFEv.m
|
.m
|
cinc-challenge2017-master/featurebased-approach/subfunctions/lib/sample_entry/comput_AFEv.m
| 2,289 |
utf_8
|
e58e29bd082b0fe4560dc416303541b7
|
% //This software is licensed under the BSD 3 Clause license: http://opensource.org/licenses/BSD-3-Clause
%
%
% //Copyright (c) 2013, University of Oxford
% //All rights reserved.
%
% //Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
%
% //Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
% //Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
% //Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
% //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
% The method implemented in this file has been patented by their original
% authors. Commercial use of this code is thus strongly not
% recocomended.
%
% //Authors: Gari D Clifford -
% // Roberta Colloca -
% // Julien Oster -
function AFEv = comput_AFEv(segment)
%comput_AFEv takes the RR intervals segment (column vector)
%and computes AFEv
%Inputs
%segment: RR intervals segment (column vector)
%Output
%AFEv: feature for detection of Atrial Fibrillation
%Compute dRR intervals series
dRR=comp_dRR(segment);
%Compute metrics
[OriginCount,IrrEv,PACEv]=metrics(dRR);
%Compute AFEvidence
AFEv=IrrEv-OriginCount-2*PACEv;
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_publishing.m
|
.m
|
numerical-tours-master/matlab/m_files/perform_publishing.m
| 8,391 |
utf_8
|
778c9d6ab67fb9f48a7acba7dba2f3d0
|
function perform_publishing(name, options)
% perform_publishing - publish a file to HTML format
%
% perform_publishing(name, options);
%
% If name is empty, process all the files (and also zip all toolboxes).
%
% options.rep set output directory (default '../../../numerical-tours-site/matlab/')
% options.repprivate set output directory for exercices (default '../solutions/')
% options.stylesheet set XSL stylesheet path.
% options.format set output format (default 'html').
%
% To put part of code that are not taken into account during publishing,
% put them as
% %CMT
% ...
% %CMT
%
% To put part of code that are release as exercises, put them as
% %EXO
% ...
% %EXO
%
% Copyright (c) 2008 Gabriel Peyre
path('../toolbox_general/', path);
options.null = 0;
if nargin<1 || isempty(name)
% batch processing
% list_ext = {'coding_' 'introduction_' 'image_' 'audio_' 'wavelet_' 'sparsity_' ...
% 'denoising_' 'inverse_' 'graphics_' 'multidim_' 'mesh_' 'variational_' 'fastmarching_'};
list_ext = {'audio' 'coding' 'cs' 'denoisingadv' 'denoisingsimp' 'denoisingwav' 'fastmarching' ...
'graphics' 'introduction' 'inverse' ...
'meshdeform' 'meshproc' 'meshwav' 'multidim' 'numerics' ...
'optim' 'optimaltransp' 'segmentation' 'shapes' ...
'sparsity' 'wavelet'};
a = dir('*_*.m');
for i=1:length(a)
name = a(i).name;
for k=1:length(list_ext)
if not(isempty( findstr(name, list_ext{k}) ))
disp(['---> Publishing ' name ' ...']);
perform_publishing(name(1:end-2));
end
end
end
% zip all toolbox files
perform_toolbox_zipping();
return;
end
if iscell(name)
for i=1:length(name)
disp(['---> Publishing ' name{i} ' ...']);
perform_publishing(name{i}, options);
end
return;
end
if not(isempty(strfind(name, '*')))
a = dir([name '.m']);
name = {};
for i=1:length(a)
name{end+1} = a(i).name(1:end-2);
end
perform_publishing(name, options);
return;
end
%% set up path
% directory where the wavelet-tour web site is
repweb = getoptions(options, 'rep', '../../../numerical-tours-site/matlab/');
% directory where the specific publishing is made
rep = [repweb name '/'];
if not(exist(rep))
mkdir(rep);
end
% directory for the exercices to be stored
repprivate = getoptions(options, 'repprivate', '../solutions/');
reppriv = [ repprivate name '/'];
if not(exist(reppriv))
mkdir(reppriv);
end
% open files
fid = fopen([name '.m'], 'rt');
name_out = 'index';
fidout = fopen([repweb name_out '.m'], 'wt');
if fid<0
error(['Cannot open ' name '.m.']);
end
% copy style files
if 0
copyfile([repweb 'style.css '],[rep 'style.css']);
else
str = ['cp ' repweb 'style.css ' rep 'style.css'];
% system( str );
end
%% First pre-process the file for publishing
exo_num = 0;
% output_line(fidout, '% special publishing token\npublishing_time = 1;\n\n');
while true
s = fgets(fid);
if not(isstr(s))
break;
end
if exo_mode(s)
% SPECIAL EXERCICE MODE
exo_num = exo_num + 1;
% Create a specific
process_exercice(fid, fidout, exo_num, repweb, reppriv, name);
elseif cmt_mode(s)
% SPECIAL CMT MODE
process_comment(fid);
elseif header_mode(s)
% SPECIAL header more
process_header(fidout, s);
else
s = strrep(s,'\','\\');
output_line(fidout, s);
end
end
fclose(fid);
fclose(fidout);
%% do the publishing
opts.format = getoptions(options, 'format', 'html');
if not(strcmp(opts.format, 'latex'))
opts.stylesheet = getoptions(options, 'stylesheet', [repweb 'nt.xsl']);
opts.stylesheet = [pwd '/' opts.stylesheet];
end
%filename = [repweb name_out '.m'];
opts.outputDir = [pwd '/' rep];
% opts.format = 'xml';
path(repweb, path);
file = publish([name_out '.m'],opts);
% web(file); % uncomment for display
delete([repweb 'exo*.m']);
delete([repweb name_out '.m']);
% make the name of the output file index.html
% movefile([opts.outputDir '/' name_out '.html'], [opts.outputDir '/index.html']);
%% do the online publishing
% disp('Performing online publishing (might take some time) ...');
% perform_online_publishing(name);
%% do the python conversion
if 0
str = ['python ../../scripts/m2nb_converter.py ./' name '.m ../'];
system(str);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% AUX FUNCTIONS %%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
function output_line(fid,s)
s = strrep(s,'%','%%');
fprintf(fid, s);
%%
function r = cmt_mode(s)
r = (length(s)>4 && strcmp(s(1:4),'%CMT'));
%%
function r = exo_mode(s)
r = (length(s)>4 && strcmp(s(1:4),'%EXO'));
%%
function r = header_mode(s)
r = (length(s)>28 && strcmp(s(1:28),'perform_toolbox_installation'));
%%
function process_header(fidout, s)
tbx = {};
if findstr(s, 'signal')
tbx{end+1} = 'signal';
end
if findstr(s, 'general')
tbx{end+1} = 'general';
end
if findstr(s, 'graph')
tbx{end+1} = 'graph';
end
if findstr(s, 'wavelet_meshes')
tbx{end+1} = 'wavelet_meshes';
end
if findstr(s, 'additional')
tbx{end+1} = 'additional';
end
output_line(fidout, '%% Installing toolboxes and setting up the path.\n\n');
% output_line(fidout, '%%\n%<? include ''../nt.sty''; ?>\n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% You need to download the following files: \n');
for i=1:length(tbx)
output_line(fidout, ['% <../toolbox_' tbx{i} '.zip ' tbx{i} ' toolbox>']);
if i<length(tbx)-1
output_line(fidout, ', \n');
elseif i==length(tbx)-1
output_line(fidout, ' and \n');
else
output_line(fidout, '.\n');
end
end
output_line(fidout, '\n%%\n');
output_line(fidout, '% You need to unzip these toolboxes in your working directory, so\n');
output_line(fidout, '% that you have \n');
for i=1:length(tbx)
output_line(fidout, ['% |toolbox_' tbx{i} '|']);
if i<length(tbx)-1
output_line(fidout, ', \n');
elseif i==length(tbx)-1
output_line(fidout, ' and \n');
else
output_line(fidout, '\n');
end
end
output_line(fidout, '% in your directory.\n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% *For Scilab user:* you must replace the Matlab comment ''%'' by its Scilab\n');
output_line(fidout, '% counterpart ''//''.\n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% *Recommandation:* You should create a text file named for instance |numericaltour.sce| (in Scilab) or |numericaltour.m| (in Matlab) to write all the\n');
output_line(fidout, '% Scilab/Matlab command you want to execute. Then, simply run |exec(''numericaltour.sce'');| (in Scilab) or |numericaltour;| (in Matlab) to run the commands. \n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% Execute this line only if you are using Matlab.\n\n');
output_line(fidout, 'getd = @(p)path(p,path); % scilab users must *not* execute this\n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% Then you can add the toolboxes to the path.\n\n');
for i=1:length(tbx)
output_line(fidout, ['getd(''toolbox_' tbx{i} '/'');\n']);
end
%%
function process_comment(fid)
while true
s = fgets(fid);
if not(isstr(s)) || cmt_mode(s)
break;
end
end
%%
function process_exercice(fid, fidout, exo_num, rep, reppriv, curname)
% create a new file
% The m file is created and executed in rep
% and also copied to reppriv.
name = ['exo' num2str(exo_num)];
filename = [name '.m'];
fidexo = fopen([rep filename], 'wt');
output_line(fidout, ['%%\n% _Exercice ' num2str(exo_num) ':_' ]);
output_line(fidout, [' (<../missing-exo/ check the solution>)\n']);
% process files
while true
s = fgets(fid);
if not(isstr(s)) || exo_mode(s)
break;
end
s = strrep(s,'#',num2str(exo_num));
s = strrep(s,'\','\\');
if length(s)>1 && strcmp(s(1:2), '%%')
s = s(2:end);
output_line(fidout, s);
else
output_line(fidexo, s);
end
end
output_line(fidout, ['\n' name ';\n']);
fclose(fidexo);
if 0
copyfile([rep filename],[reppriv filename]);
else
system(['cp ' rep filename ' ' reppriv filename]);
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_scilab_conversion.m
|
.m
|
numerical-tours-master/matlab/m_files/perform_scilab_conversion.m
| 2,210 |
utf_8
|
530502896e21ccb55e21856289190c35
|
function perform_scilab_conversion(name, outdir, toolbox_dir)
% perform_scilab_conversion - convert a matlab file to scilab
%
% perform_scilab_conversion(name);
%
% If name is empty, process all the files.
%
% Copyright (c) 2008 Gabriel Peyre
if nargin<2
outdir = '../scilab/';
end
if nargin<3
toolbox_dir = '../matlab/';
end
if nargin<1 || isempty(name)
% back processing
list_ext = {'coding_' 'introduction_' 'image_' 'audio_' 'wavelet_' 'sparsity_' 'cs_' ...
'denoising_' 'inverse_' 'graphics_' 'multidim_' 'meshproc_' 'meshdeform_' ...
'meshwav_' 'variational_' 'fastmarching_'};
a = dir('*_*.m');
for i=1:length(a)
name = a(i).name;
for k=1:length(list_ext)
if not(isempty( findstr(name, list_ext{k}) ))
disp(['---> Translating ' name ' ...']);
perform_scilab_conversion(name(1:end-2));
end
end
end
return;
end
fid = fopen([name '.m'], 'rt');
fidout = fopen([outdir name '.sce'], 'wt');
if fid<0
error(['Cannot open ' name '.m.']);
end
str1 = {'%' '\' 'getd(''' };
str2 = {'//' '\\' ['getd(''' toolbox_dir] };
while true
s = fgets(fid);
if s<0
break;
end
% remove comments and stufs
for i=1:length(str1)
s = strrep(s,str1{i},str2{i});
end
makeoutput = 1;
if length(s)>5 && strcmp(s(1:6), 'getd =')
makeoutput = 0;
end
if length(s)>28 && strcmp(s(1:28), 'perform_toolbox_installation')
process_header(fidout, s);
makeoutput = 0;
end
% write output
if makeoutput
fprintf(fidout, s);
end
end
fclose(fid);
fclose(fidout);
%%
function process_header(fidout, s)
tbx = {};
if findstr(s, 'signal')
tbx{end+1} = 'signal';
end
if findstr(s, 'general')
tbx{end+1} = 'general';
end
if findstr(s, 'graph')
tbx{end+1} = 'graph';
end
if findstr(s, 'wavelet_meshes')
tbx{end+1} = 'wavelet_meshes';
end
if findstr(s, 'additional')
tbx{end+1} = 'additional';
end
for i=1:length(tbx)
output_line(fidout, ['getd(''toolbox_' tbx{i} '/'');\n']);
end
%%
function output_line(fid,s)
s = strrep(s,'%','%%');
fprintf(fid, s);
|
github
|
alex-delalande/numerical-tours-master
|
dump_struct.m
|
.m
|
numerical-tours-master/matlab/m_files/toolbox_general/dump_struct.m
| 1,389 |
utf_8
|
746b6d65b8fc8c67e8cb806c235f5e6a
|
function fid = dump_struct(s,fid,header)
% dump_struct - dump the content of a struct to a file
%
% dump_struct(s,fid, header);
%
% Copyright (c) 2008 Gabriel Peyre
if nargin<3
header = '';
end
if isstr(fid)
fid = fopen(fid, 'a');
if fid<=0
error(['File ' fid ' does not exist.']);
end
end
if not(isempty(header))
fprintf(fid, '%s\n', header );
end
% central line (position of ':')
cl = 15;
if iscell(s)
for i=1:length(s)
fprintf(fid, '%s\n', convert_string(s{i},0) );
end
elseif isstruct(s)
s = orderfields(s);
f = fieldnames(s);
for i=1:length(f)
v = getfield(s,f{i});
fprintf(fid, '%s: %s\n', convert_string(f{i},cl), convert_string(v,0) );
end
else
error('Unknown type.');
end
if nargout==0
fclose(fid);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = convert_string(v,cl)
if nargin<2
cl = 15;
end
nmax = 10; % maximum of dumped string results
if isa(v, 'numeric')
% v = v(1);
s = [];
for i = 1:min(length(v(:)), nmax)
if mod(v,1)==0
s = [s int2str(v(i)) ' '];
else
s = [s num2str(v(i)) ' '];
end
end
if length(v(:))>nmax
s = [s '...'];
end
elseif isstr(v)
s = v;
else
s = '-';
end
% try to align on central line
d = cl - length(s);
if d>0
s = [repmat(' ',[1 d]) s];
end
|
github
|
alex-delalande/numerical-tours-master
|
poissrnd.m
|
.m
|
numerical-tours-master/matlab/m_files/toolbox_general/poissrnd.m
| 10,053 |
utf_8
|
64b00f80e484b0c01bfd50a87756f587
|
function r = poissrnd(lambda,m,n)
%POISSRND Random matrices from Poisson distribution.
% R = POISSRND(LAMBDA) returns a matrix of random numbers chosen
% from the Poisson distribution with parameter LAMBDA.
%
% The size of R is the size of LAMBDA. Alternatively,
% R = POISSRND(LAMBDA,M,N) returns an M by N matrix.
%
% POISSRND uses a waiting time method for small values of LAMBDA,
% and the method of Ahrens and Dieter for larger values of LAMBDA.
% References:
% [1] L. Devroye, "Non-Uniform Random Variate Generation",
% Springer-Verlag, 1986 page 504.
% Copyright 1993-2000 The MathWorks, Inc.
% $Revision: 2.9 $ $Date: 2000/07/28 19:33:02 $
if nargin < 1,
error('Requires at least one input argument.');
end
if nargin == 1
[errorcode rows columns] = rndcheck(1,1,lambda);
end
if nargin == 2
[errorcode rows columns] = rndcheck(2,1,lambda,m);
end
if nargin == 3
[errorcode rows columns] = rndcheck(3,1,lambda,m,n);
end
if errorcode > 0
error('Size information is inconsistent.');
end
if (prod(size(lambda)) == 1)
lambda = lambda(ones(rows*columns,1));
else
lambda = lambda(:);
end
%Initialize r to zero.
r = zeros(rows, columns);
j = (1:(rows*columns))'; % indices remaining to generate
% For large lambda, use the method of Ahrens and Dieter as
% described in Knuth, Volume 2, 1998 edition.
k = find(lambda >= 15);
if ~isempty(k)
alpha = 7/8;
lk = lambda(k);
m = floor(alpha * lk);
% Generate m waiting times, all at once
x = gamrnd(m,1);
t = x <= lk;
% If we did not overshoot, then the number of additional times
% has a Poisson distribution with a smaller mean.
r(k(t)) = m(t) + poissrnd(lk(t)-x(t));
% If we did overshoot, then the times up to m-1 are uniformly
% distributed on the interval to x, so the count of times less
% than lambda has a binomial distribution.
r(k(~t)) = binornd(m(~t)-1, lk(~t)./x(~t));
j(k) = [];
end
% For small lambda, generate and count waiting times.
p = zeros(length(j),1);
while ~isempty(j)
p = p - log(rand(length(j),1));
kc = [1:length(k)]';
t = (p < lambda(j));
j = j(t);
p = p(t);
r(j) = r(j) + 1;
end
% Return NaN if LAMBDA is negative.
r(lambda < 0) = NaN;
function [errorcode, rows, columns] = rndcheck(nargs,nparms,arg1,arg2,arg3,arg4,arg5)
%RNDCHECK error checks the argument list for the random number generators.
% B.A. Jones 1-22-93
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 2.5 $ $Date: 1997/11/29 01:46:40 $
sizeinfo = nargs - nparms;
errorcode = 0;
if nparms == 3
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
[r3 c3] = size(arg3);
end
if nparms == 2
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
end
if sizeinfo == 0
if nparms == 1
[rows columns] = size(arg1);
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg1);
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg3);
end
end
end
if sizeinfo == 1
scalararg1 = (prod(size(arg1)) == 1);
if nparms == 1
if prod(size(arg2)) ~= 2
errorcode = 2;
return;
end
if ~scalararg1 & arg2 ~= size(arg1)
errorcode = 3;
return;
end
if (arg2(1) < 0 | arg2(2) < 0 | arg2(1) ~= round(arg2(1)) | arg2(2) ~= round(arg2(2))),
errorcode = 4;
return;
end
rows = arg2(1);
columns = arg2(2);
end
if nparms == 2
if prod(size(arg3)) ~= 2
errorcode = 2;
return;
end
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if (arg3(1) < 0 | arg3(2) < 0 | arg3(1) ~= round(arg3(1)) | arg3(2) ~= round(arg3(2))),
errorcode = 4;
return;
end
if ~scalararg1
if any(arg3 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg3 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
else
rows = arg3(1);
columns = arg3(2);
end
end
if nparms == 3
if prod(size(arg4)) ~= 2
errorcode = 2;
return;
end
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if (arg4(1) < 0 | arg4(2) < 0 | arg4(1) ~= round(arg4(1)) | arg4(2) ~= round(arg4(2))),
errorcode = 4;
return;
end
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
if any(arg4 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg4 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
elseif ~scalararg3
if any(arg4 ~= size(arg3))
errorcode = 3;
return;
end
[rows columns] = size(arg3);
else
rows = arg4(1);
columns = arg4(2);
end
end
end
if sizeinfo == 2
if nparms == 1
scalararg1 = (prod(size(arg1)) == 1);
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg2 | columns ~= arg3
errorcode = 3;
return;
end
end
if (arg2 < 0 | arg3 < 0 | arg2 ~= round(arg2) | arg3 ~= round(arg3)),
errorcode = 4;
return;
end
rows = arg2;
columns = arg3;
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
else
if (arg3 < 0 | arg4 < 0 | arg3 ~= round(arg3) | arg4 ~= round(arg4)),
errorcode = 4;
return;
end
rows = arg3;
columns = arg4;
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg3
[rows columns] = size(arg3);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
else
if (arg4 < 0 | arg5 < 0 | arg4 ~= round(arg4) | arg5 ~= round(arg5)),
errorcode = 4;
return;
end
rows = arg4;
columns = arg5;
end
end
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_faces_reorientation.m
|
.m
|
numerical-tours-master/matlab/m_files/toolbox_general/perform_faces_reorientation.m
| 2,816 |
utf_8
|
2cf3d5c1ad6ea271b524352db5492c2c
|
function faces = perform_faces_reorientation(vertex,faces, options)
% perform_faces_reorientation - reorient the faces with respect to the center of the mesh
%
% faces = perform_faces_reorientation(vertex,faces, options);
%
% try to find a consistant reorientation for faces of a mesh.
%
% if options.method = 'fast', then use a fast non accurate method
% if options.method = 'slow', then use a slow exact method
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
method = getoptions(options, 'method', 'fast');
[vertex,faces] = check_face_vertex(vertex,faces);
n = size(vertex,2);
m = size(faces,2);
if strcmp(method, 'fast')
% compute the center of mass of the mesh
G = mean(vertex,2);
% center of faces
Cf = (vertex(:,faces(1,:)) + vertex(:,faces(2,:)) + vertex(:,faces(3,:)))/3;
Cf = Cf - repmat(G,[1 m]);
% normal to the faces
V1 = vertex(:,faces(2,:))-vertex(:,faces(1,:));
V2 = vertex(:,faces(3,:))-vertex(:,faces(1,:));
N = [V1(2,:).*V2(3,:) - V1(3,:).*V2(2,:) ; ...
-V1(1,:).*V2(3,:) + V1(3,:).*V2(1,:) ; ...
V1(1,:).*V2(2,:) - V1(2,:).*V2(1,:) ];
% dot product
s = sign(sum(N.*Cf));
% reverse faces
I = find(s>0);
faces(:,I) = faces(3:-1:1,I);
return
end
options.method = 'fast';
faces = perform_faces_reorientation(vertex,faces, options);
fring = compute_face_ring(faces);
tag = zeros(m,1)-1;
heap = 1;
for i=1:m
if m>100
progressbar(i,m);
end
if isempty(heap)
I = find(tag==-1);
if isempty(I)
error('Problem');
end
heap = I(1);
end
f = heap(end); heap(end) = [];
if tag(f)==1
warning('Problem');
end
tag(f) = 1; % computed
fr = fring{f};
fr = fr(tag(fr)==-1);
tag(fr)=0;
heap = [heap fr];
for k=fr(:)'
% see if re-orientation is needed
if check_orientation(faces(:,k), faces(:,f))==1
faces(1:2,k) = faces(2:-1:1,k);
end
end
end
if not(isempty(heap)) || not(isempty(find(tag<1)))
warning('Problem');
end
% try to see if face are facing in the correct direction
[normal,normalf] = compute_normal(vertex,faces);
a = mean(vertex,2);
a = repmat(a, [1 n]);
dp = sign(sum(normal.*a,1));
if sum(dp>0)<sum(dp<0)
faces(1:2,:) = faces(2:-1:1,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function o = check_orientation(f1,f2)
i1 = 0; j1 = 0;
for i=1:3
for j=1:3
if f1(i)==f2(j)
i1 = i; j1 = j;
break;
end
end
if i1~=0
break;
end
end
if i1==0
error('Problem.');
end
ia = mod(i1,3)+1;
ja = mod(j1,3)+1;
ib = mod(i1-2,3)+1;
jb = mod(j1-2,3)+1;
if f1(ia)==f2(ja) || f1(ib)==f2(jb)
o=1;
else
o = -1;
end
|
github
|
alex-delalande/numerical-tours-master
|
gamrnd.m
|
.m
|
numerical-tours-master/matlab/m_files/toolbox_general/gamrnd.m
| 10,861 |
utf_8
|
9b8a786919b4ddfbebdf74985b19ebb2
|
function r = gamrnd(a,b,m,n);
%GAMRND Random matrices from gamma distribution.
% R = GAMRND(A,B) returns a matrix of random numbers chosen
% from the gamma distribution with parameters A and B.
% The size of R is the common size of A and B if both are matrices.
% If either parameter is a scalar, the size of R is the size of the other
% parameter. Alternatively, R = GAMRND(A,B,M,N) returns an M by N matrix.
%
% mu=A*B is the mean.
% sigma^2=A*B^2 is the variance.
%
%
% Some references refer to the gamma distribution
% with a single parameter. This corresponds to GAMRND
% with B = 1. (See Devroye, pages 401-402.)
% GAMRND uses a rejection or an inversion method depending on the
% value of A.
% References:
% [1] L. Devroye, "Non-Uniform Random Variate Generation",
% Springer-Verlag, 1986
% B.A. Jones 2-1-93
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 2.8 $ $Date: 1998/09/30 19:12:40 $
if nargin < 2,
error('Requires at least two input arguments.');
end
if nargin == 2
[errorcode rows columns] = rndcheck(2,2,a,b);
end
if nargin == 3
[errorcode rows columns] = rndcheck(3,2,a,b,m);
end
if nargin == 4
[errorcode rows columns] = rndcheck(4,2,a,b,m,n);
end
if errorcode > 0
error('Size information is inconsistent.');
end
% Initialize r to zero.
lth = rows*columns;
r = zeros(lth,1);
a = a(:); b = b(:);
scalara = (length(a) == 1);
if scalara
a = a*ones(lth,1);
end
scalarb = (length(b) == 1);
if scalarb
b = b*ones(lth,1);
end
% If a == 1, then gamma is exponential. (Devroye, page 405).
k = find(a == 1);
if any(k)
r(k) = -b(k) .* log(rand(size(k)));
end
k = find(a < 1 & a > 0);
% (Devroye, page 418 Johnk's generator)
if any(k)
c = zeros(lth,1);
d = zeros(lth,1);
c(k) = 1 ./ a(k);
d(k) = 1 ./ (1 - a(k));
accept = k;
while ~isempty(accept)
u = rand(size(accept));
v = rand(size(accept));
x = u .^ c(accept);
y = v .^ d(accept);
k1 = find((x + y) <= 1);
if ~isempty(k1)
e = -log(rand(size(k1)));
r(accept(k1)) = e .* x(k1) ./ (x(k1) + y(k1));
accept(k1) = [];
end
end
r(k) = r(k) .* b(k);
end
% Use a rejection method for a > 1.
k = find(a > 1);
% (Devroye, page 410 Best's algorithm)
bb = zeros(size(a));
c = bb;
if any(k)
bb(k) = a(k) - 1;
c(k) = 3 * a(k) - 3/4;
accept = k;
count = 1;
while ~isempty(accept)
m = length(accept);
u = rand(m,1);
v = rand(m,1);
w = u .* (1 - u);
y = sqrt(c(accept) ./ w) .* (u - 0.5);
x = bb(accept) + y;
k1 = find(x >= 0);
if ~isempty(k1)
z = 64 * (w .^ 3) .* (v .^ 2);
k2 = (z(k1) <= (1 - 2 * (y(k1) .^2) ./ x(k1)));
k3 = k1(find(k2));
r(accept(k3)) = x(k3);
k4 = k1(find(~k2));
k5 = k4(find(log(z(k4)) <= (2*(bb(accept(k4)).*log(x(k4)./bb(accept(k4)))-y(k4)))));
r(accept(k5)) = x(k5);
omit = [k3; k5];
accept(omit) = [];
end
end
r(k) = r(k) .* b(k);
end
% Return NaN if a or b is not positive.
r(b <= 0 | a <= 0) = NaN;
r = reshape(r,rows,columns);
function [errorcode, rows, columns] = rndcheck(nargs,nparms,arg1,arg2,arg3,arg4,arg5)
%RNDCHECK error checks the argument list for the random number generators.
% B.A. Jones 1-22-93
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 2.5 $ $Date: 1997/11/29 01:46:40 $
sizeinfo = nargs - nparms;
errorcode = 0;
if nparms == 3
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
[r3 c3] = size(arg3);
end
if nparms == 2
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
end
if sizeinfo == 0
if nparms == 1
[rows columns] = size(arg1);
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg1);
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg3);
end
end
end
if sizeinfo == 1
scalararg1 = (prod(size(arg1)) == 1);
if nparms == 1
if prod(size(arg2)) ~= 2
errorcode = 2;
return;
end
if ~scalararg1 & arg2 ~= size(arg1)
errorcode = 3;
return;
end
if (arg2(1) < 0 | arg2(2) < 0 | arg2(1) ~= round(arg2(1)) | arg2(2) ~= round(arg2(2))),
errorcode = 4;
return;
end
rows = arg2(1);
columns = arg2(2);
end
if nparms == 2
if prod(size(arg3)) ~= 2
errorcode = 2;
return;
end
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if (arg3(1) < 0 | arg3(2) < 0 | arg3(1) ~= round(arg3(1)) | arg3(2) ~= round(arg3(2))),
errorcode = 4;
return;
end
if ~scalararg1
if any(arg3 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg3 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
else
rows = arg3(1);
columns = arg3(2);
end
end
if nparms == 3
if prod(size(arg4)) ~= 2
errorcode = 2;
return;
end
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if (arg4(1) < 0 | arg4(2) < 0 | arg4(1) ~= round(arg4(1)) | arg4(2) ~= round(arg4(2))),
errorcode = 4;
return;
end
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
if any(arg4 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg4 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
elseif ~scalararg3
if any(arg4 ~= size(arg3))
errorcode = 3;
return;
end
[rows columns] = size(arg3);
else
rows = arg4(1);
columns = arg4(2);
end
end
end
if sizeinfo == 2
if nparms == 1
scalararg1 = (prod(size(arg1)) == 1);
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg2 | columns ~= arg3
errorcode = 3;
return;
end
end
if (arg2 < 0 | arg3 < 0 | arg2 ~= round(arg2) | arg3 ~= round(arg3)),
errorcode = 4;
return;
end
rows = arg2;
columns = arg3;
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
else
if (arg3 < 0 | arg4 < 0 | arg3 ~= round(arg3) | arg4 ~= round(arg4)),
errorcode = 4;
return;
end
rows = arg3;
columns = arg4;
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg3
[rows columns] = size(arg3);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
else
if (arg4 < 0 | arg5 < 0 | arg4 ~= round(arg4) | arg5 ~= round(arg5)),
errorcode = 4;
return;
end
rows = arg4;
columns = arg5;
end
end
end
|
github
|
alex-delalande/numerical-tours-master
|
binornd.m
|
.m
|
numerical-tours-master/matlab/m_files/toolbox_general/binornd.m
| 9,362 |
utf_8
|
0ca5d51eb461d57552c90487eab9946d
|
function r=binornd(n,p,mm,nn)
% BINORND Random matrices from a binomial distribution.
% R = BINORND(N,P,MM,NN) is an MM-by-NN matrix of random
% numbers chosen from a binomial distribution with parameters N and P.
%
% The size of R is the common size of N and P if both are matrices.
% If either parameter is a scalar, the size of R is the size of the other
% parameter.
% Alternatively, R = BINORND(N,P,MM,NN) returns an MM by NN matrix.
%
% The method is direct using the definition of the binomial
% distribution as a sum of Bernoulli random variables.
% References:
% [1] L. Devroye, "Non-Uniform Random Variate Generation",
% Springer-Verlag, 1986
% See Lemma 4.1 on page 428, method on page 524.
% B.A. Jones 1-12-93
% Copyright (c) 1993 by The MathWorks, Inc.
% $Revision: 1.1 $ $Date: 1993/05/24 18:53:37 $
if nargin < 2,
error('Requires at least two input arguments.');
end
if nargin == 2
[errorcode rows columns] = rndcheck(2,2,n,p);
end
if nargin == 3
[errorcode rows columns] = rndcheck(3,2,n,p,mm);
n = n(ones(mm(1),1),ones(mm(2),1));
p = p(ones(mm(1),1),ones(mm(2),1));
end
if nargin == 4
[errorcode rows columns] = rndcheck(4,2,n,p,mm,nn);
n = n(ones(mm,1),ones(nn,1));
p = p(ones(mm,1),ones(nn,1));
end
if errorcode > 0
error('Size information is inconsistent.');
end
r = zeros(rows,columns);
for i = 1:max(max(n))
u = rand(rows,columns);
k1 = find(n >= i);
k2 = find(u(k1) < p(k1));
r(k1(k2)) = r(k1(k2)) + 1;
end
k= find(p < 0 | p > 1 | n < 0);
if any(k)
r(k) = NaN * ones(size(k));
end
function [errorcode, rows, columns] = rndcheck(nargs,nparms,arg1,arg2,arg3,arg4,arg5)
%RNDCHECK error checks the argument list for the random number generators.
% B.A. Jones 1-22-93
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 2.5 $ $Date: 1997/11/29 01:46:40 $
sizeinfo = nargs - nparms;
errorcode = 0;
if nparms == 3
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
[r3 c3] = size(arg3);
end
if nparms == 2
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
end
if sizeinfo == 0
if nparms == 1
[rows columns] = size(arg1);
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg1);
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg3);
end
end
end
if sizeinfo == 1
scalararg1 = (prod(size(arg1)) == 1);
if nparms == 1
if prod(size(arg2)) ~= 2
errorcode = 2;
return;
end
if ~scalararg1 & arg2 ~= size(arg1)
errorcode = 3;
return;
end
if (arg2(1) < 0 | arg2(2) < 0 | arg2(1) ~= round(arg2(1)) | arg2(2) ~= round(arg2(2))),
errorcode = 4;
return;
end
rows = arg2(1);
columns = arg2(2);
end
if nparms == 2
if prod(size(arg3)) ~= 2
errorcode = 2;
return;
end
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if (arg3(1) < 0 | arg3(2) < 0 | arg3(1) ~= round(arg3(1)) | arg3(2) ~= round(arg3(2))),
errorcode = 4;
return;
end
if ~scalararg1
if any(arg3 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg3 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
else
rows = arg3(1);
columns = arg3(2);
end
end
if nparms == 3
if prod(size(arg4)) ~= 2
errorcode = 2;
return;
end
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if (arg4(1) < 0 | arg4(2) < 0 | arg4(1) ~= round(arg4(1)) | arg4(2) ~= round(arg4(2))),
errorcode = 4;
return;
end
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
if any(arg4 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg4 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
elseif ~scalararg3
if any(arg4 ~= size(arg3))
errorcode = 3;
return;
end
[rows columns] = size(arg3);
else
rows = arg4(1);
columns = arg4(2);
end
end
end
if sizeinfo == 2
if nparms == 1
scalararg1 = (prod(size(arg1)) == 1);
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg2 | columns ~= arg3
errorcode = 3;
return;
end
end
if (arg2 < 0 | arg3 < 0 | arg2 ~= round(arg2) | arg3 ~= round(arg3)),
errorcode = 4;
return;
end
rows = arg2;
columns = arg3;
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
else
if (arg3 < 0 | arg4 < 0 | arg3 ~= round(arg3) | arg4 ~= round(arg4)),
errorcode = 4;
return;
end
rows = arg3;
columns = arg4;
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg3
[rows columns] = size(arg3);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
else
if (arg4 < 0 | arg5 < 0 | arg4 ~= round(arg4) | arg5 ~= round(arg5)),
errorcode = 4;
return;
end
rows = arg4;
columns = arg5;
end
end
end
|
github
|
alex-delalande/numerical-tours-master
|
dump_struct.m
|
.m
|
numerical-tours-master/matlab/toolbox_general/dump_struct.m
| 1,389 |
utf_8
|
746b6d65b8fc8c67e8cb806c235f5e6a
|
function fid = dump_struct(s,fid,header)
% dump_struct - dump the content of a struct to a file
%
% dump_struct(s,fid, header);
%
% Copyright (c) 2008 Gabriel Peyre
if nargin<3
header = '';
end
if isstr(fid)
fid = fopen(fid, 'a');
if fid<=0
error(['File ' fid ' does not exist.']);
end
end
if not(isempty(header))
fprintf(fid, '%s\n', header );
end
% central line (position of ':')
cl = 15;
if iscell(s)
for i=1:length(s)
fprintf(fid, '%s\n', convert_string(s{i},0) );
end
elseif isstruct(s)
s = orderfields(s);
f = fieldnames(s);
for i=1:length(f)
v = getfield(s,f{i});
fprintf(fid, '%s: %s\n', convert_string(f{i},cl), convert_string(v,0) );
end
else
error('Unknown type.');
end
if nargout==0
fclose(fid);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = convert_string(v,cl)
if nargin<2
cl = 15;
end
nmax = 10; % maximum of dumped string results
if isa(v, 'numeric')
% v = v(1);
s = [];
for i = 1:min(length(v(:)), nmax)
if mod(v,1)==0
s = [s int2str(v(i)) ' '];
else
s = [s num2str(v(i)) ' '];
end
end
if length(v(:))>nmax
s = [s '...'];
end
elseif isstr(v)
s = v;
else
s = '-';
end
% try to align on central line
d = cl - length(s);
if d>0
s = [repmat(' ',[1 d]) s];
end
|
github
|
alex-delalande/numerical-tours-master
|
poissrnd.m
|
.m
|
numerical-tours-master/matlab/toolbox_general/poissrnd.m
| 10,053 |
utf_8
|
64b00f80e484b0c01bfd50a87756f587
|
function r = poissrnd(lambda,m,n)
%POISSRND Random matrices from Poisson distribution.
% R = POISSRND(LAMBDA) returns a matrix of random numbers chosen
% from the Poisson distribution with parameter LAMBDA.
%
% The size of R is the size of LAMBDA. Alternatively,
% R = POISSRND(LAMBDA,M,N) returns an M by N matrix.
%
% POISSRND uses a waiting time method for small values of LAMBDA,
% and the method of Ahrens and Dieter for larger values of LAMBDA.
% References:
% [1] L. Devroye, "Non-Uniform Random Variate Generation",
% Springer-Verlag, 1986 page 504.
% Copyright 1993-2000 The MathWorks, Inc.
% $Revision: 2.9 $ $Date: 2000/07/28 19:33:02 $
if nargin < 1,
error('Requires at least one input argument.');
end
if nargin == 1
[errorcode rows columns] = rndcheck(1,1,lambda);
end
if nargin == 2
[errorcode rows columns] = rndcheck(2,1,lambda,m);
end
if nargin == 3
[errorcode rows columns] = rndcheck(3,1,lambda,m,n);
end
if errorcode > 0
error('Size information is inconsistent.');
end
if (prod(size(lambda)) == 1)
lambda = lambda(ones(rows*columns,1));
else
lambda = lambda(:);
end
%Initialize r to zero.
r = zeros(rows, columns);
j = (1:(rows*columns))'; % indices remaining to generate
% For large lambda, use the method of Ahrens and Dieter as
% described in Knuth, Volume 2, 1998 edition.
k = find(lambda >= 15);
if ~isempty(k)
alpha = 7/8;
lk = lambda(k);
m = floor(alpha * lk);
% Generate m waiting times, all at once
x = gamrnd(m,1);
t = x <= lk;
% If we did not overshoot, then the number of additional times
% has a Poisson distribution with a smaller mean.
r(k(t)) = m(t) + poissrnd(lk(t)-x(t));
% If we did overshoot, then the times up to m-1 are uniformly
% distributed on the interval to x, so the count of times less
% than lambda has a binomial distribution.
r(k(~t)) = binornd(m(~t)-1, lk(~t)./x(~t));
j(k) = [];
end
% For small lambda, generate and count waiting times.
p = zeros(length(j),1);
while ~isempty(j)
p = p - log(rand(length(j),1));
kc = [1:length(k)]';
t = (p < lambda(j));
j = j(t);
p = p(t);
r(j) = r(j) + 1;
end
% Return NaN if LAMBDA is negative.
r(lambda < 0) = NaN;
function [errorcode, rows, columns] = rndcheck(nargs,nparms,arg1,arg2,arg3,arg4,arg5)
%RNDCHECK error checks the argument list for the random number generators.
% B.A. Jones 1-22-93
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 2.5 $ $Date: 1997/11/29 01:46:40 $
sizeinfo = nargs - nparms;
errorcode = 0;
if nparms == 3
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
[r3 c3] = size(arg3);
end
if nparms == 2
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
end
if sizeinfo == 0
if nparms == 1
[rows columns] = size(arg1);
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg1);
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg3);
end
end
end
if sizeinfo == 1
scalararg1 = (prod(size(arg1)) == 1);
if nparms == 1
if prod(size(arg2)) ~= 2
errorcode = 2;
return;
end
if ~scalararg1 & arg2 ~= size(arg1)
errorcode = 3;
return;
end
if (arg2(1) < 0 | arg2(2) < 0 | arg2(1) ~= round(arg2(1)) | arg2(2) ~= round(arg2(2))),
errorcode = 4;
return;
end
rows = arg2(1);
columns = arg2(2);
end
if nparms == 2
if prod(size(arg3)) ~= 2
errorcode = 2;
return;
end
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if (arg3(1) < 0 | arg3(2) < 0 | arg3(1) ~= round(arg3(1)) | arg3(2) ~= round(arg3(2))),
errorcode = 4;
return;
end
if ~scalararg1
if any(arg3 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg3 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
else
rows = arg3(1);
columns = arg3(2);
end
end
if nparms == 3
if prod(size(arg4)) ~= 2
errorcode = 2;
return;
end
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if (arg4(1) < 0 | arg4(2) < 0 | arg4(1) ~= round(arg4(1)) | arg4(2) ~= round(arg4(2))),
errorcode = 4;
return;
end
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
if any(arg4 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg4 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
elseif ~scalararg3
if any(arg4 ~= size(arg3))
errorcode = 3;
return;
end
[rows columns] = size(arg3);
else
rows = arg4(1);
columns = arg4(2);
end
end
end
if sizeinfo == 2
if nparms == 1
scalararg1 = (prod(size(arg1)) == 1);
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg2 | columns ~= arg3
errorcode = 3;
return;
end
end
if (arg2 < 0 | arg3 < 0 | arg2 ~= round(arg2) | arg3 ~= round(arg3)),
errorcode = 4;
return;
end
rows = arg2;
columns = arg3;
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
else
if (arg3 < 0 | arg4 < 0 | arg3 ~= round(arg3) | arg4 ~= round(arg4)),
errorcode = 4;
return;
end
rows = arg3;
columns = arg4;
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg3
[rows columns] = size(arg3);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
else
if (arg4 < 0 | arg5 < 0 | arg4 ~= round(arg4) | arg5 ~= round(arg5)),
errorcode = 4;
return;
end
rows = arg4;
columns = arg5;
end
end
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_faces_reorientation.m
|
.m
|
numerical-tours-master/matlab/toolbox_general/perform_faces_reorientation.m
| 2,816 |
utf_8
|
2cf3d5c1ad6ea271b524352db5492c2c
|
function faces = perform_faces_reorientation(vertex,faces, options)
% perform_faces_reorientation - reorient the faces with respect to the center of the mesh
%
% faces = perform_faces_reorientation(vertex,faces, options);
%
% try to find a consistant reorientation for faces of a mesh.
%
% if options.method = 'fast', then use a fast non accurate method
% if options.method = 'slow', then use a slow exact method
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
method = getoptions(options, 'method', 'fast');
[vertex,faces] = check_face_vertex(vertex,faces);
n = size(vertex,2);
m = size(faces,2);
if strcmp(method, 'fast')
% compute the center of mass of the mesh
G = mean(vertex,2);
% center of faces
Cf = (vertex(:,faces(1,:)) + vertex(:,faces(2,:)) + vertex(:,faces(3,:)))/3;
Cf = Cf - repmat(G,[1 m]);
% normal to the faces
V1 = vertex(:,faces(2,:))-vertex(:,faces(1,:));
V2 = vertex(:,faces(3,:))-vertex(:,faces(1,:));
N = [V1(2,:).*V2(3,:) - V1(3,:).*V2(2,:) ; ...
-V1(1,:).*V2(3,:) + V1(3,:).*V2(1,:) ; ...
V1(1,:).*V2(2,:) - V1(2,:).*V2(1,:) ];
% dot product
s = sign(sum(N.*Cf));
% reverse faces
I = find(s>0);
faces(:,I) = faces(3:-1:1,I);
return
end
options.method = 'fast';
faces = perform_faces_reorientation(vertex,faces, options);
fring = compute_face_ring(faces);
tag = zeros(m,1)-1;
heap = 1;
for i=1:m
if m>100
progressbar(i,m);
end
if isempty(heap)
I = find(tag==-1);
if isempty(I)
error('Problem');
end
heap = I(1);
end
f = heap(end); heap(end) = [];
if tag(f)==1
warning('Problem');
end
tag(f) = 1; % computed
fr = fring{f};
fr = fr(tag(fr)==-1);
tag(fr)=0;
heap = [heap fr];
for k=fr(:)'
% see if re-orientation is needed
if check_orientation(faces(:,k), faces(:,f))==1
faces(1:2,k) = faces(2:-1:1,k);
end
end
end
if not(isempty(heap)) || not(isempty(find(tag<1)))
warning('Problem');
end
% try to see if face are facing in the correct direction
[normal,normalf] = compute_normal(vertex,faces);
a = mean(vertex,2);
a = repmat(a, [1 n]);
dp = sign(sum(normal.*a,1));
if sum(dp>0)<sum(dp<0)
faces(1:2,:) = faces(2:-1:1,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function o = check_orientation(f1,f2)
i1 = 0; j1 = 0;
for i=1:3
for j=1:3
if f1(i)==f2(j)
i1 = i; j1 = j;
break;
end
end
if i1~=0
break;
end
end
if i1==0
error('Problem.');
end
ia = mod(i1,3)+1;
ja = mod(j1,3)+1;
ib = mod(i1-2,3)+1;
jb = mod(j1-2,3)+1;
if f1(ia)==f2(ja) || f1(ib)==f2(jb)
o=1;
else
o = -1;
end
|
github
|
alex-delalande/numerical-tours-master
|
gamrnd.m
|
.m
|
numerical-tours-master/matlab/toolbox_general/gamrnd.m
| 10,861 |
utf_8
|
9b8a786919b4ddfbebdf74985b19ebb2
|
function r = gamrnd(a,b,m,n);
%GAMRND Random matrices from gamma distribution.
% R = GAMRND(A,B) returns a matrix of random numbers chosen
% from the gamma distribution with parameters A and B.
% The size of R is the common size of A and B if both are matrices.
% If either parameter is a scalar, the size of R is the size of the other
% parameter. Alternatively, R = GAMRND(A,B,M,N) returns an M by N matrix.
%
% mu=A*B is the mean.
% sigma^2=A*B^2 is the variance.
%
%
% Some references refer to the gamma distribution
% with a single parameter. This corresponds to GAMRND
% with B = 1. (See Devroye, pages 401-402.)
% GAMRND uses a rejection or an inversion method depending on the
% value of A.
% References:
% [1] L. Devroye, "Non-Uniform Random Variate Generation",
% Springer-Verlag, 1986
% B.A. Jones 2-1-93
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 2.8 $ $Date: 1998/09/30 19:12:40 $
if nargin < 2,
error('Requires at least two input arguments.');
end
if nargin == 2
[errorcode rows columns] = rndcheck(2,2,a,b);
end
if nargin == 3
[errorcode rows columns] = rndcheck(3,2,a,b,m);
end
if nargin == 4
[errorcode rows columns] = rndcheck(4,2,a,b,m,n);
end
if errorcode > 0
error('Size information is inconsistent.');
end
% Initialize r to zero.
lth = rows*columns;
r = zeros(lth,1);
a = a(:); b = b(:);
scalara = (length(a) == 1);
if scalara
a = a*ones(lth,1);
end
scalarb = (length(b) == 1);
if scalarb
b = b*ones(lth,1);
end
% If a == 1, then gamma is exponential. (Devroye, page 405).
k = find(a == 1);
if any(k)
r(k) = -b(k) .* log(rand(size(k)));
end
k = find(a < 1 & a > 0);
% (Devroye, page 418 Johnk's generator)
if any(k)
c = zeros(lth,1);
d = zeros(lth,1);
c(k) = 1 ./ a(k);
d(k) = 1 ./ (1 - a(k));
accept = k;
while ~isempty(accept)
u = rand(size(accept));
v = rand(size(accept));
x = u .^ c(accept);
y = v .^ d(accept);
k1 = find((x + y) <= 1);
if ~isempty(k1)
e = -log(rand(size(k1)));
r(accept(k1)) = e .* x(k1) ./ (x(k1) + y(k1));
accept(k1) = [];
end
end
r(k) = r(k) .* b(k);
end
% Use a rejection method for a > 1.
k = find(a > 1);
% (Devroye, page 410 Best's algorithm)
bb = zeros(size(a));
c = bb;
if any(k)
bb(k) = a(k) - 1;
c(k) = 3 * a(k) - 3/4;
accept = k;
count = 1;
while ~isempty(accept)
m = length(accept);
u = rand(m,1);
v = rand(m,1);
w = u .* (1 - u);
y = sqrt(c(accept) ./ w) .* (u - 0.5);
x = bb(accept) + y;
k1 = find(x >= 0);
if ~isempty(k1)
z = 64 * (w .^ 3) .* (v .^ 2);
k2 = (z(k1) <= (1 - 2 * (y(k1) .^2) ./ x(k1)));
k3 = k1(find(k2));
r(accept(k3)) = x(k3);
k4 = k1(find(~k2));
k5 = k4(find(log(z(k4)) <= (2*(bb(accept(k4)).*log(x(k4)./bb(accept(k4)))-y(k4)))));
r(accept(k5)) = x(k5);
omit = [k3; k5];
accept(omit) = [];
end
end
r(k) = r(k) .* b(k);
end
% Return NaN if a or b is not positive.
r(b <= 0 | a <= 0) = NaN;
r = reshape(r,rows,columns);
function [errorcode, rows, columns] = rndcheck(nargs,nparms,arg1,arg2,arg3,arg4,arg5)
%RNDCHECK error checks the argument list for the random number generators.
% B.A. Jones 1-22-93
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 2.5 $ $Date: 1997/11/29 01:46:40 $
sizeinfo = nargs - nparms;
errorcode = 0;
if nparms == 3
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
[r3 c3] = size(arg3);
end
if nparms == 2
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
end
if sizeinfo == 0
if nparms == 1
[rows columns] = size(arg1);
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg1);
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg3);
end
end
end
if sizeinfo == 1
scalararg1 = (prod(size(arg1)) == 1);
if nparms == 1
if prod(size(arg2)) ~= 2
errorcode = 2;
return;
end
if ~scalararg1 & arg2 ~= size(arg1)
errorcode = 3;
return;
end
if (arg2(1) < 0 | arg2(2) < 0 | arg2(1) ~= round(arg2(1)) | arg2(2) ~= round(arg2(2))),
errorcode = 4;
return;
end
rows = arg2(1);
columns = arg2(2);
end
if nparms == 2
if prod(size(arg3)) ~= 2
errorcode = 2;
return;
end
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if (arg3(1) < 0 | arg3(2) < 0 | arg3(1) ~= round(arg3(1)) | arg3(2) ~= round(arg3(2))),
errorcode = 4;
return;
end
if ~scalararg1
if any(arg3 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg3 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
else
rows = arg3(1);
columns = arg3(2);
end
end
if nparms == 3
if prod(size(arg4)) ~= 2
errorcode = 2;
return;
end
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if (arg4(1) < 0 | arg4(2) < 0 | arg4(1) ~= round(arg4(1)) | arg4(2) ~= round(arg4(2))),
errorcode = 4;
return;
end
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
if any(arg4 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg4 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
elseif ~scalararg3
if any(arg4 ~= size(arg3))
errorcode = 3;
return;
end
[rows columns] = size(arg3);
else
rows = arg4(1);
columns = arg4(2);
end
end
end
if sizeinfo == 2
if nparms == 1
scalararg1 = (prod(size(arg1)) == 1);
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg2 | columns ~= arg3
errorcode = 3;
return;
end
end
if (arg2 < 0 | arg3 < 0 | arg2 ~= round(arg2) | arg3 ~= round(arg3)),
errorcode = 4;
return;
end
rows = arg2;
columns = arg3;
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
else
if (arg3 < 0 | arg4 < 0 | arg3 ~= round(arg3) | arg4 ~= round(arg4)),
errorcode = 4;
return;
end
rows = arg3;
columns = arg4;
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg3
[rows columns] = size(arg3);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
else
if (arg4 < 0 | arg5 < 0 | arg4 ~= round(arg4) | arg5 ~= round(arg5)),
errorcode = 4;
return;
end
rows = arg4;
columns = arg5;
end
end
end
|
github
|
alex-delalande/numerical-tours-master
|
binornd.m
|
.m
|
numerical-tours-master/matlab/toolbox_general/binornd.m
| 9,362 |
utf_8
|
0ca5d51eb461d57552c90487eab9946d
|
function r=binornd(n,p,mm,nn)
% BINORND Random matrices from a binomial distribution.
% R = BINORND(N,P,MM,NN) is an MM-by-NN matrix of random
% numbers chosen from a binomial distribution with parameters N and P.
%
% The size of R is the common size of N and P if both are matrices.
% If either parameter is a scalar, the size of R is the size of the other
% parameter.
% Alternatively, R = BINORND(N,P,MM,NN) returns an MM by NN matrix.
%
% The method is direct using the definition of the binomial
% distribution as a sum of Bernoulli random variables.
% References:
% [1] L. Devroye, "Non-Uniform Random Variate Generation",
% Springer-Verlag, 1986
% See Lemma 4.1 on page 428, method on page 524.
% B.A. Jones 1-12-93
% Copyright (c) 1993 by The MathWorks, Inc.
% $Revision: 1.1 $ $Date: 1993/05/24 18:53:37 $
if nargin < 2,
error('Requires at least two input arguments.');
end
if nargin == 2
[errorcode rows columns] = rndcheck(2,2,n,p);
end
if nargin == 3
[errorcode rows columns] = rndcheck(3,2,n,p,mm);
n = n(ones(mm(1),1),ones(mm(2),1));
p = p(ones(mm(1),1),ones(mm(2),1));
end
if nargin == 4
[errorcode rows columns] = rndcheck(4,2,n,p,mm,nn);
n = n(ones(mm,1),ones(nn,1));
p = p(ones(mm,1),ones(nn,1));
end
if errorcode > 0
error('Size information is inconsistent.');
end
r = zeros(rows,columns);
for i = 1:max(max(n))
u = rand(rows,columns);
k1 = find(n >= i);
k2 = find(u(k1) < p(k1));
r(k1(k2)) = r(k1(k2)) + 1;
end
k= find(p < 0 | p > 1 | n < 0);
if any(k)
r(k) = NaN * ones(size(k));
end
function [errorcode, rows, columns] = rndcheck(nargs,nparms,arg1,arg2,arg3,arg4,arg5)
%RNDCHECK error checks the argument list for the random number generators.
% B.A. Jones 1-22-93
% Copyright (c) 1993-98 by The MathWorks, Inc.
% $Revision: 2.5 $ $Date: 1997/11/29 01:46:40 $
sizeinfo = nargs - nparms;
errorcode = 0;
if nparms == 3
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
[r3 c3] = size(arg3);
end
if nparms == 2
[r1 c1] = size(arg1);
[r2 c2] = size(arg2);
end
if sizeinfo == 0
if nparms == 1
[rows columns] = size(arg1);
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg1);
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
elseif ~scalararg2
[rows columns] = size(arg2);
else
[rows columns] = size(arg3);
end
end
end
if sizeinfo == 1
scalararg1 = (prod(size(arg1)) == 1);
if nparms == 1
if prod(size(arg2)) ~= 2
errorcode = 2;
return;
end
if ~scalararg1 & arg2 ~= size(arg1)
errorcode = 3;
return;
end
if (arg2(1) < 0 | arg2(2) < 0 | arg2(1) ~= round(arg2(1)) | arg2(2) ~= round(arg2(2))),
errorcode = 4;
return;
end
rows = arg2(1);
columns = arg2(2);
end
if nparms == 2
if prod(size(arg3)) ~= 2
errorcode = 2;
return;
end
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if (arg3(1) < 0 | arg3(2) < 0 | arg3(1) ~= round(arg3(1)) | arg3(2) ~= round(arg3(2))),
errorcode = 4;
return;
end
if ~scalararg1
if any(arg3 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg3 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
else
rows = arg3(1);
columns = arg3(2);
end
end
if nparms == 3
if prod(size(arg4)) ~= 2
errorcode = 2;
return;
end
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if (arg4(1) < 0 | arg4(2) < 0 | arg4(1) ~= round(arg4(1)) | arg4(2) ~= round(arg4(2))),
errorcode = 4;
return;
end
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
if any(arg4 ~= size(arg1))
errorcode = 3;
return;
end
[rows columns] = size(arg1);
elseif ~scalararg2
if any(arg4 ~= size(arg2))
errorcode = 3;
return;
end
[rows columns] = size(arg2);
elseif ~scalararg3
if any(arg4 ~= size(arg3))
errorcode = 3;
return;
end
[rows columns] = size(arg3);
else
rows = arg4(1);
columns = arg4(2);
end
end
end
if sizeinfo == 2
if nparms == 1
scalararg1 = (prod(size(arg1)) == 1);
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg2 | columns ~= arg3
errorcode = 3;
return;
end
end
if (arg2 < 0 | arg3 < 0 | arg2 ~= round(arg2) | arg3 ~= round(arg3)),
errorcode = 4;
return;
end
rows = arg2;
columns = arg3;
end
if nparms == 2
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg3 | columns ~= arg4
errorcode = 3;
return;
end
else
if (arg3 < 0 | arg4 < 0 | arg3 ~= round(arg3) | arg4 ~= round(arg4)),
errorcode = 4;
return;
end
rows = arg3;
columns = arg4;
end
end
if nparms == 3
scalararg1 = (prod(size(arg1)) == 1);
scalararg2 = (prod(size(arg2)) == 1);
scalararg3 = (prod(size(arg3)) == 1);
if ~scalararg1 & ~scalararg2
if r1 ~= r2 | c1 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1 & ~scalararg3
if r1 ~= r3 | c1 ~= c3
errorcode = 1;
return;
end
end
if ~scalararg3 & ~scalararg2
if r3 ~= r2 | c3 ~= c2
errorcode = 1;
return;
end
end
if ~scalararg1
[rows columns] = size(arg1);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg2
[rows columns] = size(arg2);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
elseif ~scalararg3
[rows columns] = size(arg3);
if rows ~= arg4 | columns ~= arg5
errorcode = 3;
return;
end
else
if (arg4 < 0 | arg5 < 0 | arg4 ~= round(arg4) | arg5 ~= round(arg5)),
errorcode = 4;
return;
end
rows = arg4;
columns = arg5;
end
end
end
|
github
|
alex-delalande/numerical-tours-master
|
iradon.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/iradon.m
| 9,900 |
utf_8
|
28cae50d959ca460cfc01acf31c2e700
|
function [img,H] = iradon(varargin)
%IRADON Compute inverse Radon transform.
% I = iradon(R,THETA) reconstructs the image I from projection
% data in the 2-D array R. The columns of R are parallel beam
% projection data. IRADON assumes that the center of rotation
% is the center point of the projections, which is defined as
% ceil(size(R,1)/2).
%
% THETA describes the angles (in degrees) at which the projections
% were taken. It can be either a vector containing the angles or
% a scalar specifying D_theta, the incremental angle between
% projections. If THETA is a vector, it must contain angles with
% equal spacing between them. If THETA is a scalar specifying
% D_theta, the projections are taken at angles THETA = m * D_theta;
% m = 0,1,2,...,size(R,2)-1. If the input is the empty matrix
% ([]), D_theta defaults to 180/size(R,2).
%
% IRADON uses the filtered backprojection algorithm to perform
% the inverse Radon transform. The filter is designed directly
% in the frequency domain and then multiplied by the FFT of the
% projections. The projections are zero-padded to a power of 2
% before filtering to prevent spatial domain aliasing and to
% speed up the FFT.
%
% I = IRADON(R,THETA,INTERP,FILTER,D,N) specifies parameters
% to use in the inverse Radon transform. You can specify
% any combination of the last four arguments. IRADON uses
% default values for any of these arguments that you omit.
%
% INTERP specifies the type of interpolation to use in the
% backprojection. The available options are listed in order
% of increasing accuracy and computational complexity:
%
% 'nearest' - nearest neighbor interpolation
% 'linear' - linear interpolation (default)
% 'spline' - spline interpolation
%
% FILTER specifies the filter to use for frequency domain filtering.
% FILTER is a string that specifies any of the following standard
% filters:
%
% 'Ram-Lak' The cropped Ram-Lak or ramp filter (default). The
% frequency response of this filter is |f|. Because
% this filter is sensitive to noise in the projections,
% one of the filters listed below may be preferable.
% 'Shepp-Logan' The Shepp-Logan filter multiplies the Ram-Lak
% filter by a sinc function.
% 'Cosine' The cosine filter multiplies the Ram-Lak filter
% by a cosine function.
% 'Hamming' The Hamming filter multiplies the Ram-Lak filter
% by a Hamming window.
% 'Hann' The Hann filter multiplies the Ram-Lak filter by
% a Hann window.
%
% D is a scalar in the range (0,1] that modifies the filter by
% rescaling its frequency axis. The default is 1. If D is less
% than 1, the filter is compressed to fit into the frequency range
% [0,D], in normalized frequencies; all frequencies above D are set
% to 0.
%
% N is a scalar that specifies the number of rows and columns in the
% reconstructed image. If N is not specified, the size is determined
% from the length of the projections:
%
% N = 2*floor(size(R,1)/(2*sqrt(2)))
%
% If you specify N, IRADON reconstructs a smaller or larger portion of
% the image, but does not change the scaling of the data.
%
% If the projections were calculated with the RADON function, the
% reconstructed image may not be the same size as the original
% image.
%
% [I,H] = iradon(...) returns the frequency response of the filter
% in the vector H.
%
% Class Support
% -------------
% All input arguments must be of class double. The output arguments are
% of class double.
%
% Example
% -------
% P = phantom(128);
% R = radon(P,0:179);
% I = iradon(R,0:179,'nearest','Hann');
% imshow(P); figure; imshow(I);
%
% See also RADON, PHANTOM.
% Copyright 1993-2002 The MathWorks, Inc.
% $Revision: 1.13 $ $Date: 2002/03/15 15:28:29 $
% References:
% A. C. Kak, Malcolm Slaney, "Principles of Computerized Tomographic
% Imaging", IEEE Press 1988.
[p,theta,filter,d,interp,N] = parse_inputs(varargin{:});
% Design the filter
len=size(p,1);
H = designFilter(filter, len, d);
p(length(H),1)=0; % Zero pad projections
% In the code below, I continuously reuse the array p so as to
% save memory. This makes it harder to read, but the comments
% explain what is going on.
p = fft(p); % p holds fft of projections
for i = 1:size(p,2)
p(:,i) = p(:,i).*H; % frequency domain filtering
end
p = real(ifft(p)); % p is the filtered projections
p(len+1:end,:) = []; % Truncate the filtered projections
img = zeros(N); % Allocate memory for the image.
% Define the x & y axes for the reconstructed image so that the origin
% (center) is in the spot which RADON would choose.
xax = (1:N)-ceil(N/2);
x = repmat(xax, N, 1); % x coordinates, the y coordinates are rot90(x)
y = rot90(x);
costheta = cos(theta);
sintheta = sin(theta);
ctrIdx = ceil(len/2); % index of the center of the projections
% Zero pad the projections to size 1+2*ceil(N/sqrt(2)) if this
% quantity is greater than the length of the projections
imgDiag = 2*ceil(N/sqrt(2))+1; % largest distance through image.
if size(p,1) < imgDiag
rz = imgDiag - size(p,1); % how many rows of zeros
p = [zeros(ceil(rz/2),size(p,2)); p; zeros(floor(rz/2),size(p,2))];
ctrIdx = ctrIdx+ceil(rz/2);
end
% Backprojection - vectorized in (x,y), looping over theta
if strcmp(interp, 'nearest neighbor')
for i=1:length(theta)
proj = p(:,i);
t = round(x*costheta(i) + y*sintheta(i));
img = img + proj(t+ctrIdx);
end
elseif strcmp(interp, 'linear')
for i=1:length(theta)
proj = p(:,i);
t = x.*costheta(i) + y.*sintheta(i);
a = floor(t);
img = img + (t-a).*proj(a+1+ctrIdx) + (a+1-t).*proj(a+ctrIdx);
end
elseif strcmp(interp, 'spline')
for i=1:length(theta)
proj = p(:,i);
taxis = (1:size(p,1)) - ctrIdx;
t = x.*costheta(i) + y.*sintheta(i);
projContrib = interp1(taxis,proj,t(:),'*spline');
img = img + reshape(projContrib,N,N);
end
end
img = img*pi/(2*length(theta));
%%%
%%% Sub-Function: designFilter
%%%
function filt = designFilter(filter, len, d)
% Returns the Fourier Transform of the filter which will be
% used to filter the projections
%
% INPUT ARGS: filter - either the string specifying the filter
% len - the length of the projections
% d - the fraction of frequencies below the nyquist
% which we want to pass
%
% OUTPUT ARGS: filt - the filter to use on the projections
order = max(64,2^nextpow2(2*len));
% First create a ramp filter - go up to the next highest
% power of 2.
filt = 2*( 0:(order/2) )./order;
w = 2*pi*(0:size(filt,2)-1)/order; % frequency axis up to Nyquist
switch filter
case 'ram-lak'
% Do nothing
case 'shepp-logan'
% be careful not to divide by 0:
filt(2:end) = filt(2:end) .* (sin(w(2:end)/(2*d))./(w(2:end)/(2*d)));
case 'cosine'
filt(2:end) = filt(2:end) .* cos(w(2:end)/(2*d));
case 'hamming'
filt(2:end) = filt(2:end) .* (.54 + .46 * cos(w(2:end)/d));
case 'hann'
filt(2:end) = filt(2:end) .*(1+cos(w(2:end)./d)) / 2;
otherwise
error('Invalid filter selected.');
end
filt(w>pi*d) = 0; % Crop the frequency response
filt = [filt' ; filt(end-1:-1:2)']; % Symmetry of the filter
%%%
%%% Sub-Function: parse_inputs
%%%
function [p,theta,filter,d,interp,N] = parse_inputs(varargin);
% Parse the input arguments and retun things
%
% Inputs: varargin - Cell array containing all of the actual inputs
%
% Outputs: p - Projection data
% theta - the angles at which the projections were taken
% filter - string specifying filter or the actual filter
% d - a scalar specifying normalized freq. at which to crop
% the frequency response of the filter
% interp - the type of interpolation to use
% N - The size of the reconstructed image
if nargin<2
error('Invalid input arguments.');
end
p = varargin{1};
theta = pi*varargin{2}/180;
% Default values
N = 0; % Size of the reconstructed image
d = 1; % Defaults to no cropping of filters frequency response
filter = 'ram-lak'; % The ramp filter is the default
interp = 'linear'; % default interpolation is linear
string_args = {'nearest neighbor', 'linear', 'spline', ...
'ram-lak','shepp-logan','cosine','hamming', 'hann'};
for i=3:nargin
arg = varargin{i};
if ischar(arg)
idx = strmatch(lower(arg),string_args);
if isempty(idx)
error(['Unknown input string: ' arg '.']);
elseif prod(size(idx)) > 1
error(['Ambiguous input string: ' arg '.']);
elseif prod(size(idx)) == 1
if idx <= 3 % It is the interpolatio
interp = string_args{idx};
elseif (idx > 3) & (idx <= 8)
filter = string_args{idx};
end
end
elseif prod(size(arg))==1
if arg <=1
d = arg;
else
N = arg;
end
else
error('Invalid input parameters');
end
end
% If the user didn't specify the size of the reconstruction, so
% deduce it from the length of projections
if N==0
N = 2*floor( size(p,1)/(2*sqrt(2)) ); % This doesn't always jive with RADON
end
% for empty theta, choose an intelligent default delta-theta
if isempty(theta)
theta = pi / size(p,2);
end
% If the user passed in delta-theta, build the vector of theta values
if prod(size(theta))==1
theta = (0:(size(p,2)-1))* theta;
end
if length(theta) ~= size(p,2)
error('THETA does not match the number of projections.');
end
|
github
|
alex-delalande/numerical-tours-master
|
load_signal.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/load_signal.m
| 12,338 |
utf_8
|
b70e4cb57d6b467ae9c90d4b3310a81f
|
function y = load_signal(name, n, options)
% load_signal - load a 1D signal
%
% y = load_signal(name, n, options);
%
% name is a string that can be :
% 'regular' (options.alpha gives regularity)
% 'step', 'rand',
% 'gaussiannoise' (options.sigma gives width of filtering in pixels),
% [natural signals]
% 'tiger', 'bell', 'bird'
% [WAVELAB signals]
% 'HeaviSine', 'Bumps', 'Blocks',
% 'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine',
% 'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp',
% 'MishMash', 'WernerSorrows' (Heisenberg),
% 'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth),
% 'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor'
% 'sineoneoverx','Cusp2','SmoothCusp','Gaussian'
% 'Piece-Polynomial' (Piece-Wise 3rd degree polynomial)
if nargin<2
n = 1024;
end
options.null = 0;
if isfield(options, 'alpha')
alpha = options.alpha;
else
alpha = 2;
end
options.rep = '';
switch lower(name)
case 'regular'
y = gen_signal(n,alpha);
case 'step'
y = linspace(0,1,n)>0.5;
case 'stepregular'
y = linspace(0,1,n)>0.5; y=y(:);
a = gen_signal(n,2); a = a(:);
a = rescale(a,-0.1,0.1);
y = y+a;
case 'gaussiannoise'
% filtered gaussian noise
y = randn(n,1);
if isfield(options, 'sigma')
sigma = options.sigma; % variance in number of pixels
else
sigma = 20;
end
m = min(n, 6*round(sigma/2)+1);
h = compute_gaussian_filter(m,sigma/(4*n),n);
options.bound = 'per';
y = perform_convolution(y,h, options);
case 'rand'
if isfield(options, 'p1')
p1 = options.p1;
else
c = 10;
p1 = 1:c; p1 = p1/sum(p1);
end
p1 = p1(:); c = length(p1);
if isfield(options, 'p2')
p2 = options.p2;
else
if isfield(options, 'evol')
evol = options.evol;
else
evol = 0;
end
p2 = p1(:) + evol*(rand(c,1)-0.5);
p2 = max(p2,0); p2 = p2/sum(p2);
end
y = zeros(n,1);
for i=1:n
a = (i-1)/(n-1);
p = a*p1+(1-a)*p2; p = p/sum(p);
y(i) = rand_discr(p, 1);
end
case 'bird'
[y,fs] = load_sound([name '.wav'], n, options);
case 'tiger'
[y,fs] = load_sound([name '.au'], n, options);
case 'bell'
[y,fs] = load_sound([name '.wav'], n, options);
otherwise
y = MakeSignal(name,n);
end
y = y(:);
function y = gen_signal(n,alpha)
% gen_signal - generate a 1D C^\alpha signal of length n.
%
% y = gen_signal(n,alpha);
%
% The signal is scaled in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
if nargin<2
alpha = 2;
end
y = randn(n,1);
fy = fft(y);
fy = fftshift(fy);
% filter with |omega|^{-\alpha}
h = (-n/2+1):(n/2);
h = (abs(h)+1).^(-alpha-0.5);
fy = fy.*h';
fy = fftshift(fy);
y = real( ifft(fy) );
y = (y-min(y))/(max(y)-min(y));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sig = MakeSignal(Name,n)
% MakeSignal -- Make artificial signal
% Usage
% sig = MakeSignal(Name,n)
% Inputs
% Name string: 'HeaviSine', 'Bumps', 'Blocks',
% 'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine',
% 'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp',
% 'MishMash', 'WernerSorrows' (Heisenberg),
% 'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth),
% 'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor'
% 'sineoneoverx','Cusp2','SmoothCusp','Gaussian'
% 'Piece-Polynomial' (Piece-Wise 3rd degree polynomial)
% n desired signal length
% Outputs
% sig 1-d signal
%
% References
% Various articles of D.L. Donoho and I.M. Johnstone
%
if nargin > 1,
t = (1:n) ./n;
end
Name = lower(Name);
if strcmp(Name,'heavisine'),
sig = 4.*sin(4*pi.*t);
sig = sig - sign(t - .3) - sign(.72 - t);
elseif strcmp(Name,'bumps'),
pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];
hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2];
wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005];
sig = zeros(size(t));
for j =1:length(pos)
sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;
end
elseif strcmp(Name,'blocks'),
pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];
hgt = [4 (-5) 3 (-4) 5 (-4.2) 2.1 4.3 (-3.1) 2.1 (-4.2)];
sig = zeros(size(t));
for j=1:length(pos)
sig = sig + (1 + sign(t-pos(j))).*(hgt(j)/2) ;
end
elseif strcmp(Name,'doppler'),
sig = sqrt(t.*(1-t)).*sin((2*pi*1.05) ./(t+.05));
elseif strcmp(Name,'ramp'),
sig = t - (t >= .37);
elseif strcmp(Name,'cusp'),
sig = sqrt(abs(t - .37));
elseif strcmp(Name,'sing'),
k = floor(n * .37);
sig = 1 ./abs(t - (k+.5)/n);
elseif strcmp(Name,'hisine'),
sig = sin( pi * (n * .6902) .* t);
elseif strcmp(Name,'losine'),
sig = sin( pi * (n * .3333) .* t);
elseif strcmp(Name,'linchirp'),
sig = sin(pi .* t .* ((n .* .500) .* t));
elseif strcmp(Name,'twochirp'),
sig = sin(pi .* t .* (n .* t)) + sin((pi/3) .* t .* (n .* t));
elseif strcmp(Name,'quadchirp'),
sig = sin( (pi/3) .* t .* (n .* t.^2));
elseif strcmp(Name,'mishmash'), % QuadChirp + LinChirp + HiSine
sig = sin( (pi/3) .* t .* (n .* t.^2)) ;
sig = sig + sin( pi * (n * .6902) .* t);
sig = sig + sin(pi .* t .* (n .* .125 .* t));
elseif strcmp(Name,'wernersorrows'),
sig = sin( pi .* t .* (n/2 .* t.^2)) ;
sig = sig + sin( pi * (n * .6902) .* t);
sig = sig + sin(pi .* t .* (n .* t));
pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81];
hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2];
wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005];
for j =1:length(pos)
sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4;
end
elseif strcmp(Name,'leopold'),
sig = (t == floor(.37 * n)/n); % Kronecker
elseif strcmp(Name,'riemann'),
sqn = round(sqrt(n));
sig = t .* 0; % Riemann's Non-differentiable Function
sig((1:sqn).^2) = 1. ./ (1:sqn);
sig = real(ifft(sig));
elseif strcmp(Name,'hypchirps'), % Hyperbolic Chirps of Mallat's book
alpha = 15*n*pi/1024;
beta = 5*n*pi/1024;
t = (1.001:1:n+.001)./n;
f1 = zeros(1,n);
f2 = zeros(1,n);
f1 = sin(alpha./(.8-t)).*(0.1<t).*(t<0.68);
f2 = sin(beta./(.8-t)).*(0.1<t).*(t<0.75);
M = round(0.65*n);
P = floor(M/4);
enveloppe = ones(1,M); % the rising cutoff function
enveloppe(1:P) = (1+sin(-pi/2+((1:P)-ones(1,P))./(P-1)*pi))/2;
enveloppe(M-P+1:M) = reverse(enveloppe(1:P));
env = zeros(1,n);
env(ceil(n/10):M+ceil(n/10)-1) = enveloppe(1:M);
sig = (f1+f2).*env;
elseif strcmp(Name,'linchirps'), % Linear Chirps of Mallat's book
b = 100*n*pi/1024;
a = 250*n*pi/1024;
t = (1:n)./n;
A1 = sqrt((t-1/n).*(1-t));
sig = A1.*(cos((a*(t).^2)) + cos((b*t+a*(t).^2)));
elseif strcmp(Name,'chirps'), % Mixture of Chirps of Mallat's book
t = (1:n)./n.*10.*pi;
f1 = cos(t.^2*n/1024);
a = 30*n/1024;
t = (1:n)./n.*pi;
f2 = cos(a.*(t.^3));
f2 = reverse(f2);
ix = (-n:n)./n.*20;
g = exp(-ix.^2*4*n/1024);
i1 = (n/2+1:n/2+n);
i2 = (n/8+1:n/8+n);
j = (1:n)/n;
f3 = g(i1).*cos(50.*pi.*j*n/1024);
f4 = g(i2).*cos(350.*pi.*j*n/1024);
sig = f1+f2+f3+f4;
enveloppe = ones(1,n); % the rising cutoff function
enveloppe(1:n/8) = (1+sin(-pi/2+((1:n/8)-ones(1,n/8))./(n/8-1)*pi))/2;
enveloppe(7*n/8+1:n) = reverse(enveloppe(1:n/8));
sig = sig.*enveloppe;
elseif strcmp(Name,'gabor'), % two modulated Gabor functions in
% Mallat's book
N = 512;
t = (-N:N)*5/N;
j = (1:N)./N;
g = exp(-t.^2*20);
i1 = (2*N/4+1:2*N/4+N);
i2 = (N/4+1:N/4+N);
sig1 = 3*g(i1).*exp(i*N/16.*pi.*j);
sig2 = 3*g(i2).*exp(i*N/4.*pi.*j);
sig = sig1+sig2;
elseif strcmp(Name,'sineoneoverx'), % sin(1/x) in Mallat's book
N = 1024;
a = (-N+1:N);
a(N) = 1/100;
a = a./(N-1);
sig = sin(1.5./(i));
sig = sig(513:1536);
elseif strcmp(Name,'cusp2'),
N = 64;
a = (1:N)./N;
x = (1-sqrt(a)) + a/2 -.5;
M = 8*N;
sig = zeros(1,M);
sig(M-1.5.*N+1:M-.5*N) = x;
sig(M-2.5*N+2:M-1.5.*N+1) = reverse(x);
sig(3*N+1:3*N + N) = .5*ones(1,N);
elseif strcmp(Name,'smoothcusp'),
sig = MakeSignal('Cusp2');
N = 64;
M = 8*N;
t = (1:M)/M;
sigma = 0.01;
g = exp(-.5.*(abs(t-.5)./sigma).^2)./sigma./sqrt(2*pi);
g = fftshift(g);
sig2 = iconv(g',sig)'/M;
elseif strcmp(Name,'piece-regular'),
sig1=-15*MakeSignal('Bumps',n);
t = (1:fix(n/12)) ./fix(n/12);
sig2=-exp(4*t);
t = (1:fix(n/7)) ./fix(n/7);
sig5=exp(4*t)-exp(4);
t = (1:fix(n/3)) ./fix(n/3);
sigma=6/40;
sig6=-70*exp(-((t-1/2).*(t-1/2))/(2*sigma^2));
sig(1:fix(n/7))= sig6(1:fix(n/7));
sig((fix(n/7)+1):fix(n/5))=0.5*sig6((fix(n/7)+1):fix(n/5));
sig((fix(n/5)+1):fix(n/3))=sig6((fix(n/5)+1):fix(n/3));
sig((fix(n/3)+1):fix(n/2))=sig1((fix(n/3)+1):fix(n/2));
sig((fix(n/2)+1):(fix(n/2)+fix(n/12)))=sig2;
sig((fix(n/2)+2*fix(n/12)):-1:(fix(n/2)+fix(n/12)+1))=sig2;
sig(fix(n/2)+2*fix(n/12)+fix(n/20)+1:(fix(n/2)+2*fix(n/12)+3*fix(n/20)))=...
-ones(1,fix(n/2)+2*fix(n/12)+3*fix(n/20)-fix(n/2)-2*fix(n/12)-fix(n/20))*25;
k=fix(n/2)+2*fix(n/12)+3*fix(n/20);
sig((k+1):(k+fix(n/7)))=sig5;
diff=n-5*fix(n/5);
sig(5*fix(n/5)+1:n)=sig(diff:-1:1);
% zero-mean
bias=sum(sig)/n;
sig=bias-sig;
elseif strcmp(Name,'piece-polynomial'),
t = (1:fix(n/5)) ./fix(n/5);
sig1=20*(t.^3+t.^2+4);
sig3=40*(2.*t.^3+t) + 100;
sig2=10.*t.^3 + 45;
sig4=16*t.^2+8.*t+16;
sig5=20*(t+4);
sig6(1:fix(n/10))=ones(1,fix(n/10));
sig6=sig6*20;
sig(1:fix(n/5))=sig1;
sig(2*fix(n/5):-1:(fix(n/5)+1))=sig2;
sig((2*fix(n/5)+1):3*fix(n/5))=sig3;
sig((3*fix(n/5)+1):4*fix(n/5))=sig4;
sig((4*fix(n/5)+1):5*fix(n/5))=sig5(fix(n/5):-1:1);
diff=n-5*fix(n/5);
sig(5*fix(n/5)+1:n)=sig(diff:-1:1);
%sig((fix(n/20)+1):(fix(n/20)+fix(n/10)))=-ones(1,fix(n/10))*20;
sig((fix(n/20)+1):(fix(n/20)+fix(n/10)))=ones(1,fix(n/10))*10;
sig((n-fix(n/10)+1):(n+fix(n/20)-fix(n/10)))=ones(1,fix(n/20))*150;
% zero-mean
bias=sum(sig)/n;
sig=sig-bias;
elseif strcmp(Name,'gaussian'),
sig=GWN(n,beta);
g=zeros(1,n);
lim=alpha*n;
mult=pi/(2*alpha*n);
g(1:lim)=(cos(mult*(1:lim))).^2;
g((n/2+1):n)=g((n/2):-1:1);
g = rnshift(g,n/2);
g=g/norm(g);
sig=iconv(g,sig);
else
disp(sprintf('MakeSignal: I don*t recognize <<%s>>',Name))
disp('Allowable Names are:')
disp('HeaviSine'),
disp('Bumps'),
disp('Blocks'),
disp('Doppler'),
disp('Ramp'),
disp('Cusp'),
disp('Crease'),
disp('Sing'),
disp('HiSine'),
disp('LoSine'),
disp('LinChirp'),
disp('TwoChirp'),
disp('QuadChirp'),
disp('MishMash'),
disp('WernerSorrows'),
disp('Leopold'),
disp('Sing'),
disp('HiSine'),
disp('LoSine'),
disp('LinChirp'),
disp('TwoChirp'),
disp('QuadChirp'),
disp('MishMash'),
disp('WernerSorrows'),
disp('Leopold'),
disp('Riemann'),
disp('HypChirps'),
disp('LinChirps'),
disp('Chirps'),
disp('sineoneoverx'),
disp('Cusp2'),
disp('SmoothCusp'),
disp('Gabor'),
disp('Piece-Regular');
disp('Piece-Polynomial');
disp('Gaussian');
end
%
% Originally made by David L. Donoho.
% Function has been enhanced.
%
% Part of WaveLab Version 802
% Built Sunday, October 3, 1999 8:52:27 AM
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
|
github
|
alex-delalande/numerical-tours-master
|
load_hdr.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/load_hdr.m
| 4,933 |
utf_8
|
6e9f25ee3fd41a80fb31c4e53984631b
|
function [img, fileinfo] = load_hdr(filename)
% load_hdr - loading a radiance RBGE file.
%
% [img, fileinfo] = load_hdr(filename);
%
% Written by Lawrence A. Taplin ([email protected])
%
% Based loosely on the c-code RGBE implementation written by Bruce Walters
% http://www.graphics.cornell.edu/~bjw/rgbe.html
%
% function to read a run length encoded RGBE picture file and header. This does
% not work if the image is not RLE!!!
do_rescale = 0;
% check if the image is in classical image (eg. TIFF) format
if ~strcmp(filename(end-2:end), 'hdr')
img = double(imread(filename));
if do_rescale
img = rescale(img);
end
fileinfo = [];
return;
end
% tic
%open the file
fid = fopen(filename,'r');
if fid<0
error(['File not found:' filename '.']);
end
%read the magic number
tline = fgetl(fid);
if length(tline)<3 | tline(1:2) ~= '#?'
error('invalid header');
end
fileinfo.identifier = tline(3:end);
%read the header variables into a structure
tline = fgetl(fid);
while ~isempty(tline)
%find and set the variable name
n = strfind(tline,'=');
if ~isempty(n) % skip stuff I don't understand
vname = lower(tline(1:n(1)-1));
vval = tline(n+1:end);
fileinfo = setfield(fileinfo,vname,tline(n+1:end));
% fprintf('Variable = %s, Value = %s\n',vname, vval);
end
%read the next line
tline = fgetl(fid);
end
%set the resolution variables
tline = fgetl(fid);
fileinfo.Ysign = tline(1);
[fileinfo.height,count,errmsg,nextindex] = sscanf(tline(4:end),'%d',1);
fileinfo.Xsign = tline(nextindex+4);
[fileinfo.width,count,errmsg,nextindex] = sscanf(tline(nextindex+7:end),'%d',1);
% fprintf('resolution: %s\n',tline);
%allocate space for the scan line data
img = zeros(fileinfo.height, fileinfo.width, 3);
%read the scanline data
if fileinfo.format == '32-bit_rle_rgbe';
% fprintf('Decoding RLE Data stream\n');
end
%read the remaining data
[data, count] = fread(fid,inf,'uint8');
fclose(fid);
scanline_width = fileinfo.width;
num_scanlines = fileinfo.height;
if ((scanline_width < 8)|(scanline_width > 32767))
% run length encoding is not allowed so read flat
img = rgbe2float(reshape(data,fileinfo.width,fileinfo.height,4));
return;
end
scanline_buffer = repmat(uint8(0),scanline_width,4);
dp = 1; %set the data pointer to the begining of the read data
% read in each successive scanline */
for scanline=1:num_scanlines
% if mod(scanline,fix(num_scanlines/100))==0
% fprintf('scanline = %d\n',scanline);
% end
%
if (data(dp) ~= 2) | (data(dp+1) ~= 2)% | (bitget(data(dp+2),8)~=1)
error('this file is not run length encoded');
end
if (bitshift(data(dp+2),8)+data(dp+3))~=scanline_width % -128
error('wrong scanline width');
end
dp = dp+4;
% read each of the four channels read the scanline into the buffer
for i=1:4
ptr = 1;
while(ptr <= scanline_width)
if (data(dp) > 128) % a run of the same value
count = data(dp)-128;
if ((count == 0)|(count-1 > scanline_width - ptr))
warning('bad scanline data');
end
scanline_buffer(ptr:ptr+count-1,i) = data(dp+1);
dp = dp+2;
ptr = ptr+count;
else % a non-run
count = data(dp);
dp = dp+1;
if ((count == 0)|(count-1 > scanline_width - ptr))
warning('bad scanline data');
end
scanline_buffer(ptr:ptr+count-1,i) = data(dp:dp+count-1);
ptr = ptr+count;
dp = dp+count;
end
end
end
% now convert data from buffer into floats
img(scanline,:,:) = rgbe2float(scanline_buffer);
end
% toc
% rescale to 0-1
if do_rescale
a = min(img(:));
b = max(img(:));
img = (img-a)/(b-a);
end
% standard conversion from float pixels to rgbe pixels
% the last dimension is assumed to be color
function [rgbe] = float2rgbe(rgb)
s = size(rgb);
rgb = reshape(rgb,prod(s)/3,3);
rgbe = reshape(repmat(uint8(0),[s(1:end-1),4]),prod(s)/3,4);
v = max(rgb,[],2); %find max rgb
l = find(v>1e-32); %find non zero pixel list
rgbe(l,4) = uint8(round(128.5+log(v)/log(2))); %find E
rgbe(l,1:3) = uint8(rgb(l,1:3)./repmat(2.^(double(rgbe(l,4))-128-8),1,3)); %find rgb multiplier
reshape(rgbe,[s(1:end-1),4]); %reshape back to original dimensions
% standard conversion from rgbe to float pixels */
% note: Ward uses ldexp(col+0.5,exp-(128+8)). However we wanted pixels */
% in the range [0,1] to map back into the range [0,1]. */
function [rgb] = rgbe2float(rgbe)
s = size(rgbe);
rgbe = reshape(rgbe,prod(s)/4,4);
rgb = zeros(prod(s)/4,3);
l = find(rgbe(:,4)>0); %nonzero pixel list
rgb(l,:) = double(rgbe(l,1:3)).*repmat(2.^(double(rgbe(l,4))-128-8),1,3);
rgb = reshape(rgb,[s(1:end-1),3]);
|
github
|
alex-delalande/numerical-tours-master
|
perform_wavortho_transf.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_wavortho_transf.m
| 2,736 |
utf_8
|
362bed43d951f6bdefb520003047e2ea
|
function f = perform_wavortho_transf(f,Jmin,dir,options)
% perform_wavortho_transf - compute orthogonal wavelet transform
%
% fw = perform_wavortho_transf(f,Jmin,dir,options);
%
% You can give the filter in options.h.
%
% Works in arbitrary dimension.
%
% Copyright (c) 2009 Gabriel Peyre
options.null = 0;
h = getoptions(options,'h', compute_wavelet_filter('Daubechies',4) );
g = [0 h(length(h):-1:2)] .* (-1).^(1:length(h));
n = size(f,1);
Jmax = log2(n)-1;
if dir==1
%%% FORWARD %%%
for j=Jmax:-1:Jmin
sel = 1:2^(j+1);
a = subselect(f,sel);
for d=1:nb_dims(f)
a = cat(d, subsampling(cconvol(a,h,d),d), subsampling(cconvol(a,g,d),d) );
end
f = subassign(f,sel,a);
end
else
%%% FORWARD %%%
for j=Jmin:Jmax
sel = 1:2^(j+1);
a = subselect(f,sel);
for d=1:nb_dims(f)
w = subselectdim(a,2^j+1:2^(j+1),d);
a = subselectdim(a,1:2^j,d);
a = cconvol(upsampling(a,d),reverse(h),d) + cconvol(upsampling(w,d),reverse(g),d);
end
f = subassign(f,sel,a);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = subselect(f,sel)
switch nb_dims(f)
case 1
f = f(sel);
case 2
f = f(sel,sel);
case 3
f = f(sel,sel,sel);
case 4
f = f(sel,sel,sel,sel);
case 5
f = f(sel,sel,sel,sel,sel);
case 6
f = f(sel,sel,sel,sel,sel,sel);
case 7
f = f(sel,sel,sel,sel,sel,sel,sel);
case 8
f = f(sel,sel,sel,sel,sel,sel,sel,sel);
otherwise
error('Not implemented');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = subselectdim(f,sel,d)
switch d
case 1
f = f(sel,:,:,:,:,:,:,:);
case 2
f = f(:,sel,:,:,:,:,:,:);
case 3
f = f(:,:,sel,:,:,:,:,:);
case 4
f = f(:,:,:,sel,:,:,:,:);
case 5
f = f(:,:,:,:,sel,:,:,:);
case 6
f = f(:,:,:,:,:,sel,:,:);
case 7
f = f(:,:,:,:,:,:,sel,:);
case 8
f = f(:,:,:,:,:,:,:,sel);
otherwise
error('Not implemented');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = subassign(f,sel,g)
switch nb_dims(f)
case 1
f(sel) = g;
case 2
f(sel,sel) = g;
case 3
f(sel,sel,sel) = g;
case 4
f(sel,sel,sel,sel) = g;
case 5
f(sel,sel,sel,sel,sel) = g;
case 6
f(sel,sel,sel,sel,sel,sel) = g;
case 7
f(sel,sel,sel,sel,sel,sel,sel) = g;
case 8
f(sel,sel,sel,sel,sel,sel,sel,sel) = g;
otherwise
error('Not implemented');
end
|
github
|
alex-delalande/numerical-tours-master
|
plot_curvelet.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/plot_curvelet.m
| 2,421 |
utf_8
|
a1a1177c6c1d743518abcfacae1e9e03
|
function J = plot_curvelet(MW, options)
% plot_curvelet - display curvelets coefficients
%
% J = plot_curvelet(MW);
%
% Based on curvelab.
%generate curvelet image (a complex array)
I = fdct_wrapping_dispcoef(MW);
% remove bckgd
U = (I==.5);
J = ones(size(I)+2);
JU = ones(size(I)+2);
J(2:end-1,2:end-1) = I;
JU(2:end-1,2:end-1) = U;
J(J==.5) = 1;
J = sign(J) .* abs(J).^.6;
if nargout==0
hold on;
imageplot(J);
[c,h] = contour( JU, [.5 .5], 'r');
set(h, 'LineWidth', 2);
end
function img = fdct_wrapping_dispcoef(C)
% fdct_wrapping_dispcoef - returns an image containing all the curvelet coefficients
%
% Inputs
% C Curvelet coefficients
%
% Outputs
% img Image containing all the curvelet coefficients. The coefficents are rescaled so that
% the largest coefficent in each subband has unit norm.
%
[m,n] = size(C{end}{1});
nbscales = floor(log2(min(m,n)))-3;
img = rescale(C{1}{1},-1,1);
% img = img/max(max(abs(img))); %normalize
for sc=2:nbscales-1
nd = length(C{sc})/4;
wcnt = 0;
ONE = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
ONE = [ONE, fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w})];
end
wcnt = wcnt+nd;
TWO = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
TWO = [TWO; fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w})];
end
wcnt = wcnt+nd;
THREE = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
THREE = [fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w}), THREE];
end
wcnt = wcnt+nd;
FOUR = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
FOUR = [fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w}); FOUR];
end
wcnt = wcnt+nd;
[p,q] = size(img);
[a,b] = size(ONE);
[g,h] = size(TWO);
m = 2*a+g; n = 2*h+b; %size of new image
scale = max(max( max(max(abs(ONE))),max(max(abs(TWO))) ), max(max(max(abs(THREE))), max(max(abs(FOUR))) )); %scaling factor
new = 0.5 * ones(m,n);%background value
new(a+1:a+g,1:h) = FOUR/scale;
new(a+g+1:2*a+g,h+1:h+b) = THREE/scale;
new(a+1:a+g,h+b+1:2*h+b) = TWO/scale;
new(1:a,h+1:h+b) = ONE/scale;%normalize
dx = floor((g-p)/2); dy = floor((b-q)/2);
new(a+1+dx:a+p+dx,h+1+dy:h+q+dy) = img;
img = new;
end
function A = fdct_wrapping_dispcoef_expand(u,v,B)
A = zeros(u,v);
[p,q] = size(B);
A(1:p,1:q) = B;
|
github
|
alex-delalande/numerical-tours-master
|
plot_tensor_field.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/plot_tensor_field.m
| 5,736 |
utf_8
|
8e241783316bc4c13529031d81db17d4
|
function h = plot_tensor_field(H, M, options)
% plot_tensor_field - display a tensor field
%
% h = plot_tensor_field(H, M, options);
%
% options.sub controls sub-sampling
% options.color controls color
%
% Copyright (c) 2006 Gabriel Peyre
if nargin<3
options.null = 0;
end
if not( isstruct(options) )
sub = options;
clear options;
options.sub = sub;
end
% sub = getoptions(options, 'sub', 1);
sub = getoptions(options, 'sub', round(size(H,1)/30) );
color = getoptions(options, 'color', 'r');
if nargin<2
M = [];
end
if not(isempty(M)) && size(M,3)==1
M = repmat(M, [1 1 3]); % ensure B&W image
end
if size(H,3)==3 && size(H,4)==1
H = cat(3, H(:,:,1), H(:,:,3), H(:,:,3), H(:,:,2) );
H = reshape(H, size(H,1), size(H,2), 2, 2);
if 0
% flip the main eigen-axes
[e1,e2,l1,l2] = perform_tensor_decomp(H);
H = perform_tensor_recomp(e2,e1,l1,l2);
end
h = plot_tensor_field(H, M, sub);
return;
end
% swap X and Y axis
%%% TODO
a = H(:,:,2,2);
H(:,:,2,2) = H(:,:,1,1);
H(:,:,1,1) = a;
hold on;
if ~isempty(M)
imagesc(rescale(M)); drawnow;
end
h = fn_tensordisplay(H(:,:,1,1),H(:,:,1,2), H(:,:,2,2), 'sub', sub, 'color', color);
axis image; axis off;
colormap jet(256);
% hold off;
function h = fn_tensordisplay(varargin)
% function h = fn_tensordisplay([X,Y,]Txx,Txy,Tyy[,'sigma',sigma][,'sub',sub][,color][,patch options...]])
% function h = fn_tensordisplay([X,Y,]e[,'sigma',sigma][,'sub',sub][,color][,patch options...]])
% X,Y,Txx,Txy,Tyy
if isstruct(varargin{1}) || isstruct(varargin{3})
if isstruct(varargin{1}), nextarg=1; else nextarg=3; end
e = varargin{nextarg};
Txx = e.ytyt;
Txy = -e.ytyx;
Tyy = e.yxyx;
if nextarg==1
[nj ni] = size(Txx);
[X Y] = meshgrid(1:ni,1:nj);
else
[X Y] = deal(varargin{1:2});
end
nextarg = nextarg+1;
else
[nj ni] = size(varargin{3});
if nargin<5 || ischar(varargin{4}) || ischar(varargin{5}) || any(size(varargin{5})~=[nj ni])
[X Y] = meshgrid(1:ni,1:nj);
nextarg = 1;
else
[X Y] = deal(varargin{1:2});
nextarg = 3;
end
[Txx Txy Tyy] = deal(varargin{nextarg:nextarg+2});
nextarg = nextarg+3;
end
if any(size(X)==1), [X Y] = meshgrid(X,Y); end
[nj,ni] = size(X);
if any(size(Y)~=[nj ni]) || ...
any(size(Txx)~=[nj ni]) || any(size(Txy)~=[nj ni]) || any(size(Tyy)~=[nj ni])
error('Matrices must be same size')
end
% sigma, sub, color
color = 'r';
while nextarg<=nargin
flag = varargin{nextarg};
nextarg=nextarg+1;
if ~ischar(flag), color = flag; continue, end
switch lower(flag)
case 'sigma'
sigma = varargin{nextarg};
nextarg = nextarg+1;
switch length(sigma)
case 1
sigmax = sigma;
sigmay = sigma;
case 2
sigmax = sigma(1);
sigmay = sigma(2);
otherwise
error('sigma definition should entail two values');
end
h = fspecial('gaussian',[ceil(2*sigmay) 1],sigmay)*fspecial('gaussian',[1 ceil(2*sigmax)],sigmax);
Txx = imfilter(Txx,h,'replicate');
Txy = imfilter(Txy,h,'replicate');
Tyy = imfilter(Tyy,h,'replicate');
case 'sub'
sub = varargin{nextarg};
nextarg = nextarg+1;
switch length(sub)
case 1
[x y] = meshgrid(1:sub:ni,1:sub:nj);
sub = y+nj*(x-1);
case 2
[x y] = meshgrid(1:sub(1):ni,1:sub(2):nj);
sub = y+nj*(x-1);
end
X = X(sub); Y = Y(sub);
Txx = Txx(sub); Txy = Txy(sub); Tyy = Tyy(sub);
[nj ni] = size(sub);
case 'color'
color = varargin{nextarg};
nextarg = nextarg+1;
otherwise
break
end
end
% options
options = {varargin{nextarg:end}};
npoints = 50;
theta = (0:npoints-1)*(2*pi/npoints);
circle = [cos(theta) ; sin(theta)];
Tensor = cat(3,Txx,Txy,Txy,Tyy); % jdisplay x idisplay x tensor
Tensor = reshape(Tensor,2*nj*ni,2); % (display x 1tensor) x 2tensor
Ellipse = Tensor * circle; % (display x uv) x npoints
Ellipse = reshape(Ellipse,nj*ni,2,npoints); % display x uv x npoints
XX = repmat(X(:),1,npoints); % display x npoints
YY = repmat(Y(:),1,npoints); % display x npoints
U = reshape(Ellipse(:,1,:),nj*ni,npoints); % display x npoints
V = reshape(Ellipse(:,2,:),nj*ni,npoints); % display x npoints
umax = max(U')'; vmax = max(V')';
umax(umax==0)=1; vmax(vmax==0)=1;
if ni==1, dx=1; else dx = X(1,2)-X(1,1); end
if nj==1, dy=1; else dy = Y(2,1)-Y(1,1); end
fact = min(dx./umax,dy./vmax)*.35;
fact = repmat(fact,1,npoints);
U = XX + fact.*U;
V = YY + fact.*V;
%-----------
MM = mmax(Txx+Tyy);
mm = mmin(Txx+Tyy);
[S1, S2] = size(U);
Colormap = zeros(S2, S1, 3);
Map = colormap(jet(256));
for k =1:npoints
Colormap(k,:,1) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 1);
Colormap(k,:,2) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 2);
Colormap(k,:,3) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 3);
end
%-----------
%h = fill(U',V',color,'EdgeColor',color,options{:});
h = fill(U',V',Colormap,'EdgeColor', 'interp');
axis ij;
if nargout==0, clear h, end
function a=mmax(a)
a = max(a(:));
function a=mmin(a)
a = min(a(:));
|
github
|
alex-delalande/numerical-tours-master
|
perform_homotopy.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_homotopy.m
| 11,418 |
utf_8
|
dd245ff8cad26000a60436c3c2e2c418
|
function [X,Lambda] = perform_homotopy(D,y)
% perform_homotopy - compute the L1 regularization path
%
% X = perform_homotopy(D,y);
%
% Copyright (c) 2012 Gabriel Peyre
[P,N] = size(D);
niter = 10*P;
X = []; Lambda = [];
% initialization
C = D'*y;
[lambda,I] = max(abs(C));
x = zeros(N,1);
X(:,end+1) = x; Lambda(end+1) = lambda;
for it=1:niter
% complementary support
J = setdiff(1:N, I);
% correlations
c = D'*(y-D*x);
if norm(c)<1e-6
break;
end
% update direction
d = zeros(N,1);
d(I) = (D(:,I)'*D(:,I)) \ sign(c(I));
% useful vector
v = D(:,I)*d(I);
% Compute minimum |gamma| so that situation 1) is in force.
w = ( lambda-c(J) ) ./ ( 1 - D(:,J)'*v );
gamma1 = min(w(w>0));
if not(isempty(gamma1))
i1 = J( w==gamma1 );
end
% Compute minimum |gamma| so that situation 2) is in force.
w = ( lambda+c(J) ) ./ ( 1 + D(:,J)'*v );
gamma2 = min(w(w>0));
if not(isempty(gamma2))
i2 = J( w==gamma2 );
end
% Compute minimum |gamma| so that situation 3) is in force.
w = -x(I)./d(I);
gamma3 = min(w(w>0));
if not(isempty(gamma3))
i3 = I( w==gamma3 );
end
% any condition is in force
gamma = min([gamma1 gamma2 gamma3]);
if isempty(gamma)
break; % final solution reached
end
% new solution
x = x + gamma*d;
lambda = lambda - gamma;
if gamma==gamma1
I = [I i1];
elseif gamma==gamma2
I = [I i2];
elseif gamma==gamma3
I(I==i3) = [];
x(i3) = 0;
end
% record sparsity and lambda
X(:,end+1) = x; Lambda(end+1) = lambda;
end
return;
n = size(D,2);
niter = getoptions(options, 'niter', min(round(size(D)))/2);
lambdaStop = 0;
solFreq = 1;
verbose = 0;
[X, numIters, activationHist] = SolveLasso(D, y, n, 'lasso', niter, lambdaStop, solFreq, verbose);
lambda_list = [];
sparsity_list = sum(X~=0);
return;
function [sols, numIters, activationHist] = SolveLasso(A, y, N, algType, maxIters, lambdaStop, solFreq, verbose, OptTol)
% SolveLasso: Implements the LARS/Lasso algorithms
% Usage
% [sols, numIters, activationHist] = SolveLasso(A, y, N, algType,
% maxIters, lambdaStop, solFreq, verbose, OptTol)
% Input
% A Either an explicit nxN matrix, with rank(A) = min(N,n)
% by assumption, or a string containing the name of a
% function implementing an implicit matrix (see below for
% details on the format of the function).
% y vector of length n.
% N length of solution vector.
% algType 'lars' for the Lars algorithm,
% 'lasso' for lars with the lasso modification (default)
% maxIters maximum number of LARS iterations to perform. If not
% specified, runs to stopping condition (default)
% lambdaStop If specified (and > 0), the algorithm terminates when the
% Lagrange multiplier <= lambdaStop.
% solFreq if =0 returns only the final solution, if >0, returns an
% array of solutions, one every solFreq iterations (default 0).
% verbose 1 to print out detailed progress at each iteration, 0 for
% no output (default)
% OptTol Error tolerance, default 1e-5
% Outputs
% sols solution of the Lasso/LARS problem
% numIters Total number of steps taken
% activationHist Array of indices showing elements entering and
% leaving the solution set
% Description
% SolveLasso implements the LARS algorithm, as described by Efron et al. in
% "Least Angle Regression". Currently, the original algorithm is
% implemented, as well as the lasso modification, which solves
% min || y - Ax ||_2^2 s.t || x ||_1 <= t
% for all t > 0, using a path following method with parameter t.
% The implementation implicitly factors the active set matrix A(:,I)
% using Choleskly updates.
% The matrix A can be either an explicit matrix, or an implicit operator
% implemented as an m-file. If using the implicit form, the user should
% provide the name of a function of the following format:
% y = OperatorName(mode, m, n, x, I, dim)
% This function gets as input a vector x and an index set I, and returns
% y = A(:,I)*x if mode = 1, or y = A(:,I)'*x if mode = 2.
% A is the m by dim implicit matrix implemented by the function. I is a
% subset of the columns of A, i.e. a subset of 1:dim of length n. x is a
% vector of length n is mode = 1, or a vector of length m is mode = 2.
% References
% B. Efron, T. Hastie, I. Johnstone and R. Tibshirani,
% "Least Angle Regression", Annals of Statistics, 32, 407-499, 2004
% See Also
% SolveOMP, SolveBP, SolveStOMP
%
if nargin < 9,
OptTol = 1e-5;
end
if nargin < 8,
verbose = 0;
end
if nargin < 7,
solFreq = 0;
end
if nargin < 6,
lambdaStop = 0;
end
if nargin < 5,
maxIters = 10*N;
end
if nargin < 4,
algType = 'lasso';
end
switch lower(algType)
case 'lars'
isLasso = 0;
case 'lasso'
isLasso = 1;
end
explicitA = ~(ischar(A) || isa(A, 'function_handle'));
n = length(y);
% Global variables for linsolve function
global opts opts_tr machPrec
opts.UT = true;
opts_tr.UT = true; opts_tr.TRANSA = true;
machPrec = 1e-5;
x = zeros(N,1);
iter = 0;
% First vector to enter the active set is the one with maximum correlation
if (explicitA)
corr = A'*y;
else
corr = feval(A,2,n,N,y,1:N,N); % = A'*y
end
lambda = max(abs(corr));
newIndices = find(abs(abs(corr)-lambda) < machPrec)';
% Initialize Cholesky factor of A_I
R_I = [];
activeSet = [];
for j = 1:length(newIndices)
iter = iter+1;
[R_I, flag] = updateChol(R_I, n, N, A, explicitA, activeSet, newIndices(j));
activeSet = [activeSet newIndices(j)];
if verbose
fprintf('Iteration %d: Adding variable %d\n', iter, activeSet(j));
end
end
activationHist = activeSet;
collinearIndices = [];
sols = [];
done = 0;
while ~done
% Compute Lars direction - Equiangular vector
dx = zeros(N,1);
% Solve the equation (A_I'*A_I)dx_I = corr_I
z = linsolve(R_I,corr(activeSet),opts_tr);
dx(activeSet) = linsolve(R_I,z,opts);
if (explicitA)
dmu = A'*(A(:,activeSet)*dx(activeSet));
else
dmu = feval(A,1,n,length(activeSet),dx(activeSet),activeSet,N);
dmu = feval(A,2,n,N,dmu,1:N,N);
end
% For Lasso, Find first active vector to violate sign constraint
if isLasso
zc = -x(activeSet)./dx(activeSet);
gammaI = min([zc(zc > 0); inf]);
removeIndices = activeSet(find(zc == gammaI));
else
gammaI = Inf;
removeIndices = [];
end
% Find first inactive vector to enter the active set
if (length(activeSet) >= min(n, N))
gammaIc = 1;
else
inactiveSet = 1:N;
inactiveSet(activeSet) = 0;
inactiveSet(collinearIndices) = 0;
inactiveSet = find(inactiveSet > 0);
lambda = abs(corr(activeSet(1)));
dmu_Ic = dmu(inactiveSet);
c_Ic = corr(inactiveSet);
epsilon = 1e-12;
gammaArr = [(lambda-c_Ic)./(lambda - dmu_Ic + epsilon) (lambda+c_Ic)./(lambda + dmu_Ic + epsilon)]';
gammaArr(gammaArr < machPrec) = inf;
gammaArr = min(gammaArr)';
[gammaIc, Imin] = min(gammaArr);
end
% If gammaIc = 1, we are at the LS solution
if (1-gammaIc) < OptTol
newIndices = [];
else
newIndices = inactiveSet(find(abs(gammaArr - gammaIc) < machPrec));
%newIndices = inactiveSet(Imin);
end
gammaMin = min(gammaIc,gammaI);
% Compute the next Lars step
x = x + gammaMin*dx;
corr = corr - gammaMin*dmu;
% Check stopping condition
if ((1-gammaMin) < OptTol) | ((lambdaStop > 0) & (lambda <= lambdaStop))
done = 1;
end
% Add new indices to active set
if (gammaIc <= gammaI) && (length(newIndices) > 0)
for j = 1:length(newIndices)
iter = iter+1;
if verbose
fprintf('Iteration %d: Adding variable %d\n', iter, newIndices(j));
end
% Update the Cholesky factorization of A_I
[R_I, flag] = updateChol(R_I, n, N, A, explicitA, activeSet, newIndices(j));
% Check for collinearity
if (flag)
collinearIndices = [collinearIndices newIndices(j)];
if verbose
fprintf('Iteration %d: Variable %d is collinear\n', iter, newIndices(j));
end
else
activeSet = [activeSet newIndices(j)];
activationHist = [activationHist newIndices(j)];
end
end
end
% Remove violating indices from active set
if (gammaI <= gammaIc)
for j = 1:length(removeIndices)
iter = iter+1;
col = find(activeSet == removeIndices(j));
if verbose
fprintf('Iteration %d: Dropping variable %d\n', iter, removeIndices(j));
end
% Downdate the Cholesky factorization of A_I
R_I = downdateChol(R_I,col);
activeSet = [activeSet(1:col-1), activeSet(col+1:length(activeSet))];
% Reset collinear set
collinearIndices = [];
end
x(removeIndices) = 0; % To avoid numerical errors
activationHist = [activationHist -removeIndices];
end
if iter >= maxIters
done = 1;
end
if done | ((solFreq > 0) & (~mod(iter,solFreq)))
sols = [sols x];
end
end
numIters = iter;
clear opts opts_tr machPrec
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R, flag] = updateChol(R, n, N, A, explicitA, activeSet, newIndex)
% updateChol: Updates the Cholesky factor R of the matrix
% A(:,activeSet)'*A(:,activeSet) by adding A(:,newIndex)
% If the candidate column is in the span of the existing
% active set, R is not updated, and flag is set to 1.
global opts_tr machPrec
flag = 0;
if (explicitA)
newVec = A(:,newIndex);
else
e = zeros(N,1);
e(newIndex) = 1;
newVec = feval(A,1,n,N,e,1:N,N);
end
if length(activeSet) == 0,
R = sqrt(sum(newVec.^2));
else
if (explicitA)
p = linsolve(R,A(:,activeSet)'*A(:,newIndex),opts_tr);
else
AnewVec = feval(A,2,n,length(activeSet),newVec,activeSet,N);
p = linsolve(R,AnewVec,opts_tr);
end
q = sum(newVec.^2) - sum(p.^2);
if (q <= machPrec) % Collinear vector
flag = 1;
else
R = [R p; zeros(1, size(R,2)) sqrt(q)];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function R = downdateChol(R, j)
% downdateChol: `Downdates' the cholesky factor R by removing the
% column indexed by j.
% Remove the j-th column
R(:,j) = [];
[m,n] = size(R);
% R now has nonzeros below the diagonal in columns j through n.
% We use plane rotations to zero the 'violating nonzeros'.
for k = j:n
p = k:k+1;
[G,R(p,k)] = planerot(R(p,k));
if k < n
R(p,k+1:n) = G*R(p,k+1:n);
end
end
% Remove last row of zeros from R
R = R(1:n,:);
%
% Copyright (c) 2006. Yaakov Tsaig and Joshua Sweetkind-Singer
%
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
|
github
|
alex-delalande/numerical-tours-master
|
load_image.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/load_image.m
| 20,275 |
utf_8
|
c700b54853577ab37402e27e4ca061b8
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
if iscell(type)
for i=1:length(type)
M{i} = load_image(type{i},n,options);
end
return;
end
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = getoptions(options, 'eta', .1);
gamma = getoptions(options, 'gamma', 1/sqrt(2));
radius = getoptions(options, 'radius', 10);
center = getoptions(options, 'center', [0 0]);
center1 = getoptions(options, 'center1', [0 0]);
w = getoptions(options, 'tube_width', 0.06);
nb_points = getoptions(options, 'nb_points', 9);
scaling = getoptions(options, 'scaling', 1);
theta = getoptions(options, 'theta', 30 * 2*pi/360);
eccentricity = getoptions(options, 'eccentricity', 1.3);
sigma = getoptions(options, 'sigma', 0);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
if strcmp(type(1:min(12,end)), 'square-tube-')
k = str2double(type(13:end));
c1 = [.22 .5]; c2 = [1-c1(1) .5];
eta = 1.5;
r1 = [c1 c1] + .21*[-1 -eta 1 eta];
r2 = [c2 c2] + .21*[-1 -eta 1 eta];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
if mod(k,2)==0
sel = n/2-k/2+1:n/2+k/2;
else
sel = n/2-(k-1)/2:n/2+(k-1)/2;
end
M( round(.25*n:.75*n), sel ) = 1;
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case 'constant'
M = ones(n);
case 'ramp'
x = linspace(0,1,n);
[Y,M] = meshgrid(x,x);
case 'bump'
s = getoptions(options, 'bump_size', .5);
c = getoptions(options, 'center', [0 0]);
if length(s)==1
s = [s s];
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
X = (X-c(1))/s(1); Y = (Y-c(2))/s(2);
M = exp( -(X.^2+Y.^2)/2 );
case 'periodic'
x = linspace(-pi,pi,n)/1.1;
[Y,X] = meshgrid(x,x);
f = getoptions(options, 'freq', 6);
M = (1+cos(f*X)).*(1+cos(f*Y));
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
M = create_letter(type(8), radius, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.im = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
options.radius = 0.45;
options.center = [.5 .5];
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T-pi/2)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
f = getoptions(options, 'frequency', 30);
eta = getoptions(options, 'width', .3);
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
width = getoptions(options, 'width', round(n/16) );
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'geometrical'
J = getoptions(options, 'Jgeometrical', 4);
sgeom = 100*n/256;
options.bound = 'per';
A = ones(n);
for j=0:J-1
B = A;
for k=1:2^j
I = find(B==k);
U = perform_blurring(randn(n),sgeom,options);
s = median(U(I));
I1 = find( (B==k) & (U>s) );
I2 = find( (B==k) & (U<=s) );
A(I1) = 2*k-1;
A(I2) = 2*k;
end
end
M = A;
case 'lic-texture'
disp('Computing random tensor field.');
options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256);
T = compute_tensor_field_random(n,options);
Flow = perform_tensor_decomp(T); % extract eigenfield.
options.isoriented = 0; % no orientation in streamlines
% initial texture
lic_width = getoptions(options, 'lic_width', 0);
M0 = perform_blurring(randn(n),lic_width);
M0 = perform_histogram_equalization( M0, 'linear');
options.histogram = 'linear';
options.dt = 0.4;
options.M0 = M0;
options.verb = 1;
options.flow_correction = 1;
options.niter_lic = 3;
w = 30;
M = perform_lic(Flow, w, options);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'tv-image'
M = rand(n);
tau = compute_total_variation(M);
options.niter = 400;
[M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options);
M = perform_histogram_equalization(M,'linear');
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'line-windowed'
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
eta = .3;
gamma = getoptions(options, 'gamma', pi/10);
parabola = getoptions(options, 'parabola', 0);
M = (X-eta) - gamma*Y - parabola*Y.^2 < 0;
f = sin( pi*x ).^2;
M = M .* ( f'*f );
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
theta = getoptions(options, 'theta', .2);
freq = getoptions(options, 'freq', .2);
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'twodisks'
M = zeros(n);
options.center = [.25 .25];
M = load_image('disk', n, options);
options.center = [.75 .75];
M = M + load_image('disk', n, options);
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
alpha = getoptions(options, 'alpha', 1);
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
sigma = getoptions(options, 'sigma', 10);
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
c = getoptions(c, 'c', .1);
% angle
theta = getoptions(options, 'theta', pi/sqrt(2));
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
nbr_periods = getoptions(options, 'nbr_periods', 8);
theta = getoptions(options, 'theta', 1/sqrt(2));
skew = getoptions(options, 'skew', 1/sqrt(2) );
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
sigma = getoptions(options, 'sigma', 1);
M = randn(n) * sigma;
case 'disk-corner'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
rho = .3; eta = .1;
M1 = rho*X+eta<Y;
c = [0 .2]; r = .85;
d = (X-c(1)).^2 + (Y-c(2)).^2;
M2 = d<r^2;
M = M1.*M2;
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
if strcmp(type, 'peppers-bw')
M(:,1) = M(:,2);
M(1,:) = M(2,:);
end
if sigma>0
M = perform_blurring(M,sigma);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
M = perform_blurring(M,sigma);
end
M = rescale(M);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github
|
alex-delalande/numerical-tours-master
|
perform_curvelet_transform.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_curvelet_transform.m
| 33,957 |
utf_8
|
63811c4cedefc4b0a5ede5a2b3269c54
|
function y = perform_curvelet_transform(x,options)
% perform_curvelet_transform - a wrapper to curvlab
%
% M = perform_curvelet_transform(MW,options);
%
% Forward and backward curvelet transform
% You must provide options.n (width of the image).
%
% Visit www.curvelab.org for the full code.
options.null = 0;
finest = getoptions(options, 'finest',1) ; % =1(curv) =2(wav)
nbscales = getoptions(options, 'nbscales', 5); % log2(size(M,1))-2;
nbangles_coarse = getoptions(options, 'nbangles_coarse', 16);
is_real = getoptions(options, 'is_real', 0);
n = getoptions(options, 'n', 1,1);
if not(iscell(x))
% fwd transform
y = fdct_wrapping(x, is_real, finest, nbscales, nbangles_coarse);
else
y = real( ifdct_wrapping(x, is_real, n,n ) );
end
%%
function C = fdct_wrapping(x, is_real, finest, nbscales, nbangles_coarse)
% fdct_wrapping.m - Fast Discrete Curvelet Transform via wedge wrapping - Version 1.0
%
% Inputs
% x M-by-N matrix
%
% Optional Inputs
% is_real Type of the transform
% 0: complex-valued curvelets
% 1: real-valued curvelets
% [default set to 0]
% finest Chooses one of two possibilities for the coefficients at the
% finest level:
% 1: curvelets
% 2: wavelets
% [default set to 2]
% nbscales number of scales including the coarsest wavelet level
% [default set to ceil(log2(min(M,N)) - 3)]
% nbangles_coarse
% number of angles at the 2nd coarsest level, minimum 8,
% must be a multiple of 4. [default set to 16]
%
% Outputs
% C Cell array of curvelet coefficients.
% C{j}{l}(k1,k2) is the coefficient at
% - scale j: integer, from finest to coarsest scale,
% - angle l: integer, starts at the top-left corner and
% increases clockwise,
% - position k1,k2: both integers, size varies with j
% and l.
% If is_real is 1, there are two types of curvelets,
% 'cosine' and 'sine'. For a given scale j, the 'cosine'
% coefficients are stored in the first two quadrants (low
% values of l), the 'sine' coefficients in the last two
% quadrants (high values of l).
%
% See also ifdct_wrapping.m, fdct_wrapping_param.m
%
% By Laurent Demanet, 2004
X = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)));
[N1,N2] = size(X);
if nargin < 2, is_real = 0; end;
if nargin < 3, finest = 2; end;
if nargin < 4, nbscales = ceil(log2(min(N1,N2)) - 3); end;
if nargin < 5, nbangles_coarse = 16; end;
% Initialization: data structure
nbangles = [1, nbangles_coarse .* 2.^(ceil((nbscales-(nbscales:-1:2))/2))];
if finest == 2, nbangles(nbscales) = 1; end;
C = cell(1,nbscales);
for j = 1:nbscales
C{j} = cell(1,nbangles(j));
end;
% Loop: pyramidal scale decomposition
M1 = N1/3;
M2 = N2/3;
if finest == 1,
% Initialization: smooth periodic extension of high frequencies
bigN1 = 2*floor(2*M1)+1;
bigN2 = 2*floor(2*M2)+1;
equiv_index_1 = 1+mod(floor(N1/2)-floor(2*M1)+(1:bigN1)-1,N1);
equiv_index_2 = 1+mod(floor(N2/2)-floor(2*M2)+(1:bigN2)-1,N2);
X = X(equiv_index_1,equiv_index_2);
% Invariant: equiv_index_1(floor(2*M1)+1) == (N1 + 2 - mod(N1,2))/2
% is the center in frequency. Same for M2, N2.
window_length_1 = floor(2*M1) - floor(M1) - 1 - (mod(N1,3)==0);
window_length_2 = floor(2*M2) - floor(M2) - 1 - (mod(N2,3)==0);
% Invariant: floor(M1) + floor(2*M1) == N1 - (mod(M1,3)~=0)
% Same for M2, N2.
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
if mod(N1,3)==0, lowpass_1 = [0, lowpass_1, 0]; end;
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
if mod(N2,3)==0, lowpass_2 = [0, lowpass_2, 0]; end;
lowpass = lowpass_1'*lowpass_2;
Xlow = X .* lowpass;
scales = nbscales:-1:2;
else
M1 = M1/2;
M2 = M2/2;
window_length_1 = floor(2*M1) - floor(M1) - 1;
window_length_2 = floor(2*M2) - floor(M2) - 1;
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
lowpass = lowpass_1'*lowpass_2;
hipass = sqrt(1 - lowpass.^2);
Xlow_index_1 = ((-floor(2*M1)):floor(2*M1)) + ceil((N1+1)/2);
Xlow_index_2 = ((-floor(2*M2)):floor(2*M2)) + ceil((N2+1)/2);
Xlow = X(Xlow_index_1, Xlow_index_2) .* lowpass;
Xhi = X;
Xhi(Xlow_index_1, Xlow_index_2) = Xhi(Xlow_index_1, Xlow_index_2) .* hipass;
C{nbscales}{1} = fftshift(ifft2(ifftshift(Xhi)))*sqrt(prod(size(Xhi)));
if is_real, C{nbscales}{1} = real(C{nbscales}{1}); end;
scales = (nbscales-1):-1:2;
end;
for j = scales,
M1 = M1/2;
M2 = M2/2;
window_length_1 = floor(2*M1) - floor(M1) - 1;
window_length_2 = floor(2*M2) - floor(M2) - 1;
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
lowpass = lowpass_1'*lowpass_2;
hipass = sqrt(1 - lowpass.^2);
Xhi = Xlow; % size is 2*floor(4*M1)+1 - by - 2*floor(4*M2)+1
Xlow_index_1 = ((-floor(2*M1)):floor(2*M1)) + floor(4*M1) + 1;
Xlow_index_2 = ((-floor(2*M2)):floor(2*M2)) + floor(4*M2) + 1;
Xlow = Xlow(Xlow_index_1, Xlow_index_2);
Xhi(Xlow_index_1, Xlow_index_2) = Xlow .* hipass;
Xlow = Xlow .* lowpass; % size is 2*floor(2*M1)+1 - by - 2*floor(2*M2)+1
% Loop: angular decomposition
l = 0;
nbquadrants = 2 + 2*(~is_real);
nbangles_perquad = nbangles(j)/4;
for quadrant = 1:nbquadrants
M_horiz = M2 * (mod(quadrant,2)==1) + M1 * (mod(quadrant,2)==0);
M_vert = M1 * (mod(quadrant,2)==1) + M2 * (mod(quadrant,2)==0);
if mod(nbangles_perquad,2),
wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);
wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;
wedge_ticks = [wedge_ticks_left, wedge_ticks_right(end:-1:1)];
else
wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);
wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;
wedge_ticks = [wedge_ticks_left, wedge_ticks_right((end-1):-1:1)];
end;
wedge_endpoints = wedge_ticks(2:2:(end-1)); % integers
wedge_midpoints = (wedge_endpoints(1:(end-1)) + wedge_endpoints(2:end))/2;
% integers or half-integers
% Left corner wedge
l = l+1;
first_wedge_endpoint_vert = round(2*floor(4*M_vert)/(2*nbangles_perquad) + 1);
length_corner_wedge = floor(4*M_vert) - floor(M_vert) + ceil(first_wedge_endpoint_vert/4);
Y_corner = 1:length_corner_wedge;
[XX,YY] = meshgrid(1:(2*floor(4*M_horiz)+1),Y_corner);
width_wedge = wedge_endpoints(2) + wedge_endpoints(1) - 1;
slope_wedge = (floor(4*M_horiz) + 1 - wedge_endpoints(1))/floor(4*M_vert);
left_line = round(2 - wedge_endpoints(1) + slope_wedge*(Y_corner - 1));
% integers
[wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));
first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...
mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
% Coordinates of the top-left corner of the wedge wrapped
% around the origin. Some subtleties when the wedge is
% even-sized because of the forthcoming 90 degrees rotation
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+1+abs(cols-1)));
new_row = 1 + mod(row - first_row, length_corner_wedge);
wrapped_data(new_row,:) = Xhi(row,admissible_cols) .* (cols > 0);
wrapped_XX(new_row,:) = XX(row,admissible_cols);
wrapped_YY(new_row,:) = YY(row,admissible_cols);
end;
slope_wedge_right = (floor(4*M_horiz)+1 - wedge_midpoints(1))/floor(4*M_vert);
mid_line_right = wedge_midpoints(1) + slope_wedge_right*(wrapped_YY - 1);
% not integers in general
coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(2) - wedge_endpoints(1)) * ...
(wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);
C2 = 1/(1/(2*(floor(4*M_horiz))/(wedge_endpoints(1) - 1) - 1) + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));
C1 = C2 / (2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1);
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) = ...
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) + 1;
coord_corner = C1 + C2 * ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert))) ./ ...
(2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert))));
wl_left = fdct_wrapping_window(coord_corner);
[wl_right,wr_right] = fdct_wrapping_window(coord_right);
wrapped_data = wrapped_data .* (wl_left .* wr_right);
switch is_real
case 0
wrapped_data = rot90(wrapped_data,-(quadrant-1));
C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
case 1
wrapped_data = rot90(wrapped_data,-(quadrant-1));
x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
C{j}{l} = sqrt(2)*real(x);
C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);
end;
% Regular wedges
length_wedge = floor(4*M_vert) - floor(M_vert);
Y = 1:length_wedge;
first_row = floor(4*M_vert)+2-ceil((length_wedge+1)/2)+...
mod(length_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
for subl = 2:(nbangles_perquad-1);
l = l+1;
width_wedge = wedge_endpoints(subl+1) - wedge_endpoints(subl-1) + 1;
slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(subl))/floor(4*M_vert);
left_line = round(wedge_endpoints(subl-1) + slope_wedge*(Y - 1));
[wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_wedge,width_wedge));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
new_row = 1 + mod(row - first_row, length_wedge);
wrapped_data(new_row,:) = Xhi(row,cols);
wrapped_XX(new_row,:) = XX(row,cols);
wrapped_YY(new_row,:) = YY(row,cols);
end;
slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(subl-1))/floor(4*M_vert);
mid_line_left = wedge_midpoints(subl-1) + slope_wedge_left*(wrapped_YY - 1);
coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl) - wedge_endpoints(subl-1)) * ...
(wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);
slope_wedge_right = ((floor(4*M_horiz)+1) - wedge_midpoints(subl))/floor(4*M_vert);
mid_line_right = wedge_midpoints(subl) + slope_wedge_right*(wrapped_YY - 1);
coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl+1) - wedge_endpoints(subl)) * ...
(wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);
wl_left = fdct_wrapping_window(coord_left);
[wl_right,wr_right] = fdct_wrapping_window(coord_right);
wrapped_data = wrapped_data .* (wl_left .* wr_right);
switch is_real
case 0
wrapped_data = rot90(wrapped_data,-(quadrant-1));
C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
case 1
wrapped_data = rot90(wrapped_data,-(quadrant-1));
x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
C{j}{l} = sqrt(2)*real(x);
C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);
end;
end;
% Right corner wedge
l = l+1;
width_wedge = 4*floor(4*M_horiz) + 3 - wedge_endpoints(end) - wedge_endpoints(end-1);
slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(end))/floor(4*M_vert);
left_line = round(wedge_endpoints(end-1) + slope_wedge*(Y_corner - 1));
[wrapped_data, wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));
first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...
mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));
new_row = 1 + mod(row - first_row, length_corner_wedge);
wrapped_data(new_row,:) = Xhi(row,admissible_cols) .* (cols <= (2*floor(4*M_horiz)+1));
wrapped_XX(new_row,:) = XX(row,admissible_cols);
wrapped_YY(new_row,:) = YY(row,admissible_cols);
end;
slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(end))/floor(4*M_vert);
mid_line_left = wedge_midpoints(end) + slope_wedge_left*(wrapped_YY - 1);
coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(end) - wedge_endpoints(end-1)) * ...
(wrapped_XX - mid_line_left)./(floor(4*M_vert) + 1 - wrapped_YY);
C2 = -1/(2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1 + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));
C1 = -C2 * (2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1);
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY - 1)/floor(4*M_vert)) = ...
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY - 1)/floor(4*M_vert)) - 1;
coord_corner = C1 + C2 * (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert)))) ./ ...
((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert)));
wl_left = fdct_wrapping_window(coord_left);
[wl_right,wr_right] = fdct_wrapping_window(coord_corner);
wrapped_data = wrapped_data .* (wl_left .* wr_right);
switch is_real
case 0
wrapped_data = rot90(wrapped_data,-(quadrant-1));
C{j}{l} = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
case 1
wrapped_data = rot90(wrapped_data,-(quadrant-1));
x = fftshift(ifft2(ifftshift(wrapped_data)))*sqrt(prod(size(wrapped_data)));
C{j}{l} = sqrt(2)*real(x);
C{j}{l+nbangles(j)/2} = sqrt(2)*imag(x);
end;
if quadrant < nbquadrants, Xhi = rot90(Xhi); end;
end;
end;
% Coarsest wavelet level
C{1}{1} = fftshift(ifft2(ifftshift(Xlow)))*sqrt(prod(size(Xlow)));
if is_real == 1,
C{1}{1} = real(C{1}{1});
end;
function x = ifdct_wrapping(C, is_real, M, N)
% ifdct_wrapping.m - Inverse Fast Discrete Curvelet Transform via wedge wrapping - Version 1.0
% This is in fact the adjoint, also the pseudo-inverse
%
% Inputs
% C Cell array containing curvelet coefficients (see
% description in fdct_wrapping.m)
% is_real As used in fdct_wrapping.m
% M, N Size of the image to be recovered (not necessary if finest
% = 2)
%
% Outputs
% x M-by-N matrix
%
% See also fdct_wrapping.m
%
% By Laurent Demanet, 2004
% Initialization
nbscales = length(C);
nbangles_coarse = length(C{2});
nbangles = [1, nbangles_coarse .* 2.^(ceil((nbscales-(nbscales:-1:2))/2))];
if length(C{end}) == 1, finest = 2; else finest = 1; end;
if finest == 2, nbangles(nbscales) = 1; end;
if nargin < 2, is_real = 0; end;
if nargin < 4,
if finest == 1, error('Syntax: IFCT_wrapping(C,M,N) where the matrix to be recovered is M-by-N'); end;
[N1,N2] = size(C{end}{1});
else
N1 = M;
N2 = N;
end;
M1 = N1/3;
M2 = N2/3;
if finest == 1;
bigN1 = 2*floor(2*M1)+1;
bigN2 = 2*floor(2*M2)+1;
X = zeros(bigN1,bigN2);
% Initialization: preparing the lowpass filter at finest scale
window_length_1 = floor(2*M1) - floor(M1) - 1 - (mod(N1,3)==0);
window_length_2 = floor(2*M2) - floor(M2) - 1 - (mod(N2,3)==0);
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
if mod(N1,3)==0, lowpass_1 = [0, lowpass_1, 0]; end;
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
if mod(N2,3)==0, lowpass_2 = [0, lowpass_2, 0]; end;
lowpass = lowpass_1'*lowpass_2;
scales = nbscales:-1:2;
else
M1 = M1/2;
M2 = M2/2;
bigN1 = 2*floor(2*M1)+1;
bigN2 = 2*floor(2*M2)+1;
X = zeros(bigN1,bigN2);
window_length_1 = floor(2*M1) - floor(M1) - 1;
window_length_2 = floor(2*M2) - floor(M2) - 1;
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
lowpass = lowpass_1'*lowpass_2;
hipass_finest = sqrt(1 - lowpass.^2);
scales = (nbscales-1):-1:2;
end;
% Loop: pyramidal reconstruction
Xj_topleft_1 = 1;
Xj_topleft_2 = 1;
for j = scales,
M1 = M1/2;
M2 = M2/2;
window_length_1 = floor(2*M1) - floor(M1) - 1;
window_length_2 = floor(2*M2) - floor(M2) - 1;
coord_1 = 0:(1/window_length_1):1;
coord_2 = 0:(1/window_length_2):1;
[wl_1,wr_1] = fdct_wrapping_window(coord_1);
[wl_2,wr_2] = fdct_wrapping_window(coord_2);
lowpass_1 = [wl_1, ones(1,2*floor(M1)+1), wr_1];
lowpass_2 = [wl_2, ones(1,2*floor(M2)+1), wr_2];
lowpass_next = lowpass_1'*lowpass_2;
hipass = sqrt(1 - lowpass_next.^2);
Xj = zeros(2*floor(4*M1)+1,2*floor(4*M2)+1);
% Loop: angles
l = 0;
nbquadrants = 2 + 2*(~is_real);
nbangles_perquad = nbangles(j)/4;
for quadrant = 1:nbquadrants
M_horiz = M2 * (mod(quadrant,2)==1) + M1 * (mod(quadrant,2)==0);
M_vert = M1 * (mod(quadrant,2)==1) + M2 * (mod(quadrant,2)==0);
if mod(nbangles_perquad,2),
wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);
wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;
wedge_ticks = [wedge_ticks_left, wedge_ticks_right(end:-1:1)];
else
wedge_ticks_left = round((0:(1/(2*nbangles_perquad)):.5)*2*floor(4*M_horiz) + 1);
wedge_ticks_right = 2*floor(4*M_horiz) + 2 - wedge_ticks_left;
wedge_ticks = [wedge_ticks_left, wedge_ticks_right((end-1):-1:1)];
end;
wedge_endpoints = wedge_ticks(2:2:(end-1)); % integers
wedge_midpoints = (wedge_endpoints(1:(end-1)) + wedge_endpoints(2:end))/2;
% Left corner wedge
l = l+1;
first_wedge_endpoint_vert = round(2*floor(4*M_vert)/(2*nbangles_perquad) + 1);
length_corner_wedge = floor(4*M_vert) - floor(M_vert) + ceil(first_wedge_endpoint_vert/4);
Y_corner = 1:length_corner_wedge;
[XX,YY] = meshgrid(1:(2*floor(4*M_horiz)+1),Y_corner);
width_wedge = wedge_endpoints(2) + wedge_endpoints(1) - 1;
slope_wedge = (floor(4*M_horiz) + 1 - wedge_endpoints(1))/floor(4*M_vert);
left_line = round(2 - wedge_endpoints(1) + slope_wedge*(Y_corner - 1));
[wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));
first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...
mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
new_row = 1 + mod(row - first_row, length_corner_wedge);
admissible_cols = round(1/2*(cols+1+abs(cols-1)));
wrapped_XX(new_row,:) = XX(row,admissible_cols);
wrapped_YY(new_row,:) = YY(row,admissible_cols);
end;
slope_wedge_right = (floor(4*M_horiz)+1 - wedge_midpoints(1))/floor(4*M_vert);
mid_line_right = wedge_midpoints(1) + slope_wedge_right*(wrapped_YY - 1);
% not integers
% in general
coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(2) - wedge_endpoints(1)) * ...
(wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);
C2 = 1/(1/(2*(floor(4*M_horiz))/(wedge_endpoints(1) - 1) - 1) + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));
C1 = C2 / (2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1);
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) = ...
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) + (wrapped_YY-1)/floor(4*M_vert) == 2) + 1;
coord_corner = C1 + C2 * ((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert))) ./ ...
(2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert))));
wl_left = fdct_wrapping_window(coord_corner);
[wl_right,wr_right] = fdct_wrapping_window(coord_right);
switch is_real
case 0
wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));
wrapped_data = rot90(wrapped_data,(quadrant-1));
case 1
x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};
wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);
wrapped_data = rot90(wrapped_data,(quadrant-1));
end;
wrapped_data = wrapped_data .* (wl_left .* wr_right);
% Unwrapping data
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+1+abs(cols-1)));
new_row = 1 + mod(row - first_row, length_corner_wedge);
Xj(row,admissible_cols) = Xj(row,admissible_cols) + wrapped_data(new_row,:);
% We use the following property: in an assignment
% A(B) = C where B and C are vectors, if
% some value x repeats in B, then the
% last occurrence of x is the one
% corresponding to the eventual assignment.
end;
% Regular wedges
length_wedge = floor(4*M_vert) - floor(M_vert);
Y = 1:length_wedge;
first_row = floor(4*M_vert)+2-ceil((length_wedge+1)/2)+...
mod(length_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
for subl = 2:(nbangles_perquad-1);
l = l+1;
width_wedge = wedge_endpoints(subl+1) - wedge_endpoints(subl-1) + 1;
slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(subl))/floor(4*M_vert);
left_line = round(wedge_endpoints(subl-1) + slope_wedge*(Y - 1));
[wrapped_XX, wrapped_YY] = deal(zeros(length_wedge,width_wedge));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
new_row = 1 + mod(row - first_row, length_wedge);
wrapped_XX(new_row,:) = XX(row,cols);
wrapped_YY(new_row,:) = YY(row,cols);
end;
slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(subl-1))/floor(4*M_vert);
mid_line_left = wedge_midpoints(subl-1) + slope_wedge_left*(wrapped_YY - 1);
coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl) - wedge_endpoints(subl-1)) * ...
(wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);
slope_wedge_right = ((floor(4*M_horiz)+1) - wedge_midpoints(subl))/floor(4*M_vert);
mid_line_right = wedge_midpoints(subl) + slope_wedge_right*(wrapped_YY - 1);
coord_right = 1/2 + floor(4*M_vert)/(wedge_endpoints(subl+1) - wedge_endpoints(subl)) * ...
(wrapped_XX - mid_line_right)./(floor(4*M_vert)+1 - wrapped_YY);
wl_left = fdct_wrapping_window(coord_left);
[wl_right,wr_right] = fdct_wrapping_window(coord_right);
switch is_real
case 0
wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));
wrapped_data = rot90(wrapped_data,(quadrant-1));
case 1
x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};
wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);
wrapped_data = rot90(wrapped_data,(quadrant-1));
end;
wrapped_data = wrapped_data .* (wl_left .* wr_right);
% Unwrapping data
for row = Y
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
new_row = 1 + mod(row - first_row, length_wedge);
Xj(row,cols) = Xj(row,cols) + wrapped_data(new_row,:);
end;
end; % for subl
% Right corner wedge
l = l+1;
width_wedge = 4*floor(4*M_horiz) + 3 - wedge_endpoints(end) - wedge_endpoints(end-1);
slope_wedge = ((floor(4*M_horiz)+1) - wedge_endpoints(end))/floor(4*M_vert);
left_line = round(wedge_endpoints(end-1) + slope_wedge*(Y_corner - 1));
[wrapped_XX, wrapped_YY] = deal(zeros(length_corner_wedge,width_wedge));
first_row = floor(4*M_vert)+2-ceil((length_corner_wedge+1)/2)+...
mod(length_corner_wedge+1,2)*(quadrant-2 == mod(quadrant-2,2));
first_col = floor(4*M_horiz)+2-ceil((width_wedge+1)/2)+...
mod(width_wedge+1,2)*(quadrant-3 == mod(quadrant-3,2));
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));
new_row = 1 + mod(row - first_row, length_corner_wedge);
wrapped_XX(new_row,:) = XX(row,admissible_cols);
wrapped_YY(new_row,:) = YY(row,admissible_cols);
end;
YY = Y_corner'*ones(1,width_wedge);
slope_wedge_left = ((floor(4*M_horiz)+1) - wedge_midpoints(end))/floor(4*M_vert);
mid_line_left = wedge_midpoints(end) + slope_wedge_left*(wrapped_YY - 1);
coord_left = 1/2 + floor(4*M_vert)/(wedge_endpoints(end) - wedge_endpoints(end-1)) * ...
(wrapped_XX - mid_line_left)./(floor(4*M_vert)+1 - wrapped_YY);
C2 = -1/(2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1 + 1/(2*(floor(4*M_vert))/(first_wedge_endpoint_vert - 1) - 1));
C1 = -C2 * (2*(floor(4*M_horiz))/(wedge_endpoints(end) - 1) - 1);
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY-1)/floor(4*M_vert)) = ...
wrapped_XX((wrapped_XX - 1)/floor(4*M_horiz) == (wrapped_YY-1)/floor(4*M_vert)) - 1;
coord_corner = C1 + C2 * (2-((wrapped_XX - 1)/(floor(4*M_horiz)) + (wrapped_YY - 1)/(floor(4*M_vert)))) ./ ...
((wrapped_XX - 1)/(floor(4*M_horiz)) - (wrapped_YY - 1)/(floor(4*M_vert)));
wl_left = fdct_wrapping_window(coord_left);
[wl_right,wr_right] = fdct_wrapping_window(coord_corner);
switch is_real
case 0
wrapped_data = fftshift(fft2(ifftshift(C{j}{l})))/sqrt(prod(size(C{j}{l})));
wrapped_data = rot90(wrapped_data,(quadrant-1));
case 1
x = C{j}{l} + sqrt(-1)*C{j}{l+nbangles(j)/2};
wrapped_data = fftshift(fft2(ifftshift(x)))/sqrt(prod(size(x)))/sqrt(2);
wrapped_data = rot90(wrapped_data,(quadrant-1));
end;
wrapped_data = wrapped_data .* (wl_left .* wr_right);
% Unwrapping data
for row = Y_corner
cols = left_line(row) + mod((0:(width_wedge-1))-(left_line(row)-first_col),width_wedge);
admissible_cols = round(1/2*(cols+2*floor(4*M_horiz)+1-abs(cols-(2*floor(4*M_horiz)+1))));
new_row = 1 + mod(row - first_row, length_corner_wedge);
Xj(row,fliplr(admissible_cols)) = Xj(row,fliplr(admissible_cols)) + wrapped_data(new_row,end:-1:1);
% We use the following property: in an assignment
% A(B) = C where B and C are vectors, if
% some value x repeats in B, then the
% last occurrence of x is the one
% corresponding to the eventual assignment.
end;
Xj = rot90(Xj);
end; % for quadrant
Xj = Xj .* lowpass;
Xj_index1 = ((-floor(2*M1)):floor(2*M1)) + floor(4*M1) + 1;
Xj_index2 = ((-floor(2*M2)):floor(2*M2)) + floor(4*M2) + 1;
Xj(Xj_index1, Xj_index2) = Xj(Xj_index1, Xj_index2) .* hipass;
loc_1 = Xj_topleft_1 + (0:(2*floor(4*M1)));
loc_2 = Xj_topleft_2 + (0:(2*floor(4*M2)));
X(loc_1,loc_2) = X(loc_1,loc_2) + Xj;
% Preparing for loop reentry or exit
Xj_topleft_1 = Xj_topleft_1 + floor(4*M1) - floor(2*M1);
Xj_topleft_2 = Xj_topleft_2 + floor(4*M2) - floor(2*M2);
lowpass = lowpass_next;
end; % for j
if is_real
Y = X;
X = rot90(X,2);
X = X + conj(Y);
end
% Coarsest wavelet level
M1 = M1/2;
M2 = M2/2;
Xj = fftshift(fft2(ifftshift(C{1}{1})))/sqrt(prod(size(C{1}{1})));
loc_1 = Xj_topleft_1 + (0:(2*floor(4*M1)));
loc_2 = Xj_topleft_2 + (0:(2*floor(4*M2)));
X(loc_1,loc_2) = X(loc_1,loc_2) + Xj .* lowpass;
% Finest level
M1 = N1/3;
M2 = N2/3;
if finest == 1,
% Folding back onto N1-by-N2 matrix
shift_1 = floor(2*M1)-floor(N1/2);
shift_2 = floor(2*M2)-floor(N2/2);
Y = X(:,(1:N2)+shift_2);
Y(:,N2-shift_2+(1:shift_2)) = Y(:,N2-shift_2+(1:shift_2)) + X(:,1:shift_2);
Y(:,1:shift_2) = Y(:,1:shift_2) + X(:,N2+shift_2+(1:shift_2));
X = Y((1:N1)+shift_1,:);
X(N1-shift_1+(1:shift_1),:) = X(N1-shift_1+(1:shift_1),:) + Y(1:shift_1,:);
X(1:shift_1,:) = X(1:shift_1,:) + Y(N1+shift_1+(1:shift_1),:);
else
% Extension to a N1-by-N2 matrix
Y = fftshift(fft2(ifftshift(C{nbscales}{1})))/sqrt(prod(size(C{nbscales}{1})));
X_topleft_1 = ceil((N1+1)/2) - floor(M1);
X_topleft_2 = ceil((N2+1)/2) - floor(M2);
loc_1 = X_topleft_1 + (0:(2*floor(M1)));
loc_2 = X_topleft_2 + (0:(2*floor(M2)));
Y(loc_1,loc_2) = Y(loc_1,loc_2) .* hipass_finest + X;
X = Y;
end;
x = fftshift(ifft2(ifftshift(X)))*sqrt(prod(size(X)));
if is_real, x = real(x); end;
function [wl,wr] = fdct_wrapping_window(x)
% fdct_wrapping_window.m - Creates the two halves of a C^inf compactly supported window
%
% Inputs
% x vector or matrix of abscissae, the relevant ones from 0 to 1
%
% Outputs
% wl,wr vector or matrix containing samples of the left, resp. right
% half of the window
%
% Used at least in fdct_wrapping.m and ifdct_wrapping.m
%
% By Laurent Demanet, 2004
wr = zeros(size(x));
wl = zeros(size(x));
x(abs(x) < 2^-52) = 0;
wr((x > 0) & (x < 1)) = exp(1-1./(1-exp(1-1./x((x > 0) & (x < 1)))));
wr(x <= 0) = 1;
wl((x > 0) & (x < 1)) = exp(1-1./(1-exp(1-1./(1-x((x > 0) & (x < 1))))));
wl(x >= 1) = 1;
normalization = sqrt(wl.^2 + wr.^2);
wr = wr ./ normalization;
wl = wl ./ normalization;
|
github
|
alex-delalande/numerical-tours-master
|
perform_wavelet_transf.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_wavelet_transf.m
| 6,359 |
utf_8
|
e186b6bffa94179c6c7e4497ba32e904
|
function x = perform_wavelet_transf(x, Jmin, dir, options)
% perform_wavelet_transf - peform fast lifting transform
%
% y = perform_wavelet_transf(x, Jmin, dir, options);
%
% Implement 1D and 2D symmetric wavelets with symmetric boundary treatements, using
% a lifting implementation.
%
% h = options.filter gives the coefficients of the lifting filter.
% You can use h='linear' or h='7-9' to select automatically biorthogonal
% transform with 2 and 4 vanishing moments.
%
% You can set options.ti=1 to compute a translation invariant wavelet
% transform.
%
% You can set options.separable=1 to compute a separable 2D wavelet
% transform.
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
h = getoptions(options, 'filter', '9-7');
separable = getoptions(options, 'separable', 0);
% detect dimensionality
% d = getoptions(options,'ndims',-1);
d = -1;
if isfield(options, 'ndims')
d = options.ndims;
end
if d<0
if size(x,1)==1 || size(x,2)==1
d = 1;
else
d = 2;
end
end
if isstr(h)
% P/U/P/U/etc the last coefficient is scaling
switch lower(h)
case 'haar'
if d==1 || separable==0
x = perform_haar_transf(x, Jmin, dir, options);
return;
end
case {'linear' '5-3'}
h = [1/2 1/4 sqrt(2)];
case {'9-7' '7-9'}
h = [1.586134342 -.05298011854 -.8829110762 .4435068522 1.149604398];
otherwise
error('Unknown filter');
end
end
if d==1 && size(x,1)==1
warning('For 1D transform, the vector should be a column vector.');
x = x(:);
end
ti = getoptions(options, 'ti', 0);
if d==2 && separable==1
options.ti = 0;
if ti==1
warning('Separable does not works for translation invariant transform');
end
% perform a separable wavelet transform
n = size(x,1);
if dir==1
for i=1:n
x(:,i) = perform_wavelet_transf(x(:,i),Jmin,dir,options);
end
for i=1:n
x(i,:) = perform_wavelet_transf(x(i,:)',Jmin,dir,options)';
end
else
for i=1:n
x(i,:) = perform_wavelet_transf(x(i,:)',Jmin,dir,options)';
end
for i=1:n
x(:,i) = perform_wavelet_transf(x(:,i),Jmin,dir,options);
end
end
return;
end
% number of lifting steps
n = size(x,1);
m = (length(h)-1)/2;
Jmax = log2(n)-1;
jlist = Jmax:-1:Jmin;
if dir==-1
jlist = jlist(end:-1:1);
end
if ti==0
% subsampled
for j=jlist
if d==1
x(1:2^(j+1),:) = lifting_step( x(1:2^(j+1),:), h, dir);
else
x(1:2^(j+1),1:2^(j+1)) = lifting_step( x(1:2^(j+1),1:2^(j+1)), h, dir);
x(1:2^(j+1),1:2^(j+1)) = lifting_step( x(1:2^(j+1),1:2^(j+1))', h, dir)';
end
end
else
% TI
nJ = Jmax-Jmin+1;
if dir==1 && d==1
x = repmat(x,[1 1 nJ+1]);
elseif dir==1 && d==2
x = repmat(x,[1 1 3*nJ+1]);
end
for j=jlist
dist = 2^(Jmax-j);
if d==1
if dir==1
x(:,:,[1 j-Jmin+2]) = lifting_step_ti( x(:,:,1), h, dir, dist);
else
x(:,:,1) = lifting_step_ti( x(:,:,[1 j-Jmin+2]), h, dir, dist);
end
else
dj = 3*(j-Jmin);
if dir==1
x(:,:,[1 dj+2]) = lifting_step_ti( x(:,:,1), h, dir, dist);
x(:,:,[1 dj+3]) = lifting_step_ti( x(:,:,1)', h, dir, dist);
x(:,:,1) = x(:,:,1)'; x(:,:,dj+3) = x(:,:,dj+3)';
x(:,:,[dj+[2 4]]) = lifting_step_ti( x(:,:,dj+2)', h, dir, dist);
x(:,:,dj+2) = x(:,:,dj+2)';
x(:,:,dj+4) = x(:,:,dj+4)';
else
x(:,:,dj+2) = x(:,:,dj+2)';
x(:,:,dj+4) = x(:,:,dj+4)';
x(:,:,dj+2) = lifting_step_ti( x(:,:,[dj+[2 4]]), h, dir, dist)';
x(:,:,1) = x(:,:,1)';
x(:,:,dj+3) = x(:,:,dj+3)';
x(:,:,1) = lifting_step_ti( x(:,:,[1 dj+3]), h, dir, dist)';
x(:,:,1) = lifting_step_ti( x(:,:,[1 dj+2]), h, dir, dist);
end
end
end
if dir==-1
x = x(:,:,1);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = lifting_step(x, h, dir)
% number of lifting steps
m = (length(h)-1)/2;
if dir==1
% split
d = x(2:2:end,:);
x = x(1:2:end,:);
for i=1:m
d = d - h(2*i-1) * ( x + x([2:end end],:) );
x = x + h(2*i ) * ( d + d([1 1:end-1],:) );
end
x = [x*h(end);d/h(end)];
else
% retrieve detail coefs
d = x(end/2+1:end,:)*h(end);
x = x(1:end/2,:)/h(end);
for i=m:-1:1
x = x - h(2*i ) * ( d + d([1 1:end-1],:) );
d = d + h(2*i-1) * ( x + x([2:end end],:) );
end
% merge
x1 = zeros(size(x,1)*2,size(x,2));
x1(1:2:end,:) = x;
x1(2:2:end,:) = d;
x = x1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = lifting_step_ti(x, h, dir, dist)
% number of lifting steps
m = (length(h)-1)/2;
n = size(x,1);
s1 = (1:n)+dist;
s2 = (1:n)-dist;
% boundary conditions
s1(s1>n) = 2*n-s1(s1>n); s1(s1<1) = 2-s1(s1<1);
s2(s2>n) = 2*n-s2(s2>n); s2(s2<1) = 2-s2(s2<1);
% s1 = [2 1:n-1]; s2 = [2:n n-1];
if dir==1
% split
d = x;
for i=1:m
d = d - h(2*i-1) * ( x(s1,:) + x(s2,:) );
x = x + h(2*i ) * ( d(s1,:) + d(s2,:) );
end
x = cat(3,x*h(end),d/h(end));
else
% retrieve detail coefs
d = x(:,:,2)*h(end);
x = x(:,:,1)/h(end);
for i=m:-1:1
x = x - h(2*i ) * ( d(s1,:) + d(s2,:) );
d = d + h(2*i-1) * ( x(s1,:) + x(s2,:) );
end
% merge
x = (x+d)/2;
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_thresholding.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_thresholding.m
| 6,251 |
utf_8
|
47aba185bb0bd0505c7e8aa326bc40c1
|
function y = perform_thresholding(x, t, type, options)
% perform_thresholding - perform hard or soft thresholding
%
% y = perform_thresholding(x, t, type, options);
%
% t is the threshold
% type is either 'hard' or 'soft' or 'semisoft' or 'strict' or 'block'.
%
% works also for complex data, and for cell arrays.
%
% if type is 'strict' then it keeps the t largest entry in each
% column of x.
%
% for block thresholding, you can set options.block_size to determing the
% block size.
%
% Copyright (c) 2006 Gabriel Peyre
options.null = 0;
if nargin==3 && isstruct(type)
options = type;
type = getoptions(options, 'type', 'hard');
end
if nargin<3
type = 'hard';
end
if iscell(x) && not(strcmp(type, 'freeze'))
% for cell arrays
for i=1:size(x,1)
for j=1:size(x,2)
y{i,j} = perform_thresholding(x{i,j},t, type);
end
end
return;
end
switch lower(type)
case {'hard', ''}
y = perform_hard_thresholding(x,t);
case 'soft'
y = perform_soft_thresholding(x,t);
case 'semisoft'
y = perform_semisoft_thresholding(x,t);
case 'strict'
y = perform_strict_thresholding(x,t);
case 'largest'
y = perform_largest_thresh(x,t);
case {'block' 'block-hard' 'block-soft'}
if strcmp(type, 'block')
type = 'block-soft';
end
bs = getoptions(options, 'block_size', 4);
y = perform_block_thresholding(x,t,bs, type);
case 'quantize'
y = perform_quant_thresholding(x,t);
case 'freeze'
y = perform_freeze_thresholding(x,t);
case 'soft-multichannel'
y = perform_softm_thresholding(x,t);
case {'stein' 'soft-quad'}
y = perform_stein_thresh(x,t);
otherwise
error('Unkwnown thresholding type.');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function X = perform_strict_thresholding(X,s)
%% keep only the s largest coefficients in each column of X
v = sort(abs(X)); v = v(end:-1:1,:);
v = v(round(s),:);
v = repmat(v, [size(X,1) 1]);
X = X .* (abs(X)>=v);
function X = perform_largest_thresh(X,s)
v = sort(abs(X(:))); v = v(end:-1:1,:);
v = v(round(s));
X = X .* (abs(X)>=v);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_hard_thresholding(x,t)
t = t(1);
y = x .* (abs(x) > t);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_quant_thresholding(x,t)
t = t(1);
y = floor(abs(x/t)).*sign(x);
y = sign(y) .* (abs(y)+.5) * t;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_stein_thresh(x,t)
t = t(1);
y = x .* max( 1-t^2 ./ abs(x).^2, 0 );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_softm_thresholding(x,t)
% dimension of thresholding
dm = nb_dims(x);
% soft multichannel
d = sqrt( sum( abs(x).^2, dm) );
d = repmat(d, [ones(dm-1,1); size(x,dm)]);
y = max( 1-t./d, 0 ) .* x;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_soft_thresholding(x,t)
if not(isreal(x))
% complex threshold
d = abs(x);
d(d<eps) = 1;
y = x./d .* perform_soft_thresholding(d,t);
return;
end
%if nb_dims(x)==nb_dims(t) && size(t)~=size(x)
t = t(1);
%end
s = abs(x) - t;
s = (s + abs(s))/2;
y = sign(x).*s;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_freeze_thresholding(x,t)
if iscell(x)
if length(x)~=length(t)
error('Vector should have same length');
end
for i=1:length(x)
y{i} = perform_freeze_thresholding(x{i},t{i});
end
return;
end
y = x;
y(t==0) = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_semisoft_thresholding(x,t)
if length(t)==1
t = [t 2*t];
end
t = sort(t);
y = x;
y(abs(x)<t(1)) = 0;
I = find(abs(x)>=t(1) & abs(x)<t(2));
y( I ) = sign(x(I)) .* t(2)/(t(2)-t(1)) .* (abs(x(I))-t(1));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = perform_block_thresholding(x,t,bs, type)
n = size(x,1);
if nb_dims(x)==2
p = size(x,2);
if length(bs)==1
bs = [bs bs];
end
% compute indexing
[dX,dY,X,Y] = ndgrid(0:bs(1)-1,0:bs(2)-1,1:bs(1):n-bs(1)+1,1:bs(2):p-bs(2)+1);
I = X+dX + (Y+dY-1)*n;
% reshape as block
H = x(I);
% threshold
v = mean(mean(abs(H).^2,1),2); v = max(v,1e-15);
if strcmp(type, 'block-soft')
H = repmat(max(1-t^2./v,0),[bs(1) bs(2) 1 1]) .* H;
else
H = repmat(v>t^2,[bs bs 1 1]) .* H;
end
elseif nb_dims(x)==1
%% 1D %%
[dX,X] = meshgrid(0:bs-1,1:bs:n-bs+1);
I = X+dX;
% reshape as block
H = x(I);
% threshold
v = mean(H.^2); v = max(v,1e-15);
if strcmp(type, 'block-soft')
H = repmat(max(1-t^2./v,0),[bs 1]) .* H;
else
H = double( repmat(v>t^2,[bs 1]) ) .* H;
end
elseif nb_dims(x)==3
for i=1:size(x,3)
y(:,:,i) = perform_block_thresholding(x(:,:,i),t,bs, type);
end
return;
else
error('Wrong size');
end
% reconstruct
y = x; y(I) = H;
|
github
|
alex-delalande/numerical-tours-master
|
perform_stft.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_stft.m
| 5,289 |
utf_8
|
b4057f12e297c275b4333d8483ce92dd
|
function y = perform_stft(x, w,q, options)
% perform_stft - compute a local Fourier transform
%
% Forward transform:
% MF = perform_stft(M,w,q, options);
% Backward transform:
% M = perform_stft(MF,w,q, options);
%
% w is the width of the window used to perform local computation.
% q is the spacing betwen each window.
%
% MF(:,i) contains the spectrum around point (i-1)*q
%
% A typical use, for an redundancy of 2 could be w=2*q+1
%
% options.bound can be either 'per' or 'sym'
%
% options.normalization can be set to
% 'tightframe': tight frame transform, with energy conservation.
% 'unit': unit norm basis vectors, usefull to do thresholding
%
% If w and q are vectors, then it computes a multi-window (Gabor) STFT,
% and the output of the forward transform is a cell array.
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
if length(w)>1
% Gabor STFT
if length(w)~=length(w)
error('w and q must have the same length');
end
% mult-window STFT
if ~iscell(x)
% direct transform
for i=1:length(w)
y{i} = perform_stft(x, w(i), q(i), options);
end
else
n = getoptions(options, 'n', 1, 1);
y = zeros(n,size(x{1}, 3));
% backward transform
for i=1:length(w)
y = y + perform_stft(x{i}, w(i), q(i), options);
end
y = y/length(w);
end
return;
end
multichannel = getoptions(options, 'multichannel', 0);
if multichannel
options.multichannel = 0;
% multichannel transform
if nb_dims(x)==3
% backward transform
for i=1:size(x,3)
y(:,i) = perform_stft(x(:,:,i), w,q, options);
end
else
for i=1:size(x,2)
y(:,:,i) = perform_stft(x(:,i), w,q, options);
end
end
return;
end
if size(x,1)==1 || size(x,2)==1
x = x(:); dir = 1;
n = length(x);
else
dir = -1;
n = getoptions(options, 'n', 1, 1);
end
bound = getoptions(options, 'bound', 'per');
transform_type = getoptions(options, 'transform_type', 'fourier');
normalization = getoptions(options, 'normalization', 'tightframe');
window_type = getoptions(options, 'window_type', 'sin');
eta = getoptions(options, 'eta', 1);
% perform sampling
X = 1:q:n+1;
p = length(X);
if mod(w,2)==1
% w = ceil((w-1)/2)*2+1;
w1 = (w-1)/2;
dX = (-w1:w1)';
else
dX = (-w/2+1:w/2)';
end
X1 = repmat(X, [w 1]) + repmat(dX, [1 p]);
switch lower(bound)
case 'sym'
X1(X1<1) = 1-X1(X1<1);
X1(X1>n) = 2*n+1-X1(X1>n);
case 'per'
X1 = mod(X1-1,n)+1;
end
I = X1;
% build a weight function
switch lower(window_type)
case {'sin' 'hanning'}
% t = linspace(-pi,pi,w);
% W = cos(t(:))+1;
W = .5 *(1 - cos( 2*pi*(0:w-1)'/(w-1) ));
case 'constant'
W = ones(w,1);
otherwise
error('Unkwnown winow.');
end
%% renormalize the windows
weight = zeros(n,1);
for i=1:p
weight(I(:,i)) = weight(I(:,i)) + W.^2;
end
weight = sqrt(weight);
Weight = repmat(W, [1 p]);
for i=1:p
Weight(:,i) = Weight(:,i) ./ weight(I(:,i));
end
if strcmp(normalization, 'unit')
if strcmp(transform_type, 'fourier')
% for Fourier it is easy
Renorm = sqrt( sum( Weight.^2, 1 ) )/w;
else
error('Not yet implemented');
% for DCT it is less easy ...
% take a typical window in the middle of the image
weight = Weight(:,:,round(end/2),round(end/2));
% compute diracs
[X,Y,fX,fY] = ndgrid(0:w-1,0:w-1,0:w-1,0:w-1);
A = 2 * cos( pi/w * ( X+1/2 ).*fX ) .* cos( pi/w * ( Y+1/2 ).*fY ) / w;
A(:,:,1,:) = A(:,:,1,:) / sqrt(2); % scale zero frequency
A(:,:,:,1) = A(:,:,:,1) / sqrt(2);
A = A .* repmat( weight, [1 1 w w] );
Renorm = sqrt( sum( sum( abs(A).^2, 1 ),2 ) );
end
end
%% compute the transform
if dir==1
y = zeros(eta*w,p);
if mod(w,2)==1
m = (eta*w+1)/2; w1 = (w-1)/2;
sel = m-w1:m+w1;
else
m = (eta*w)/2+1; w1 = w/2;
sel = m-w1:m+w1-1;
end
y(sel,:) = x(I) .* Weight;
% perform the transform
y = my_transform( y, +1, transform_type );
% renormalize if necessary
if strcmp(normalization, 'unit')
y = y ./ repmat( Renorm, [1 p] );
end
else
if strcmp(normalization, 'unit')
x = x .* repmat( Renorm, [1 p] );
end
x = my_transform( x, -1, transform_type );
x = real( x.*Weight );
y = zeros(n,1);
for i=1:p
y(I(:,i)) = y(I(:,i)) + x(:,i);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = my_transform(x,dir,transform_type)
% my_transform - perform either FFT or DCT with energy conservation.
% Works on array of size (w,w,a,b) on the 2 first dimensions.
w = size(x,1);
if strcmp(transform_type, 'fourier')
% normalize for energy conservation
if dir==1
y = fft(x) / sqrt(w);
else
y = ifft( x*sqrt(w) );
end
elseif strcmp(transform_type, 'dct')
for i=1:size(x,2)
y(:,i) = perform_dct_transform(x(:,i),dir);
end
else
error('Unknown transform');
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_solve_bp.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_solve_bp.m
| 72,049 |
utf_8
|
527f7660ac12d11f05dda0f0f346b726
|
function sol = p(A, y, N, maxIters, lambda, OptTol)
% SolveBP: Solves a Basis Pursuit problem
% Usage
% sol = SolveBP(A, y, N, maxIters, lambda, OptTol)
% Input
% A Either an explicit nxN matrix, with rank(A) = min(N,n)
% by assumption, or a string containing the name of a
% function implementing an implicit matrix (see below for
% details on the format of the function).
% y vector of length n.
% N length of solution vector.
% maxIters maximum number of PDCO iterations to perform, default 20.
% lambda If 0 or omitted, Basis Pursuit is applied to the data,
% otherwise, Basis Pursuit Denoising is applied with
% parameter lambda (default 0).
% OptTol Error tolerance, default 1e-3
% Outputs
% sol solution of BP
% Description
% SolveBP solves the basis pursuit problem
% min ||x||_1 s.t. A*x = y
% by reducing it to a linear program, and calling PDCO, a primal-dual
% log-barrier algorithm. Alternatively, if lambda ~= 0, it solves the
% Basis Pursuit Denoising (BPDN) problem
% min lambda*||x||_1 + 1/2||y - A*x||_2^2
% by transforming it to an SOCP, and calling PDCO.
% The matrix A can be either an explicit matrix, or an implicit operator
% implemented as a function. If using the implicit form, the user should
% provide the name of a function of the following format:
% y = OperatorName(mode, m, n, x, I, dim)
% This function gets as input a vector x and an index set I, and returns
% y = A(:,I)*x if mode = 1, or y = A(:,I)'*x if mode = 2.
% A is the m by dim implicit matrix implemented by the function. I is a
% subset of the columns of A, i.e. a subset of 1:dim of length n. x is a
% vector of length n is mode = 1, or a vector of length m is mode = 2.
% See Also
% SolveLasso, SolveOMP, SolveITSP
%
if nargin < 6,
OptTol = 1e-3;
end
if nargin < 5,
lambda = 0;
end
if nargin < 4,
maxIters = 20;
end
n = length(y);
n_pdco = 2*N; % Input size
m_pdco = n; % Output size
% upper and lower bounds
bl = zeros(n_pdco,1);
bu = Inf .* ones(n_pdco,1);
% generate the vector c
if (lambda ~= 0)
c = lambda .* ones(n_pdco,1);
else
c = ones(n_pdco,1);
end
% Generate an initial guess
x0 = ones(n_pdco,1)/n_pdco; % Initial x
y0 = zeros(m_pdco,1); % Initial y
z0 = ones(n_pdco,1)/n_pdco; % Initial z
d1 = 1e-4; % Regularization parameters
if (lambda ~= 0) % BPDN
d2 = 1;
else
d2 = 1e-4;
end
xsize = 1; % Estimate of norm(x,inf) at solution
zsize = 1; % Estimate of norm(z,inf) at solution
options = pdcoSet; % Option set for the function pdco
options = pdcoSet( options, ...
'MaxIter ', maxIters , ...
'FeaTol ', OptTol , ...
'OptTol ', OptTol , ...
'StepTol ', 0.99 , ...
'StepSame ', 0 , ...
'x0min ', 0.1 , ...
'z0min ', 1.0 , ...
'mu0 ', 0.01 , ...
'method ', 1 , ...
'LSQRMaxIter', 20 , ...
'LSQRatol1 ', 1e-3 , ...
'LSQRatol2 ', 1e-15 , ...
'wait ', 0 );
if (ischar(A) || isa(A, 'function_handle'))
[xx,yy,zz,inform,PDitns,CGitns,time] = ...
pdco(c, @pdcoMat, y, bl, bu, d1, d2, options, x0, y0, z0, xsize, zsize);
else
Phi = [A -A];
[xx,yy,zz,inform,PDitns,CGitns,time] = ...
pdco(c, Phi, y, bl, bu, d1, d2, options, x0, y0, z0, xsize, zsize);
end
% Extract the solution from the output vector x
sol = xx(1:N) - xx((N+1):(2*N));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = pdcoMat(mode,m,n,x)
if (mode == 1) % Direct operator
% Decompose input
n2 = n/2;
u = x(1:n2);
v = x(n2+1:n);
% Apply matrix A
Au = feval(A,1,m,n2,u,1:n2,n2);
Av = feval(A,1,m,n2,v,1:n2,n2);
y = Au-Av;
else % Adjoint operator
n2 = n/2;
Atx = feval(A,2,m,n2,x,1:n2,n2);
y = [Atx; -Atx];
end
%
% Copyright (c) 2006. Yaakov Tsaig
%
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function [x,y,z,inform,PDitns,CGitns,time] = ...
pdco( Fname,Aname,b,bl,bu,d1,d2,options,x0,y0,z0,xsize,zsize )
%-----------------------------------------------------------------------
% pdco.m: Primal-Dual Barrier Method for Convex Objectives (23 Sep 2003)
%-----------------------------------------------------------------------
% [x,y,z,inform,PDitns,CGitns,time] = ...
% pdco(Fname,Aname,b,bl,bu,d1,d2,options,x0,y0,z0,xsize,zsize);
%
% solves optimization problems of the form
%
% minimize phi(x) + 1/2 norm(D1*x)^2 + 1/2 norm(r)^2
% x,r
% subject to A*x + D2*r = b, bl <= x <= bu, r unconstrained,
%
% where
% phi(x) is a smooth convex function defined by function Fname;
% A is an m x n matrix defined by matrix or function Aname;
% b is a given m-vector;
% D1, D2 are positive-definite diagonal matrices defined from d1, d2.
% In particular, d2 indicates the accuracy required for
% satisfying each row of Ax = b.
%
% D1 and D2 (via d1 and d2) provide primal and dual regularization
% respectively. They ensure that the primal and dual solutions
% (x,r) and (y,z) are unique and bounded.
%
% A scalar d1 is equivalent to d1 = ones(n,1), D1 = diag(d1).
% A scalar d2 is equivalent to d2 = ones(m,1), D2 = diag(d2).
% Typically, d1 = d2 = 1e-4.
% These values perturb phi(x) only slightly (by about 1e-8) and request
% that A*x = b be satisfied quite accurately (to about 1e-8).
% Set d1 = 1e-4, d2 = 1 for least-squares problems with bound constraints.
% The problem is then equivalent to
%
% minimize phi(x) + 1/2 norm(d1*x)^2 + 1/2 norm(A*x - b)^2
% subject to bl <= x <= bu.
%
% More generally, d1 and d2 may be n and m vectors containing any positive
% values (preferably not too small, and typically no larger than 1).
% Bigger elements of d1 and d2 improve the stability of the solver.
%
% At an optimal solution, if x(j) is on its lower or upper bound,
% the corresponding z(j) is positive or negative respectively.
% If x(j) is between its bounds, z(j) = 0.
% If bl(j) = bu(j), x(j) is fixed at that value and z(j) may have
% either sign.
%
% Also, r and y satisfy r = D2 y, so that Ax + D2^2 y = b.
% Thus if d2(i) = 1e-4, the i-th row of Ax = b will be satisfied to
% approximately 1e-8. This determines how large d2(i) can safely be.
%
%
% EXTERNAL FUNCTIONS:
% options = pdcoSet; provided with pdco.m
% [obj,grad,hess] = Fname( x ); provided by user
% y = Aname( name,mode,m,n,x ); provided by user if pdMat
% is a string, not a matrix
%
% INPUT ARGUMENTS:
% Fname may be an explicit n x 1 column vector c,
% or a string containing the name of a function Fname.m
%%%!!! Revised 12/16/04 !!!
% (Fname cannot be a function handle)
% such that [obj,grad,hess] = Fname(x) defines
% obj = phi(x) : a scalar,
% grad = gradient of phi(x) : an n-vector,
% hess = diag(Hessian of phi): an n-vector.
% Examples:
% If phi(x) is the linear function c'*x, Fname could be
% be the vector c, or the name or handle of a function
% that returns
% [obj,grad,hess] = [c'*x, c, zeros(n,1)].
% If phi(x) is the entropy function E(x) = sum x(j) log x(j),
% Fname should return
% [obj,grad,hess] = [E(x), log(x)+1, 1./x].
% Aname may be an explicit m x n matrix A (preferably sparse!),
% or a string containing the name of a function Aname.m
%%%!!! Revised 12/16/04 !!!
% (Aname cannot be a function handle)
% such that y = aname( name,mode,m,n,x )
% returns y = A*x (mode=1) or y = A'*x (mode=2).
% The input parameter "name" will be the string 'Aname'
% or whatever the name of the actual function is.
% b is an m-vector.
% bl is an n-vector of lower bounds. Non-existent bounds
% may be represented by bl(j) = -Inf or bl(j) <= -1e+20.
% bu is an n-vector of upper bounds. Non-existent bounds
% may be represented by bu(j) = Inf or bu(j) >= 1e+20.
% d1, d2 may be positive scalars or positive vectors (see above).
% options is a structure that may be set and altered by pdcoSet
% (type help pdcoSet).
% x0, y0, z0 provide an initial solution.
% xsize, zsize are estimates of the biggest x and z at the solution.
% They are used to scale (x,y,z). Good estimates
% should improve the performance of the barrier method.
%
%
% OUTPUT ARGUMENTS:
% x is the primal solution.
% y is the dual solution associated with Ax + D2 r = b.
% z is the dual solution associated with bl <= x <= bu.
% inform = 0 if a solution is found;
% = 1 if too many iterations were required;
% = 2 if the linesearch failed too often.
% = 3 if the step lengths became too small.
% PDitns is the number of Primal-Dual Barrier iterations required.
% CGitns is the number of Conjugate-Gradient iterations required
% if an iterative solver is used (LSQR).
% time is the cpu time used.
%----------------------------------------------------------------------
% PRIVATE FUNCTIONS:
% pdxxxbounds
% pdxxxdistrib
% pdxxxlsqr
% pdxxxlsqrmat
% pdxxxmat
% pdxxxmerit
% pdxxxresid1
% pdxxxresid2
% pdxxxstep
%
% GLOBAL VARIABLES:
% global pdDDD1 pdDDD2 pdDDD3
%
%
% NOTES:
% The matrix A should be reasonably well scaled: norm(A,inf) =~ 1.
% The vector b and objective phi(x) may be of any size, but ensure that
% xsize and zsize are reasonably close to norm(x,inf) and norm(z,inf)
% at the solution.
%
% The files defining Fname and Aname
% must not be called Fname.m or Aname.m!!
%
%
% AUTHOR:
% Michael Saunders, Systems Optimization Laboratory (SOL),
% Stanford University, Stanford, California, USA.
% [email protected]
%
% CONTRIBUTORS:
% Byunggyoo Kim, Samsung, Seoul, Korea.
% [email protected]
%
% DEVELOPMENT:
% 20 Jun 1997: Original version of pdsco.m derived from pdlp0.m.
% 29 Sep 2002: Original version of pdco.m derived from pdsco.m.
% Introduced D1, D2 in place of gamma*I, delta*I
% and allowed for general bounds bl <= x <= bu.
% 06 Oct 2002: Allowed for fixed variabes: bl(j) = bu(j) for any j.
% 15 Oct 2002: Eliminated some work vectors (since m, n might be LARGE).
% Modularized residuals, linesearch
% 16 Oct 2002: pdxxx..., pdDDD... names rationalized.
% pdAAA eliminated (global copy of A).
% Aname is now used directly as an explicit A or a function.
% NOTE: If Aname is a function, it now has an extra parameter.
% 23 Oct 2002: Fname and Aname can now be function handles.
% 01 Nov 2002: Bug fixed in feval in pdxxxmat.
% 19 Apr 2003: Bug fixed in pdxxxbounds.
% 07 Aug 2003: Let d1, d2 be scalars if input that way.
% 10 Aug 2003: z isn't needed except at the end for output.
% 10 Aug 2003: mu0 is now an absolute value -- the initial mu.
% 13 Aug 2003: Access only z1(low) and z2(upp) everywhere.
% stepxL, stepxU introduced to keep x within bounds.
% (With poor starting points, dx may take x outside,
% where phi(x) may not be defined.
% Entropy once gave complex values for the gradient!)
% 16 Sep 2003: Fname can now be a vector c, implying a linear obj c'*x.
% 19 Sep 2003: Large system K4 dv = rhs implemented.
% 23 Sep 2003: Options LSproblem and LSmethod replaced by Method.
% 18 Nov 2003: stepxL, stepxU gave trouble on lptest (see 13 Aug 2003).
% Disabled them for now. Nonlinear problems need good x0.
% 19 Nov 2003: Bugs with x(fix) and z(fix).
% In particular, x(fix) = bl(fix) throughout, so Objective
% in iteration log is correct for LPs with explicit c vector.
%-----------------------------------------------------------------------
global pdDDD1 pdDDD2 pdDDD3
if 0
myprintf('\n --------------------------------------------------------')
myprintf('\n pdco.m Version of 19 Nov 2003')
myprintf('\n Primal-dual barrier method to minimize a convex function')
myprintf('\n subject to linear constraints Ax + r = b, bl <= x <= bu')
myprintf('\n --------------------------------------------------------\n')
end
m = length(b);
n = length(bl);
%---------------------------------------------------------------------
% Decode Fname.
%---------------------------------------------------------------------
%%%!!! Revised 12/16/04 !!!
% Fname cannot be a function handle
operator = ischar(Fname);
explicitF = ~operator;
if explicitF
myprintf('\n')
mydisp('The objective is linear')
else
fname = Fname;
myprintf('\n')
mydisp(['The objective function is named ' fname])
end
%---------------------------------------------------------------------
% Decode Aname.
%---------------------------------------------------------------------
%%%!!! Revised 12/16/04 !!!
% Aname cannot be a function handle
operator = ischar(Aname) || isa(Aname, 'function_handle');
explicitA = ~operator;
if explicitA % assume Aname is an explicit matrix A.
nnzA = nnz(Aname);
if issparse(Aname)
myprintf('The matrix A is an explicit sparse matrix')
else
myprintf('The matrix A is an explicit dense matrix' )
end
myprintf('\n\nm = %8g n = %8g nnz(A) =%9g', m,n,nnzA)
else
if ischar(Aname)
mydisp(['The matrix A is an operator defined by ' Aname])
end
myprintf('\nm = %8g n = %8g', m,n)
end
normb = norm(b ,inf); normx0 = norm(x0,inf);
normy0 = norm(y0,inf); normz0 = norm(z0,inf);
myprintf('\nmax |b | = %8g max |x0| = %8.1e', normb , normx0)
myprintf( ' xsize = %8.1e', xsize)
myprintf('\nmax |y0| = %8g max |z0| = %8.1e', normy0, normz0)
myprintf( ' zsize = %8.1e', zsize)
%---------------------------------------------------------------------
% Initialize.
%---------------------------------------------------------------------
true = 1;
false = 0;
zn = zeros(n,1);
nb = n + m;
nkkt = nb;
CGitns = 0;
inform = 0;
% 07 Aug 2003: No need for next lines.
%if length(d1)==1, d1 = d1*ones(n,1); end % Allow scalar d1, d2
%if length(d2)==1, d2 = d2*ones(m,1); end % to mean d1*e, d2*e
%---------------------------------------------------------------------
% Grab input options.
%---------------------------------------------------------------------
maxitn = options.MaxIter;
featol = options.FeaTol;
opttol = options.OptTol;
steptol = options.StepTol;
stepSame = options.StepSame; % 1 means stepx==stepz
x0min = options.x0min;
z0min = options.z0min;
mu0 = options.mu0;
Method = options.Method;
itnlim = options.LSQRMaxIter * min(m,n);
atol1 = options.LSQRatol1; % Initial atol
atol2 = options.LSQRatol2; % Smallest atol, unless atol1 is smaller
conlim = options.LSQRconlim;
wait = options.wait;
%---------------------------------------------------------------------
% Set other parameters.
%---------------------------------------------------------------------
kminor = 0; % 1 stops after each iteration
eta = 1e-4; % Linesearch tolerance for "sufficient descent"
maxf = 10; % Linesearch backtrack limit (function evaluations)
maxfail = 1; % Linesearch failure limit (consecutive iterations)
bigcenter = 1e+3; % mu is reduced if center < bigcenter
thresh = 1e-8; % For sparse LU with Method=41
% Parameters for LSQR.
atolmin = eps; % Smallest atol if linesearch back-tracks
btol = 0; % Should be small (zero is ok)
show = false; % Controls LSQR iteration log
gamma = max(d1);
delta = max(d2);
myprintf('\n\nx0min = %8g featol = %8.1e', x0min, featol)
myprintf( ' d1max = %8.1e', gamma)
myprintf( '\nz0min = %8g opttol = %8.1e', z0min, opttol)
myprintf( ' d2max = %8.1e', delta)
myprintf( '\nmu0 = %8.1e steptol = %8g', mu0 , steptol)
myprintf( ' bigcenter= %8g' , bigcenter)
myprintf('\n\nLSQR:')
myprintf('\natol1 = %8.1e atol2 = %8.1e', atol1 , atol2 )
myprintf( ' btol = %8.1e', btol )
myprintf('\nconlim = %8.1e itnlim = %8g' , conlim, itnlim)
myprintf( ' show = %8g' , show )
% Method = 3; %%% Hardwire LSQR
% Method = 41; %%% Hardwire K4 and sparse LU
myprintf('\n\nMethod = %8g (1=chol 2=QR 3=LSQR 41=K4)', Method)
if wait
myprintf('\n\nReview parameters... then type "return"\n')
keyboard
end
if eta < 0
myprintf('\n\nLinesearch disabled by eta < 0')
end
%---------------------------------------------------------------------
% All parameters have now been set.
% Check for valid Method.
%---------------------------------------------------------------------
time = cputime;
if operator
if Method==3
% relax
else
myprintf('\n\nWhen A is an operator, we have to use Method = 3')
Method = 3;
end
end
if Method== 1, solver = ' Chol'; head3 = ' Chol';
elseif Method== 2, solver = ' QR'; head3 = ' QR';
elseif Method== 3, solver = ' LSQR'; head3 = ' atol LSQR Inexact';
elseif Method==41, solver = ' LU'; head3 = ' L U res';
else error('Method must be 1, 2, 3, or 41')
end
%---------------------------------------------------------------------
% Categorize bounds and allow for fixed variables by modifying b.
%---------------------------------------------------------------------
[low,upp,fix] = pdxxxbounds( bl,bu );
nfix = length(fix);
if nfix > 0
x1 = zn; x1(fix) = bl(fix);
r1 = pdxxxmat( Aname, 1, m, n, x1 );
b = b - r1;
% At some stage, might want to look at normfix = norm(r1,inf);
end
%---------------------------------------------------------------------
% Scale the input data.
% The scaled variables are
% xbar = x/beta,
% ybar = y/zeta,
% zbar = z/zeta.
% Define
% theta = beta*zeta;
% The scaled function is
% phibar = ( 1 /theta) fbar(beta*xbar),
% gradient = (beta /theta) grad,
% Hessian = (beta2/theta) hess.
%---------------------------------------------------------------------
beta = xsize; if beta==0, beta = 1; end % beta scales b, x.
zeta = zsize; if zeta==0, zeta = 1; end % zeta scales y, z.
theta = beta*zeta; % theta scales obj.
% (theta could be anything, but theta = beta*zeta makes
% scaled grad = grad/zeta = 1 approximately if zeta is chosen right.)
bl(fix)= bl(fix)/beta;
bu(fix)= bu(fix)/beta;
bl(low)= bl(low)/beta;
bu(upp)= bu(upp)/beta;
d1 = d1*( beta/sqrt(theta) );
d2 = d2*( sqrt(theta)/beta );
beta2 = beta^2;
b = b /beta; y0 = y0/zeta;
x0 = x0/beta; z0 = z0/zeta;
%---------------------------------------------------------------------
% Initialize vectors that are not fully used if bounds are missing.
%---------------------------------------------------------------------
rL = zn; rU = zn;
cL = zn; cU = zn;
x1 = zn; x2 = zn;
z1 = zn; z2 = zn;
dx1 = zn; dx2 = zn;
dz1 = zn; dz2 = zn;
clear zn
%---------------------------------------------------------------------
% Initialize x, y, z1, z2, objective, etc.
% 10 Aug 2003: z isn't needed here -- just at end for output.
%---------------------------------------------------------------------
x = x0;
y = y0;
x(fix) = bl(fix);
x(low) = max( x(low) , bl(low));
x(upp) = min( x(upp) , bu(upp));
x1(low)= max( x(low) - bl(low), x0min );
x2(upp)= max(bu(upp) - x(upp), x0min );
z1(low)= max( z0(low) , z0min );
z2(upp)= max(-z0(upp) , z0min );
clear x0 y0 z0
%%%%%%%%%% Assume hess is diagonal for now. %%%%%%%%%%%%%%%%%%
if explicitF
obj = (Fname'*x)*beta; grad = Fname; hess = zeros(n,1);
else
[obj,grad,hess] = feval( Fname, (x*beta) );
end
obj = obj /theta; % Scaled obj.
grad = grad*(beta /theta) + (d1.^2).*x;% grad includes x regularization.
H = hess*(beta2/theta) + (d1.^2); % H includes x regularization.
%---------------------------------------------------------------------
% Compute primal and dual residuals:
% r1 = b - A*x - d2.^2*y
% r2 = grad - A'*y + (z2-z1)
% rL = bl - x + x1
% rU = -bu + x + x2
%---------------------------------------------------------------------
[r1,r2,rL,rU,Pinf,Dinf] = ...
pdxxxresid1( Aname,fix,low,upp, ...
b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 );
%---------------------------------------------------------------------
% Initialize mu and complementarity residuals:
% cL = mu*e - X1*z1.
% cU = mu*e - X2*z2.
%
% 25 Jan 2001: Now that b and obj are scaled (and hence x,y,z),
% we should be able to use mufirst = mu0 (absolute value).
% 0.1 worked poorly on StarTest1 with x0min = z0min = 0.1.
% 29 Jan 2001: We might as well use mu0 = x0min * z0min;
% so that most variables are centered after a warm start.
% 29 Sep 2002: Use mufirst = mu0*(x0min * z0min),
% regarding mu0 as a scaling of the initial center.
% 07 Aug 2003: mulast is controlled by opttol.
% mufirst should not be smaller.
% 10 Aug 2003: Revert to mufirst = mu0 (absolute value).
%---------------------------------------------------------------------
% mufirst = mu0*(x0min * z0min);
mufirst = mu0;
mulast = 0.1 * opttol;
mufirst = max( mufirst, mulast );
mu = mufirst;
[cL,cU,center,Cinf,Cinf0] = ...
pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 );
fmerit = pdxxxmerit( low,upp,r1,r2,rL,rU,cL,cU );
% Initialize other things.
PDitns = 0;
converged = 0;
atol = atol1;
atol2 = max( atol2, atolmin );
atolmin = atol2;
pdDDD2 = d2; % Global vector for diagonal matrix D2
% Iteration log.
stepx = 0;
stepz = 0;
nf = 0;
itncg = 0;
nfail = 0;
head1 = '\n\nItn mu stepx stepz Pinf Dinf';
head2 = ' Cinf Objective nf center';
myprintf([ head1 head2 head3 ])
regterm = norm(d1.*x)^2 + norm(d2.*y)^2;
objreg = obj + 0.5*regterm;
objtrue = objreg * theta;
myprintf('\n%3g ', PDitns )
myprintf('%6.1f%6.1f' , log10(Pinf ), log10(Dinf))
myprintf('%6.1f%15.7e', log10(Cinf0), objtrue )
myprintf(' %8.1f' , center )
if Method==41
myprintf(' thresh=%7.1e', thresh)
end
if kminor
myprintf('\n\nStart of first minor itn...\n')
keyboard
end
%---------------------------------------------------------------------
% Main loop.
%---------------------------------------------------------------------
while ~converged
PDitns = PDitns + 1;
% 31 Jan 2001: Set atol according to progress, a la Inexact Newton.
% 07 Feb 2001: 0.1 not small enough for Satellite problem. Try 0.01.
% 25 Apr 2001: 0.01 seems wasteful for Star problem.
% Now that starting conditions are better, go back to 0.1.
r3norm = max([Pinf Dinf Cinf]);
atol = min([atol r3norm*0.1]);
atol = max([atol atolmin ]);
if Method<=3
%-----------------------------------------------------------------
% Solve (*) for dy.
%-----------------------------------------------------------------
% Define a damped Newton iteration for solving f = 0,
% keeping x1, x2, z1, z2 > 0. We eliminate dx1, dx2, dz1, dz2
% to obtain the system
%
% [-H2 A' ] [dx] = [w ], H2 = H + D1^2 + X1inv Z1 + X2inv Z2,
% [ A D2^2] [dy] = [r1] w = r2 - X1inv(cL + Z1 rL)
% + X2inv(cU + Z2 rU),
%
% which is equivalent to the least-squares problem
%
% min || [ D A']dy - [ D w ] ||, D = H2^{-1/2}. (*)
% || [ D2 ] [D2inv r1] ||
%-----------------------------------------------------------------
H(low) = H(low) + z1(low)./x1(low);
H(upp) = H(upp) + z2(upp)./x2(upp);
w = r2;
w(low) = w(low) - (cL(low) + z1(low).*rL(low))./x1(low);
w(upp) = w(upp) + (cU(upp) + z2(upp).*rU(upp))./x2(upp);
H = 1./H; % H is now Hinv (NOTE!)
H(fix) = 0;
D = sqrt(H);
pdDDD1 = D;
rw = [explicitA Method m n 0 0 0]; % Passed to LSQR.
if Method==1
% --------------------------------------------------------------
% Use chol to get dy
% --------------------------------------------------------------
AD = Aname*sparse( 1:n, 1:n, D, n, n );
ADDA = AD*AD' + sparse( 1:m, 1:m, (d2.^2), m, m );
if PDitns==1, P = symamd(ADDA); end % Do ordering only once.
[R,indef] = chol(ADDA(P,P));
if indef
myprintf('\n\n chol says AD^2A'' is not pos def')
myprintf('\n Use bigger d2, or set options.Method = 2 or 3')
break
end
% dy = ADDA \ rhs;
rhs = Aname*(H.*w) + r1;
dy = R \ (R'\rhs(P));
dy(P) = dy;
elseif Method==2
% --------------------------------------------------------------
% Use QR to get dy
% --------------------------------------------------------------
DAt = sparse( 1:n, 1:n, D, n, n )*(Aname');
if PDitns==1, P = colamd(DAt); end % Do ordering only once.
if length(d2)==1
D2 = d2*speye(m);
else
D2 = spdiags(d2,0,m,m);
end
DAt = [ DAt; D2 ];
rhs = [ D.*w; r1./d2 ];
% dy = DAt \ rhs;
[rhs,R] = qr(DAt(:,P),rhs,0);
dy = R \ rhs;
dy(P) = dy;
else
% --------------------------------------------------------------
% Method=3. Use LSQR (iterative solve) to get dy
% --------------------------------------------------------------
rhs = [ D.*w; r1./d2 ];
damp = 0;
if explicitA % A is a sparse matrix.
precon = true;
if precon % Construct diagonal preconditioner for LSQR
AD = Aname*sparse( 1:n, 1:n, D, n, n );
AD = AD.^2;
wD = sum(AD,2); % Sum of sqrs of each row of AD. %(Sparse)
wD = sqrt( full(wD) + (d2.^2) ); %(Dense)
pdDDD3 = 1./wD;
clear AD wD
end
else % A is an operator
precon = false;
end
rw(7) = precon;
info.atolmin = atolmin;
info.r3norm = fmerit; % Must be the 2-norm here.
[ dy, istop, itncg, outfo ] = ...
pdxxxlsqr( nb,m,'pdxxxlsqrmat',Aname,rw,rhs,damp, ...
atol,btol,conlim,itnlim,show,info );
if precon, dy = pdDDD3 .* dy; end
if istop==3 | istop==7 % conlim or itnlim
myprintf('\n LSQR stopped early: istop = %3d', istop)
end
atolold = outfo.atolold;
atol = outfo.atolnew;
r3ratio = outfo.r3ratio;
CGitns = CGitns + itncg;
end % computation of dy
% dy is now known. Get dx, dx1, dx2, dz1, dz2.
grad = pdxxxmat( Aname,2,m,n,dy ); % grad = A'dy
grad(fix) = 0; % Is this needed? % grad is a work vector
dx = H .* (grad - w);
dx1(low) = - rL(low) + dx(low);
dx2(upp) = - rU(upp) - dx(upp);
dz1(low) = (cL(low) - z1(low).*dx1(low)) ./ x1(low);
dz2(upp) = (cU(upp) - z2(upp).*dx2(upp)) ./ x2(upp);
elseif Method==41
%-----------------------------------------------------------------
% Solve the symmetric-structure 4 x 4 system K4 dv = t:
%
% ( X1 Z1 ) [dz1] = [tL], tL = cL + Z1 rL
% ( X2 -Z2 ) [dz2] [tU] tU = cU + Z2 rU
% ( I -I -H1 A' ) [dx ] [r2]
% ( A D2^2 ) [dy ] [r1]
%-----------------------------------------------------------------
X1 = ones(n,1); X1(low) = x1(low);
X2 = ones(n,1); X2(upp) = x2(upp);
if length(d2)==1
D22 = d2^2*speye(m);
else
D22 = spdiags(d2.^2,0,m,m);
end
Onn = sparse(n,n);
Omn = sparse(m,n);
if PDitns==1 % First time through: Choose LU ordering from
% lower-triangular part of dummy K4
I1 = sparse( low, low, ones(length(low),1), n, n );
I2 = sparse( upp, upp, ones(length(upp),1), n, n );
K4 =[speye(n) Onn Onn Omn'
Onn speye(n) Onn Omn'
I1 I2 speye(n) Omn'
Omn Omn Aname speye(m)];
p = symamd(K4);
% mydisp(' '); keyboard
end
K4 = [spdiags(X1,0,n,n) Onn spdiags(z1,0,n,n) Omn'
Onn spdiags(X2,0,n,n) -spdiags(z2,0,n,n) Omn'
I1 -I2 -spdiags(H,0,n,n) Aname'
Omn Omn Aname D22];
tL = zeros(n,1); tL(low) = cL(low) + z1(low).*rL(low);
tU = zeros(n,1); tU(upp) = cU(upp) + z2(upp).*rU(upp);
rhs = [tL; tU; r2; r1];
% dv = K4 \ rhs; % BIG SYSTEM!
[L,U,P] = lu( K4(p,p), thresh ); % P K4 = L U
dv = U \ (L \ (P*rhs(p)));
dv(p) = dv;
resK4 = norm((K4*dv - rhs),inf) / norm(rhs,inf);
dz1 = dv( 1: n);
dz2 = dv( n+1:2*n);
dx = dv(2*n+1:3*n);
dy = dv(3*n+1:3*n+m);
dx1(low) = - rL(low) + dx(low);
dx2(upp) = - rU(upp) - dx(upp);
end
%-------------------------------------------------------------------
% Find the maximum step.
% 13 Aug 2003: We need stepxL, stepxU also to keep x feasible
% so that nonlinear functions are defined.
% 18 Nov 2003: But this gives stepx = 0 for lptest. (??)
%--------------------------------------------------------------------
stepx1 = pdxxxstep( x1(low), dx1(low) );
stepx2 = pdxxxstep( x2(upp), dx2(upp) );
stepz1 = pdxxxstep( z1(low), dz1(low) );
stepz2 = pdxxxstep( z2(upp), dz2(upp) );
% stepxL = pdxxxstep( x(low), dx(low) );
% stepxU = pdxxxstep( x(upp), dx(upp) );
% stepx = min( [stepx1, stepx2, stepxL, stepxU] );
stepx = min( [stepx1, stepx2] );
stepz = min( [stepz1, stepz2] );
stepx = min( [steptol*stepx, 1] );
stepz = min( [steptol*stepz, 1] );
if stepSame % For NLPs, force same step
stepx = min( stepx, stepz ); % (true Newton method)
stepz = stepx;
end
%-------------------------------------------------------------------
% Backtracking linesearch.
%-------------------------------------------------------------------
fail = true;
nf = 0;
while nf < maxf
nf = nf + 1;
x = x + stepx * dx;
y = y + stepz * dy;
x1(low) = x1(low) + stepx * dx1(low);
x2(upp) = x2(upp) + stepx * dx2(upp);
z1(low) = z1(low) + stepz * dz1(low);
z2(upp) = z2(upp) + stepz * dz2(upp);
if explicitF
obj = (Fname'*x)*beta; grad = Fname; hess = zeros(n,1);
else
[obj,grad,hess] = feval( Fname, (x*beta) );
end
obj = obj /theta;
grad = grad*(beta /theta) + (d1.^2).*x;
H = hess*(beta2/theta) + (d1.^2);
[r1,r2,rL,rU,Pinf,Dinf] = ...
pdxxxresid1( Aname,fix,low,upp, ...
b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 );
[cL,cU,center,Cinf,Cinf0] = ...
pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 );
fmeritnew = pdxxxmerit( low,upp,r1,r2,rL,rU,cL,cU );
step = min( stepx, stepz );
if fmeritnew <= (1 - eta*step)*fmerit
fail = false;
break;
end
% Merit function didn't decrease.
% Restore variables to previous values.
% (This introduces a little error, but save lots of space.)
x = x - stepx * dx;
y = y - stepz * dy;
x1(low) = x1(low) - stepx * dx1(low);
x2(upp) = x2(upp) - stepx * dx2(upp);
z1(low) = z1(low) - stepz * dz1(low);
z2(upp) = z2(upp) - stepz * dz2(upp);
% Back-track.
% If it's the first time,
% make stepx and stepz the same.
if nf==1 & stepx~=stepz
stepx = step;
elseif nf < maxf
stepx = stepx/2;
end;
stepz = stepx;
end
if fail
myprintf('\n Linesearch failed (nf too big)');
nfail = nfail + 1;
else
nfail = 0;
end
%-------------------------------------------------------------------
% Set convergence measures.
%--------------------------------------------------------------------
regterm = norm(d1.*x)^2 + norm(d2.*y)^2;
objreg = obj + 0.5*regterm;
objtrue = objreg * theta;
primalfeas = Pinf <= featol;
dualfeas = Dinf <= featol;
complementary = Cinf0 <= opttol;
enough = PDitns>= 4; % Prevent premature termination.
converged = primalfeas & dualfeas & complementary & enough;
%-------------------------------------------------------------------
% Iteration log.
%-------------------------------------------------------------------
str1 = sprintf('\n%3g%5.1f' , PDitns , log10(mu) );
str2 = sprintf('%6.3f%6.3f' , stepx , stepz );
if stepx < 0.001 | stepz < 0.001
str2 = sprintf('%6.1e%6.1e' , stepx , stepz );
end
str3 = sprintf('%6.1f%6.1f' , log10(Pinf) , log10(Dinf));
str4 = sprintf('%6.1f%15.7e', log10(Cinf0), objtrue );
str5 = sprintf('%3g%8.1f' , nf , center );
if center > 99999
str5 = sprintf('%3g%8.1e' , nf , center );
end
myprintf([str1 str2 str3 str4 str5])
if Method== 1
if PDitns==1, myprintf(' %8g', nnz(R)); end
elseif Method== 2
if PDitns==1, myprintf(' %8g', nnz(R)); end
elseif Method== 3
myprintf(' %5.1f%7g%7.3f', log10(atolold), itncg, r3ratio)
elseif Method==41,
resK4 = max( resK4, 1e-99 );
myprintf(' %8g%8g%6.1f', nnz(L),nnz(U),log10(resK4))
end
%-------------------------------------------------------------------
% Test for termination.
%-------------------------------------------------------------------
if kminor
myprintf( '\nStart of next minor itn...\n')
keyboard
end
if converged
myprintf('\nConverged')
elseif PDitns >= maxitn
myprintf('\nToo many iterations')
inform = 1;
break
elseif nfail >= maxfail
myprintf('\nToo many linesearch failures')
inform = 2;
break
elseif step <= 1e-10
myprintf('\nStep lengths too small')
inform = 3;
break
else
% Reduce mu, and reset certain residuals.
stepmu = min( stepx , stepz );
stepmu = min( stepmu, steptol );
muold = mu;
mu = mu - stepmu * mu;
if center >= bigcenter, mu = muold; end
% mutrad = mu0*(sum(Xz)/n); % 24 May 1998: Traditional value, but
% mu = min(mu,mutrad ); % it seemed to decrease mu too much.
mu = max(mu,mulast); % 13 Jun 1998: No need for smaller mu.
[cL,cU,center,Cinf,Cinf0] = ...
pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 );
fmerit = pdxxxmerit( low,upp,r1,r2,rL,rU,cL,cU );
% Reduce atol for LSQR (and SYMMLQ).
% NOW DONE AT TOP OF LOOP.
atolold = atol;
% if atol > atol2
% atolfac = (mu/mufirst)^0.25;
% atol = max( atol*atolfac, atol2 );
% end
% atol = min( atol, mu ); % 22 Jan 2001: a la Inexact Newton.
% atol = min( atol, 0.5*mu ); % 30 Jan 2001: A bit tighter
% If the linesearch took more than one function (nf > 1),
% we assume the search direction needed more accuracy
% (though this may be true only for LPs).
% 12 Jun 1998: Ask for more accuracy if nf > 2.
% 24 Nov 2000: Also if the steps are small.
% 30 Jan 2001: Small steps might be ok with warm start.
% 06 Feb 2001: Not necessarily. Reinstated tests in next line.
if nf > 2 | step <= 0.01
atol = atolold*0.1;
end
end
end
%---------------------------------------------------------------------
% End of main loop.
%---------------------------------------------------------------------
% Print statistics.
x(fix) = 0; % Exclude x(fix) temporarily from |x|.
z = zeros(n,1); % Exclude z(fix) also.
z(low) = z1(low);
z(upp) = z(upp) - z2(upp);
myprintf('\n\nmax |x| =%10.3f', norm(x,inf))
myprintf(' max |y| =%10.3f', norm(y,inf))
myprintf(' max |z| =%10.3f', norm(z,inf)) % excludes z(fix)
myprintf(' scaled')
bl(fix)= bl(fix)*beta; % Unscale bl, bu, x, y, z.
bu(fix)= bu(fix)*beta;
bl(low)= bl(low)*beta;
bu(upp)= bu(upp)*beta;
x = x*beta; y = y*zeta; z = z*zeta;
myprintf( '\nmax |x| =%10.3f', norm(x,inf))
myprintf(' max |y| =%10.3f', norm(y,inf))
myprintf(' max |z| =%10.3f', norm(z,inf)) % excludes z(fix)
myprintf(' unscaled')
x(fix) = bl(fix); % Reinstate x(fix).
% Reconstruct b.
b = b *beta;
if nfix > 0
x1 = zeros(n,1); x1(fix) = bl(fix);
r1 = pdxxxmat( Aname, 1, m, n, x1 );
b = b + r1;
myprintf('\nmax |x| and max |z| exclude fixed variables')
end
% Evaluate function at final point.
% Reconstruct z. This finally defines z(fix).
if explicitF
obj = (Fname'*x); grad = Fname; hess = zeros(n,1);
else
[obj,grad,hess] = feval( Fname, x );
end
z = grad - pdxxxmat( Aname,2,m,n,y ); % z = grad - A'y
time = cputime - time;
str1 = sprintf('\nPDitns =%10g', PDitns );
str2 = sprintf( 'itns =%10g', CGitns );
myprintf( [str1 ' ' solver str2] )
myprintf(' time =%10.1f', time);
pdxxxdistrib( abs(x),abs(z) ); % Private function
if wait
keyboard
end
%-----------------------------------------------------------------------
% End function pdco.m
%-----------------------------------------------------------------------
function [low,upp,fix] = pdxxxbounds( bl,bu )
% Categorize various types of bounds.
% pos overlaps with low.
% neg overlaps with upp.
% two overlaps with low and upp.
% fix and free are disjoint from all other sets.
bigL = -9.9e+19;
bigU = 9.9e+19;
pos = find( bl==0 & bu>=bigU );
neg = find( bl<=bigL & bu==0 );
low = find( bl> bigL & bl< bu );
upp = find( bu< bigU & bl< bu );
two = find( bl> bigL & bu< bigU & bl< bu );
fix = find( bl==bu );
free = find( bl<=bigL & bu>=bigU );
myprintf('\n\nBounds:\n [0,inf] [-inf,0]')
myprintf(' Finite bl Finite bu Two bnds Fixed Free')
myprintf('\n %8g %9g %10g %10g %9g %7g %7g', ...
length(pos), length(neg), length(low), ...
length(upp), length(two), length(fix), length(free))
%-----------------------------------------------------------------------
% End private function pdxxxbounds
%-----------------------------------------------------------------------
function pdxxxdistrib( x,z )
% pdxxxdistrib(x) or pdxxxdistrib(x,z) prints the
% distribution of 1 or 2 vectors.
%
% 18 Dec 2000. First version with 2 vectors.
two = nargin > 1;
myprintf('\n\nDistribution of vector x')
if two, myprintf(' z'); end
x1 = 10^(floor(log10(max(x)+eps)) + 1);
z1 = 10^(floor(log10(max(z)+eps)) + 1);
x1 = max(x1,z1);
kmax = 10;
for k = 1:kmax
x2 = x1; x1 = x1/10;
if k==kmax, x1 = 0; end
nx = length(find(x>=x1 & x<x2));
myprintf('\n[%7.3g,%7.3g )%10g', x1, x2, nx);
if two
nz = length(find(z>=x1 & z<x2));
myprintf('%10g', nz);
end
end
mydisp(' ')
%-----------------------------------------------------------------------
% End private function pdxxxdistrib
%-----------------------------------------------------------------------
function [ x, istop, itn, outfo ] = ...
pdxxxlsqr( m, n, aprodname, iw, rw, b, damp, ...
atol, btol, conlim, itnlim, show, info )
% Special version of LSQR for use with pdco.m.
% It continues with a reduced atol if a pdco-specific test isn't
% satisfied with the input atol.
%
% LSQR solves Ax = b or min ||b - Ax||_2 if damp = 0,
% or min || (b) - ( A )x || otherwise.
% || (0) (damp I) ||2
% A is an m by n matrix defined by y = aprod( mode,m,n,x,iw,rw ),
% where the parameter 'aprodname' refers to a function 'aprod' that
% performs the matrix-vector operations.
% If mode = 1, aprod must return y = Ax without altering x.
% If mode = 2, aprod must return y = A'x without altering x.
% WARNING: The file containing the function 'aprod'
% must not be called aprodname.m !!!!
%-----------------------------------------------------------------------
% LSQR uses an iterative (conjugate-gradient-like) method.
% For further information, see
% 1. C. C. Paige and M. A. Saunders (1982a).
% LSQR: An algorithm for sparse linear equations and sparse least squares,
% ACM TOMS 8(1), 43-71.
% 2. C. C. Paige and M. A. Saunders (1982b).
% Algorithm 583. LSQR: Sparse linear equations and least squares problems,
% ACM TOMS 8(2), 195-209.
% 3. M. A. Saunders (1995). Solution of sparse rectangular systems using
% LSQR and CRAIG, BIT 35, 588-604.
%
% Input parameters:
% iw, rw are not used by lsqr, but are passed to aprod.
% atol, btol are stopping tolerances. If both are 1.0e-9 (say),
% the final residual norm should be accurate to about 9 digits.
% (The final x will usually have fewer correct digits,
% depending on cond(A) and the size of damp.)
% conlim is also a stopping tolerance. lsqr terminates if an estimate
% of cond(A) exceeds conlim. For compatible systems Ax = b,
% conlim could be as large as 1.0e+12 (say). For least-squares
% problems, conlim should be less than 1.0e+8.
% Maximum precision can be obtained by setting
% atol = btol = conlim = zero, but the number of iterations
% may then be excessive.
% itnlim is an explicit limit on iterations (for safety).
% show = 1 gives an iteration log,
% show = 0 suppresses output.
% info is a structure special to pdco.m, used to test if
% was small enough, and continuing if necessary with smaller atol.
%
%
% Output parameters:
% x is the final solution.
% istop gives the reason for termination.
% istop = 1 means x is an approximate solution to Ax = b.
% = 2 means x approximately solves the least-squares problem.
% rnorm = norm(r) if damp = 0, where r = b - Ax,
% = sqrt( norm(r)**2 + damp**2 * norm(x)**2 ) otherwise.
% xnorm = norm(x).
% var estimates diag( inv(A'A) ). Omitted in this special version.
% outfo is a structure special to pdco.m, returning information
% about whether atol had to be reduced.
%
% Other potential output parameters:
% anorm, acond, arnorm, xnorm
%
% 1990: Derived from Fortran 77 version of LSQR.
% 22 May 1992: bbnorm was used incorrectly. Replaced by anorm.
% 26 Oct 1992: More input and output parameters added.
% 01 Sep 1994: Matrix-vector routine is now a parameter 'aprodname'.
% Print log reformatted.
% 14 Jun 1997: show added to allow printing or not.
% 30 Jun 1997: var added as an optional output parameter.
% It returns an estimate of diag( inv(A'A) ).
% 12 Feb 2001: atol can now be reduced and iterations continued if necessary.
% info, outfo are new problem-dependent parameters for such purposes.
% In this version they are specialized for pdco.m.
%-----------------------------------------------------------------------
% Initialize.
msg=['The exact solution is x = 0 '
'Ax - b is small enough, given atol, btol '
'The least-squares solution is good enough, given atol '
'The estimate of cond(Abar) has exceeded conlim '
'Ax - b is small enough for this machine '
'The least-squares solution is good enough for this machine'
'Cond(Abar) seems to be too large for this machine '
'The iteration limit has been reached '];
% wantvar= nargout >= 6;
% if wantvar, var = zeros(n,1); end
itn = 0; istop = 0; nstop = 0;
ctol = 0; if conlim > 0, ctol = 1/conlim; end;
anorm = 0; acond = 0;
dampsq = damp^2; ddnorm = 0; res2 = 0;
xnorm = 0; xxnorm = 0; z = 0;
cs2 = -1; sn2 = 0;
% Set up the first vectors u and v for the bidiagonalization.
% These satisfy beta*u = b, alfa*v = A'u.
u = b(1:m); x = zeros(n,1);
alfa = 0; beta = norm( u );
if beta > 0
u = (1/beta) * u; v = feval( aprodname, 2, m, n, u, iw, rw );
alfa = norm( v );
end
if alfa > 0
v = (1/alfa) * v; w = v;
end
arnorm = alfa * beta; if arnorm==0, mydisp(msg(1,:)); return, end
rhobar = alfa; phibar = beta; bnorm = beta;
rnorm = beta;
head1 = ' Itn x(1) Function';
head2 = ' Compatible LS Norm A Cond A';
if show
mydisp(' ')
mydisp([head1 head2])
test1 = 1; test2 = alfa / beta;
str1 = sprintf( '%6g %12.5e %10.3e', itn, x(1), rnorm );
str2 = sprintf( ' %8.1e %8.1e', test1, test2 );
mydisp([str1 str2])
end
%----------------------------------------------------------------
% Main iteration loop.
%----------------------------------------------------------------
while itn < itnlim
itn = itn + 1;
% Perform the next step of the bidiagonalization to obtain the
% next beta, u, alfa, v. These satisfy the relations
% beta*u = A*v - alfa*u,
% alfa*v = A'*u - beta*v.
u = feval( aprodname, 1, m, n, v, iw, rw ) - alfa*u;
beta = norm( u );
if beta > 0
u = (1/beta) * u;
anorm = norm([anorm alfa beta damp]);
v = feval( aprodname, 2, m, n, u, iw, rw ) - beta*v;
alfa = norm( v );
if alfa > 0, v = (1/alfa) * v; end
end
% Use a plane rotation to eliminate the damping parameter.
% This alters the diagonal (rhobar) of the lower-bidiagonal matrix.
rhobar1 = norm([rhobar damp]);
cs1 = rhobar / rhobar1;
sn1 = damp / rhobar1;
psi = sn1 * phibar;
phibar = cs1 * phibar;
% Use a plane rotation to eliminate the subdiagonal element (beta)
% of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix.
rho = norm([rhobar1 beta]);
cs = rhobar1/ rho;
sn = beta / rho;
theta = sn * alfa;
rhobar = - cs * alfa;
phi = cs * phibar;
phibar = sn * phibar;
tau = sn * phi;
% Update x and w.
t1 = phi /rho;
t2 = - theta/rho;
dk = (1/rho)*w;
x = x + t1*w;
w = v + t2*w;
ddnorm = ddnorm + norm(dk)^2;
% if wantvar, var = var + dk.*dk; end
% Use a plane rotation on the right to eliminate the
% super-diagonal element (theta) of the upper-bidiagonal matrix.
% Then use the result to estimate norm(x).
delta = sn2 * rho;
gambar = - cs2 * rho;
rhs = phi - delta * z;
zbar = rhs / gambar;
xnorm = sqrt(xxnorm + zbar^2);
gamma = norm([gambar theta]);
cs2 = gambar / gamma;
sn2 = theta / gamma;
z = rhs / gamma;
xxnorm = xxnorm + z^2;
% Test for convergence.
% First, estimate the condition of the matrix Abar,
% and the norms of rbar and Abar'rbar.
acond = anorm * sqrt( ddnorm );
res1 = phibar^2;
res2 = res2 + psi^2;
rnorm = sqrt( res1 + res2 );
arnorm = alfa * abs( tau );
% Now use these norms to estimate certain other quantities,
% some of which will be small near a solution.
test1 = rnorm / bnorm;
test2 = arnorm/( anorm * rnorm );
test3 = 1 / acond;
t1 = test1 / (1 + anorm * xnorm / bnorm);
rtol = btol + atol * anorm * xnorm / bnorm;
% The following tests guard against extremely small values of
% atol, btol or ctol. (The user may have set any or all of
% the parameters atol, btol, conlim to 0.)
% The effect is equivalent to the normal tests using
% atol = eps, btol = eps, conlim = 1/eps.
if itn >= itnlim, istop = 7; end
if 1 + test3 <= 1, istop = 6; end
if 1 + test2 <= 1, istop = 5; end
if 1 + t1 <= 1, istop = 4; end
% Allow for tolerances set by the user.
if test3 <= ctol, istop = 3; end
if test2 <= atol, istop = 2; end
if test1 <= rtol, istop = 1; end
%-------------------------------------------------------------------
% SPECIAL TEST THAT DEPENDS ON pdco.m.
% Aname in pdco is iw in lsqr.
% dy is x
% Other stuff is in info.
% We allow for diagonal preconditioning in pdDDD3.
%-------------------------------------------------------------------
if istop > 0
r3new = arnorm;
r3ratio = r3new / info.r3norm;
atolold = atol;
atolnew = atol;
if atol > info.atolmin
if r3ratio <= 0.1 % dy seems good
% Relax
elseif r3ratio <= 0.5 % Accept dy but make next one more accurate.
atolnew = atolnew * 0.1;
else % Recompute dy more accurately
myprintf('\n ')
myprintf(' ')
myprintf(' %5.1f%7g%7.3f', log10(atolold), itn, r3ratio)
atol = atol * 0.1;
atolnew = atol;
istop = 0;
end
end
outfo.atolold = atolold;
outfo.atolnew = atolnew;
outfo.r3ratio = r3ratio;
end
%-------------------------------------------------------------------
% See if it is time to print something.
%-------------------------------------------------------------------
prnt = 0;
if n <= 40 , prnt = 1; end
if itn <= 10 , prnt = 1; end
if itn >= itnlim-10, prnt = 1; end
if rem(itn,10)==0 , prnt = 1; end
if test3 <= 2*ctol , prnt = 1; end
if test2 <= 10*atol , prnt = 1; end
if test1 <= 10*rtol , prnt = 1; end
if istop ~= 0 , prnt = 1; end
if prnt==1
if show
str1 = sprintf( '%6g %12.5e %10.3e', itn, x(1), rnorm );
str2 = sprintf( ' %8.1e %8.1e', test1, test2 );
str3 = sprintf( ' %8.1e %8.1e', anorm, acond );
mydisp([str1 str2 str3])
end
end
if istop > 0, break, end
end
% End of iteration loop.
% Print the stopping condition.
if show
mydisp(' ')
mydisp('LSQR finished')
mydisp(msg(istop+1,:))
mydisp(' ')
str1 = sprintf( 'istop =%8g itn =%8g', istop, itn );
str2 = sprintf( 'anorm =%8.1e acond =%8.1e', anorm, acond );
str3 = sprintf( 'rnorm =%8.1e arnorm =%8.1e', rnorm, arnorm );
str4 = sprintf( 'bnorm =%8.1e xnorm =%8.1e', bnorm, xnorm );
mydisp([str1 ' ' str2])
mydisp([str3 ' ' str4])
mydisp(' ')
end
%-----------------------------------------------------------------------
% End private function pdxxxlsqr
%-----------------------------------------------------------------------
function y = pdxxxlsqrmat( mode, mlsqr, nlsqr, x, Aname, rw )
% pdxxxlsqrmat is required by pdco.m (when it calls pdxxxlsqr.m).
% It forms Mx or M'x for some operator M that depends on Method below.
%
% mlsqr, nlsqr are the dimensions of the LS problem that lsqr is solving.
%
% Aname is pdco's Aname.
%
% rw contains parameters [explicitA Method LSdamp]
% from pdco.m to say which least-squares subproblem is being solved.
%
% global pdDDD1 pdDDD3 provides various diagonal matrices
% for each value of Method.
%-----------------------------------------------------------------------
% 17 Mar 1998: First version to go with pdsco.m and lsqr.m.
% 01 Apr 1998: global pdDDD1 pdDDD3 now used for efficiency.
% 11 Feb 2000: Added diagonal preconditioning for LSQR, solving for dy.
% 14 Dec 2000: Added diagonal preconditioning for LSQR, solving for dx.
% 12 Feb 2001: Included in pdco.m as private function.
% Specialized to allow only solving for dy.
% 03 Oct 2002: First version to go with pdco.m with general H2 and D2.
% 16 Oct 2002: Aname is now the user's Aname.
%-----------------------------------------------------------------------
global pdDDD1 pdDDD2 pdDDD3
Method = rw(2);
precon = rw(7);
if Method==3
% The operator M is [ D1 A'; D2 ].
m = nlsqr;
n = mlsqr - m;
if mode==1
if precon, x = pdDDD3.*x; end
t = pdxxxmat( Aname, 2, m, n, x ); % Ask 'aprod' to form t = A'x.
y = [ (pdDDD1.*t); (pdDDD2.*x) ];
else
t = pdDDD1.*x(1:n);
y = pdxxxmat( Aname, 1, m, n, t ); % Ask 'aprod' to form y = A t.
y = y + pdDDD2.*x(n+1:mlsqr);
if precon, y = pdDDD3.*y; end
end
else
error('Error in pdxxxlsqrmat: Only Method = 3 is allowed at present')
end
%-----------------------------------------------------------------------
% End private function pdxxxlsqrmat
%-----------------------------------------------------------------------
function y = pdxxxmat( Aname, mode, m, n, x )
% y = pdxxxmat( Aname, mode, m, n, x )
% computes y = Ax (mode=1) or A'x (mode=2)
% for a matrix A defined by pdco's input parameter Aname.
%-----------------------------------------------------------------------
% 04 Apr 1998: Default A*x and A'*y function for pdco.m.
% Assumed A was a global matrix pdAAA created by pdco.m
% from the user's input parameter A.
% 16 Oct 2002: pdAAA eliminated to save storage.
% User's parameter Aname is now passed thru to here.
% 01 Nov 2002: Bug: feval had one too many parameters.
%-----------------------------------------------------------------------
if (ischar(Aname) || isa(Aname, 'function_handle'))
y = feval( Aname, mode, m, n, x );
else
if mode==1, y = Aname*x; else y = Aname'*x; end
end
%-----------------------------------------------------------------------
% End private function pdxxxmat
%-----------------------------------------------------------------------
function fmerit = pdxxxmerit( low,upp,r1,r2,rL,rU,cL,cU )
% Evaluate the merit function for Newton's method.
% It is the 2-norm of the three sets of residuals.
f = [norm(r1)
norm(r2)
norm(rL(low))
norm(rU(upp))
norm(cL(low))
norm(cU(upp))];
fmerit = norm(f);
%-----------------------------------------------------------------------
% End private function pdxxxmerit
%-----------------------------------------------------------------------
function [r1,r2,rL,rU,Pinf,Dinf] = ...
pdxxxresid1( Aname,fix,low,upp, ...
b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 )
% Form residuals for the primal and dual equations.
% rL, rU are output, but we input them as full vectors
% initialized (permanently) with any relevant zeros.
% 13 Aug 2003: z2-z1 coded more carefully
% (although MATLAB was doing the right thing).
% 19 Nov 2003: r2(fix) = 0 has to be done after r2 = grad - r2;
m = length(b);
n = length(bl);
x(fix) = 0;
r1 = pdxxxmat( Aname, 1, m, n, x );
r2 = pdxxxmat( Aname, 2, m, n, y );
r1 = b - r1 - (d2.^2).*y;
r2 = grad - r2; % + (z2-z1); % grad includes (d1.^2)*x
r2(fix) = 0;
r2(upp) = r2(upp) + z2(upp);
r2(low) = r2(low) - z1(low);
rL(low) = ( bl(low) - x(low)) + x1(low);
rU(upp) = (- bu(upp) + x(upp)) + x2(upp);
Pinf = max([norm(r1,inf) norm(rL(low),inf) norm(rU(upp),inf)]);
Dinf = norm(r2,inf);
Pinf = max( Pinf, 1e-99 );
Dinf = max( Dinf, 1e-99 );
%-----------------------------------------------------------------------
% End private function pdxxxresid1
%-----------------------------------------------------------------------
function [cL,cU,center,Cinf,Cinf0] = ...
pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 )
% Form residuals for the complementarity equations.
% cL, cU are output, but we input them as full vectors
% initialized (permanently) with any relevant zeros.
% Cinf is the complementarity residual for X1 z1 = mu e, etc.
% Cinf0 is the same for mu=0 (i.e., for the original problem).
x1z1 = x1(low).*z1(low);
x2z2 = x2(upp).*z2(upp);
cL(low) = mu - x1z1;
cU(upp) = mu - x2z2;
maxXz = max( [max(x1z1) max(x2z2)] );
minXz = min( [min(x1z1) min(x2z2)] );
maxXz = max( maxXz, 1e-99 );
minXz = max( minXz, 1e-99 );
center = maxXz / minXz;
Cinf = max([norm(cL(low),inf) norm(cU(upp),inf)]);
Cinf0 = maxXz;
%-----------------------------------------------------------------------
% End private function pdxxxresid2
%-----------------------------------------------------------------------
function step = pdxxxstep( x, dx )
% Assumes x > 0.
% Finds the maximum step such that x + step*dx >= 0.
step = 1e+20;
blocking = find( dx < 0 );
if length( blocking ) > 0
steps = x(blocking) ./ (- dx(blocking));
step = min( steps );
end
%
% Copyright (c) 2006. Michael Saunders
%
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
function myprintf(s,a,b,c,d,e,f,g,h,i,j,k,l,m,n)
function mydisp(s)
function options = pdcoSet(varargin)
%pdcoSet creates or alters an options structure for pdco.m.
%It is modeled after MATLAB's original version of optimset.
%
% options = pdcoSet (with no input arguments) creates a structure
% with all fields set to their default values. Each field is an
% option (also called a parameter).
%
% pdcoSet (with no input or output arguments) displays all options
% and their default values.
%
% options = pdcoSet('PARAM1',VALUE1,'PARAM2',VALUE2,...);
% creates a structure with the specified named parameters and values.
% Any unspecified parameters are set to [].
% It is sufficient to use only the leading characters that uniquely
% identify the parameter. Case is ignored for parameter names.
%
% NOTE: For values that are strings, correct case and the complete string
% are required; if an invalid string is provided, the default is used.
%
% options = pdcoSet(oldopts,'PARAM1',VALUE1,...);
% creates a copy of oldopts with the named parameters reset to the
% specified values.
%
% options = pdcoSet(oldopts,newopts);
% combines an existing structure oldopts with a new structure newopts.
% Any parameters in newopts with non-empty values overwrite the
% corresponding old parameters in oldopts.
%
% options.MaxIter Maximum iterations of the primal-dual barrier method.
% Most problems should solve within 30 PDitns.
% options.FeaTol Accuracy for satisfying Ax + D2 r = b, A'y + z = gobj
% and x - x1 = bl, x + x2 = bu, where x1, x2 > 0.
% 1e-6 is typically small enough.
% 1e-5 may be acceptable also.
% options.OptTol Accuracy for satisfying x1.*z1 = 0, x2.*z2 = 0,
% where z = z1 - z2 and z1, z2 > 0.
% Typically the same as Featol.
% options.StepTol (between 0 and 1): Controls how close each an
% x or z may be to reaching a bound at each step.
% For safety, should not be bigger than 0.99 (say)
% for nonlinear problems.
% options.StepSame 1 (true) if stepx and stepz should be the same
% (gives true Newton method for nonlinear problems);
% 0 (false) if stepx and stepz may be different
% (gives better performance for linear programs).
% options.x0min Min distance between x0 and bl or bu AFTER SCALING.
% 1.0 is about right for cold starts.
% 0.1 or 0.01 may be ok if x0, z0 are "good".
% options.z0min Min distance between abs(z0) and zero AFTER SCALING,
% when z0 is used to initialize z1 > 0 and z2 > 0.
% Typically the same as x0min.
% options.mu0 Initial mu (ABSOLUTE VALUE) for solving scaled problem.
% options.Method Specifies how each search direction (dx,dy,dz1,dz2)
% should be computed. Several methods exist for
% experimental purposes. If A has fewer rows than columns
% (m < n) we usually solve for dy first (most of the work)
% and then get the other components cheaply.
%
% Method Solve for Using Implemented?
% 1 dy Sparse Cholesky on (A D^2 A' + D2^2 I). Yes
% 2 dy Sparse QR on corresponding least-squares problem Yes
% 3 dy LSQR on least-squares problem Yes
%
% 11 dx Sparse Cholesky on (D A'A D + D2^2 I). No
% 12 dx Sparse QR on corresponding least-squares problem No
% 13 dx LSQR on least-squares problem No
%
% 21 dx,dy Sparse LU on 2x2 KKT-type system No
% 23 dx,dy SYMMLQ on same system No
%
% 31 dx,dy,dz1 Sparse LU on 3x3 system (only for problems with No
% with vanilla bounds: 0 < x < inf).
% This is a HUGE system, but it is relatively
% well-conditioned compared to the other systems.
%
% 41 dx,dy,dz1,dz2 Sparse LU on 4x4 system with general bounds. Yes
% This is an even HUGER system.
%
% If A is an explicit sparse matrix, all methods are applicable.
% 1 is usually best (e.g. for LPs).
% 2 may be more reliable; it's there for checking.
% 3 is sometimes more efficient (e.g. for entropy problems).
% Diagonal preconditioning is possible.
%
% If A is an operator,
% 3 must be used. Diagonal preconditioning is not possible.
%
% Notes:
% Method = 1 On ENTROPY.big, symamd can find an ordering
% but chol never finishes.
% Method = 41 On ENTROPY.big, symamd never finishes.
%
% The following options control LSQR when Method = 3:
%
% options.LSQRMaxIter * min(m,n) is the maximum LSQR (CG) iterations.
% options.LSQRatol1 is the starting value of the LSQR accuracy
% tolerance "atol" (if LSmethod = 3).
% 1e-3 or 1e-4 sometimes works.
% 1e-8 may be needed for LPs.
% In general, if max(Pinf,Dinf,Cinf) doesn't decrease
% every iteration, set atol1 to a smaller value.
% options.LSQRatol2 is the smallest value atol is reduced to.
% options.LSQRconlim shuts LSQR down early if its matrix is ill-conditioned.
%
% options.wait = 0 means pdco should proceed to solve the problem.
% = 1 means pdco should pause to allow interactive resetting
% of some of the parameters.
% pdcoSet.m is derived from optimset.m (Revision 1.14, 1998/08/17)
% in the Optimization Toolbox of The MathWorks, Inc.
%
% 28 Sep 2000: First version of pdscoSet.m.
% 30 Sep 2002: First version of pdcoSet.m derived from pdscoSet.m.
% 04 Oct 2002: StepSame introduced.
% 10 Aug 2003: mu0 is now an absolute value -- the initial mu.
% 19 Sep 2003: Method = 41 implemented.
% 22 Sep 2003: LSproblem and LSmethod replaced by Method.
%
%
% Michael Saunders, SOL, Stanford University.
if (nargin == 0) % Set default options.
defoptions.MaxIter = 30;
defoptions.FeaTol = 1e-6;
defoptions.OptTol = 1e-6;
defoptions.StepTol = 0.99;
defoptions.StepSame = 1; % 1 for stepx == stepz (NLPs)
defoptions.x0min = 1.0; % 1.0 | 0.1 for cold | warm starts?
defoptions.z0min = 1.0; % 1.0 | 0.1 for cold | warm starts?
defoptions.mu0 = 1e-1; % < 1.0 better than 1.0?
defoptions.Method = 3; % 3 = computed dy using LSQR
defoptions.LSQRMaxIter = 10.0;
defoptions.LSQRatol1 = 1e-08;
defoptions.LSQRatol2 = 1e-15; %
defoptions.LSQRconlim = 1e+12; % Somewhere between e+8 and e+16
defoptions.wait = 0;
defoptions.NOTE = 'LSQRMaxIter is scaled by the matrix dimension';
if (nargout == 0) % Display options.
disp('pdco default options:')
disp( defoptions )
else
options = defoptions;
end
return;
end
Names = ...
[
'MaxIter '
'FeaTol '
'OptTol '
'StepTol '
'StepSame '
'x0min '
'z0min '
'mu0 '
'Method '
'LSQRMaxIter'
'LSQRatol1 '
'LSQRatol2 '
'LSQRconlim '
'wait '
'NOTE '
];
m = size (Names,1);
names = lower(Names);
% The remaining clever stuff is from optimset.m.
% We should obtain permission from the MathWorks.
% Combine all leading options structures o1, o2, ... in pdcoSet(o1,o2,...).
options = [];
for j = 1:m
eval(['options.' Names(j,:) '= [];']);
end
i = 1;
while i <= nargin
arg = varargin{i};
if isstr(arg) % arg is an option name
break;
end
if ~isempty(arg) % [] is a valid options argument
if ~isa(arg,'struct')
error(sprintf(['Expected argument %d to be a ' ...
'string parameter name ' ...
'or an options structure\ncreated with pdcoSet.'], i));
end
for j = 1:m
if any(strcmp(fieldnames(arg),deblank(Names(j,:))))
eval(['val = arg.' Names(j,:) ';']);
else
val = [];
end
if ~isempty(val)
eval(['options.' Names(j,:) '= val;']);
end
end
end
i = i + 1;
end
% A finite state machine to parse name-value pairs.
if rem(nargin-i+1,2) ~= 0
error('Arguments must occur in name-value pairs.');
end
expectval = 0; % start expecting a name, not a value
while i <= nargin
arg = varargin{i};
if ~expectval
if ~isstr(arg)
error(sprintf(['Expected argument %d to be a ' ...
'string parameter name.'], i));
end
lowArg = lower(arg);
j = strmatch(lowArg,names);
if isempty(j) % if no matches
error(sprintf('Unrecognized parameter name ''%s''.', arg));
elseif length(j) > 1 % if more than one match
% Check for any exact matches
% (in case any names are subsets of others)
k = strmatch(lowArg,names,'exact');
if length(k) == 1
j = k;
else
msg = sprintf('Ambiguous parameter name ''%s'' ', arg);
msg = [msg '(' deblank(Names(j(1),:))];
for k = j(2:length(j))'
msg = [msg ', ' deblank(Names(k,:))];
end
msg = sprintf('%s).', msg);
error(msg);
end
end
else
eval(['options.' Names(j,:) '= arg;']);
end
expectval = ~expectval;
i = i + 1;
end
if expectval
error(sprintf('Expected value for parameter ''%s''.', arg));
end
%
% Copyright (c) 2006. Michael Saunders
%
%
% Part of SparseLab Version:100
% Created Tuesday March 28, 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
%
|
github
|
alex-delalande/numerical-tours-master
|
phantom.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/phantom.m
| 6,447 |
utf_8
|
5cac992f6a3cdfa201a0e3dc7206f4b3
|
function [p,ellipse]=phantom(varargin)
%PHANTOM Generate a head phantom image.
% P = PHANTOM(DEF,N) generates an image of a head phantom that can
% be used to test the numerical accuracy of RADON and IRADON or other
% 2-D reconstruction algorithms. P is a grayscale intensity image that
% consists of one large ellipse (representing the brain) containing
% several smaller ellipses (representing features in the brain).
%
% DEF is a string that specifies the type of head phantom to generate.
% Valid values are:
%
% 'Shepp-Logan' A test image used widely by researchers in
% tomography
% 'Modified Shepp-Logan' (default) A variant of the Shepp-Logan phantom
% in which the contrast is improved for better
% visual perception.
%
% N is a scalar that specifies the number of rows and columns in P.
% If you omit the argument, N defaults to 256.
%
% P = PHANTOM(E,N) generates a user-defined phantom, where each row
% of the matrix E specifies an ellipse in the image. E has six columns,
% with each column containing a different parameter for the ellipses:
%
% Column 1: A the additive intensity value of the ellipse
% Column 2: a the length of the horizontal semi-axis of the ellipse
% Column 3: b the length of the vertical semi-axis of the ellipse
% Column 4: x0 the x-coordinate of the center of the ellipse
% Column 5: y0 the y-coordinate of the center of the ellipse
% Column 6: phi the angle (in degrees) between the horizontal semi-axis
% of the ellipse and the x-axis of the image
%
% For purposes of generating the phantom, the domains for the x- and
% y-axes span [-1,1]. Columns 2 through 5 must be specified in terms
% of this range.
%
% [P,E] = PHANTOM(...) returns the matrix E used to generate the phantom.
%
% Class Support
% -------------
% All inputs must be of class double. All outputs are of class double.
%
% Remarks
% -------
% For any given pixel in the output image, the pixel's value is equal to the
% sum of the additive intensity values of all ellipses that the pixel is a
% part of. If a pixel is not part of any ellipse, its value is 0.
%
% The additive intensity value A for an ellipse can be positive or negative;
% if it is negative, the ellipse will be darker than the surrounding pixels.
% Note that, depending on the values of A, some pixels may have values outside
% the range [0,1].
%
% See also RADON, IRADON.
% Copyright 1993-2003 The MathWorks, Inc.
% $Revision: 1.13.4.2 $ $Date: 2003/08/01 18:09:35 $
% References:
% A. K. Jain, "Fundamentals of Digital Image Processing", p. 439.
% P. A. Toft, "The Radon Transform, Theory and Implementation" (unpublished
% dissertation), p. 199.
[ellipse,n] = parse_inputs(varargin{:});
p = zeros(n);
xax = ( (0:n-1)-(n-1)/2 ) / ((n-1)/2);
xg = repmat(xax, n, 1); % x coordinates, the y coordinates are rot90(xg)
for k = 1:size(ellipse,1)
asq = ellipse(k,2)^2; % a^2
bsq = ellipse(k,3)^2; % b^2
phi = ellipse(k,6)*pi/180; % rotation angle in radians
x0 = ellipse(k,4); % x offset
y0 = ellipse(k,5); % y offset
A = ellipse(k,1); % Amplitude change for this ellipse
x=xg-x0; % Center the ellipse
y=rot90(xg)-y0;
cosp = cos(phi);
sinp = sin(phi);
idx=find(((x.*cosp + y.*sinp).^2)./asq + ((y.*cosp - x.*sinp).^2)./bsq <= 1);
p(idx) = p(idx) + A;
end
function [e,n] = parse_inputs(varargin)
% e is the m-by-6 array which defines ellipses
% n is the size of the phantom brain image
n=256; % The default size
e = [];
defaults = {'shepp-logan', 'modified shepp-logan'};
for i=1:nargin
if ischar(varargin{i}) % Look for a default phantom
def = lower(varargin{i});
idx = strmatch(def, defaults);
if isempty(idx)
eid = sprintf('Images:%s:unknownPhantom',mfilename);
msg = 'Unknown default phantom selected.';
error(eid,'%s',msg);
end
switch defaults{idx}
case 'shepp-logan'
e = shepp_logan;
case 'modified shepp-logan'
e = modified_shepp_logan;
end
elseif numel(varargin{i})==1
n = varargin{i}; % a scalar is the image size
elseif ndims(varargin{i})==2 && size(varargin{i},2)==6
e = varargin{i}; % user specified phantom
else
eid = sprintf('Images:%s:invalidInputArgs',mfilename);
msg = 'Invalid input arguments.';
error(eid,'%s',msg);
end
end
if isempty(e) % ellipse is not yet defined
e = modified_shepp_logan;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Default head phantoms:
%
function shep=shepp_logan
%
% This is the default head phantom, taken from AK Jain, 439.
%
% A a b x0 y0 phi
% ---------------------------------
shep = [ 1 .69 .92 0 0 0
-.98 .6624 .8740 0 -.0184 0
-.02 .1100 .3100 .22 0 -18
-.02 .1600 .4100 -.22 0 18
.01 .2100 .2500 0 .35 0
.01 .0460 .0460 0 .1 0
.01 .0460 .0460 0 -.1 0
.01 .0460 .0230 -.08 -.605 0
.01 .0230 .0230 0 -.606 0
.01 .0230 .0460 .06 -.605 0 ];
function toft=modified_shepp_logan
%
% This head phantom is the same as the Shepp-Logan except
% the intensities are changed to yield higher contrast in
% the image. Taken from Toft, 199-200.
%
% A a b x0 y0 phi
% ---------------------------------
toft = [ 1 .69 .92 0 0 0
-.8 .6624 .8740 0 -.0184 0
-.2 .1100 .3100 .22 0 -18
-.2 .1600 .4100 -.22 0 18
.1 .2100 .2500 0 .35 0
.1 .0460 .0460 0 .1 0
.1 .0460 .0460 0 -.1 0
.1 .0460 .0230 -.08 -.605 0
.1 .0230 .0230 0 -.606 0
.1 .0230 .0460 .06 -.605 0 ];
|
github
|
alex-delalande/numerical-tours-master
|
perform_arith_coding.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_arith_coding.m
| 30,315 |
utf_8
|
b017b1e1fe107dfccde92738b628d194
|
function [y,nbr_bits] = perform_arith_coding(xC, dir)
% perform_arithmetic_coding_slow - perform adaptive arithmetic coding
%
% [y,nbr_bits] = perform_arithmetic_coding_slow(x, dir);
%
% dir=1 for encoding, dir=-1 for decoding.
%
% Based on the code of (c) Karl Skretting
%
% Copyright (c) 2008 Gabriel Peyre
%
% ------------------------------------------------------------------
% Arguments:
% y a column vector of non-negative integers (bytes) representing
% the code, 0 <= y(i) <= 255.
% Res a matrix that sum up the results, size is (NumOfX+1)x4
% one line for each of the input sequences, the columns are
% Res(:,1) - number of elements in the sequence
% Res(:,2) - unused (=0)
% Res(:,3) - bits needed to code the sequence
% Res(:,4) - bit rate for the sequence, Res(:,3)/Res(:,1)
% Then the last line is total (which include bits needed to store NumOfX)
% x a cell array of column vectors of integers representing the
% symbol sequences. (should not be to large integers)
% If only one sequence is to be coded, we must make the cell array
% like: xC=cell(2,1); xC{1}=x; % where x is the sequence
% ------------------------------------------------------------------
% Note: this routine is extremely slow since it is all Matlab code
% SOME NOTES ON THE FUNCTION
% This function is almost like Arith06, but some important changes have
% been done. Arith06 is buildt almost like Huff06, but this close connection
% is removed in Arith07. This imply that to understand the way Arith06
% works you should read the dokumentation for Huff06 and especially the
% article on Recursive Huffman Coding. To understand how Arith07 works it is
% only confusing to read about the recursive Huffman coder, Huff06.
%
% Arith07 code each of the input sequences in xC in sequence, the
% method used for each sequence depends on what kind (xType) the
% sequence is. We have
% xType Explanation
% 0 Empty sequence (L=0)
% 1 Only one symbol (L=1) and x>1
% 9 Only one symbol (L=1) and x=0/1
% 11 Only one symbol (L=1) and x<0
% 2 all symbols are equal, L>1, x(1)=x(2)=...=x(L)>1
% 8 all symbols are equal, L>1, x(1)=x(2)=...=x(L)=0/1
% 10 all symbols are equal, L>1, x(1)=x(2)=...=x(L)<0
% 3 non-negative integers, 0<=x(l)<=1000
% 4 not to large integers, -1000<=x(l)<=1000
% 5 large non-negative integers possible, 0<=x(l)
% 6 also possible with large negative numbers
% 7 A binary sequence, x(l)=0/1.
% Many functions are defined in this m-file:
% PutBit, GetBit read and write bit from/to bitstream
% PutABit, GetABit Arithmetic encoding of a bit, P{0}=P{1}=0.5
% PutVLIC, GetVLIC Variable Length Integer Code
% PutS(x,S,C), GetS(S,C) A symbol x, which is in S, is aritmetic coded
% according to the counts given by C.
% Ex: A binary variable with the givene probabilities
% P{0}=0.8 and P{1}=0.2, PutS(x,[0,1],[4,1]).
% PutN(x,N), GetN(N) Arithmetic coding of a number x in range 0<=x<=N where
% we assume equal probability, P{0}=P{1}=...=P{N}=1/(N+1)
if iscell(xC) & length(xC)>1
nbr_bits = 0;
for k=1:length(xC)
[y{k},nb] = perform_arithmetic_coding(xC{k}, dir);
nbr_bits = nbr_bits + nb;
end
return;
end
if dir==1
xC = {xC};
end
%----------------------------------------------------------------------
% Copyright (c) 1999-2001. Karl Skretting. All rights reserved.
% Hogskolen in Stavanger (Stavanger University), Signal Processing Group
% Mail: [email protected] Homepage: http://www.ux.his.no/~karlsk/
%
% HISTORY:
% Ver. 1.0 19.05.2001 KS: Function made (based on Arith06 and Huff06)
%----------------------------------------------------------------------
% these global variables are used to read from or write to the compressed sequence
global y Byte BitPos
% and these are used by the subfunctions for arithmetic coding
global high low range ub hc lc sc K code
Mfile='Arith07';
K=24; % number of bits to use in integers (4 <= K <= 24)
Display=0; % display progress and/or results
% check input and output arguments, and assign values to arguments
if (nargin < 1);
error([Mfile,': function must have input arguments, see help.']);
end
if (nargout < 1);
error([Mfile,': function must have output arguments, see help.']);
end
if (~iscell(xC))
Encode=0;Decode=1;
y=xC(:); % first argument is y
y=[y;0;0;0;0]; % add some zeros to always have bits available
else
Encode=1;Decode=0;
NumOfX = length(xC);
end
Byte=0;BitPos=1; % ready to read/write into first position
low=0;high=2^K-1;ub=0; % initialize the coder
code=0;
% we just select some probabilities which we belive will work quite well
TypeS=[ 3, 4, 5, 7, 6, 1, 9, 11, 2, 8, 10, 0];
TypeC=[100, 50, 50, 50, 20, 10, 10, 10, 4, 4, 2, 1];
if Encode
Res=zeros(NumOfX,4);
% initalize the global variables
y=zeros(10,1); % put some zeros into y initially
% start encoding, first write VLIC to give number of sequences
PutVLIC(NumOfX);
% now encode each sequence continuously
Ltot=0;
for num=1:NumOfX
x=xC{num};
x=full(x(:)); % make sure x is a non-sparse column vector
L=length(x);
Ltot=Ltot+L;
y=[y(1:Byte);zeros(50+2*L,1)]; % make more space available in y
StartPos=Byte*8-BitPos+ub; % used for counting bits
% find what kind of sequenqe we have, save this in xType
if (L==0)
xType=0;
elseif L==1
if (x==0) | (x==1) % and it is 0/1
xType=9;
elseif (x>1) % and it is not 0/1 (and positive)
xType=1;
else % and it is not 0/1 (and negative)
xType=11;
end
else
% now find some more info about x
maxx=max(x);
minx=min(x);
rangex=maxx-minx+1;
if (rangex==1) % only one symbol
if (maxx==0) | (maxx==1) % and it is 0/1
xType=8;
elseif (maxx>1) % and it is not 0/1 (and positive)
xType=2;
else % and it is not 0/1 (and negative)
xType=10;
end
elseif (minx == 0) & (maxx == 1) % a binary sequence
xType=7;
elseif (minx >= 0) & (maxx <= 1000)
xType=3;
elseif (minx >= 0)
xType=5;
elseif (minx >= -1000) & (maxx <= 1000)
xType=4;
else
xType=6;
end
end % if (L==0)
if Display >= 2
disp([Mfile,': sequence ',int2str(num),' has xType=',int2str(xType)]);
end
%
if sum(xType==[4,6]) % negative values are present
I=find(x); % non-zero entries in x
Sg=(sign(x(I))+1)/2; % the signs will be needed later, 0/1
x=abs(x);
end
if sum(xType==[5,6]) % we take the logarithms of the values
I=find(x); % non-zero entries in x
xa=x; % additional bits
x(I)=floor(log2(x(I)));
xa(I)=xa(I)-2.^x(I);
x(I)=x(I)+1;
end
% now do the coding of this sequence
PutS(xType,TypeS,TypeC);
if (xType==1) % one symbol and x=x(1)>1
PutVLIC(x-2);
elseif (xType==2) % L>1 but only one symbol, x(1)=x(2)=...=x(L)>1
PutVLIC(L-2);
PutVLIC(x(1)-2);
elseif sum(xType==[3,4,5,6]) % now 'normalized' sequences: 0 <= x(i) <= 1000
PutVLIC(L-2);
M=max(x);
PutN(M,1000); % some bits for M
% initialize model
T=[ones(M+2,1);0];
Tu=flipud((-1:(M+1))'); % (-1) since ESC never is used in Tu context
% and code the symbols in the sequence x
for l=1:L
sc=T(1);
m=x(l);
hc=T(m+1);lc=T(m+2);
if hc==lc % unused symbol, code ESC symbol first
hc=T(M+2);lc=T(M+3);
EncodeSymbol; % code escape with T table
sc=Tu(1);hc=Tu(m+1);lc=Tu(m+2); % symbol with Tu table
Tu(1:(m+1))=Tu(1:(m+1))-1; % update Tu table
end
EncodeSymbol; % code actual symbol with T table (or Tu table)
% update T table, MUST be identical in Encode and Decode
% this avoid very large values in T even if sequence is very long
T(1:(m+1))=T(1:(m+1))+1;
if (rem(l,5000)==0)
dT=T(1:(M+2))-T(2:(M+3));
dT=floor(dT*7/8+1/8);
for m=(M+2):(-1):1; T(m)=T(m+1)+dT(m); end;
end
end % for l=1:L
% this end the "elseif sum(xType==[3,4,5,6])"-clause
elseif (xType==7) % L>1 and 0 <= x(i) <= 1
PutVLIC(L-2);
EncodeBin(x,L); % code this sequence a special way
elseif (xType==8) % L>1 and 0 <= x(1)=x(2)=...=x(L) <= 1
PutVLIC(L-2);
PutABit(x(1));
elseif (xType==9) % L=1 and 0 <= x(1) <= 1
PutABit(x(1));
elseif (xType==10) % L>1 and x(1)=x(2)=...=x(L) <= -1
PutVLIC(L-2);
PutVLIC(-1-x(1));
elseif (xType==11) % L=1 and x(1) <= -1
PutVLIC(-1-x);
end % if (xType==1)
% additional information should be coded as well
if 0 % first the way it is not done any more
if sum(xType==[4,6]) % sign must be stored
for i=1:length(Sg); PutABit(Sg(i)); end;
end
if sum(xType==[5,6]) % additional bits must be stored
for i=1:L
for ii=(x(i)-1):(-1):1
PutABit(bitget(xa(i),ii));
end
end
end
else % this is how we do it
if sum(xType==[4,6]) % sign must be stored
EncodeBin(Sg,length(I)); % since length(I)=length(Sg)
end
if sum(xType==[5,6]) % additional bits must be stored
b=zeros(sum(x)-length(I),1); % number of additional bits
bi=0;
for i=1:L
for ii=(x(i)-1):(-1):1
bi=bi+1;
b(bi)=bitget(xa(i),ii);
end
end
if (bi~=(sum(x)-length(I)))
error([Mfile,': logical error, bi~=(sum(x)-length(I)).']);
end
EncodeBin(b,bi); % since bi=(sum(x)-length(I))
end
end
%
EndPos=Byte*8-BitPos+ub; % used for counting bits
bits=EndPos-StartPos;
Res(num,1)=L;
Res(num,2)=0;
Res(num,3)=bits;
if L>0; Res(num,4)=bits/L; else Res(num,4)=bits; end;
if Display
disp([Mfile,': Sequence ',int2str(num),' of ',int2str(L),' symbols ',...
'encoded using ',int2str(bits),' bits.']);
end
end % for num=1:NumOfX
% flush the arithmetic coder
PutBit(bitget(low,K-1));
ub=ub+1;
while ub>0
PutBit(~bitget(low,K-1));
ub=ub-1;
end
% flush is finished
y=y(1:Byte);
varargout(1) = {y};
if (nargout >= 2)
% now calculate results for the total
Res(NumOfX+1,1)=Ltot;
Res(NumOfX+1,2)=0;
Res(NumOfX+1,3)=Byte*8;
if (Ltot>0); Res(NumOfX+1,4)=Byte*8/Ltot; else Res(NumOfX+1,4)=Byte*8; end;
varargout(2) = {Res};
end
end % if Encode
if Decode
for k=1:K
code=code*2;
code=code+GetBit; % read bits into code
end
NumOfX=GetVLIC; % first read number of sequences
xC=cell(NumOfX,1);
for num=1:NumOfX
% find what kind of sequenqe we have, xType, stored first in sequence
xType=GetS(TypeS,TypeC);
% now decode the different kind of sequences, each the way it was stored
if (xType==0) % empty sequence, no more symbols coded
x=[];
elseif (xType==1) % one symbol and x=x(1)>1
x=GetVLIC+2;
elseif (xType==2) % L>1 but only one symbol, x(1)=x(2)=...=x(L)>1
L=GetVLIC+2;
x=ones(L,1)*(GetVLIC+2);
elseif sum(xType==[3,4,5,6]) % now 'normalized' sequences: 0 <= x(i) <= 1000
L=GetVLIC+2;
x=zeros(L,1);
M=GetN(1000); % M is max(x)
% initialize model
T=[ones(M+2,1);0];
Tu=flipud((-1:(M+1))'); % (-1) since ESC never is used in Tu context
% and decode the symbols in the sequence x
for l=1:L
sc=T(1);
range=high-low+1;
counts=floor(( (code-low+1)*sc-1 )/range);
m=2; while (T(m)>counts); m=m+1; end;
hc=T(m-1);lc=T(m);m=m-2;
RemoveSymbol;
if (m>M) % decoded ESC symbol, find symbol from Tu table
sc=Tu(1);range=high-low+1;
counts=floor(( (code-low+1)*sc-1 )/range);
m=2; while (Tu(m)>counts); m=m+1; end;
hc=Tu(m-1);lc=Tu(m);m=m-2;
RemoveSymbol;
Tu(1:(m+1))=Tu(1:(m+1))-1; % update Tu table
end
x(l)=m;
% update T table, MUST be identical in Encode and Decode
% this avoid very large values in T even if sequence is very long
T(1:(m+1))=T(1:(m+1))+1;
if (rem(l,5000)==0)
dT=T(1:(M+2))-T(2:(M+3));
dT=floor(dT*7/8+1/8);
for m=(M+2):(-1):1; T(m)=T(m+1)+dT(m); end;
end
end % for l=1:L
% this end the "elseif sum(xType==[3,4,5,6])"-clause
elseif (xType==7) % L>1 and 0 <= x(i) <= 1
L=GetVLIC+2;
x=DecodeBin(L); % decode this sequence a special way
elseif (xType==8) % L>1 and 0 <= x(1)=x(2)=...=x(L) <= 1
L=GetVLIC+2;
x=ones(L,1)*GetABit;
elseif (xType==9) % L=1 and 0 <= x(1) <= 1
x=GetABit;
elseif (xType==10) % L>1 and x(1)=x(2)=...=x(L) <= -1
L=GetVLIC+2;
x=ones(L,1)*(-1-GetVLIC);
elseif (xType==11) % L=1 and x(1) <= -1
x=(-1-GetVLIC);
end % if (xType==0)
% additional information should be decoded as well
L=length(x);
I=find(x);
if 0
if sum(xType==[4,6]) % sign must be retrieved
Sg=zeros(size(I));
for i=1:length(I); Sg(i)=GetABit; end; % and the signs (0/1)
Sg=Sg*2-1; % (-1/1)
end
if sum(xType==[5,6]) % additional bits must be retrieved
xa=zeros(L,1);
for i=1:L
for ii=2:x(i)
xa(i)=2*xa(i)+GetABit;
end
end
x(I)=2.^(x(I)-1);
x=x+xa;
end
else
if sum(xType==[4,6]) % sign must be retrieved
Sg=DecodeBin(length(I)); % since length(I)=length(Sg)
Sg=Sg*2-1; % (-1/1)
end
if sum(xType==[5,6]) % additional bits must be retrieved
bi=sum(x)-length(I); % number of additional bits
b=DecodeBin(bi);
bi=0;
xa=zeros(L,1);
for i=1:L
for ii=2:x(i)
bi=bi+1;
xa(i)=2*xa(i)+b(bi);
end
end
x(I)=2.^(x(I)-1);
x=x+xa;
end
end
if sum(xType==[4,6]) % sign must be used
x(I)=x(I).*Sg;
end
% now x is the retrieved sequence
xC{num}=x;
end % for num=1:NumOfX
varargout(1) = {xC};
end
if dir==1
nbr_bits = Res(1,3);
else
% undef for decoding
nbr_bits = -1;
y = xC{1};
end
return % end of main function, Arith07
%----------------------------------------------------------------------
%----------------------------------------------------------------------
% --- The functions for binary sequences: EncodeBin and DecodeBin -------
% These function may call themselves recursively
function EncodeBin(x,L)
global y Byte BitPos
global high low range ub hc lc sc K code
Display=0;
x=x(:);
if (length(x)~=L); error('EncodeBin: length(x) not equal L.'); end;
% first we try some different coding methods to find out which one
% that might do best. Many more methods could have been tried, for
% example methods to check if x is a 'byte' sequence, or if the bits
% are grouped in other ways. The calling application is the best place
% to detect such dependencies, since it will (might) know the process and
% possible also its statistical (or deterministic) properties.
% Here we just check some few coding methods: direct, split, diff, diff+split
% The main variables used for the different methods are:
% direct: x, I, J, L11, b0
% split: x is split into x1 and x2, L1, L2, b1 is bits needed
% diff: x3 is generated from x, I3, J3 L31, b2
% diff+split: x3 is split into x4 and x5, L4, L5, b3
%
MetS=[0,1,2,3]; % the different methods, direct, split, diff, diff+split
MetC=[9,3,3,1]; % and the counts (which gives the probabilities)
% first set how many bits needed to code the method
b0=log2(sum(MetC))-log2(MetC(1));
b1=log2(sum(MetC))-log2(MetC(2));
b2=log2(sum(MetC))-log2(MetC(3));
b3=log2(sum(MetC))-log2(MetC(4));
I=find(x(1:(L-1))==1); % except last element in x
J=find(x(1:(L-1))==0);
L11=length(I);
% perhaps is 'entropy' interesting
% N1=L11+x(L);
% N0=L-N1;
% b=N1*log2(L/N1)+N0*log2(L/N0);
% disp(['L=',int2str(L),', N1=',int2str(N1),', (e)bits=',num2str(b)]);
b0=b0+BitEst(L,L11+x(L)); % bits needed for the sequence without splitting
if Display
disp(['EncodeBin: x of length ',int2str(L),' and ',int2str(L11+x(L)),...
' ones (p=',num2str((L11+x(L))/L,'%1.3f'),...
') can be coded by ',num2str(b0,'%6.0f'),' bits.']);
end
% diff with a binary sequence is to indicate wether or not a symbol is
% the same as preceeding symbol or not, x(0) is assumed to be '0' (zero).
% This is the DPCM coding scheme on a binary sequence
x3=abs(x-[0;x(1:(L-1))]);
I3=find(x3(1:(L-1))==1); % except last element in x3
J3=find(x3(1:(L-1))==0);
L31=length(I3);
b2=b2+BitEst(L,L31+x3(L)); % bits needed for the sequence without splitting
if Display
disp(['EncodeBin: diff x, L=',int2str(L),' gives ',int2str(L31+x3(L)),...
' ones (p=',num2str((L31+x3(L))/L,'%1.3f'),...
') can be coded by ',num2str(b2,'%6.0f'),' bits.']);
end
%
if (L>40)
% only now we try to split the sequences x and x3
if (L11>3) & ((L-L11)>3)
% try to split x into x1 and x2, depending on previous symbol
if L11<(L/2)
x1=x(I+1);
x2=[x(1);x(J+1)];
L1=L11;L2=L-L11;
else
x1=[x(1);x(I+1)];
x2=x(J+1);
L1=L11+1;L2=L-L11-1;
end
b11=BitEst(L1,length(find(x1))); % bits needed for x1
b12=BitEst(L2,length(find(x2))); % bits needed for x2
% b1 is bits to code: Method, L11, x1 and x2
b1=b1+log2(L)+b11+b12;
if Display
disp(['EncodeBin, x -> x1+x2: lengths are ',int2str(L1),'+',int2str(L2),...
' bits are ',num2str(b11,'%6.0f'),'+',num2str(b12,'%6.0f'),...
'. Total is ',num2str(b1,'%6.0f'),' bits.']);
end
else
b1=b0+1; % just to make this larger
end
if (L31>3) & ((L-L31)>3)
% try to split x3 into x4 and x5, depending on previous symbol
if L31<(L/2)
x4=x3(I3+1);
x5=[x3(1);x3(J3+1)];
L4=L31;L5=L-L31;
else
x4=[x3(1);x3(I3+1)];
x5=x3(J3+1);
L4=L31+1;L5=L-L31-1;
end
b31=BitEst(L4,length(find(x4))); % bits needed for x4
b32=BitEst(L5,length(find(x5))); % bits needed for x5
% b3 is bits to code: Method, L31, x4 and x5
b3=b3+log2(L)+b31+b32;
if Display
disp(['EncodeBin, diff x -> x4+x5: lengths are ',int2str(L4),'+',int2str(L5),...
' bits are ',num2str(b31,'%6.0f'),'+',num2str(b32,'%6.0f'),...
'. Total is ',num2str(b3,'%6.0f'),' bits.']);
end
else
b3=b2+1; % just to make this larger
end
else
b1=b0+1; % just to make this larger
b3=b2+1; % just to make this larger
end
% now code x by the best method of those investigated
[b,MetI]=min([b0,b1,b2,b3]);
MetI=MetI-1;
PutS(MetI,MetS,MetC); % code which method to use
%
if MetI==0
% code the sequence x
N1=L11+x(L);
N0=L-N1;
PutN(N1,L); % code N1, 0<=N1<=L
for n=1:L
if ~(N0*N1); break; end;
PutS(x(n),[0,1],[N0,N1]); % code x(n)
N0=N0-1+x(n);N1=N1-x(n); % update model (of rest of the sequence)
end
elseif MetI==1
% code x1 and x2
clear x4 x5 x3 x I3 J3 I J
PutN(L11,L-1); % 0<=L11<=(L-1)
EncodeBin(x1,L1);
EncodeBin(x2,L2);
elseif MetI==2
% code the sequence x3
N1=L31+x3(L);
N0=L-N1;
PutN(N1,L); % code N1, 0<=N1<=L
for n=1:L
if ~(N0*N1); break; end;
PutS(x3(n),[0,1],[N0,N1]); % code x3(n)
N0=N0-1+x3(n);N1=N1-x3(n); % update model (of rest of the sequence)
end
elseif MetI==3
% code x4 and x5
clear x1 x2 x3 x I3 J3 I J
PutN(L31,L-1); % 0<=L31<=(L-1)
EncodeBin(x4,L4);
EncodeBin(x5,L5);
end
return % end of EncodeBin
function x = DecodeBin(L)
global y Byte BitPos
global high low range ub hc lc sc K code
% these must be as in EncodeBin
MetS=[0,1,2,3]; % the different methods, direct, split, diff, diff+split
MetC=[9,3,3,1]; % and the counts (which gives the probabilities)
MetI=GetS(MetS,MetC); % encode which method to use
if (MetI==1) | (MetI==3) % a split was done
L11=GetN(L-1); % 0<=L11<=(L-1)
if L11<(L/2)
L1=L11;L2=L-L11;
else
L1=L11+1;L2=L-L11-1;
end
x1=DecodeBin(L1);
x2=DecodeBin(L2);
% build sequence x from x1 and x2
x=zeros(L,1);
if L11<(L/2)
x(1)=x2(1);
n1=0;n2=1; % index for the last in x1 and x2
else
x(1)=x1(1);
n1=1;n2=0; % index for the last in x1 and x2
end
for n=2:L
if (x(n-1))
n1=n1+1;
x(n)=x1(n1);
else
n2=n2+1;
x(n)=x2(n2);
end
end
else % no split
N1=GetN(L);
N0=L-N1;
x=zeros(L,1);
for n=1:L
if (N0==0); x(n:L)=1; break; end;
if (N1==0); break; end;
x(n)=GetS([0,1],[N0,N1]); % decode x(n)
N0=N0-1+x(n);N1=N1-x(n); % update model (of rest of the sequence)
end
end
if (MetI==2) | (MetI==3) % x is diff coded
for n=2:L
x(n)=x(n-1)+x(n);
end
x=rem(x,2);
end
return % end of DecodeBin
% ------- Other subroutines ------------------------------------------------
% Functions to write and read a Variable Length Integer Code word
% This is a way of coding non-negative integers that uses fewer
% bits for small integers than for large ones. The scheme is:
% '00' + 4 bit - integers from 0 to 15
% '01' + 8 bit - integers from 16 to 271
% '10' + 12 bit - integers from 272 to 4367
% '110' + 16 bit - integers from 4368 to 69903
% '1110' + 20 bit - integers from 69940 to 1118479
% '1111' + 24 bit - integers from 1118480 to 17895695
% not supported - integers >= 17895696 (=2^4+2^8+2^12+2^16+2^20+2^24)
function PutVLIC(N)
global y Byte BitPos
global high low range ub hc lc sc K code
if (N<0)
error('Arith07-PutVLIC: Number is negative.');
elseif (N<16)
PutABit(0);PutABit(0);
for (i=4:-1:1); PutABit(bitget(N,i)); end;
elseif (N<272)
PutABit(0);PutABit(1);
N=N-16;
for (i=8:-1:1); PutABit(bitget(N,i)); end;
elseif (N<4368)
PutABit(1);PutABit(0);
N=N-272;
for (i=12:-1:1); PutABit(bitget(N,i)); end;
elseif (N<69940)
PutABit(1);PutABit(1);PutABit(0);
N=N-4368;
for (i=16:-1:1); PutABit(bitget(N,i)); end;
elseif (N<1118480)
PutABit(1);PutABit(1);PutABit(1);PutABit(0);
N=N-69940;
for (i=20:-1:1); PutABit(bitget(N,i)); end;
elseif (N<17895696)
PutABit(1);PutABit(1);PutABit(1);PutABit(1);
N=N-1118480;
for (i=24:-1:1); PutABit(bitget(N,i)); end;
else
error('Arith07-PutVLIC: Number is too large.');
end
return
function N=GetVLIC
global y Byte BitPos
global high low range ub hc lc sc K code
N=0;
if GetABit
if GetABit
if GetABit
if GetABit
for (i=1:24); N=N*2+GetABit; end;
N=N+1118480;
else
for (i=1:20); N=N*2+GetABit; end;
N=N+69940;
end
else
for (i=1:16); N=N*2+GetABit; end;
N=N+4368;
end
else
for (i=1:12); N=N*2+GetABit; end;
N=N+272;
end
else
if GetABit
for (i=1:8); N=N*2+GetABit; end;
N=N+16;
else
for (i=1:4); N=N*2+GetABit; end;
end
end
return
% Aritmetic coding of a number or symbol x, the different symbols (numbers)
% are given in the array S, and the counts (which gives the probabilities)
% are given in C, an array of same length as S.
% x must be a number in S.
% example with symbols 0 and 1, where probabilites are P{0}=0.8, P{1}=0.2
% PutS(x,[0,1],[4,1]) and x=GetS([0,1],[4,1])
% An idea: perhaps the array S should be only in the calling function, and
% that it do not need to be passed as an argument at all.
% Hint: it may be best to to the most likely symbols (highest counts) in
% the beginning of the tables S and C.
function PutS(x,S,C)
global y Byte BitPos
global high low range ub hc lc sc K code
N=length(S); % also length(C)
m=find(S==x); % m is a single value, index in S, 1 <= m <= N
sc=sum(C);
lc=sc-sum(C(1:m));
hc=lc+C(m);
% disp(['PutS: lc=',int2str(lc),' hc=',int2str(hc),' sc=',int2str(sc),' m=',int2str(m)]);
EncodeSymbol; % code the bit
return
function x=GetS(S,C)
global y Byte BitPos
global high low range ub hc lc sc K code
range=high-low+1;
sc=sum(C);
counts=floor(( (code-low+1)*sc-1 )/range);
m=1;
lc=sc-C(1);
while (lc>counts); m=m+1; lc=lc-C(m); end;
hc=lc+C(m);
x=S(m);
% disp(['GetS: lc=',int2str(lc),' hc=',int2str(hc),' sc=',int2str(sc),' m=',int2str(m)]);
RemoveSymbol;
return
% Aritmetic coding of a number x, 0<=x<=N, P{0}=P{1}=...=P{N}=1/(N+1)
function PutN(x,N) % 0<=x<=N
global y Byte BitPos
global high low range ub hc lc sc K code
sc=N+1;
lc=x;
hc=x+1;
EncodeSymbol; % code the bit
return
function x=GetN(N)
global y Byte BitPos
global high low range ub hc lc sc K code
range=high-low+1;
sc=N+1;
x=floor(( (code-low+1)*sc-1 )/range);
hc=x+1;lc=x;
RemoveSymbol;
return
% Aritmetic coding of a bit, probability is 0.5 for both 1 and 0
function PutABit(Bit)
global y Byte BitPos
global high low range ub hc lc sc K code
sc=2;
if Bit
hc=1;lc=0;
else
hc=2;lc=1;
end
EncodeSymbol; % code the bit
return
function Bit=GetABit
global y Byte BitPos
global high low range ub hc lc sc K code
range=high-low+1;
sc=2;
counts=floor(( (code-low+1)*sc-1 )/range);
if (1>counts)
Bit=1;hc=1;lc=0;
else
Bit=0;hc=2;lc=1;
end
RemoveSymbol;
return;
% The EncodeSymbol function encode a symbol, (correspond to encode_symbol page 149)
function EncodeSymbol
global y Byte BitPos
global high low range ub hc lc sc K code
range=high-low+1;
high=low+floor(((range*hc)/sc)-1);
low=low+floor((range*lc)/sc);
while 1 % for loop on page 149
if bitget(high,K)==bitget(low,K)
PutBit(bitget(high,K));
while ub > 0
PutBit(~bitget(high,K));
ub=ub-1;
end
elseif (bitget(low,K-1) & (~bitget(high,K-1)))
ub=ub+1;
low=bitset(low,K-1,0);
high=bitset(high,K-1,1);
else
break
end
low=bitset(low*2,K+1,0);
high=bitset(high*2+1,K+1,0);
end
return
% The RemoveSymbol function removes (and fill in new) bits from
% file, y, to code
function RemoveSymbol
global y Byte BitPos
global high low range ub hc lc sc K code
range=high-low+1;
high=low+floor(((range*hc)/sc)-1);
low=low+floor((range*lc)/sc);
while 1
if bitget(high,K)==bitget(low,K)
% do nothing (shift bits out)
elseif (bitget(low,K-1) & (~bitget(high,K-1)))
code=bitset(code,K-1,~bitget(code,K-1)); % switch bit K-1
low=bitset(low,K-1,0);
high=bitset(high,K-1,1);
else
break
end
low=bitset(low*2,K+1,0);
high=bitset(high*2+1,K+1,0);
code=bitset(code*2+GetBit,K+1,0);
end
if (low > high); error('low > high'); end;
return
% Functions to write and read a Bit
function PutBit(Bit)
global y Byte BitPos
BitPos=BitPos-1;
if (~BitPos); Byte=Byte+1; BitPos=8; end;
y(Byte) = bitset(y(Byte),BitPos,Bit);
return
function Bit=GetBit
global y Byte BitPos
BitPos=BitPos-1;
if (~BitPos); Byte=Byte+1; BitPos=8; end;
Bit=bitget(y(Byte),BitPos);
return
function b=BitEst(N,N1);
if (N1>(N/2)); N1=N-N1; end;
N0=N-N1;
if (N>1000)
b=(N+3/2)*log2(N)-(N0+1/2)*log2(N0)-(N1+1/2)*log2(N1)-1.3256;
elseif (N1>20)
b=(N+3/2)*log2(N)-(N0+1/2)*log2(N0)-(N1+1/2)*log2(N1)-0.020984*log2(log2(N))-1.25708;
else
b=log2(N+1)+sum(log2(N-(0:(N1-1))))-sum(log2(N1-(0:(N1-1))));
end
return
|
github
|
alex-delalande/numerical-tours-master
|
perform_omp.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_omp.m
| 9,857 |
utf_8
|
84fa05746f22e0ac58735d2c53b486f1
|
function X = perform_omp(D,Y,options)
% perform_omp - perform orthogonal matching pursuit
%
% X = perform_omp(D,Y,options);
%
% D is the dictionary of size (n,p) of p atoms
% Y are the m vectors to decompose of size (n,m)
% X are the m coefficients of the decomposition of size (p,m).
%
% Orthogonal matching pursuit is a greedy procedure to minimise
% |x|_0 under the constraint that D*x=y.
% (maximum sparsity).
% You can stop the iteration after |x|_0=k by setting options.nbr_max_atoms=k
% You can set relative tolerance options.tol so that iterations stops when
% |Y-D*X| < tol*|Y|
%
% This code calls the fast mex version of Antoine Grolleau
% when possible.
%
% Copyright (c) 2006 Gabriel Peyre
if isfield(options, 'sparse_coder') && strcmp(options.sparse_coder, 'mp')
X = perform_mp(D,Y,options);
return;
end
options.null = 0;
nbr_max_atoms = getoptions(options, 'nbr_max_atoms', 50);
tol = getoptions(options, 'tol', 1e-3);
use_slow_code = getoptions(options, 'use_slow_code', 0);
verb = getoptions(options, 'verb', 1);
% P : number of signals, n dimension
[n,P]=size(Y);
% K : size of the dictionary
[n,K]=size(D);
if isfield(options, 'use_mex') && options.use_mex==1 && exist('perform_omp_mex')==3
% use fast mex interface
X = zeros(K,P);
for k=1:P
X(:,k) = perform_omp_mex(D,Y(:,k),nbr_max_atoms);
end
return;
end
if use_slow_code
X = perform_omp_other(Y,D,tol,nbr_max_atoms);
return;
end
for k=1:1:P,
if P>20 && verb==1
progressbar(k,P);
end
a=[];
x = Y(:,k);
r = x; % residual
I = zeros(nbr_max_atoms,1); % index of the chosen atoms
% norm of the original signal
e0 = sqrt( sum( r.^2 ) );
for j=1:1:nbr_max_atoms,
proj = D'*r;
pos = find(abs(proj)==max(abs(proj)));
pos = pos(1);
I(j) = pos;
a=pinv(D(:,I(1:j)))*x;
r=x-D(:,I(1:j))*a;
% compute error
e = sqrt( sum( r.^2 ) );
if e/e0 < tol
break;
end
end;
temp=zeros(K,1);
temp(I(1:length(a)))=a;
X(:,k)=sparse(temp);
end;
return;
function [D,Di,Q,beta,c] = perform_omp_other(f,D,tol,No,ind)
% perform_omp - Optimized Orthogonal Matching Pursuit
%
% It creates an atomic decomposition of a signal using OOMP method. You can choose a
% tolerance, the number of atoms to take in or an initial subspace to influence the OOMP
% algorithm. Non-selected atoms subtracted by their component in the chosen space are also
% available.
%
% Usage:
% x = perform_omp_other(f,D,tol,No,ind);
%
% Inputs:
% f analyzing signal of size (n,s) where s is the number of signals.
% D dictionary of normalized atoms of size (n,d) where d is the number
% of atoms.
% tol desired distance between f and its approximation
% the routine will stop if norm(f'-Dsub*(f*beta)')*sqrt(delta)<tol
% where delta=1/nbr_max_atoms, nbr_max_atoms is number of points in a sample
% No (optional) maximal number of atoms to choose, if the number of chosen
% atoms equals to No, routine will stop (default No=size(D,2)
% ind (optional) indices determining the initial subspace,
%
% Outputs:
% x coefficients of the decomposition such that f \approx D*x of size (p,s)
%
% References:
% nbr_max_atoms. Rebollo-Neira and D. Lowe, "Optimized Orthogonal Matching Pursuit Approach",
% IEEE Signal Processing Letters, Vol(9,4), 137-140, (2002).
%
% See also OMPF.
% [Dnew,Di]=oompf(f,D,tol);
% [Dnew,Di,Q,beta,c]=oompf(f,D,tol,No,ind);
% D the dictionary D rearranged according to the selection process
% D(:,1:k) contains the atoms chosen into the atomic decomposition
% Di indices of atoms in new D written w.r.t the original D
% Q Q(:,1:k) contains orthonormal functions spanning new D(:,1:k)
% Q(:,k+1:N) contains new D(:,k+1:N) subtracted by the projection
% onto the space generated by Q(:,1:k) (resp. D(:,1:k))
% beta 'k' biorthogonal functions corresponding to new D(:,1:k)
% c 'k' coefficients of the atomic decomposition
% See http://www.ncrg.aston.ac.uk/Projects/BiOrthog/ for more details
% verbosity
verb = 0;
name='OOMPF'; %name of routine
% get inputs and setup parameters
[nbr_max_atoms,N]=size(D);
beta=[];
Di=1:N; % index vector of full-dictionary
Q=D;
%delta=1/nbr_max_atoms; %uncomment in the case of analytical norm
delta=1; %uncomment in the case of discrete norm
if nargin<5 ind=[];end
if nargin<4 No=N;end
if nargin<3 tol=0.01;end;
if size(f,2)>1
% code several vectors
s = size(f,2);
x = zeros(size(D,2),s);
for i=1:s
if s>20
progressbar(i,s);
end
x(:,i) = perform_omp_other(f(:,i),D,tol,No,ind);
end
D = x;
return;
end
% the code use transposed data
f = f';
numind=length(ind);
%atoms having smaller norm than tol1 are supposed be zero ones
tol1=1e-7; %1e-5
%threshold for coefficients
tol2=1e-10; %0.0001 %1e-5
if verb
tic;
fprintf('\n%s is running for tol=%g, tol1=%g and tol2=%g.\n',name,tol,tol1,tol2);
fprintf('tol -> required precision, distance ||f-f_approx||\n')
fprintf('tol1 -> atoms having smaller norm are supposed to be zero ones.\n');
fprintf('tol2 -> algorithm stops if max(|<f,q>|/||q||)<= tol2.\n');
end
%===============================
% Main algorithm: at kth iteration
%===============================
H=min(No,N); %maximal number of function in sub-dictionary
for k=1:H
%finding of maximal coefficient
c=zeros(1,N);cc=zeros(1,N);
if k<=numind
[test,q]=ismember(ind(k),Di);
if test~=1 error('Demanded index %d is out of dictionary',ind(k));end
c(k)=norm(Q(:,q));
if c(k)<tol1
error('Demanded atom with index %d is dependent on the others.',ind(k));
end;
else
for p=k:N, c(p)=norm(Q(:,p));
if c(p)>tol1 cc(p)=abs(f*Q(:,p))/c(p);end;
end
[max_c,q]=max(cc);
%stopping criterion (coefficient)
if max_c<tol2
k=k-1;
if verb
fprintf('%s stopped, max(|<f,q>|/||q||)<= tol2=%g.\n',name,tol2);
end
break;
end
end
if q~=k
Q(:,[k q])=Q(:,[q k]); % swap k-th and q-th columns
D(:,[k q])=D(:,[q k]);
Di([k q])=Di([q k]);
end
%re-orthogonalization of Q(:,k) w.r.t Q(:,1),..., Q(:,k-1)
if k>1
for p=1:k-1
Q(:,k)=Q(:,k)-(Q(:,p)'*Q(:,k))*Q(:,p);
end
end
nork=norm(Q(:,k));
Q(:,k)=Q(:,k)/nork; %normalization
% compute biorthogonal functions beta from 1 to k-1
if k>1
beta=beta-Q(:,k)*(D(:,k)'*beta)/nork;
end
beta(:,k)=Q(:,k)/nork; % kth biorthogonal function
%orthogonalization of Q(:,k+1:n) wrt Q(:,k)
if k==N, break; end
for p=k+1:N
% orthogonalization of Q(:,p) wrt Q(:,k)
Q(:,p)=Q(:,p)-(Q(:,k)'*Q(:,p))*Q(:,k);
end
%stopping criterion (distance)
if (tol~= 0) & (norm(f'-D(:,1:k)*(f*beta)')*sqrt(delta) < tol) break;end;
end
c=f*beta;
normf=norm(f'-D(:,1:k)*c')*sqrt(delta);
if verb
fprintf('From %d atoms in this dictionary %s has chosen %d atoms.\n',N,name,k);
fprintf('\n%s lasted %g seconds\n',name,toc);
fprintf('\nNorm ||f-f_approx|| is %g. \n',normf);
end
% error testing
% orthogonality
errortest(Q(:,1:k));
% biorthogonality
errortest(D(:,1:k),beta);
if nargout==1
x = zeros( size(D,2),1 );
Di = Di(1:length(c));
x(Di(:)) = c(:);
D = x;
end
%Copyright (C) 2006 Miroslav ANDRLE and Laura REBOLLO-NEIRA
%
%This program is free software; you can redistribute it and/or modify it under the terms
%of the GNU General Public License as published by the Free Software Foundation; either
%version 2 of the License, or (at your option) any later version.
%
%This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
%without even the implied warranty of MERCHANTABILITY or FITNESS FOR X PARTICULAR PURPOSE.
%See the GNU General Public License for more details.
%
%You should have received a copy of the GNU General Public License along with this program;
%if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
%Boston, MA 02110-1301, USA.
function f=errortest(D,beta);
% ERRORTEST tests orthogonality of a sequence or biorthogonality of two sequences.
%
% Usage: errortest(D,beta);
% errortest(Q);
%
% Inputs:
% D sequence of vectors
% beta (optional) biorthogonal sequence
%
% Output:
% f orthogonality of D or biorthogonality D w.r.t beta
% See http://www.ncrg.aston.ac.uk/Projects/BiOrthog/ for more details
name='ERRORTEST';
verb = 0;
if nargin==1
% orthogonality
PP=D'*D;f=norm(eye(size(PP))-PP);
if verb
fprintf('Orthogonality: %g \n',f);
end
elseif nargin==2
% biorthogonality
PP=beta'*D;f=norm(eye(size(PP))-PP);
if verb
fprintf('Biorthogonality: %g \n',f);
end
else
if verb
fprintf('%s: Wrong number of arguments',name);
end
end
%Copyright (C) 2006 Miroslav ANDRLE and Laura REBOLLO-NEIRA
%
%This program is free software; you can redistribute it and/or modify it under the terms
%of the GNU General Public License as published by the Free Software Foundation; either
%version 2 of the License, or (at your option) any later version.
%
%This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
%without even the implied warranty of MERCHANTABILITY or FITNESS FOR X PARTICULAR PURPOSE.
%See the GNU General Public License for more details.
%
%You should have received a copy of the GNU General Public License along with this program;
%if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
%Boston, MA 02110-1301, USA.
|
github
|
alex-delalande/numerical-tours-master
|
mad.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/mad.m
| 7,921 |
utf_8
|
6d4949e64f7802d97e068c87415b0460
|
function y = mad(x,flag)
%MAD Mean/median absolute deviation.
% Y = MAD(X) returns the mean absolute deviation of the values in X. For
% vector input, Y is MEAN(ABS(X-MEAN(X)). For a matrix input, Y is a row
% vector containing the mean absolute deviation of each column of X. For
% N-D arrays, MAD operates along the first non-singleton dimension.
%
% MAD(X,1) computes Y based on medians, i.e. MEDIAN(ABS(X-MEDIAN(X)).
% MAD(X,0) is the same as MAD(X), and uses means.
%
% MAD treats NaNs as missing values, and removes them.
%
% See also VAR, STD, IQR.
% References:
% [1] L. Sachs, "Applied Statistics: A Handbook of Techniques",
% Springer-Verlag, 1984, page 253.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.10.2.2 $ $Date: 2004/01/24 09:34:28 $
% The output size for [] is a special case, handle it here.
if isequal(x,[])
y = NaN;
return;
end;
if nargin < 2
flag = 0;
end
% Figure out which dimension nanmean will work along.
sz = size(x);
dim = find(sz ~= 1, 1);
if isempty(dim)
dim = 1;
end
% Need to tile the output of nanmean to center X.
tile = ones(1,ndims(x));
tile(dim) = sz(dim);
if flag
% Compute the median of the absolute deviations from the median.
y = nanmedian(abs(x - repmat(nanmedian(x), tile)));
else
% Compute the mean of the absolute deviations from the mean.
y = nanmean(abs(x - repmat(nanmean(x), tile)));
end
function y = nanmedian(x,dim)
%NANMEDIAN Median value, ignoring NaNs.
% M = NANMEDIAN(X) returns the sample median of X, treating NaNs as
% missing values. For vector input, M is the median value of the non-NaN
% elements in X. For matrix input, M is a row vector containing the
% median value of non-NaN elements in each column. For N-D arrays,
% NANMEDIAN operates along the first non-singleton dimension.
%
% NANMEDIAN(X,DIM) takes the median along the dimension DIM of X.
%
% See also MEDIAN, NANMEAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.12.2.2 $ $Date: 2004/01/24 09:34:33 $
if nargin == 1
y = prctile(x, 50);
else
y = prctile(x, 50,dim);
end
function m = nanmean(x,dim)
%NANMEAN Mean value, ignoring NaNs.
% M = NANMEAN(X) returns the sample mean of X, treating NaNs as missing
% values. For vector input, M is the mean value of the non-NaN elements
% in X. For matrix input, M is a row vector containing the mean value of
% non-NaN elements in each column. For N-D arrays, NANMEAN operates
% along the first non-singleton dimension.
%
% NANMEAN(X,DIM) takes the mean along the dimension DIM of X.
%
% See also MEAN, NANMEDIAN, NANSTD, NANVAR, NANMIN, NANMAX, NANSUM.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.13.4.2 $ $Date: 2004/01/24 09:34:32 $
% Find NaNs and set them to zero
nans = isnan(x);
x(nans) = 0;
if nargin == 1 % let sum deal with figuring out which dimension to use
% Count up non-NaNs.
n = sum(~nans);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x) ./ n;
else
% Count up non-NaNs.
n = sum(~nans,dim);
n(n==0) = NaN; % prevent divideByZero warnings
% Sum up non-NaNs, and divide by the number of non-NaNs.
m = sum(x,dim) ./ n;
end
function y = prctile(x,p,dim)
%PRCTILE Percentiles of a sample.
% Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar
% or a vector of percent values. When X is a vector, Y is the same size
% as P, and Y(i) contains the P(i)-th percentile. When X is a matrix,
% the i-th row of Y contains the P(i)-th percentiles of each column of X.
% For N-D arrays, PRCTILE operates along the first non-singleton
% dimension.
%
% Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The
% DIM'th dimension of Y has length LENGTH(P).
%
% Percentiles are specified using percentages, from 0 to 100. For an N
% element vector X, PRCTILE computes percentiles as follows:
% 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N),
% ..., 100*((N-0.5)/N) percentiles.
% 2) Linear interpolation is used to compute percentiles for percent
% values between 100*(0.5/N) and 100*((N-0.5)/N)
% 3) The minimum or maximum values in X are assigned to percentiles
% for percent values outside that range.
%
% PRCTILE treats NaNs as missing values, and removes them.
%
% Examples:
% y = prctile(x,50); % the median of x
% y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x
%
% See also IQR, MEDIAN, NANMEDIAN, QUANTILE.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.12.4.4 $ $Date: 2004/01/24 09:34:55 $
if ~isvector(p) || numel(p) == 0
error('stats:prctile:BadPercents', ...
'P must be a scalar or a non-empty vector.');
elseif any(p < 0 | p > 100)
error('stats:prctile:BadPercents', ...
'P must take values between 0 and 100');
end
% Figure out which dimension prctile will work along.
sz = size(x);
if nargin < 3
dim = find(sz ~= 1,1);
if isempty(dim)
dim = 1;
end
dimArgGiven = false;
else
% Permute the array so that the requested dimension is the first dim.
nDimsX = ndims(x);
perm = [dim:max(nDimsX,dim) 1:dim-1];
x = permute(x,perm);
% Pad with ones if dim > ndims.
if dim > nDimsX
sz = [sz ones(1,dim-nDimsX)];
end
sz = sz(perm);
dim = 1;
dimArgGiven = true;
end
% If X is empty, return all NaNs.
if isempty(x)
if isequal(x,[]) && ~dimArgGiven
y = nan(size(p),class(x));
else
szout = sz; szout(dim) = numel(p);
y = nan(szout,class(x));
end
else
% Drop X's leading singleton dims, and combine its trailing dims. This
% leaves a matrix, and we can work along columns.
nrows = sz(dim);
ncols = prod(sz) ./ nrows;
x = reshape(x, nrows, ncols);
x = sort(x,1);
nonnans = ~isnan(x);
% If there are no NaNs, do all cols at once.
if all(nonnans(:))
n = sz(dim);
if isequal(p,50) % make the median fast
if rem(n,2) % n is odd
y = x((n+1)/2,:);
else % n is even
y = (x(n/2,:) + x(n/2+1,:))/2;
end
else
q = [0 100*(0.5:(n-0.5))./n 100]';
xx = [x(1,:); x(1:n,:); x(n,:)];
y = zeros(numel(p), ncols, class(x));
y(:,:) = interp1q(q,xx,p(:));
end
% If there are NaNs, work on each column separately.
else
% Get percentiles of the non-NaN values in each column.
y = nan(numel(p), ncols, class(x));
for j = 1:ncols
nj = find(nonnans(:,j),1,'last');
if nj > 0
if isequal(p,50) % make the median fast
if rem(nj,2) % nj is odd
y(:,j) = x((nj+1)/2,j);
else % nj is even
y(:,j) = (x(nj/2,j) + x(nj/2+1,j))/2;
end
else
q = [0 100*(0.5:(nj-0.5))./nj 100]';
xx = [x(1,j); x(1:nj,j); x(nj,j)];
y(:,j) = interp1q(q,xx,p(:));
end
end
end
end
% Reshape Y to conform to X's original shape and size.
szout = sz; szout(dim) = numel(p);
y = reshape(y,szout);
end
% undo the DIM permutation
if dimArgGiven
y = ipermute(y,perm);
end
% If X is a vector, the shape of Y should follow that of P, unless an
% explicit DIM arg was given.
if ~dimArgGiven && isvector(x)
y = reshape(y,size(p));
end
|
github
|
alex-delalande/numerical-tours-master
|
plot_hufftree.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/plot_hufftree.m
| 792 |
utf_8
|
b3a28991b5dc6e37df21dad9f445068a
|
function plot_hufftree(T,p)
% plot_hufftree - plot a huffman tree
%
% plot_hufftree(T);
%
% Copyright (c) 2008 Gabriel Peyre
hold on;
plot_tree(T{1},[0,0],1);
hold off;
axis tight;
axis off;
%%
function plot_tree(T,x,j)
tw = 15;
lw = 1.5;
ms = 10;
if not(iscell(T))
de = [-.02 -.2];
% display a string
u = text(x(1)+de(1),x(2)+de(2),num2str(T));
set(u,'FontSize',tw);
else
% display a split
h0 = 1/2^j;
h = 1 * h0;
u = plot( [x(1) x(1)-h], [x(2) x(2)-1], '.-' );
set(u,'MarkerSize',ms);
set(u,'LineWidth',lw);
u = plot( [x(1) x(1)+h], [x(2) x(2)-1], '.-' );
set(u,'MarkerSize',ms);
set(u,'LineWidth',lw);
plot_tree(T{1},[x(1)-h x(2)-1],j+1);
plot_tree(T{2},[x(1)+h x(2)-1],j+1);
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_haar_transf.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_haar_transf.m
| 3,170 |
utf_8
|
14b7d7fd610eca05949ef196c55d7b83
|
function f = perform_haar_transf(f, Jmin, dir, options)
% perform_haar_transf - peform fast Haar transform
%
% y = perform_haar_transf(x, Jmin, dir);
%
% Implement a Haar wavelets.
% Works in any dimension.
%
% Copyright (c) 2008 Gabriel Peyre
n = size(f,1);
Jmax = log2(n)-1;
if dir==1
%%% FORWARD %%%
for j=Jmax:-1:Jmin
sel = 1:2^(j+1);
a = subselect(f,sel);
for d=1:nb_dims(f)
Coarse = ( subselectdim(a,1:2:size(a,d),d) + subselectdim(a,2:2:size(a,d),d) )/sqrt(2);
Detail = ( subselectdim(a,1:2:size(a,d),d) - subselectdim(a,2:2:size(a,d),d) )/sqrt(2);
a = cat(d, Coarse, Detail );
end
f = subassign(f,sel,a);
end
else
%%% BACKWARD %%%
for j=Jmin:Jmax
sel = 1:2^(j+1);
a = subselect(f,sel);
for d=1:nb_dims(f)
Detail = subselectdim(a,2^j+1:2^(j+1),d);
Coarse = subselectdim(a,1:2^j,d);
a = subassigndim(a, 1:2:2^(j+1), ( Coarse + Detail )/sqrt(2),d );
a = subassigndim(a, 2:2:2^(j+1), ( Coarse - Detail )/sqrt(2),d );
end
f = subassign(f,sel,a);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = subselect(f,sel)
switch nb_dims(f)
case 1
f = f(sel);
case 2
f = f(sel,sel);
case 3
f = f(sel,sel,sel);
case 4
f = f(sel,sel,sel,sel);
case 5
f = f(sel,sel,sel,sel,sel);
case 6
f = f(sel,sel,sel,sel,sel,sel);
case 7
f = f(sel,sel,sel,sel,sel,sel,sel);
case 8
f = f(sel,sel,sel,sel,sel,sel,sel,sel);
otherwise
error('Not implemented');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = subselectdim(f,sel,d)
switch d
case 1
f = f(sel,:,:,:,:,:,:,:);
case 2
f = f(:,sel,:,:,:,:,:,:);
case 3
f = f(:,:,sel,:,:,:,:,:);
case 4
f = f(:,:,:,sel,:,:,:,:);
case 5
f = f(:,:,:,:,sel,:,:,:);
case 6
f = f(:,:,:,:,:,sel,:,:);
case 7
f = f(:,:,:,:,:,:,sel,:);
case 8
f = f(:,:,:,:,:,:,:,sel);
otherwise
error('Not implemented');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = subassign(f,sel,g)
switch nb_dims(f)
case 1
f(sel) = g;
case 2
f(sel,sel) = g;
case 3
f(sel,sel,sel) = g;
case 4
f(sel,sel,sel,sel) = g;
case 5
f(sel,sel,sel,sel,sel) = g;
case 6
f(sel,sel,sel,sel,sel,sel) = g;
case 7
f(sel,sel,sel,sel,sel,sel,sel) = g;
case 8
f(sel,sel,sel,sel,sel,sel,sel,sel) = g;
otherwise
error('Not implemented');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = subassigndim(f,sel,g,d)
switch d
case 1
f(sel,:,:,:,:,:,:,:) = g;
case 2
f(:,sel,:,:,:,:,:,:) = g;
case 3
f(:,:,sel,:,:,:,:,:) = g;
case 4
f(:,:,:,sel,:,:,:,:) = g;
case 5
f(:,:,:,:,sel,:,:,:) = g;
case 6
f(:,:,:,:,:,sel,:,:) = g;
case 7
f(:,:,:,:,:,:,sel,:) = g;
case 8
f(:,:,:,:,:,:,:,sel) = g;
otherwise
error('Not implemented');
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_huffcoding.m
|
.m
|
numerical-tours-master/matlab/toolbox_signal/perform_huffcoding.m
| 1,491 |
utf_8
|
41a9144e1a2da192d37cf10a40add3e2
|
function y = perform_huffcoding(x,T,dir)
% perform_huffcoding - perform huffman coding
%
% y = perform_huffcoding(x,T,dir);
%
% dir=+1 for coding
% dir=-1 for decoding
%
% T is a Huffman tree, computed with compute_hufftree
%
% Copyright (c) 2008 Gabriel Peyre
if dir==1
%%% CODING %%%
C = huffman_gencode(T);
m = length(C);
x = round(x);
if min(x)<1 || max(x)>m
error('Too small or too large token');
end
y = [];
for i=1:length(x)
y = [y C{x(i)}];
end
else
%%% DE-CODING %%%
t = T{1};
y = [];
while not(isempty(x))
if x(1)==0
t = t{1};
else
t = t{2};
end
x(1) = [];
if not(iscell(t))
y = [y t];
t = T{1};
end
end
y = y(:);
end
%%
function C = huffman_gencode(T)
if not(iscell(T)) % || not(length(T)==2)
C = {};
C{T} = -1;
elseif length(T)==1
C = huffman_gencode(T{1});
% remove traling -1
for i=1:length(C)
C{i} = C{i}(1:end-1);
end
elseif length(T)==2
C1 = huffman_gencode(T{1});
C2 = huffman_gencode(T{2});
C = {};
for i=1:length(C1)
if not(isempty(C1{i}))
C{i} = [0 C1{i}];
end
end
for i=1:length(C2)
if not(isempty(C2{i}))
C{i} = [1 C2{i}];
end
end
else
error('Problem');
end
|
github
|
alex-delalande/numerical-tours-master
|
select3d.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/select3d.m
| 10,864 |
utf_8
|
64f6b58cf8db75c3508f68035be9892e
|
function [pout, vout, viout, facevout, faceiout] = select3d(obj)
%SELECT3D(H) Determines the selected point in 3-D data space.
% P = SELECT3D determines the point, P, in data space corresponding
% to the current selection position. P is a point on the first
% patch or surface face intersected along the selection ray. If no
% face is encountered along the selection ray, P returns empty.
%
% P = SELECT3D(H) constrains selection to graphics handle H and,
% if applicable, any of its children. H can be a figure, axes,
% patch, or surface object.
%
% [P V] = SELECT3D(...), V is the closest face or line vertex
% selected based on the figure's current object.
%
% [P V VI] = SELECT3D(...), VI is the index into the object's
% x,y,zdata properties corresponding to V, the closest face vertex
% selected.
%
% [P V VI FACEV] = SELECT3D(...), FACE is an array of vertices
% corresponding to the face polygon containing P and V.
%
% [P V VI FACEV FACEI] = SELECT3D(...), FACEI is the row index into
% the object's face array corresponding to FACE. For patch
% objects, the face array can be obtained by doing
% get(mypatch,'faces'). For surface objects, the face array
% can be obtained from the output of SURF2PATCH (see
% SURF2PATCH for more information).
%
% RESTRICTIONS:
% SELECT3D supports surface, patch, or line object primitives. For surface
% and patches, the algorithm assumes non-self-intersecting planar faces.
% For line objects, the algorithm always returns P as empty, and V will
% be the closest vertex relative to the selection point.
%
% Example:
%
% h = surf(peaks);
% zoom(10);
% disp('Click anywhere on the surface, then hit return')
% pause
% [p v vi face facei] = select3d;
% marker1 = line('xdata',p(1),'ydata',p(2),'zdata',p(3),'marker','o',...
% 'erasemode','xor','markerfacecolor','k');
% marker2 = line('xdata',v(1),'ydata',v(2),'zdata',v(3),'marker','o',...
% 'erasemode','xor','markerfacecolor','k');
% marker2 = line('erasemode','xor','xdata',face(1,:),'ydata',face(2,:),...
% 'zdata',face(3,:),'linewidth',10);
% disp(sprintf('\nYou clicked at\nX: %.2f\nY: %.2f\nZ: %.2f',p(1),p(2),p(3)'))
% disp(sprintf('\nThe nearest vertex is\nX: %.2f\nY: %.2f\nZ: %.2f',v(1),v(2),v(3)'))
%
% Version 1.3 11-11-04
% Copyright Joe Conti 2004
% Send comments to [email protected]
%
% See also GINPUT, GCO.
% Output variables
pout = [];
vout = [];
viout = [];
facevout = [];
faceiout = [];
% other variables
ERRMSG = 'Input argument must be a valid graphics handle';
isline = logical(0);
isperspective = logical(0);
% Parse input arguments
if nargin<1
obj = gco;
end
if isempty(obj) | ~ishandle(obj) | length(obj)~=1
error(ERRMSG);
end
% if obj is a figure
if strcmp(get(obj,'type'),'figure')
fig = obj;
ax = get(fig,'currentobject');
currobj = get(fig,'currentobject');
% bail out if not a child of the axes
if ~strcmp(get(get(currobj,'parent'),'type'),'axes')
return;
end
% if obj is an axes
elseif strcmp(get(obj,'type'),'axes')
ax = obj;
fig = get(ax,'parent');
currobj = get(fig,'currentobject');
currax = get(currobj,'parent');
% Bail out if current object is under an unspecified axes
if ~isequal(ax,currax)
return;
end
% if obj is child of axes
elseif strcmp(get(get(obj,'parent'),'type'),'axes')
currobj = obj;
ax = get(obj,'parent');
fig = get(ax,'parent');
% Bail out
else
return
end
axchild = currobj;
obj_type = get(axchild,'type');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Get vertex, face, and current point data %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
cp = get(ax,'currentpoint')';
% If surface object
if strcmp(obj_type,'surface')
% Get surface face and vertices
fv = surf2patch(axchild);
vert = fv.vertices;
faces = fv.faces;
% If patch object
elseif strcmp(obj_type,'patch')
vert = get(axchild,'vertices');
faces = get(axchild,'faces');
% If line object
elseif strcmp(obj_type,'line')
xdata = get(axchild,'xdata');
ydata = get(axchild,'ydata');
zdata = get(axchild,'zdata');
vert = [xdata', ydata',zdata'];
faces = [];
isline = logical(1);
% Ignore all other objects
else
return;
end
% Add z if empty
if size(vert,2)==2
vert(:,3) = zeros(size(vert(:,2)));
if isline
zdata = vert(:,3);
end
end
% NaN and Inf check
nan_inf_test1 = isnan(faces) | isinf(faces);
nan_inf_test2 = isnan(vert) | isinf(vert);
if any(nan_inf_test1(:)) | any(nan_inf_test2(:))
warning(sprintf('%s does not support NaNs or Infs in face/vertex data.',mfilename));
end
% For debugging
% if 0
% ax1 = getappdata(ax,'testselect3d');
% if isempty(ax1) | ~ishandle(ax1)
% fig = figure;
% ax1 = axes;
% axis(ax1,'equal');
% setappdata(ax,'testselect3d',ax1);
% end
% cla(ax1);
% patch('parent',ax1,'faces',faces,'vertices',xvert','facecolor','none','edgecolor','k');
% line('parent',ax1,'xdata',xcp(1,2),'ydata',xcp(2,2),'zdata',0,'marker','o','markerfacecolor','r','erasemode','xor');
% end
% Transform vertices from data space to pixel space
xvert = local_Data2PixelTransform(ax,vert)';
xcp = local_Data2PixelTransform(ax,cp')';
% Translate vertices so that the selection point is at the origin.
xvert(1,:) = xvert(1,:) - xcp(1,2);
xvert(2,:) = xvert(2,:) - xcp(2,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% simple algorithm (almost naive algorithm!) for line objects %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isline
% Ignoring line width and marker attributes, find closest
% vertex in 2-D view space.
d = xvert(1,:).*xvert(1,:) + xvert(2,:).*xvert(2,:);
[val i] = min(d);
i = i(1); % enforce only one output
% Assign output
vout = [ xdata(i) ydata(i) zdata(i)];
viout = i;
return % Bail out early
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Perform 2-D crossing test (Jordan Curve Theorem) %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Find all vertices that have y components less than zero
vert_with_negative_y = zeros(size(faces));
face_y_vert = xvert(2,faces);
ind_vert_with_negative_y = find(face_y_vert<0);
vert_with_negative_y(ind_vert_with_negative_y) = logical(1);
% Find all the line segments that span the x axis
is_line_segment_spanning_x = abs(diff([vert_with_negative_y, vert_with_negative_y(:,1)],1,2));
% Find all the faces that have line segments that span the x axis
ind_is_face_spanning_x = find(any(is_line_segment_spanning_x,2));
% Ignore data that doesn't span the x axis
candidate_faces = faces(ind_is_face_spanning_x,:);
vert_with_negative_y = vert_with_negative_y(ind_is_face_spanning_x,:);
is_line_segment_spanning_x = is_line_segment_spanning_x(ind_is_face_spanning_x,:);
% Create line segment arrays
pt1 = candidate_faces;
pt2 = [candidate_faces(:,2:end), candidate_faces(:,1)];
% Point 1
x1 = reshape(xvert(1,pt1),size(pt1));
y1 = reshape(xvert(2,pt1),size(pt1));
% Point 2
x2 = reshape(xvert(1,pt2),size(pt2));
y2 = reshape(xvert(2,pt2),size(pt2));
% Cross product of vector to origin with line segment
cross_product_test = -x1.*(y2-y1) > -y1.*(x2-x1);
% Find all line segments that cross the positive x axis
crossing_test = (cross_product_test==vert_with_negative_y) & is_line_segment_spanning_x;
% If the number of line segments is odd, then we intersected the polygon
s = sum(crossing_test,2);
s = mod(s,2);
ind_intersection_test = find(s~=0);
% Bail out early if no faces were hit
if isempty(ind_intersection_test)
return;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Plane/ray intersection test %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Perform plane/ray intersection with the faces that passed
% the polygon intersection tests. Grab the only the first
% three vertices since that is all we need to define a plane).
% assuming planar polygons.
candidate_faces = candidate_faces(ind_intersection_test,1:3);
candidate_faces = reshape(candidate_faces',1,prod(size(candidate_faces)));
vert = vert';
candidate_facev = vert(:,candidate_faces);
candidate_facev = reshape(candidate_facev,3,3,length(ind_intersection_test));
% Get three contiguous vertices along polygon
v1 = squeeze(candidate_facev(:,1,:));
v2 = squeeze(candidate_facev(:,2,:));
v3 = squeeze(candidate_facev(:,3,:));
% Get normal to face plane
vec1 = [v2-v1];
vec2 = [v3-v2];
crs = cross(vec1,vec2);
mag = sqrt(sum(crs.*crs));
nplane(1,:) = crs(1,:)./mag;
nplane(2,:) = crs(2,:)./mag;
nplane(3,:) = crs(3,:)./mag;
% Compute intersection between plane and ray
cp1 = cp(:,1);
cp2 = cp(:,2);
d = cp2-cp1;
dp = dot(-nplane,v1);
%A = dot(nplane,d);
A(1,:) = nplane(1,:).*d(1);
A(2,:) = nplane(2,:).*d(2);
A(3,:) = nplane(3,:).*d(3);
A = sum(A,1);
%B = dot(nplane,pt1)
B(1,:) = nplane(1,:).*cp1(1);
B(2,:) = nplane(2,:).*cp1(2);
B(3,:) = nplane(3,:).*cp1(3);
B = sum(B,1);
% Distance to intersection point
t = (-dp-B)./A;
% Find "best" distance (smallest)
[tbest ind_best] = min(t);
% Determine intersection point
pout = cp1 + tbest .* d;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Assign additional output variables %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargout>1
% Get face index and vertices
faceiout = ind_is_face_spanning_x(ind_intersection_test(ind_best));
facevout = vert(:,faces(faceiout,:));
% Determine index of closest face vertex intersected
facexv = xvert(:,faces(faceiout,:));
dist = sqrt(facexv(1,:).*facexv(1,:) + facexv(2,:).*facexv(2,:));
min_dist = min(dist);
min_index = find(dist==min_dist);
% Get closest vertex index and vertex
viout = faces(faceiout,min_index);
vout = vert(:,viout);
end
%--------------------------------------------------------%
function [p] = local_Data2PixelTransform(ax,vert)
% Transform vertices from data space to pixel space.
% Get needed transforms
xform = get(ax,'x_RenderTransform');
offset = get(ax,'x_RenderOffset');
scale = get(ax,'x_RenderScale');
% Equivalent: nvert = vert/scale - offset;
nvert(:,1) = vert(:,1)./scale(1) - offset(1);
nvert(:,2) = vert(:,2)./scale(2) - offset(2);
nvert(:,3) = vert(:,3)./scale(3) - offset(3);
% Equivalent xvert = xform*xvert;
w = xform(4,1) * nvert(:,1) + xform(4,2) * nvert(:,2) + xform(4,3) * nvert(:,3) + xform(4,4);
xvert(:,1) = xform(1,1) * nvert(:,1) + xform(1,2) * nvert(:,2) + xform(1,3) * nvert(:,3) + xform(1,4);
xvert(:,2) = xform(2,1) * nvert(:,1) + xform(2,2) * nvert(:,2) + xform(2,3) * nvert(:,3) + xform(2,4);
% w may be 0 for perspective plots
ind = find(w==0);
w(ind) = 1; % avoid divide by zero warning
xvert(ind,:) = 0; % set pixel to 0
p(:,1) = xvert(:,1) ./ w;
p(:,2) = xvert(:,2) ./ w;
|
github
|
alex-delalande/numerical-tours-master
|
compute_parameterization.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/compute_parameterization.m
| 7,948 |
utf_8
|
ccbb3294b8723d824f8bfa35c4ea64dc
|
function vertex1 = compute_parameterization(vertex,face, options)
% compute_parameterization - compute a planar parameterization
%
% vertex1 = compute_parameterization(vertex,face, options);
%
% options.method can be:
% 'parameterization': solve classical parameterization, the boundary
% is specified by options.boundary which is either 'circle',
% 'square' or 'triangle'. The kind of laplacian used is specified
% by options.laplacian which is either 'combinatorial' or 'conformal'
% 'freeboundary': same be leave the boundary free.
% 'flattening': solve spectral embedding using a laplacian
% specified by options.laplacian.
% 'isomap': use Isomap approach.
% 'drawing': to draw a graph whose adjacency is options.A.
% Then leave vertex and face empty.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
method = getoptions(options, 'method', 'parameterization');
laplacian = getoptions(options, 'laplacian', 'conformal');
boundary = getoptions(options, 'boundary', 'square');
ndim = getoptions(options, 'ndim', 2);
[vertex,face] = check_face_vertex(vertex,face);
options.symmetrize=1;
options.normalize=0;
switch lower(method)
case 'parameterization'
vertex1 = compute_parametrization_boundary(vertex,face,laplacian,boundary, options);
case 'freeboundary'
vertex1 = compute_parameterization_free(vertex,face, laplacian, options);
case 'drawing'
if isfield(options, 'A')
A = options.A;
else
error('You must specify options.A.');
end
L = compute_mesh_laplacian(vertex,face,'combinatorial',options);
[U,S,V] = eigs(L, ndim+1, 'SM');
if abs(S(1))<eps
vertex1 = U(:,end-ndim+1:end);
elseif abs(S(ndim))<eps
vertex1 = U(:,1:ndim);
else
error('Problem with Laplacian matrix');
end
case 'flattening'
L = compute_mesh_laplacian(vertex,face,laplacian,options);
[U,S] = eig(full(L));
vertex1 = U(:,2:3);
if 0
[U,S,V] = eigs(L, ndim+1, 'SM');
if abs(S(1))<1e-9
vertex1 = U(:,end-ndim+1:end);
elseif abs(S(ndim))<eps
vertex1 = U(:,1:ndim);
else
error('Problem with Laplacian matrix');
end
end
case 'isomap'
A = triangulation2adjacency(face);
% build distance graph
D = build_euclidean_weight_matrix(A,vertex,Inf);
vertex1 = isomap(D,ndim, options);
otherwise
error('Unknown method.');
end
if size(vertex1,2)<size(vertex1,1)
vertex1 = vertex1';
end
if ndim==2
vertex1 = rectify_embedding(vertex(1:ndim,:),vertex1);
end
function xy_spec1 = rectify_embedding(xy,xy_spec)
% rectify_embedding - try to match the embeding
% with another one.
% Use the Y coord to select 2 base points.
%
% xy_spec = rectify_embedding(xy,xy_spec);
%
% Copyright (c) 2003 Gabriel Peyr?
I = find( xy(2,:)==max(xy(2,:)) );
n1 = I(1);
I = find( xy(2,:)==min(xy(2,:)) );
n2 = I(1);
v1 = xy(:,n1)-xy(:,n2);
v2 = xy_spec(:,n1)-xy_spec(:,n2);
theta = acos( dot(v1,v2)/sqrt(dot(v1,v1)*dot(v2,v2)) );
theta = theta * sign( det([v1 v2]) );
M = [cos(theta) sin(theta); -sin(theta) cos(theta)];
xy_spec1 = M*xy_spec;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function xy = compute_parameterization_free(vertex,face, laplacian, options)
n = size(vertex,2);
% extract boundary
boundary = compute_boundary(face,options);
nbound = length(boundary);
options.symmetrize=1;
options.normalize=0;
% compute Laplacian
if ~isstr(laplacian)
L = laplacian;
laplacian = 'user';
else
L = compute_mesh_laplacian(vertex,face,laplacian,options);
end
A = sparse(2*n,2*n);
A(1:end/2,1:end/2) = L;
A(end/2+1:end,end/2+1:end) = L;
% set up boundary conditions
for s = 1:nbound
% neighboring values
s1 = mod(s-2,nbound)+1;
s2 = mod(s,nbound)+1;
i = boundary(s);
i1 = boundary(s1);
i2 = boundary(s2);
e = 1;
A(i,i1+n) = +e;
A(i,i2+n) = -e;
A(i+n,i1) = -e;
A(i+n,i2) = +e;
end
% set up pinned vertices
i1 = boundary(1);
i2 = boundary(round(end/2));
A(i1,:) = 0; A(i1+n,:) = 0;
A(i1,i1) = 1; A(i1+n,i1+n) = 1;
A(i2,:) = 0; A(i2+n,:) = 0;
A(i2,i2) = 1; A(i2+n,i2+n) = 1;
p1 = [0 0]; p2 = [1 0]; % position of pinned vertices
y = zeros(2*n,1);
y(i1) = p1(1); y(i1+n) = p1(2);
y(i2) = p2(1); y(i2+n) = p2(2);
% solve for the position
xy = A\y;
xy = reshape(xy, [n 2])';
function xy = compute_parametrization_boundary(vertex,face,laplacian,boundary_type,options)
% compute_parametrization - compute a planar parameterization
% of a given disk-like triangulated manifold.
%
% compute_parametrization(vertex,face,laplacian,boundary_type);
%
% 'laplacian' is either 'combinatorial', 'conformal' or 'authalic'
% 'boundary_type' is either 'circle', 'square' or 'triangle'
%
% Copyright (c) 2004 Gabriel Peyr?
if size(vertex,2)>size(vertex,1)
vertex = vertex';
end
if size(face,2)>size(face,1)
face = face';
end
nface = size(face,1);
nvert = max(max(face));
options.symmetrize=1;
options.normalize=0;
if nargin<2
error('Not enough arguments.');
end
if nargin<3
laplacian = 'conformal';
end
if nargin<4
boundary_type = 'circle';
end
if ~isstr(laplacian)
L = laplacian;
laplacian = 'user';
else
% compute Laplacian
L = compute_mesh_laplacian(vertex,face,laplacian,options);
end
% compute the boundary
boundary = compute_boundary(face, options);
% compute the position of the boundary vertex
nbound = length(boundary);
xy_boundary = zeros(nbound,2);
% compute total length
d = 0;
ii = boundary(end); % last index
for i=boundary
d = d + norme( vertex(i,:)-vertex(ii,:) );
ii = i;
end
% vertices along the boundary
vb = vertex(boundary,:);
% compute the length of the boundary
sel = [2:nbound 1];
D = cumsum( sqrt( sum( (vb(sel,:)-vb).^2, 2 ) ) );
d = D(end);
% curvilinear abscice
t = (D-D(1))/d; t = t(:);
switch lower(boundary_type)
case 'circle'
xy_boundary = [cos(2*pi*t),sin(2*pi*t)];
case 'square'
t = t*4;
[tmp,I] = min(abs(t-1)); t(I) = 1;
[tmp,I] = min(abs(t-2)); t(I) = 2;
[tmp,I] = min(abs(t-3)); t(I) = 3;
xy_boundary = [];
I = find(t<1); nI = length(I);
xy_boundary = [xy_boundary; [t(I),t(I)*0]];
I = find(t>=1 & t<2); nI = length(I);
xy_boundary = [xy_boundary; [t(I)*0+1,t(I)-1]];
I = find(t>=2 & t<3); nI = length(I);
xy_boundary = [xy_boundary; [3-t(I),t(I)*0+1]];
I = find(t>=3); nI = length(I);
xy_boundary = [xy_boundary; [t(I)*0,4-t(I)]];
case 'triangle'
t = t*3;
[tmp,I] = min(abs(t-1)); t(I) = 1;
[tmp,I] = min(abs(t-2)); t(I) = 2;
xy_boundary = [];
I = find(t<1); nI = length(I);
xy_boundary = [xy_boundary; [t(I),t(I)*0]];
I = find(t>=1 & t<2); nI = length(I);
xy_boundary = [xy_boundary; (t(I)-1)*[0.5,sqrt(2)/2] + (2-t(I))*[1,0] ];
I = find(t>=2 & t<3); nI = length(I);
xy_boundary = [xy_boundary; (3-t(I))*[0.5,sqrt(2)/2] ];
end
% set up the matrix
M = L;
for i=boundary
M(i,:) = zeros(1,nvert);
M(i,i) = 1;
end
% solve the system
xy = zeros(nvert,2);
for coord = 1:2
% compute right hand side
x = zeros(nvert,1);
x(boundary) = xy_boundary(:,coord);
xy(:,coord) = M\x;
end
function y = norme( x );
y = sqrt( sum(x(:).^2) );
|
github
|
alex-delalande/numerical-tours-master
|
select3dtool.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/select3dtool.m
| 2,713 |
utf_8
|
fdf7d572638e6ebd059c63f233d26704
|
function select3dtool(arg)
%SELECT3DTOOL A simple tool for interactively obtaining 3-D coordinates
%
% SELECT3DTOOL(FIG) Specify figure handle
%
% Example:
% surf(peaks);
% select3dtool;
% % click on surface
if nargin<1
arg = gcf;
end
if ~ishandle(arg)
feval(arg);
return;
end
%% initialize gui %%
fig = arg;
figure(fig);
uistate = uiclearmode(fig);
[tool, htext] = createUI;
hmarker1 = line('marker','o','markersize',10,'markerfacecolor','k','erasemode','xor','visible','off');
hmarker2 = line('marker','o','markersize',10,'markerfacecolor','r','erasemode','xor','visible','off');
state.uistate = uistate;
state.text = htext;
state.tool = tool;
state.fig = fig;
state.marker1 = hmarker1;
state.marker2 = hmarker2;
setappdata(fig,'select3dtool',state);
setappdata(state.tool,'select3dhost',fig);
set(fig,'windowbuttondownfcn','select3dtool(''click'')');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function off
state = getappdata(gcbf,'select3dtool');
if ~isempty(state)
delete(state.tool);
end
fig = getappdata(gcbf,'select3dhost');
if ~isempty(fig) & ishandle(fig)
state = getappdata(fig,'select3dtool');
uirestore(state.uistate);
delete(state.marker1);
delete(state.marker2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function click
[p v vi] = select3d;
state = getappdata(gcbf,'select3dtool');
if ~ishandle(state.text)
state.text = createUI;
end
if ~ishandle(state.marker1)
state.marker1 = [];
end
if ~ishandle(state.marker2)
state.marker2 = [];
end
setappdata(state.fig,'select3dtool',state);
if isempty(v)
v = [nan nan nan];
vi = nan;
set(state.marker2,'visible','off');
else
set(state.marker2,'visible','on','xdata',v(1),'ydata',v(2),'zdata',v(3));
end
if isempty(p)
p = [nan nan nan];
set(state.marker1,'visible','off');
else
set(state.marker1,'visible','on','xdata',p(1),'ydata',p(2),'zdata',p(3));
end
% Update tool and markers
set(state.text,'string',createString(p(1),p(2),p(3),v(1),v(2),v(3),vi));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fig, h] = createUI
pos = [200 200 200 200];
% Create selection tool %
fig = figure('handlevisibility','off','menubar','none','resize','off',...
'numbertitle','off','name','Select 3-D Tool','position',pos,'deletefcn','select3dtool(''off'')');
h = uicontrol('style','text','parent',fig,'string',createString(0,0,0,0,0,0,0),...
'units','norm','position',[0 0 1 1],'horizontalalignment','left');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [str] = createString(px,py,pz,vx,vy,vz,vi)
str = sprintf(' Position:\n X %f\n Y: %f\n Z: %f \n\n Vertex:\n X: %f\n Y: %f\n Z: %f \n\n Vertex Index:\n %d',px,py,pz,vx,vy,vz,vi);
|
github
|
alex-delalande/numerical-tours-master
|
compute_boundary.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/compute_boundary.m
| 2,537 |
utf_8
|
1722359a4efff29fd344fc6e14eddba5
|
function boundary=compute_boundary(face, options)
% compute_boundary - compute the vertices on the boundary of a 3D mesh
%
% boundary=compute_boundary(face);
%
% Copyright (c) 2007 Gabriel Peyre
if size(face,1)<size(face,2)
face=face';
end
%% compute edges (i,j) that are adjacent to only 1 face
A = compute_edge_face_ring(face);
[i,j,v] = find(A);
i = i(v==-1);
j = j(v==-1);
%% build the boundary by traversing the edges
boundary = i(1); i(1) = []; j(1) = [];
while not(isempty(i))
b = boundary(end);
I = find(i==b);
if isempty(I)
I = find(j==b);
if isempty(I)
warning('Problem with boundary');
break;
end
boundary(end+1) = i(I);
else
boundary(end+1) = j(I);
end
i(I) = []; j(I) = [];
end
return;
%% OLD CODE %%
nvert=max(max(face));
nface=size(face,1);
% count number of faces adjacent to a vertex
A=sparse(nvert,nvert);
for i=1:nface
if verb
progressbar(i,nface);
end
f=face(i,:);
A(f(1),f(2))=A(f(1),f(2))+1;
A(f(1),f(3))=A(f(1),f(3))+1;
A(f(3),f(2))=A(f(3),f(2))+1;
end
A=A+A';
for i=1:nvert
u=find(A(i,:)==1);
if ~isempty(u)
boundary=[i u(1)];
break;
end
end
s=boundary(2);
i=2;
while(i<=nvert)
u=find(A(s,:)==1);
if length(u)~=2
warning('problem in boundary');
end
if u(1)==boundary(i-1)
s=u(2);
else
s=u(1);
end
if s~=boundary(1)
boundary=[boundary s];
else
break;
end
i=i+1;
end
if i>nvert
warning('problem in boundary');
end
%%% OLD %%%
function v = compute_boundary_old(faces)
nvert = max(face(:));
ring = compute_vertex_ring( face );
% compute boundary
v = -1;
for i=1:nvert % first find a starting vertex
f = ring{i};
if f(end)<0
v = i;
break;
end
end
if v<0
error('No boundary found.');
end
boundary = [v];
prev = -1;
while true
f = ring{v};
if f(end)>=0
error('Problem in boundary');
end
if f(1)~=prev
prev = v;
v = f(1);
else
prev = v;
v = f(end-1);
end
if ~isempty( find(boundary==v) )
% we have reach the begining of the boundary
if v~=boundary(1)
warning('Begining and end of boundary doesn''t match.');
else
break;
end
end
boundary = [boundary,v];
end
|
github
|
alex-delalande/numerical-tours-master
|
compute_geometric_laplacian.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/compute_geometric_laplacian.m
| 5,760 |
utf_8
|
b6c0f7f8acdbb0c203c5f1a297957760
|
function L = compute_geometric_laplacian(vertex,face,type)
% compute_geometric_laplacian - return a laplacian
% of a given triangulation (can be combinatorial or geometric).
%
% L = compute_geometric_laplacian(vertex,face,type);
%
% Type is either :
% - 'combinatorial' : combinatorial laplacian, doesn't take into
% acount geometry.
% - 'conformal' : conformal (i.e. harmonic) weights,
% - 'authalic' : area-preserving weights (not implemented yet).
% - 'distance' : L(i,j) = 1/|xi-xj|^2
%
% Reference:
% M.S.Floater and K.Hormann
% Recent Advances in Surface Parameterization
% Multiresolution in geometric modelling
% <http://vcg.isti.cnr.it/~hormann/papers/survey.pdf>
%
% Copyright (c) 2003 Gabriel Peyre
error('Not used anymore');
[vertex,face] = check_face_vertex(vertex,face);
nface = size(face,1);
n = max(max(face));
if nargin<3
type = 'conformal';
end
if strcmp(lower(type),'combinatorial')
L = compute_combinatorial_laplacian( triangulation2adjacency(face) );
return;
end
if strcmp(lower(type),'distance')
D = build_euclidean_weight_matrix(triangulation2adjacency(face),vertex,0);
D(D>0) = 1/D(D>0).^2;
L = diag( sum(D) ) - D;
L = (L+L')/2;
return;
end
if strcmp(lower(type),'authalic')
error('Not implemented');
end
if not(strcmp(lower(type),'conformal'))
error('Unknown laplacian type.');
end
% conformal laplacian
L = sparse(n,n);
ring = compute_vertex_face_ring(face);
for i = 1:n
for b = ring{i}
% b is a face adjacent to a
bf = face(:,b);
% compute complementary vertices
if bf(1)==i
v = bf(2:3);
elseif bf(2)==i
v = bf([1 3]);
elseif bf(3)==i
v = bf(1:2);
else
error('Problem in face ring.');
end
j = v(1); k = v(2);
vi = vertex(:,i);
vj = vertex(:,j);
vk = vertex(:,k);
% angles
alpha = myangle(vk-vi,vk-vj);
beta = myangle(vj-vi,vj-vk);
% add weight
L(i,j) = L(i,j) + cot( alpha );
L(i,k) = L(i,k) + cot( beta );
end
end
L = L - diag(sum(L,2));
return;
%% old code
if strcmp(lower(type),'combinatorial')
L = compute_combinatorial_laplacian( triangulation2adjacency(face) );
elseif strcmp(lower(type),'conformal') || strcmp(lower(type),'authalic')
if nargin<4
disp('--> Computing 1-ring.');
ring = compute_vertex_ring( face );
end
disp('--> Computing laplacian.');
for i=1:n
vi = vertex(i,:);
r = ring{i};
if r(end)==-1
% no circularity
s = length(r)-1;
r = [r(1), r(1:(end-1)), r(end-1)];
else
% circularity
s = length(r);
r = [r(end), r, r(1)];
end
% circulate on the 1-ring
for x = 2:(s+1)
j = r(x);
if L(i,j)==0
gche = r(x-1);
drte = r(x+1);
vj = vertex(j,:);
v1 = vertex(gche,:);
v2 = vertex(drte,:);
% we use cot(acos(x))=x/sqrt(1-x^2)
if strcmp(lower(type),'conformal')
d1 = sqrt(dot(vi-v2,vi-v2));
d2 = sqrt(dot(vj-v2,vj-v2));
if d1>eps && d2>eps
z = dot(vi-v2,vj-v2)/( d1*d2 );
L(i,j) = L(i,j) + z/sqrt(1-z^2);
end
d1 = sqrt(dot(vi-v1,vi-v1));
d2 = sqrt(dot(vj-v1,vj-v1));
if d1>eps && d2>eps
z = dot(vi-v1,vj-v1)/( d1*d2 );
L(i,j) = L(i,j) + z/sqrt(1-z^2);
end
else
d1 = sqrt(dot(vi-vj,vi-vj));
d2 = sqrt(dot(v2-vj,v2-vj));
if d1>eps && d2>eps
z = dot(vi-vj,v2-vj)/( d1*d2 );
L(i,j) = L(i,j) + z/sqrt(1-z^2);
end
d1 = sqrt(dot(vi-vj,vi-vj));
d2 = sqrt(dot(v1-vj,v1-vj));
if d1>eps && d2>eps
z = dot(vi-vj,v1-vj)/( d1*d2 );
L(i,j) = L(i,j) + z/sqrt(1-z^2);
end
if d1>eps
L(i,j) = L(i,j) / (d1*d1);
end
end
if 0 % uncomment for symmeterization
if L(j,i)==0
L(j,i) = L(i,j);
else
L(j,i) = (L(j,i)+L(i,j))/2;
end
end
end
end
end
for i=1:n
L(i,i) = -sum( L(i,:) );
end
else
error('Unknown type.');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function beta = myangle(u,v);
du = sqrt( sum(u.^2) );
dv = sqrt( sum(v.^2) );
du = max(du,eps); dv = max(dv,eps);
beta = acos( sum(u.*v) / (du*dv) );
|
github
|
alex-delalande/numerical-tours-master
|
check_face_vertex.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/check_face_vertex.m
| 671 |
utf_8
|
21c65f119991c973909eedd356838dad
|
function [vertex,face] = check_face_vertex(vertex,face, options)
% check_face_vertex - check that vertices and faces have the correct size
%
% [vertex,face] = check_face_vertex(vertex,face);
%
% Copyright (c) 2007 Gabriel Peyre
vertex = check_size(vertex,2,4);
face = check_size(face,3,4);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = check_size(a,vmin,vmax)
if isempty(a)
return;
end
if size(a,1)>size(a,2)
a = a';
end
if size(a,1)<3 && size(a,2)==3
a = a';
end
if size(a,1)<=3 && size(a,2)>=3 && sum(abs(a(:,3)))==0
% for flat triangles
% a = a';
end
if size(a,1)<vmin || size(a,1)>vmax
error('face or vertex is not of correct size');
end
|
github
|
alex-delalande/numerical-tours-master
|
compute_voronoi_triangulation.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/compute_voronoi_triangulation.m
| 2,807 |
utf_8
|
f9daaae570bef29e30a0956f719d9c19
|
function faces = compute_voronoi_triangulation(Q, vertex)
% compute_voronoi_triangulation - compute a triangulation
%
% face = compute_voronoi_triangulation(Q);
%
% Q is a Voronoi partition function, computed using
% perform_fast_marching.
% face(:,i) is the ith face.
%
% Works in 2D and in 3D.
%
% Copyright (c) 2008 Gabriel Peyre
d = nb_dims(Q);
if d==2
faces = compute_voronoi_triangulation_2d(Q, vertex);
elseif d==3
faces = compute_voronoi_triangulation_3d(Q, vertex);
else
error('Works only for 2D or 3D data.');
end
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function faces = compute_voronoi_triangulation_3d(Q, vertex)
[dx dy dz] = meshgrid(0:1,0:1,0:1);
V = [];
for i=1:8
v = Q(1+dx(i):end-1+dx(i),1+dy(i):end-1+dy(i),1+dz(i):end-1+dz(i));
V = [V v(:)];
end
V = sort(V,2);
V = unique(V, 'rows');
V = V( prod(V,2)>0 ,:);
d = V(:,1)*0;
for i=1:7
d = d+(V(:,i)~=V(:,i+1));
end
if sum(d==4)>1
% warning('Problem with triangulation.');
end
% split 5 folds into 2
I = find(d==4);
faces = [];
for i=1:length(I)
v = unique(V(I(i),:));
x = vertex(:,v); % points
% barycenter
a = sum( x, 2 ) / 5;
x = x-repmat(a, [1 size(x,2)]);
t = atan2(x(2,:),x(1,:));
[tmp,s] = sort(t);
faces = [faces v( s([1 2 3 5]))'];
faces = [faces v( s([3 4 1 5]))'];
end
% faces = [V(I,1:3);V(I,[3 4 1])];
% remaining triangles
V = V( d==3 ,:);
for i=1:size(V,1)
V(i,1:4) = unique(V(i,:));
end
faces = [faces, V(:,1:4)'];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function faces = compute_voronoi_triangulation_2d(Q, vertex)
V = [];
v = Q(1:end-1,1:end-1); V = [V v(:)];
v = Q(2:end,1:end-1); V = [V v(:)];
v = Q(1:end-1,2:end); V = [V v(:)];
v = Q(2:end,2:end); V = [V v(:)];
V = sort(V,2);
V = unique(V, 'rows');
V = V( prod(V,2)>0 ,:);
d = (V(:,1)~=V(:,2)) + (V(:,2)~=V(:,3)) + (V(:,3)~=V(:,4));
if sum(d==3)>1
% warning('Problem with triangulation.');
end
% split squares into 2 triangles
I = find(d==3);
faces = [];
for i=1:length(I)
v = V(I(i),:);
x = vertex(:,v); % points
% barycenter
a = sum( x, 2 ) / 4;
x = x-repmat(a, [1 size(x,2)]);
t = atan2(x(2,:),x(1,:));
[tmp,s] = sort(t);
faces = [faces; v( s([1 2 3]))];
faces = [faces; v( s([3 4 1]))];
end
% faces = [V(I,1:3);V(I,[3 4 1])];
% remaining triangles
V = V( d==2 ,:);
for i=1:size(V,1)
V(i,1:3) = unique(V(i,:));
end
faces = [faces; V(:,1:3)];
% return in correct format
faces = faces';
|
github
|
alex-delalande/numerical-tours-master
|
plot_graph.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/plot_graph.m
| 2,140 |
utf_8
|
337033b66fe405903639bcac59c2b34d
|
function h = plot_graph(A,xy, options)
% plot_graph - display a 2D or 3D graph.
%
% plot_graph(A,xy, options);
%
% options.col set the display (e.g. 'k.-')
%
% Copyright (c) 2006 Gabriel Peyre
if size(xy,1)>size(xy,2)
xy = xy';
end
if nargin<3
options.null = 0;
end
if not(isstruct(options))
col = options; clear options;
options.null = 0;
else
if isfield(options, 'col')
col = options.col;
else
col = 'k.-';
end
end
lw = getoptions(options, 'lw', 2);
ps = getoptions(options, 'ps', 20);
B = full(A); B = B(:); B = B( B~=0 );
isvarying = std(B)>0;
if size(xy,1)==2
if ~isstr(col)
col = [];
end
% 2D display
h = gplotvarying(A,xy, col);
% h = gplot(A,xy', col);
axis tight; axis equal; axis off;
elseif size(xy,1)==3
% 3D display
if isstr(col)
if ~isvarying
h = gplot3(A,xy', col);
else
h = gplotvarying3(A,xy, col);
end
else
hold on;
if ~isvarying
h = gplot3(A,xy', col);
else
h = gplotvarying3(A,xy, col);
end
plot_scattered(xy, col);
hold off;
view(3);
end
axis off;
cameramenu;
else
error('Works only for 2D and 3D graphs');
end
set(h, 'LineWidth', lw);
set(h, 'MarkerSize', ps);
function h = gplotvarying(A,xy,col)
[i,j,s] = find(sparse(A));
I = find(i<=j);
i = i(I); j = j(I); s = s(I);
x = [xy(1,i);xy(1,j)];
y = [xy(2,i);xy(2,j)];
h = plot(x,y,col);
function h = gplotvarying3(A,xy,col)
[i,j,s] = find(sparse(A));
I = find(i<=j);
i = i(I); j = j(I); s = s(I);
x = [xy(1,i);xy(1,j)];
y = [xy(2,i);xy(2,j)];
y = [xy(3,i);xy(3,j)];
h = plot3(x,y,z,col);
function h = gplot3(A,xy,lc)
[i,j] = find(A);
[ignore, p] = sort(max(i,j));
i = i(p);
j = j(p);
% Create a long, NaN-separated list of line segments,
% rather than individual segments.
X = [ xy(i,1) xy(j,1) repmat(NaN,size(i))]';
Y = [ xy(i,2) xy(j,2) repmat(NaN,size(i))]';
Z = [ xy(i,3) xy(j,3) repmat(NaN,size(i))]';
X = X(:);
Y = Y(:);
Z = Z(:);
if nargin<3,
h = plot3(X, Y, Z)
else
h = plot3(X, Y, Z, lc);
end
|
github
|
alex-delalande/numerical-tours-master
|
vol3d.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/vol3d.m
| 5,899 |
utf_8
|
9ce5b72520d76d1225023aa3732b653d
|
function [model] = vol3d(varargin)
%H = VOL3D Volume render 3-D data.
% VOL3D uses the orthogonal plane 2-D texture mapping technique for
% volume rending 3-D data in OpenGL. Use the 'texture' option to fine
% tune the texture mapping technique. This function is best used with
% fast OpenGL hardware.
%
% H = vol3d('CData',data) Create volume render object from input
% 3-D data. Use interp3 on data to increase volume
% rendering resolution. Returns a struct
% encapsulating the pseudo-volume rendering object.
%
% vol3d(...'Parent',axH) Specify parent axes
%
% vol3d(...,'texture','2D') Default. Only render texture planes parallel
% to nearest orthogonal viewing plane. Requires
% doing vol3d(h) to refresh if the view is
% rotated (i.e. using cameratoolbar).
%
% vol3d(...,'texture','3D') Render x,y,z texture planes simultaneously.
% This avoids the need to refresh the view but
% requires faster OpenGL hardware peformance.
%
% vol3d(H) Refresh view. Updates rendering of texture planes
% to reduce visual aliasing when using the 'texture'='2D'
% option.
%
% NOTES
% Use vol3dtool for editing the colormap and alphamap.
% Adjusting these maps will allow you to explore your 3-D volume
% data at various intensity levels. See documentation on
% alphamap and colormap for more information.
%
% Use interp3 on input date to increase/decrease resolution of data
%
% Examples:
%
% % Visualizing fluid flow
% v = flow(50);
% h = vol3d('cdata',v,'texture','2D');
% view(3);
% % Update view since 'texture' = '2D'
% vol3d(h);
% alphamap('rampdown'), alphamap('decrease'), alphamap('decrease')
%
% % Visualizing MRI data
% load mri.mat
% D = squeeze(D);
% h = vol3d('cdata',D,'texture','2D');
% view(3);
% % Update view since 'texture' = '2D'
% vol3d(h);
% axis tight; daspect([1 1 .4])
% alphamap('rampup');
% alphamap(.06 .* alphamap);
%
% See also vol3dtool, alphamap, colormap, opengl, isosurface
% Copyright Joe Conti, 2004
if isstruct(varargin{1})
model = varargin{1};
if length(varargin) > 1
varargin = {varargin{2:end}};
end
else
model = localGetDefaultModel;
end
if length(varargin)>1
for n = 1:2:length(varargin)
switch(lower(varargin{n}))
case 'cdata'
model.cdata = varargin{n+1};
case 'parent'
model.parent = varargin{n+1};
case 'texture'
model.texture = varargin{n+1};
end
end
end
if isempty(model.parent)
model.parent = gca;
end
% choose default 3-D view
ax = model.parent;
axis(ax,'vis3d');
axis(ax,'tight');
[model] = local_draw(model);
%------------------------------------------%
function [model] = localGetDefaultModel
model.cdata = [];
model.xdata = [];
model.ydata = [];
model.zdata = [];
model.parent = [];
model.handles = [];
model.texture = '2D';
%------------------------------------------%
function [model,ax] = local_draw(model)
cdata = model.cdata;
siz = size(cdata);
% Define [x,y,z]data
if isempty(model.xdata)
model.xdata = [0 siz(2)];
end
if isempty(model.ydata)
model.ydata = [0 siz(1)];
end
if isempty(model.zdata)
model.zdata = [0 siz(3)];
end
try,
delete(model.handles);
end
ax = model.parent;
cam_dir = camtarget(ax) - campos(ax);
[m,ind] = max(abs(cam_dir));
h = findobj(ax,'type','surface','tag','vol3d');
for n = 1:length(h)
try,
delete(h(n));
end
end
is3DTexture = strcmpi(model.texture,'3D');
handle_ind = 1;
% Create z-slice
if(ind==3 || is3DTexture )
x = [model.xdata(1), model.xdata(2); model.xdata(1), model.xdata(2)];
y = [model.ydata(1), model.ydata(1); model.ydata(2), model.ydata(2)];
z = [model.zdata(1), model.zdata(1); model.zdata(1), model.zdata(1)];
diff = model.zdata(2)-model.zdata(1);
delta = diff/size(cdata,3);
for n = 1:size(cdata,3)
slice = double(squeeze(cdata(:,:,n)));
h(handle_ind) = surface(x,y,z,'Parent',ax);
set(h(handle_ind),'cdatamapping','scaled','facecolor','texture','cdata',slice,...
'edgealpha',0,'alphadata',double(slice),'facealpha','texturemap','tag','vol3d');
z = z + delta;
handle_ind = handle_ind + 1;
end
end
% Create x-slice
if (ind==1 || is3DTexture )
x = [model.xdata(1), model.xdata(1); model.xdata(1), model.xdata(1)];
y = [model.ydata(1), model.ydata(1); model.ydata(2), model.ydata(2)];
z = [model.zdata(1), model.zdata(2); model.zdata(1), model.zdata(2)];
diff = model.xdata(2)-model.xdata(1);
delta = diff/size(cdata,2);
for n = 1:size(cdata,2)
slice = double(squeeze(cdata(:,n,:)));
h(handle_ind) = surface(x,y,z,'Parent',ax);
set(h(handle_ind),'cdatamapping','scaled','facecolor','texture','cdata',slice,...
'edgealpha',0,'alphadata',double(slice),'facealpha','texturemap','tag','vol3d');
x = x + delta;
handle_ind = handle_ind + 1;
end
end
% Create y-slice
if (ind==2 || is3DTexture)
x = [model.xdata(1), model.xdata(1); model.xdata(2), model.xdata(2)];
y = [model.ydata(1), model.ydata(1); model.ydata(1), model.ydata(1)];
z = [model.zdata(1), model.zdata(2); model.zdata(1), model.zdata(2)];
diff = model.ydata(2)-model.ydata(1);
delta = diff/size(cdata,1);
for n = 1:size(cdata,1)
slice = double(squeeze(cdata(n,:,:)));
h(handle_ind) = surface(x,y,z,'Parent',ax);
set(h(handle_ind),'cdatamapping','scaled','facecolor','texture','cdata',slice,...
'edgealpha',0,'alphadata',double(slice),'facealpha','texturemap','tag','vol3d');
y = y + delta;
handle_ind = handle_ind + 1;
end
end
model.handles = h;
|
github
|
alex-delalande/numerical-tours-master
|
perform_delaunay_flipping.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/perform_delaunay_flipping.m
| 2,420 |
utf_8
|
7c5e250e94e9e69d99c556c805b4d2fe
|
function [face, flips, flipsinv] = perform_delaunay_flipping(vertex,face,options)
% perform_delaunay_flipping - compute Dalaunay triangulation via flipping
%
% [face1, flips, flipsinv] = perform_delaunay_flipping(vertex,face,options);
%
% Set options.display_flips = 1 for graphical display.
%
% face is turned into a Delaunay triangulation face1 of the points by flipping
% the edges.
%
% 'flips' list the flips needed to go from face to face1.
% 'flipsinv' list the flips needed to go from face1 to face.
%
% Copyright (c) 2008 Gabriel Peyre
options.null = 0;
display_flips = getoptions(options, 'display_flips', 0);
verb = getoptions(options, 'verb', 1);
% edge topology
edge = compute_edges(face);
e2f = compute_edge_face_ring(face);
% initialize the stack
estack = find( check_incircle_edge(vertex,face,edge)==0 );
A = sort( compute_triangulation_angles(vertex,face) );
count = 0;
flips = []; flipsinv = [];
ntot = length(estack);
vbar = 0;
while not(isempty(estack))
if verb
vbar = max(vbar, ntot - length(estack) );
progressbar( max(vbar,1), ntot);
end
count = count+1;
if count>Inf % ntot
warning('Problem with Delaunay flipping');
break;
end
% pop non valid edge
k = estack(1); estack(1) = [];
i = edge(1,k); j = edge(2,k);
f1 = e2f(i,j); f2 = e2f(j,i);
%%% try to flip it %%%
% find the two other points
k1 = find_other( face(:,f1), i,j );
k2 = find_other( face(:,f2), i,j );
% new faces
t1 = [k1;k2;i];
t2 = [k1;k2;j];
flips(:,end+1) = [i;j];
flipsinv(:,end+1) = [k1;k2];
face(:,f1) = t1;
face(:,f2) = t2;
% update e2f
edge(:,k) = [k1;k2];
e2f = compute_edge_face_ring(face);
% display
if display_flips
clf; plot_graph(triangulation2adjacency(face),vertex);
drawnow; % pause(.01);
end
Anew = sort( compute_triangulation_angles(vertex,face) );
if lexicmp(Anew,A)<=0
warning('Problem with flipping.');
end
A = Anew;
% update the stack
estack = find( check_incircle_edge(vertex,face,edge)==0 );
estack = [ estack(estack>k); estack(estack<=k) ];
end
flipsinv = flipsinv(:,end:-1:1);
progressbar(ntot, ntot);
%%
function f = find_other( f, i,j )
I = find(f==i);
if length(I)~=1
error('Problem');
end
f(I) = [];
I = find(f==j);
if length(I)~=1
error('Problem');
end
f(I) = [];
|
github
|
alex-delalande/numerical-tours-master
|
check_incircle_edge.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/check_incircle_edge.m
| 1,633 |
utf_8
|
dca2fc799d9cf120df9156a15c47b5fa
|
function ic = check_incircle_edge(vertex, face, edge)
% check_incicle_edge - compute "empty circle" property for a set of edges
%
% ic = check_incicle_edge(vertex,face, edge);
%
% ic(i)==1 if edge(:,i) is delaunay valid (boundary or empty circles or non convex).
% It thus should be flipped if ic(i)==0.
%
% Copyright (c) 2008 Gabriel Peyre
if nargin<3
edge = compute_edges(face);
end
n = size(edge, 2);
e2f = compute_edge_face_ring(face);
m = size(e2f,1);
f1 = full( e2f(edge(1,:)+(edge(2,:)-1)*m) );
f2 = full( e2f(edge(2,:)+(edge(1,:)-1)*m) );
if not( isempty( find(f1==0 & f2==0) ) )
warning('Problem with triangulation');
end
ic = ones(n,1);
isconvex = ones(n,1);
I = find(f1>0 & f2>0);
f1 = f1(I); f2 = f2(I);
f1 = face(:,f1);
f2 = face(:,f2);
edge = edge(:,I);
n = length(I);
points1 = find_other(f2, edge(1,:), edge(2,:));
ic1 = check_incircle(vertex, f1, points1 );
points2 = find_other(f1, edge(1,:), edge(2,:));
ic2 = check_incircle(vertex, f2, points2 );
ic(I) = ic1 & ic2;
% check for convexity
v = vertex(:,points2) - vertex(:,points1);
u1 = vertex(:,edge(1,:)) - vertex(:,points1);
u2 = vertex(:,edge(2,:)) - vertex(:,points1);
A = zeros(2,2,n); B = zeros(2,2,n);
A(:,1,:) = reshape(v, [2 1 n]);
A(:,2,:) = reshape(u1, [2 1 n]);
B(:,1,:) = reshape(v, [2 1 n]);
B(:,2,:) = reshape(u2, [2 1 n]);
isconvex(I) = ( det3(A) .* det3(B) ) < 0;
% non convex should not be flipped
ic(isconvex==0) = 1;
%%
function f = find_other(f,a,b)
u = f - repmat(a, [3 1]); f(u==0) = 0;
u = f - repmat(b, [3 1]); f(u==0) = 0;
if sum( sum(f==0)~=2 )>0
error('Problem with triangulation');
end
f = sum(f);
|
github
|
alex-delalande/numerical-tours-master
|
perform_faces_reorientation.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/perform_faces_reorientation.m
| 2,865 |
utf_8
|
a575bdfcd3e6c86cde45febdeb343983
|
function faces = perform_faces_reorientation(vertex,faces, options)
% perform_faces_reorientation - reorient the faces with respect to the center of the mesh
%
% faces = perform_faces_reorientation(vertex,faces, options);
%
% try to find a consistant reorientation for faces of a mesh.
%
% if options.method = 'fast', then use a fast non accurate method
% if options.method = 'slow', then use a slow exact method
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
method = getoptions(options, 'method', 'fast');
verb = getoptions(options, 'verb', 1);
[vertex,faces] = check_face_vertex(vertex,faces);
n = size(vertex,2);
m = size(faces,2);
if strcmp(method, 'fast')
% compute the center of mass of the mesh
G = mean(vertex,2);
% center of faces
Cf = (vertex(:,faces(1,:)) + vertex(:,faces(2,:)) + vertex(:,faces(3,:)))/3;
Cf = Cf - repmat(G,[1 m]);
% normal to the faces
V1 = vertex(:,faces(2,:))-vertex(:,faces(1,:));
V2 = vertex(:,faces(3,:))-vertex(:,faces(1,:));
N = [V1(2,:).*V2(3,:) - V1(3,:).*V2(2,:) ; ...
-V1(1,:).*V2(3,:) + V1(3,:).*V2(1,:) ; ...
V1(1,:).*V2(2,:) - V1(2,:).*V2(1,:) ];
% dot product
s = sign(sum(N.*Cf));
% reverse faces
I = find(s>0);
faces(:,I) = faces(3:-1:1,I);
return
end
options.method = 'fast';
faces = perform_faces_reorientation(vertex,faces, options);
fring = compute_face_ring(faces);
tag = zeros(m,1)-1;
heap = 1;
for i=1:m
if m>100 & verb==1
progressbar(i,m);
end
if isempty(heap)
I = find(tag==-1);
if isempty(I)
error('Problem');
end
heap = I(1);
end
f = heap(end); heap(end) = [];
if tag(f)==1
warning('Problem');
end
tag(f) = 1; % computed
fr = fring{f};
fr = fr(tag(fr)==-1);
tag(fr)=0;
heap = [heap fr];
for k=fr(:)'
% see if re-orientation is needed
if check_orientation(faces(:,k), faces(:,f))==1
faces(1:2,k) = faces(2:-1:1,k);
end
end
end
if not(isempty(heap)) || not(isempty(find(tag<1)))
warning('Problem');
end
% try to see if face are facing in the correct direction
[normal,normalf] = compute_normal(vertex,faces);
a = mean(vertex,2);
a = repmat(a, [1 n]);
dp = sign(sum(normal.*a,1));
if sum(dp>0)<sum(dp<0)
faces(1:2,:) = faces(2:-1:1,:);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function o = check_orientation(f1,f2)
i1 = 0; j1 = 0;
for i=1:3
for j=1:3
if f1(i)==f2(j)
i1 = i; j1 = j;
break;
end
end
if i1~=0
break;
end
end
if i1==0
error('Problem.');
end
ia = mod(i1,3)+1;
ja = mod(j1,3)+1;
ib = mod(i1-2,3)+1;
jb = mod(j1-2,3)+1;
if f1(ia)==f2(ja) || f1(ib)==f2(jb)
o=1;
else
o = -1;
end
|
github
|
alex-delalande/numerical-tours-master
|
compute_geodesic_mesh.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/compute_geodesic_mesh.m
| 4,234 |
utf_8
|
39b158e6251c6dbe79e025b1c95061b2
|
function [path,vlist,plist] = compute_geodesic_mesh(D, vertex, face, x, options)
% compute_geodesic_mesh - extract a discrete geodesic on a mesh
%
% [path,vlist,plist] = compute_geodesic_mesh(D, vertex, face, x, options);
%
% D is the set of geodesic distances.
%
% path is a 3D curve that is the shortest path starting at x.
% You can force to use a fully discrete descent using
% options.method='discrete'.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
verb = getoptions(options, 'verb', 0);
if length(x)>1
path = {}; vlist = {}; plist = {};
for i=1:length(x)
if length(x)>5
if verb
progressbar(i,length(x));
end
end
[path{i},vlist{i},plist{i}] = compute_geodesic_mesh(D, vertex, face, x(i), options);
end
return;
end
method = getoptions(options, 'method', 'continuous');
[vertex,face] = check_face_vertex(vertex,face);
if strcmp(method, 'discrete')
if isfield(options, 'v2v')
vring = options.v2v;
else
vring = compute_vertex_ring(face);
end
% path purely on edges
vlist = x;
vprev = D(x);
while true
x0 = vlist(end);
r = vring{x0};
[v,J] = min(D(r));
x = r(J);
if v>=vprev || v==0
break;
end
vprev = v;
vlist(end+1) = x;
end
path = vertex(:,vlist);
plist = vlist*0+1;
return;
end
%%% gradient descent on edges
% retrieve adjacency lists
m = size(face,2); n = size(vertex,2);
% precompute the adjacency datasets
if isfield(options, 'e2f')
e2f = options.e2f;
else
e2f = compute_edge_face_ring(face);
end
if isfield(options, 'v2v')
v2v = options.v2v;
else
v2v = compute_vertex_ring(face);
end
% initialize the paths
[w,f] = vertex_stepping(face, x, e2f, v2v, D);
vlist = [x;w];
plist = [1];
Dprev = D(x);
while true;
% current triangle
i = vlist(1,end);
j = vlist(2,end);
k = get_vertex_face(face(:,f),i,j);
a = D(i); b = D(j); c = D(k);
% adjacent faces
f1 = get_face_face(e2f, f, i,k);
f2 = get_face_face(e2f, f, j,k);
% compute gradient in local coordinates
x = plist(end); y = 1-x;
gr = [a-c;b-c];
% twist the gradient
u = vertex(:,i) - vertex(:,k);
v = vertex(:,j) - vertex(:,k);
A = [u v]; A = (A'*A)^(-1);
gr = A*gr;
nx = gr(1); ny = gr(2);
% compute intersection point
etas = -y/ny;
etat = -x/nx;
s = x + etas*nx;
t = y + etat*ny;
if etas<0 && s>=0 && s<=1 && f1>0
%%% CASE 1 %%%
plist(end+1) = s;
vlist(:,end+1) = [i k];
% next face
f = f1;
elseif etat<0 && t>=0 && t<=1 && f2>0
%%% CASE 2 %%%
plist(end+1) = t;
vlist(:,end+1) = [j k];
% next face
f = f2;
else
%%% CASE 3 %%%
if a<=b
z = i;
else
z = j;
end
[w,f] = vertex_stepping( face, z, e2f, v2v, D);
vlist(:,end+1) = [z w];
plist(end+1) = 1;
end
Dnew = D(vlist(1,end))*plist(end) + D(vlist(2,end))*(1-plist(end));
if Dnew==0 || (Dprev==Dnew && length(plist)>1)
break;
end
Dprev=Dnew;
end
v1 = vertex(:,vlist(1,:));
v2 = vertex(:,vlist(2,:));
path = v1.*repmat(plist, [3 1]) + v2.*repmat(1-plist, [3 1]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [w,f] = vertex_stepping(face, v, e2f, v2v, D)
% adjacent vertex with minimum distance
[tmp,I] = min( D(v2v{v}) ); w = v2v{v}(I);
f1 = e2f(v,w);
f2 = e2f(w,v);
if f1<0
f = f2; return;
end
if f2<0
f = f1; return;
end
z1 = get_vertex_face(face(:,f1),v,w);
z2 = get_vertex_face(face(:,f2),v,w);
if D(z1)<D(z2);
f = f1;
else
f = f2;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function k = get_vertex_face(f,v1,v2)
if nargin==2
v2 = v1(2); v1 = v1(1);
end
k = setdiff(f, [v1 v2]);
if length(k)~=1
error('Error in get_vertex_face');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = get_face_face(e2f, f, i,j)
f1 = e2f(i,j); f2 = e2f(j,i);
if f==f1
f = f2;
else
f = f1;
end
|
github
|
alex-delalande/numerical-tours-master
|
compute_mesh_weight.m
|
.m
|
numerical-tours-master/matlab/toolbox_graph/compute_mesh_weight.m
| 3,464 |
utf_8
|
14ba480ba7ded730c631eceea16f8b05
|
function W = compute_mesh_weight(vertex,face,type,options)
% compute_mesh_weight - compute a weight matrix
%
% W = compute_mesh_weight(vertex,face,type,options);
%
% W is sparse weight matrix and W(i,j)=0 is vertex i and vertex j are not
% connected in the mesh.
%
% type is either
% 'combinatorial': W(i,j)=1 is vertex i is conntected to vertex j.
% 'distance': W(i,j) = 1/d_ij^2 where d_ij is distance between vertex
% i and j.
% 'conformal': W(i,j) = cot(alpha_ij)+cot(beta_ij) where alpha_ij and
% beta_ij are the adjacent angle to edge (i,j)
%
% If options.normalize=1, the the rows of W are normalize to sum to 1.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
[vertex,face] = check_face_vertex(vertex,face);
nface = size(face,1);
n = max(max(face));
verb = getoptions(options, 'verb', n>5000);
if nargin<3
type = 'conformal';
end
switch lower(type)
case 'combinatorial'
W = triangulation2adjacency(face);
case 'distance'
W = my_euclidean_distance(triangulation2adjacency(face),vertex);
W(W>0) = 1./W(W>0);
W = (W+W')/2;
case 'conformal'
% conformal laplacian
W = sparse(n,n);
for i=1:3
i1 = mod(i-1,3)+1;
i2 = mod(i ,3)+1;
i3 = mod(i+1,3)+1;
pp = vertex(:,face(i2,:)) - vertex(:,face(i1,:));
qq = vertex(:,face(i3,:)) - vertex(:,face(i1,:));
% normalize the vectors
pp = pp ./ repmat( sqrt(sum(pp.^2,1)), [3 1] );
qq = qq ./ repmat( sqrt(sum(qq.^2,1)), [3 1] );
% compute angles
ang = acos(sum(pp.*qq,1));
W = W + sparse(face(i2,:),face(i3,:),cot(ang),n,n);
W = W + sparse(face(i3,:),face(i2,:),cot(ang),n,n);
end
if 0
%% OLD CODE
W = sparse(n,n);
ring = compute_vertex_face_ring(face);
for i = 1:n
if verb
progressbar(i,n);
end
for b = ring{i}
% b is a face adjacent to a
bf = face(:,b);
% compute complementary vertices
if bf(1)==i
v = bf(2:3);
elseif bf(2)==i
v = bf([1 3]);
elseif bf(3)==i
v = bf(1:2);
else
error('Problem in face ring.');
end
j = v(1); k = v(2);
vi = vertex(:,i);
vj = vertex(:,j);
vk = vertex(:,k);
% angles
alpha = myangle(vk-vi,vk-vj);
beta = myangle(vj-vi,vj-vk);
% add weight
W(i,j) = W(i,j) + cot( alpha );
W(i,k) = W(i,k) + cot( beta );
end
end
end
otherwise
error('Unknown type.')
end
if isfield(options, 'normalize') && options.normalize==1
W = diag(sum(W,2).^(-1)) * W;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function beta = myangle(u,v);
du = sqrt( sum(u.^2) );
dv = sqrt( sum(v.^2) );
du = max(du,eps); dv = max(dv,eps);
beta = acos( sum(u.*v) / (du*dv) );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function W = my_euclidean_distance(A,vertex)
if size(vertex,1)<size(vertex,2)
vertex = vertex';
end
[i,j,s] = find(sparse(A));
d = sum( (vertex(i,:) - vertex(j,:)).^2, 2);
W = sparse(i,j,d);
|
github
|
alex-delalande/numerical-tours-master
|
perform_publishing.m
|
.m
|
numerical-tours-master/matlab/toolbox_publishing/perform_publishing.m
| 7,675 |
utf_8
|
fd2b999e87072411470e6fca15cdc9b1
|
function perform_publishing(name, options)
% perform_publishing - publish a file to HTML format
%
% perform_publishing(name, options);
%
% If name is empty, process all the files (and also zip all toolboxes).
%
% options.rep set output directory (default 'html/')
% options.repprivate set output directory for exercices (default 'private-svg/')
% options.stylesheet set XSL stylesheet path.
% options.format set output format (default 'html').
%
% To put part of code that are not taken into account during publishing,
% put them as
% %CMT
% ...
% %CMT
%
% To put part of code that are release as exercises, put them as
% %EXO
% ...
% %EXO
%
% Copyright (c) 2008 Gabriel Peyre
path('toolbox_general/', path);
options.null = 0;
if nargin<1 || isempty(name)
% batch processing
% list_ext = {'coding_' 'introduction_' 'image_' 'audio_' 'wavelet_' 'sparsity_' ...
% 'denoising_' 'inverse_' 'graphics_' 'multidim_' 'mesh_' 'variational_' 'fastmarching_'};
list_ext = {'audio' 'coding' 'cs' 'denoising' 'fastmarching' 'graphics' 'introduction' 'inverse' 'mesh' 'multidim' 'numerics' 'sparsity' 'variational' 'wavelet' 'optim'};
a = dir('*_*.m');
for i=1:length(a)
name = a(i).name;
for k=1:length(list_ext)
if not(isempty( findstr(name, list_ext{k}) ))
disp(['---> Publishing ' name ' ...']);
perform_publishing(name(1:end-2));
end
end
end
% zip all toolbox files
perform_toolbox_zipping();
return;
end
if iscell(name)
for i=1:length(name)
disp(['---> Publishing ' name{i} ' ...']);
perform_publishing(name{i}, options);
end
return;
end
if not(isempty(strfind(name, '*')))
a = dir([name '.m']);
name = {};
for i=1:length(a)
name{end+1} = a(i).name(1:end-2);
end
perform_publishing(name, options);
return;
end
%% set up path
% directory where the wavelet-tour web site is
repweb = getoptions(options, 'rep', '../html/');
% directory where the specific publishing is made
rep = [repweb name '/'];
if not(exist(rep))
mkdir(rep);
end
% directory for the exercices to be stored
repprivate = getoptions(options, 'repprivate', 'private-svg/');
reppriv = [repweb repprivate name '/'];
if not(exist(reppriv))
mkdir(reppriv);
end
% open files
fid = fopen([name '.m'], 'rt');
fidout = fopen([repweb 'index.m'], 'wt');
if fid<0
error(['Cannot open ' name '.m.']);
end
% copy style files
if 0
copyfile([repweb 'style.css '],[rep 'style.css']);
else
str = ['cp ' repweb 'style.css ' rep 'style.css'];
% system( str );
end
%% First pre-process the file for publishing
exo_num = 0;
% output_line(fidout, '% special publishing token\npublishing_time = 1;\n\n');
while true
s = fgets(fid);
if not(isstr(s))
break;
end
if exo_mode(s)
% SPECIAL EXERCICE MODE
exo_num = exo_num + 1;
% Create a specific
process_exercice(fid, fidout, exo_num, repweb, reppriv, name);
elseif cmt_mode(s)
% SPECIAL CMT MODE
process_comment(fid);
elseif header_mode(s)
% SPECIAL header more
process_header(fidout, s);
else
s = strrep(s,'\','\\');
output_line(fidout, s);
end
end
fclose(fid);
fclose(fidout);
%% do the publishing
opts.format = getoptions(options, 'format', 'html');
if not(strcmp(opts.format, 'latex'))
opts.stylesheet = getoptions(options, 'stylesheet', [repweb 'nt.xsl']);
opts.stylesheet = [pwd '/' opts.stylesheet];
end
filename = [repweb 'index.m'];
opts.outputDir = [pwd '/' rep];
% opts.format = 'xml';
path(repweb, path);
file = publish('index.m',opts);
% web(file);
% delete([repweb 'exo*.m']);
% delete([repweb 'index.m']);
% path(repweb, path);
% file = publish('index.m',opts);
disp('Performing online publishing (might take some time) ...');
perform_online_publishing(name);
%%
function output_line(fid,s)
s = strrep(s,'%','%%');
fprintf(fid, s);
%%
function r = cmt_mode(s)
r = (length(s)>4 && strcmp(s(1:4),'%CMT'));
%%
function r = exo_mode(s)
r = (length(s)>4 && strcmp(s(1:4),'%EXO'));
%%
function r = header_mode(s)
r = (length(s)>28 && strcmp(s(1:28),'perform_toolbox_installation'));
%%
function process_header(fidout, s)
tbx = {};
if findstr(s, 'signal')
tbx{end+1} = 'signal';
end
if findstr(s, 'general')
tbx{end+1} = 'general';
end
if findstr(s, 'graph')
tbx{end+1} = 'graph';
end
if findstr(s, 'wavelet_meshes')
tbx{end+1} = 'wavelet_meshes';
end
if findstr(s, 'additional')
tbx{end+1} = 'additional';
end
output_line(fidout, '%% Installing toolboxes and setting up the path.\n\n');
% output_line(fidout, '%%\n%<? include ''../nt.sty''; ?>\n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% You need to download the following files: \n');
for i=1:length(tbx)
output_line(fidout, ['% <../toolbox_' tbx{i} '.zip ' tbx{i} ' toolbox>']);
if i<length(tbx)-1
output_line(fidout, ', \n');
elseif i==length(tbx)-1
output_line(fidout, ' and \n');
else
output_line(fidout, '.\n');
end
end
output_line(fidout, '\n%%\n');
output_line(fidout, '% You need to unzip these toolboxes in your working directory, so\n');
output_line(fidout, '% that you have \n');
for i=1:length(tbx)
output_line(fidout, ['% |toolbox_' tbx{i} '|']);
if i<length(tbx)-1
output_line(fidout, ', \n');
elseif i==length(tbx)-1
output_line(fidout, ' and \n');
else
output_line(fidout, '\n');
end
end
output_line(fidout, '% in your directory.\n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% *For Scilab user:* you must replace the Matlab comment ''%'' by its Scilab\n');
output_line(fidout, '% counterpart ''//''.\n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% *Recommandation:* You should create a text file named for instance |numericaltour.sce| (in Scilab) or |numericaltour.m| (in Matlab) to write all the\n');
output_line(fidout, '% Scilab/Matlab command you want to execute. Then, simply run |exec(''numericaltour.sce'');| (in Scilab) or |numericaltour;| (in Matlab) to run the commands. \n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% Execute this line only if you are using Matlab.\n\n');
output_line(fidout, 'getd = @(p)path(p,path); % scilab users must *not* execute this\n\n');
output_line(fidout, '%%\n');
output_line(fidout, '% Then you can add the toolboxes to the path.\n\n');
for i=1:length(tbx)
output_line(fidout, ['getd(''toolbox_' tbx{i} '/'');\n']);
end
%%
function process_comment(fid)
while true
s = fgets(fid);
if not(isstr(s)) || cmt_mode(s)
break;
end
end
%%
function process_exercice(fid, fidout, exo_num, rep, reppriv, curname)
% create a new file
% The m file is created and executed in rep
% and also copied to reppriv.
name = ['exo' num2str(exo_num)];
filename = [name '.m'];
fidexo = fopen([rep filename], 'wt');
output_line(fidout, ['%%\n% _Exercice ' num2str(exo_num) ':_' ]);
output_line(fidout, [' (the solution is <../missing-exo.html ' filename '>)\n']);
% process files
while true
s = fgets(fid);
if not(isstr(s)) || exo_mode(s)
break;
end
s = strrep(s,'#',num2str(exo_num));
s = strrep(s,'\','\\');
if length(s)>1 && strcmp(s(1:2), '%%')
s = s(2:end);
output_line(fidout, s);
else
output_line(fidexo, s);
end
end
output_line(fidout, ['\n' name ';\n']);
fclose(fidexo);
if 0
copyfile([rep filename],[reppriv filename]);
else
system(['cp ' rep filename ' ' reppriv filename]);
end
|
github
|
alex-delalande/numerical-tours-master
|
perform_scilab_conversion.m
|
.m
|
numerical-tours-master/matlab/toolbox_publishing/perform_scilab_conversion.m
| 2,210 |
utf_8
|
530502896e21ccb55e21856289190c35
|
function perform_scilab_conversion(name, outdir, toolbox_dir)
% perform_scilab_conversion - convert a matlab file to scilab
%
% perform_scilab_conversion(name);
%
% If name is empty, process all the files.
%
% Copyright (c) 2008 Gabriel Peyre
if nargin<2
outdir = '../scilab/';
end
if nargin<3
toolbox_dir = '../matlab/';
end
if nargin<1 || isempty(name)
% back processing
list_ext = {'coding_' 'introduction_' 'image_' 'audio_' 'wavelet_' 'sparsity_' 'cs_' ...
'denoising_' 'inverse_' 'graphics_' 'multidim_' 'meshproc_' 'meshdeform_' ...
'meshwav_' 'variational_' 'fastmarching_'};
a = dir('*_*.m');
for i=1:length(a)
name = a(i).name;
for k=1:length(list_ext)
if not(isempty( findstr(name, list_ext{k}) ))
disp(['---> Translating ' name ' ...']);
perform_scilab_conversion(name(1:end-2));
end
end
end
return;
end
fid = fopen([name '.m'], 'rt');
fidout = fopen([outdir name '.sce'], 'wt');
if fid<0
error(['Cannot open ' name '.m.']);
end
str1 = {'%' '\' 'getd(''' };
str2 = {'//' '\\' ['getd(''' toolbox_dir] };
while true
s = fgets(fid);
if s<0
break;
end
% remove comments and stufs
for i=1:length(str1)
s = strrep(s,str1{i},str2{i});
end
makeoutput = 1;
if length(s)>5 && strcmp(s(1:6), 'getd =')
makeoutput = 0;
end
if length(s)>28 && strcmp(s(1:28), 'perform_toolbox_installation')
process_header(fidout, s);
makeoutput = 0;
end
% write output
if makeoutput
fprintf(fidout, s);
end
end
fclose(fid);
fclose(fidout);
%%
function process_header(fidout, s)
tbx = {};
if findstr(s, 'signal')
tbx{end+1} = 'signal';
end
if findstr(s, 'general')
tbx{end+1} = 'general';
end
if findstr(s, 'graph')
tbx{end+1} = 'graph';
end
if findstr(s, 'wavelet_meshes')
tbx{end+1} = 'wavelet_meshes';
end
if findstr(s, 'additional')
tbx{end+1} = 'additional';
end
for i=1:length(tbx)
output_line(fidout, ['getd(''toolbox_' tbx{i} '/'');\n']);
end
%%
function output_line(fid,s)
s = strrep(s,'%','%%');
fprintf(fid, s);
|
github
|
alex-delalande/numerical-tours-master
|
compute_butterfly_neighbors.m
|
.m
|
numerical-tours-master/matlab/toolbox_wavelet_meshes/compute_butterfly_neighbors.m
| 1,398 |
utf_8
|
0a690efe10cc4cbba37565df43f15a2f
|
function [e,v,g] = compute_butterfly_neighbors(k, nj)
% compute_butterfly_neighbors - compute local neighbors of a vertex
%
% [e,v,g] = compute_butterfly_neighbors(k, nj);
%
% This is for internal use.
%
% e are the 2 direct edge neighbors
% v are the 2 indirect neighbors
% g are the fare neighbors
%
% You need to provide:
% for e: vring, e2f
% for v: fring
% for g: facej
%
% Copyright (c) 2007 Gabriel Peyre
global vring e2f fring facej;
% find the 2 edges in the fine subdivition
vr = vring{k};
I = find(vr<=nj);
e = vr(I);
% find the coarse faces associated to the edge e
f = [e2f(e(1),e(2)) e2f(e(2),e(1))];
% symmetrize for boundary faces ...
f(f==-1) = f(3 - find(f==-1));
if nargout>1
F1 = mysetdiff(fring{f(1)}, f(2));
F2 = mysetdiff(fring{f(2)}, f(1));
% symmetrize for boundary faces
F1 = [F1 repmat(f(1), 1, 3-length(F1))];
F2 = [F2 repmat(f(2), 1, 3-length(F2))];
v = [ mysetdiff( facej(:,f(1)), e ) mysetdiff( facej(:,f(2)), e ) ];
if nargout>2
d = [v, e];
g = [setdiff( facej(:,F1(1)),d ), ...
mysetdiff( facej(:,F1(2)),d ), ...
mysetdiff( facej(:,F2(1)),d ), ...
mysetdiff( facej(:,F2(2)),d ) ];
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = mysetdiff(a,b)
% removed in a entries equal to entries in b
for s=b
a(a==s) = [];
end
|
github
|
alex-delalande/numerical-tours-master
|
load_spherical_function.m
|
.m
|
numerical-tours-master/matlab/toolbox_wavelet_meshes/load_spherical_function.m
| 2,090 |
utf_8
|
fa00de26d8ccf7c2c8363fafa5f729dd
|
function f = load_spherical_function(name, pos, options)
% load_spherical_function - load a function on the sphere
%
% f = load_spherical_function(name, pos, options);
%
% Copyright (c) 2007 Gabriel Peyre
if iscell(pos)
pos = pos{end};
end
if size(pos,1)>size(pos,2)
pos = pos';
end
x = pos(1,:); x = x(:);
M = [];
if not(isstr(name))
M = name;
name = 'image';
end
switch name
case 'linear'
f = x;
case 'cos'
f = cos(6*pi*x);
case 'singular'
f = abs(x).^.4;
case 'image'
name = getoptions(options, 'image_name', 'lena');
if isempty(M)
M = load_image(name);
q = size(M,1);
q = min(q,512);
M = crop(M,q);
M = perform_blurring(M,4);
end
f = perform_spherical_interpolation(pos,M);
case 'etopo'
resol = 15;
fname = ['ETOPO' num2str(resol)];
fid = fopen(fname, 'rb');
if fid<0
error('Unable to read ETOPO file');
end
s = [360*(60/resol), 180*(60/resol)];
M = fread(fid, Inf, 'short');
M = reshape(M, s(1),s(2) );
fclose(fid);
f = perform_spherical_interpolation(pos,M, 0);
case {'earth' 'earth-grad'}
filename = 'earth-bw';
M = double( load_image(filename) );
M = perform_blurring(M,4);
if strcmp(name, 'earth-grad')
G = grad(M);
M = sqrt(sum(G.^2,3));
M = perform_blurring(M,15);
end
f = perform_spherical_interpolation(pos,M,0);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function f = perform_spherical_interpolation(pos,M,center)
if nargin<3
center = 1;
end
qx = size(M,1);
qy = size(M,2);
Y = atan2(pos(2,:),pos(1,:))/(2*pi) + 1/2;
if center
X = acos(pos(3,:))/(2*pi) + 1/4;
else
X = acos(pos(3,:))/(pi);
end
x = linspace(0,1,qx);
y = linspace(0,1,qy);
f = interp2( y,x,M, Y(:),X(:) );
|
github
|
alex-delalande/numerical-tours-master
|
perform_spherial_planar_sampling.m
|
.m
|
numerical-tours-master/matlab/toolbox_wavelet_meshes/perform_spherial_planar_sampling.m
| 2,981 |
utf_8
|
5bfd95a6221f7c73d61eab4013f13321
|
function posw = perform_spherial_planar_sampling(pos_sphere, sampling_type, options)
% perform_spherial_planar_sampling - project sampling location from sphere to a square
%
% posw = perform_spherial_planar_sampling(pos_sphere, type)
%
% 'type' can be 'area' or 'gnomonic'.
%
% This is used to produced spherical geometry images.
% The sampling is first projected onto an octahedron and then unfolded on
% a square.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
sampling_type = 'area';
end
% all 3-tuple of {-1,1}
a = [-1 1];
[X,Y,Z] = meshgrid(a,a,a);
anchor_2d = {};
anchor_3d = {};
for i=1:8
x = X(i); y = Y(i); z = Z(i);
a2d = []; a3d = [];
if z>0
a2d = [a2d, [0;0]];
else
a2d = [a2d, [x;y]];
end
a2d = [a2d, [x;0]];
a2d = [a2d, [0;y]];
anchor_2d{i} = a2d;
a3d = [a3d, [0;0;z]];
a3d = [a3d, [x;0;0]];
a3d = [a3d, [0;y;0]];
anchor_3d{i} = a3d;
end
pos = pos_sphere;
n = size(pos, 2);
posw = zeros(2,n);
for s = 1:8
x = X(s); y = Y(s); z = Z(s);
anc2d = anchor_2d{s};
anc3d = anchor_3d{s};
I = find( signe(pos(1,:))==x & signe(pos(2,:))==y & signe(pos(3,:))==z );
posI = pos(:,I);
nI = length(I);
if strcmp(sampling_type, 'area')
% find the area of the 3 small triangles
p1 = repmat(anc3d(:,1), 1, nI);
p2 = repmat(anc3d(:,2), 1, nI);
p3 = repmat(anc3d(:,3), 1, nI);
a1 = compute_spherical_area( posI, p2, p3 );
a2 = compute_spherical_area( posI, p1, p3 );
a3 = compute_spherical_area( posI, p1, p2 );
% barycentric coordinates
a = a1+a2+a3;
% aa = compute_spherical_area( p1, p2, p3 );
a1 = a1./a; a2 = a2./a; a3 = a3./a;
elseif strcmp(sampling_type, 'gnomonic')
% we are searching for a point y=b*x (projection on the triangle)
% such that : a1*anc3d(:,1)+a2*anc3d(:,2)+a3*anc3d(:,3)-b*x=0
% a1+a2+a3=1
a1 = zeros(1,nI); a2 = a1; a3 = a1;
for i=1:nI
x = posI(:,i);
M = [1 1 1 0; anc3d(:,1), anc3d(:,2), anc3d(:,3), x];
a = M\[1;0;0;0];
a1(i) = a(1);
a2(i) = a(2);
a3(i) = a(3);
end
else
error('Unknown projection method.');
end
posw(:,I) = anc2d(:,1)*a1 + anc2d(:,2)*a2 + anc2d(:,3)*a3;
end
function y = signe(x)
y = double(x>=0)*2-1;
function A = compute_spherical_area( p1, p2, p3 )
% length of the sides of the triangles :
% cos(a)=p1*p2
a = acos( dotp(p2,p3) );
b = acos( dotp(p1,p3) );
c = acos( dotp(p1,p2) );
s = (a+b+c)/2;
% use L'Huilier's Theorem
% tand(E/4)^2 = tan(s/2).*tan( (s-a)/2 ).*tan( (s-b)/2 ).*tan( (s-c)/2 )
E = tan(s/2).*tan( (s-a)/2 ).*tan( (s-b)/2 ).*tan( (s-c)/2 );
A = 4*atan( sqrt( E ) );
A = real(A);
function d = dotp(x,y)
d = x(1,:).*y(1,:) + x(2,:).*y(2,:) + x(3,:).*y(3,:);
|
github
|
alex-delalande/numerical-tours-master
|
load_image.m
|
.m
|
numerical-tours-master/matlab/toolbox_wavelet_meshes/toolbox/load_image.m
| 19,503 |
utf_8
|
16a3a912ce98f3734882ac9fe80494c2
|
function M = load_image(type, n, options)
% load_image - load benchmark images.
%
% M = load_image(name, n, options);
%
% name can be:
% Synthetic images:
% 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line',
% 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle',
% 'parabola', 'sin', 'phantom', 'circ_oscil',
% 'fnoise' (1/f^alpha noise).
% Natural images:
% 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own.
%
% Copyright (c) 2004 Gabriel Peyre
if nargin<2
n = 512;
end
options.null = 0;
type = lower(type);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% parameters for geometric objects
eta = 0.1; % translation
gamma = 1/sqrt(2); % slope
if isfield( options, 'eta' )
eta = options.eta;
end
if isfield( options, 'gamma' )
eta = options.gamma;
end
if isfield( options, 'radius' )
radius = options.radius;
end
if isfield( options, 'center' )
center = options.center;
end
if isfield( options, 'center1' )
center1 = options.center1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for the line, can be vertical / horizontal / diagonal / any
if strcmp(type, 'line_vertical')
eta = 0.5; % translation
gamma = 0; % slope
elseif strcmp(type, 'line_horizontal')
eta = 0.5; % translation
gamma = Inf; % slope
elseif strcmp(type, 'line_diagonal')
eta = 0; % translation
gamma = 1; % slope
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% for some blurring
sigma = 0;
if isfield(options, 'sigma')
sigma = options.sigma;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch lower(type)
case {'letter-x' 'letter-v' 'letter-z' 'letter-y'}
if isfield(options, 'radius')
r = options.radius;
else
r = 10;
end
M = create_letter(type(8), r, n);
case 'l'
r1 = [.1 .1 .3 .9];
r2 = [.1 .1 .9 .4];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) );
case 'ellipse'
c1 = [0.15 0.5];
c2 = [0.85 0.5];
if isfield(options, 'eccentricity')
eccentricity = options.eccentricity;
else
eccentricity = 1.3;
end
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2);
M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) );
case 'ellipse-thin'
options.eccentricity = 1.06;
M = load_image('ellipse', n, options);
case 'ellipse-fat'
options.eccentricity = 1.3;
M = load_image('ellipse', n, options);
case 'square-tube'
if isfield(options, 'tube_width')
w = options.tube_width;
else
w = 0.06;
end
c1 = [.25 .5];
c2 = [.75 .5];
r1 = [c1 c1] + .18*[-1 -1 1 1];
r2 = [c2 c2] + .18*[-1 -1 1 1];
r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w];
M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) );
case 'square-tube-1'
options.tube_width = 0.03;
M = load_image('square-tube', n, options);
case 'square-tube-2'
options.tube_width = 0.06;
M = load_image('square-tube', n, options);
case 'square-tube-3'
options.tube_width = 0.09;
M = load_image('square-tube', n, options);
case 'polygon'
if isfield(options, 'nb_points')
nb_points = options.nb_points;
else
nb_points = 9;
end
if isfield(options, 'scaling')
scaling = options.scaling;
else
scaling = 1;
end
theta = sort( rand(nb_points,1)*2*pi );
radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93);
points = [cos(theta) sin(theta)] .* repmat(radius, 1,2);
points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:);
M = draw_polygons(zeros(n),0.8,{points'});
[x,y] = ind2sub(size(M),find(M));
p = 100; m = length(x);
lambda = linspace(0,1,p);
X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]);
Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]);
I = round(X) + (round(Y)-1)*n;
M = zeros(n); M(I) = 1;
case 'polygon-8'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-10'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'polygon-12'
options.nb_points = 8;
M = load_image('polygon', n, options);
case 'pacman'
if isfield(options, 'theta')
theta = options.theta;
else
theta = 30 * 2*pi/360;
end
options.radius = 0.45;
M = load_image('disk', n, options);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
T =atan2(Y,X);
M = M .* (1-(abs(T)<theta/2));
case 'square-hole'
options.radius = 0.45;
M = load_image('disk', n, options);
options.scaling = 0.5;
M = M - load_image('polygon-10', n, options);
case 'grid-circles'
if isempty(n)
n = 256;
end
if isfield(options, 'frequency')
f = options.frequency;
else
f = 30;
end
if isfield(options, 'width')
eta = options.width;
else
eta = 0.3;
end
x = linspace(-n/2,n/2,n) - round(n*0.03);
y = linspace(0,n,n);
[Y,X] = meshgrid(y,x);
R = sqrt(X.^2+Y.^2);
theta = 0.05*pi/2;
X1 = cos(theta)*X+sin(theta)*Y;
Y1 = -sin(theta)*X+cos(theta)*Y;
A1 = abs(cos(2*pi*R/f))<eta;
A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta );
M = A1;
M(X1>0) = A2(X1>0);
case 'chessboard1'
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (2*(Y>=0)-1).*(2*(X>=0)-1);
case 'chessboard'
if ~isfield( options, 'width' )
width = round(n/16);
else
width = options.width;
end
[Y,X] = meshgrid(0:n-1,0:n-1);
M = mod( floor(X/width)+floor(Y/width), 2 ) == 0;
case 'square'
if ~isfield( options, 'radius' )
radius = 0.6;
end
x = -1:2/(n-1):1;
[Y,X] = meshgrid(x,x);
M = max( abs(X),abs(Y) )<radius;
case 'squareregular'
M = rescale(load_image('square',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'regular1'
options.alpha = 1;
M = load_image('fnoise',n,options);
case 'regular2'
options.alpha = 2;
M = load_image('fnoise',n,options);
case 'regular3'
options.alpha = 3;
M = load_image('fnoise',n,options);
case 'sparsecurves'
options.alpha = 3;
M = load_image('fnoise',n,options);
M = rescale(M);
ncurves = 3;
M = cos(2*pi*ncurves);
case 'square_texture'
M = load_image('square',n);
M = rescale(M);
% make a texture patch
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta );
case 'oscillatory_texture'
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
theta = pi/3;
x = cos(theta)*X + sin(theta)*Y;
c = [0.3,0.4]; r = 0.2;
I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 );
eta = 3/n; lambda = 0.3;
M = sin( x * 2*pi / eta );
case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'}
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
if gamma~=Inf
M = (X-eta) - gamma*Y < 0;
else
M = (Y-eta) < 0;
end
case 'grating'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
if isfield(options, 'theta')
theta = options.theta;
else
theta = 0.2;
end
if isfield(options, 'freq')
freq = options.freq;
else
freq = 0.2;
end
X = cos(theta)*X + sin(theta)*Y;
M = sin(2*pi*X/freq);
case 'disk'
if ~isfield( options, 'radius' )
radius = 0.35;
end
if ~isfield( options, 'center' )
center = [0.5, 0.5]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'diskregular'
M = rescale(load_image('disk',n,options));
if not(isfield(options, 'alpha'))
options.alpha = 3;
end
S = load_image('fnoise',n,options);
M = M + rescale(S,-0.3,0.3);
case 'quarterdisk'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
case 'fading_contour'
if ~isfield( options, 'radius' )
radius = 0.95;
end
if ~isfield( options, 'center' )
center = -[0.1, 0.1]; % center of the circle
end
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
theta = 2/pi*atan2(Y,X);
h = 0.5;
M = exp(-(1-theta).^2/h^2).*M;
case '3contours'
radius = 1.3;
center = [-1, 1];
radius1 = 0.8;
center1 = [0, 0];
x = 0:1/(n-1):1;
[Y,X] = meshgrid(x,x);
f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2;
f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2;
M = f1 + 0.5*f2.*(1-f1);
case 'line_circle'
gamma = 1/sqrt(2);
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
M1 = double( X>gamma*Y+0.25 );
M2 = X.^2 + Y.^2 < 0.6^2;
M = 20 + max(0.5*M1,M2) * 216;
case 'fnoise'
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
if isfield(options, 'alpha')
alpha = options.alpha;
else
alpha = 1;
end
M = gen_noisy_image(n,alpha);
case 'gaussiannoise'
% generate an image of filtered noise with gaussian
if isfield(options, 'sigma')
sigma = options.sigma;
else
sigma = 10;
end
M = randn(n);
m = 51;
h = compute_gaussian_filter([m m],sigma/(4*n),[n n]);
M = perform_convolution(M,h);
return;
case {'bwhorizontal','bwvertical','bwcircle'}
[Y,X] = meshgrid(0:n-1,0:n-1);
if strcmp(type, 'bwhorizontal')
d = X;
elseif strcmp(type, 'bwvertical')
d = Y;
elseif strcmp(type, 'bwcircle')
d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 );
end
if isfield(options, 'stripe_width')
stripe_width = options.stripe_width;
else
stripe_width = 5;
end
if isfield(options, 'black_prop')
black_prop = options.black_prop;
else
black_prop = 0.5;
end
M = double( mod( d/(2*stripe_width),1 )>=black_prop );
case 'parabola'
% curvature
if isfield(options, 'c')
c = options.c;
else
c = 0.1;
end
% angle
if isfield(options, 'theta');
theta = options.theta;
else
theta = pi/sqrt(2);
end
x = -0.5:1/(n-1):0.5;
[Y,X] = meshgrid(x,x);
Xs = X*cos(theta) + Y*sin(theta);
Y =-X*sin(theta) + Y*cos(theta); X = Xs;
M = Y>c*X.^2;
case 'sin'
[Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1);
M = Y >= 0.6*cos(pi*X);
M = double(M);
case 'circ_oscil'
x = linspace(-1,1,n);
[Y,X] = meshgrid(x,x);
R = sqrt(X.^2+Y.^2);
M = cos(R.^3*50);
case 'phantom'
M = phantom(n);
case 'periodic_bumps'
if isfield(options, 'nbr_periods')
nbr_periods = options.nbr_periods;
else
nbr_periods = 8;
end
if isfield(options, 'theta')
theta = options.theta;
else
theta = 1/sqrt(2);
end
if isfield(options, 'skew')
skew = options.skew;
else
skew = 1/sqrt(2);
end
A = [cos(theta), -sin(theta); sin(theta), cos(theta)];
B = [1 skew; 0 1];
T = B*A;
x = (0:n-1)*2*pi*nbr_periods/(n-1);
[Y,X] = meshgrid(x,x);
pos = [X(:)'; Y(:)'];
pos = T*pos;
X = reshape(pos(1,:), n,n);
Y = reshape(pos(2,:), n,n);
M = cos(X).*sin(Y);
case 'noise'
if isfield(options, 'sigma')
sigma = options.sigma;
else
sigma = 1;
end
M = randn(n);
otherwise
ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'};
for i=1:length(ext)
name = [type '.' ext{i}];
if( exist(name) )
M = imread( name );
M = double(M);
if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2
M = image_resize(M,n,n);
end
return;
end
end
error( ['Image ' type ' does not exists.'] );
end
M = double(M);
if sigma>0
h = compute_gaussian_filter( [9 9], sigma/(2*n), [n n]);
M = perform_convolution(M,h);
end
M = rescale(M) * 256;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = create_letter(a, r, n)
c = 0.2;
p1 = [c;c];
p2 = [c; 1-c];
p3 = [1-c; 1-c];
p4 = [1-c; c];
p4 = [1-c; c];
pc = [0.5;0.5];
pu = [0.5; c];
switch a
case 'x'
point_list = { [p1 p3] [p2 p4] };
case 'z'
point_list = { [p2 p3 p1 p4] };
case 'v'
point_list = { [p2 pu p3] };
case 'y'
point_list = { [p2 pc pu] [pc p3] };
end
% fit image
for i=1:length(point_list)
a = point_list{i}(2:-1:1,:);
a(1,:) = 1-a(1,:);
point_list{i} = round( a*(n-1)+1 );
end
M = draw_polygons(zeros(n),r,point_list);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_polygons(mask,r,point_list)
sk = mask*0;
for i=1:length(point_list)
pl = point_list{i};
for k=2:length(pl)
sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function sk = draw_line(sk,x1,y1,x2,y2,r)
n = size(sk,1);
[Y,X] = meshgrid(1:n,1:n);
q = 100;
t = linspace(0,1,q);
x = x1*t+x2*(1-t); y = y1*t+y2*(1-t);
if r==0
x = round( x ); y = round( y );
sk( x+(y-1)*n ) = 1;
else
for k=1:q
I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 );
sk(I) = 1;
end
end
function M = gen_noisy_image(n,alpha)
% gen_noisy_image - generate a noisy cloud-like image.
%
% M = gen_noisy_image(n,alpha);
%
% generate an image M whose Fourier spectrum amplitude is
% |M^(omega)| = 1/f^{omega}
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin<1
n = 128;
end
if nargin<2
alpha = 1.5;
end
if mod(n(1),2)==0
x = -n/2:n/2-1;
else
x = -(n-1)/2:(n-1)/2;
end
[Y,X] = meshgrid(x,x);
d = sqrt(X.^2 + Y.^2) + 0.1;
f = rand(n)*2*pi;
M = (d.^(-alpha)) .* exp(f*1i);
% M = real(ifft2(fftshift(M)));
M = ifftshift(M);
M = real( ifft2(M) );
function y = gen_signal_2d(n,alpha)
% gen_signal_2d - generate a 2D C^\alpha signal of length n x n.
% gen_signal_2d(n,alpha) generate a 2D signal C^alpha.
%
% The signal is scale in [0,1].
%
% Copyright (c) 2003 Gabriel Peyr?
% new new method
[Y,X] = meshgrid(0:n-1, 0:n-1);
A = X+Y+1;
B = X-Y+n+1;
a = gen_signal(2*n+1, alpha);
b = gen_signal(2*n+1, alpha);
y = a(A).*b(B);
% M = a(1:n)*b(1:n)';
return;
% new method
h = (-n/2+1):(n/2); h(n/2)=1;
[X,Y] = meshgrid(h,h);
h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2);
h = h .* exp( 2i*pi*rand(n,n) );
h = fftshift(h);
y = real( ifft2(h) );
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
return;
%% old code
y = rand(n,n);
y = y - mean(mean(y));
for i=1:alpha
y = cumsum(cumsum(y)')';
y = y - mean(mean(y));
end
m1 = min(min(y));
m2 = max(max(y));
y = (y-m1)/(m2-m1);
function newimg = image_resize(img,p1,q1,r1)
% image_resize - resize an image using bicubic interpolation
%
% newimg = image_resize(img,nx,ny,nz);
% or
% newimg = image_resize(img,newsize);
%
% Works for 2D, 2D 2 or 3 channels, 3D images.
%
% Copyright (c) 2004 Gabriel Peyr?
if nargin==2
% size specified as an array
q1 = p1(2);
if length(p1)>2
r1 = p1(3);
else
r1 = size(img,3);
end
p1 = p1(1);
end
if nargin<4
r1 = size(img,3);
end
if ndims(img)<2 || ndims(img)>3
error('Works only for grayscale or color images');
end
if ndims(img)==3 && size(img,3)<4
% RVB image
newimg = zeros(p1,q1, size(img,3));
for m=1:size(img,3)
newimg(:,:,m) = image_resize(img(:,:,m), p1, q1);
end
return;
elseif ndims(img)==3
p = size(img,1);
q = size(img,2);
r = size(img,3);
[Y,X,Z] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1), (0:r-1)/(r-1) );
[YI,XI,ZI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1), (0:r1-1)/(r1-1) );
newimg = interp3( Y,X,Z, img, YI,XI,ZI ,'cubic');
return;
end
p = size(img,1);
q = size(img,2);
[Y,X] = meshgrid( (0:q-1)/(q-1), (0:p-1)/(p-1) );
[YI,XI] = meshgrid( (0:q1-1)/(q1-1), (0:p1-1)/(p1-1) );
newimg = interp2( Y,X, img, YI,XI ,'cubic');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function M = draw_rectangle(r,n)
x = linspace(0,1,n);
[Y,X] = meshgrid(x,x);
M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
|
github
|
alex-delalande/numerical-tours-master
|
check_face_vertex.m
|
.m
|
numerical-tours-master/matlab/toolbox_wavelet_meshes/toolbox/check_face_vertex.m
| 646 |
utf_8
|
fe3c5da3b1ca8f15eb7eed61acfc2259
|
function [vertex,face] = check_face_vertex(vertex,face, options)
% check_face_vertex - check that vertices and faces have the correct size
%
% [vertex,face] = check_face_vertex(vertex,face);
%
% Copyright (c) 2007 Gabriel Peyre
vertex = check_size(vertex);
face = check_size(face);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function a = check_size(a)
if isempty(a)
return;
end
if size(a,1)>size(a,2)
a = a';
end
if size(a,1)<3 && size(a,2)==3
a = a';
end
if size(a,1)<=3 && size(a,2)>=3 && sum(abs(a(:,3)))==0
% for flat triangles
a = a';
end
if size(a,1)~=3 && size(a,1)~=4
error('face or vertex is not of correct size');
end
|
github
|
alex-delalande/numerical-tours-master
|
compute_mesh_weight.m
|
.m
|
numerical-tours-master/matlab/toolbox_wavelet_meshes/toolbox/compute_mesh_weight.m
| 2,820 |
utf_8
|
c90377b7ee516f5f952ce8c31dcfd43b
|
function W = compute_mesh_weight(vertex,face,type,options)
% compute_mesh_weight - compute a weight matrix
%
% W = compute_mesh_weight(vertex,face,type,options);
%
% W is sparse weight matrix and W(i,j)=0 is vertex i and vertex j are not
% connected in the mesh.
%
% type is either
% 'combinatorial': W(i,j)=1 is vertex i is conntected to vertex j.
% 'distance': W(i,j) = 1/d_ij^2 where d_ij is distance between vertex
% i and j.
% 'conformal': W(i,j) = cot(alpha_ij)+cot(beta_ij) where alpha_ij and
% beta_ij are the adjacent angle to edge (i,j)
%
% If options.normalize=1, the the rows of W are normalize to sum to 1.
%
% Copyright (c) 2007 Gabriel Peyre
options.null = 0;
[vertex,face] = check_face_vertex(vertex,face);
nface = size(face,1);
n = max(max(face));
if isfield(options, 'verb')
verb = options.verb;
else
verb = n>5000;
end
if nargin<3
type = 'conformal';
end
switch lower(type)
case 'combinatorial'
W = triangulation2adjacency(face);
case 'distance'
W = my_euclidean_distance(triangulation2adjacency(face),vertex);
W(W>0) = 1./W(W>0);
W = (W+W')/2;
case 'conformal'
% conformal laplacian
W = sparse(n,n);
ring = compute_vertex_face_ring(face);
for i = 1:n
if verb
progressbar(i,n);
end
for b = ring{i}
% b is a face adjacent to a
bf = face(:,b);
% compute complementary vertices
if bf(1)==i
v = bf(2:3);
elseif bf(2)==i
v = bf([1 3]);
elseif bf(3)==i
v = bf(1:2);
else
error('Problem in face ring.');
end
j = v(1); k = v(2);
vi = vertex(:,i);
vj = vertex(:,j);
vk = vertex(:,k);
% angles
alpha = myangle(vk-vi,vk-vj);
beta = myangle(vj-vi,vj-vk);
% add weight
W(i,j) = W(i,j) + cot( alpha );
W(i,k) = W(i,k) + cot( beta );
end
end
otherwise
error('Unknown type.')
end
if isfield(options, 'normalize') && options.normalize==1
W = diag(sum(W,2).^(-1)) * W;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function beta = myangle(u,v);
du = sqrt( sum(u.^2) );
dv = sqrt( sum(v.^2) );
du = max(du,eps); dv = max(dv,eps);
beta = acos( sum(u.*v) / (du*dv) );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function W = my_euclidean_distance(A,vertex)
if size(vertex,1)<size(vertex,2)
vertex = vertex';
end
[i,j,s] = find(sparse(A));
d = sum( (vertex(i,:) - vertex(j,:)).^2, 2);
W = sparse(i,j,d);
|
github
|
ai-med/QuickNATv2-master
|
QuickNAT_Train.m
|
.m
|
QuickNATv2-master/QuickNAT_Networks/QuickNAT_Train.m
| 18,894 |
utf_8
|
1ee46a55261e93f102e78ae6ec3f1929
|
function [net, info] = QuickNAT_Train(imdb, netF, inpt, varargin)
% some common options
trainer = @cnn_train_dag_seg;
opts.train.extractStatsFn = @extract_stats_segmentation_Mod;
opts.train.batchSize = 4;
opts.train.numEpochs = 15;
opts.train.continue = true ;
opts.train.gpus = [2] ;
opts.train.learningRate = [1e-1*ones(1, 5), 1e-2*ones(1, 5), 1e-3*ones(1, 5), 1e-4*ones(1,1)];
opts.train.weightDecay = 1e-3;
opts.train.momentum = 0.95;
opts.train.expDir = inpt.expDir;
opts.train.savePlots = false;
opts.train.numSubBatches = 1;
% getBatch options
bopts.useGpu = numel(opts.train.gpus) > 0 ;
opts.border = [8 8 8 8]; % tblr
% augmenting data - Jitter and Fliplr
augData = zeros(size(imdb.images.data) + [sum(opts.border(1:2)) ...
sum(opts.border(3:4)) 0 0], 'like', imdb.images.data);
augLabels = zeros(size(imdb.images.label) + [sum(opts.border(1:2)) ...
sum(opts.border(3:4)) 0 0], 'like', imdb.images.label);
augData(opts.border(1)+1:end-opts.border(2), ...
opts.border(3)+1:end-opts.border(4), :, :) = imdb.images.data;
% Mirroring Borders for augData
augData(1:opts.border(1), ...
opts.border(3)+1:end-opts.border(4), :, :) = imdb.images.data(opts.border(1):-1:1, ...
:, :, :);
augData(end-opts.border(2)+1:end, ...
opts.border(3)+1:end-opts.border(4), :, :) = imdb.images.data(end:-1:end-opts.border(2)+1, ...
:, :, :);
augData(:, ...
opts.border(3):-1:1, :, :) = augData(:, ...
opts.border(3)+1:2*opts.border(3), :, :);
augData(:, ...
end-opts.border(4)+1:end, :, :) = augData(:, ...
end-opts.border(4):-1:end-2*opts.border(4)+1, :, :);
% Augmenting Labels
augLabels(opts.border(1)+1:end-opts.border(2), ...
opts.border(3)+1:end-opts.border(4), :, :) = imdb.images.label;
% Mirroring Borders for augLabels
augLabels(1:opts.border(1), ...
opts.border(3)+1:end-opts.border(4), :, :) = imdb.images.label(opts.border(1):-1:1, ...
:, :, :);
augLabels(end-opts.border(2)+1:end, ...
opts.border(3)+1:end-opts.border(4), :, :) = imdb.images.label(end:-1:end-opts.border(2)+1, ...
:, :, :);
augLabels(:, ...
opts.border(3):-1:1, :, :) = augLabels(:, ...
opts.border(3)+1:2*opts.border(3), :, :);
augLabels(:, ...
end-opts.border(4)+1:end, :, :) = augLabels(:, ...
end-opts.border(4):-1:end-2*opts.border(4)+1, :, :);
imdb.images.augData = augData;
imdb.images.augLabels = augLabels;
clear augData augLabels
% organize data
K = 2; % how many examples per domain
trainData = find(imdb.images.set == 1);
valData = find(imdb.images.set == 3);
% debuging code
opts.train.exampleIndices = [trainData(randperm(numel(trainData), K)), valData(randperm(numel(valData), K))];
% opts.train.classesNames = {'sky', 'building', 'road', 'sidewalk', 'fence', 'vegetation', 'pole', 'car', 'sign', 'pedestrian', 'cyclist'};
colorMap = (1/255)*[
128 128 128
128 0 0
128 64 128
0 0 192
64 64 128
128 128 0
192 192 128
64 0 128
192 128 128
64 64 0
0 128 192
128 128 128
128 0 0
128 64 128
0 0 192
64 64 128
128 128 0
192 192 128
64 0 128
192 128 128
64 64 0
0 128 192
128 128 128
128 0 0
128 64 128
0 0 192
64 64 128
128 128 0
];
opts.train.colorMapGT = [0 0 0; colorMap];
opts.train.colorMapEst = colorMap;
% network definition
net = dagnn.DagNN() ;
% Dense Encoder 1
net.addLayer('bn1_1', dagnn.BatchNorm('numChannels', 1), {'input'}, {'bn1_1'}, {'bn1_1f', 'bn1_1b', 'bn1_1m'});
net.addLayer('relu1_1', dagnn.ReLU(), {'bn1_1'}, {'relu1_1'}, {});
net.addLayer('conv1_1', dagnn.Conv('size', [5 5 1 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'relu1_1'}, {'conv1_1'}, {'conv1_1f' 'conv1_1b'});
net.addLayer('concat1_1', dagnn.Concat('dim',3), {'input','conv1_1'}, {'concat1_1'});
net.addLayer('bn1_2', dagnn.BatchNorm('numChannels', 65), {'concat1_1'}, {'bn1_2'}, {'bn1_2f', 'bn1_2b', 'bn1_2m'});
net.addLayer('relu1_2', dagnn.ReLU(), {'bn1_2'}, {'relu1_2'}, {});
net.addLayer('conv1_2', dagnn.Conv('size', [5 5 65 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'relu1_2'}, {'conv1_2'}, {'conv1_2f' 'conv1_2b'});
net.addLayer('concat1_2', dagnn.Concat('dim',3), {'input','conv1_1', 'conv1_2'}, {'concat1_2'});
net.addLayer('bn1_3', dagnn.BatchNorm('numChannels', 129), {'concat1_2'}, {'bn1_3'}, {'bn1_3f', 'bn1_3b', 'bn1_3m'});
net.addLayer('relu1_3', dagnn.ReLU(), {'bn1_3'}, {'relu1_3'}, {});
net.addLayer('conv1_3', dagnn.Conv('size', [1 1 129 64], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'relu1_3'}, {'conv1_3'}, {'conv1_3f' 'conv1_3b'});
net.addLayer('pool1', dagnn.PoolingInd('method', 'max', 'poolSize', [2, 2], 'stride', [2, 2], 'pad', [0 0 0 0]), {'conv1_3'}, {'pool1', 'pool_indices_1', 'sizes_pre_pool_1', 'sizes_post_pool_1'}, {});
% Dense Encoder 2
net.addLayer('bn2_1', dagnn.BatchNorm('numChannels', 64), {'pool1'}, {'bn2_1'}, {'bn2_1f', 'bn2_1b', 'bn2_1m'});
net.addLayer('relu2_1', dagnn.ReLU(), {'bn2_1'}, {'relu2_1'}, {});
net.addLayer('conv2_1', dagnn.Conv('size', [5 5 64 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'relu2_1'}, {'conv2_1'}, {'conv2_1f' 'conv2_1b'});
net.addLayer('concat2_1', dagnn.Concat('dim',3), {'pool1','conv2_1'}, {'concat2_1'});
net.addLayer('bn2_2', dagnn.BatchNorm('numChannels', 128), {'concat2_1'}, {'bn2_2'}, {'bn2_2f', 'bn2_2b', 'bn2_2m'});
net.addLayer('relu2_2', dagnn.ReLU(), {'bn2_2'}, {'relu2_2'}, {});
net.addLayer('conv2_2', dagnn.Conv('size', [5 5 128 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'relu2_2'}, {'conv2_2'}, {'conv2_2f' 'conv2_2b'});
net.addLayer('concat2_2', dagnn.Concat('dim',3), {'pool1','conv2_1', 'conv2_2'}, {'concat2_2'});
net.addLayer('bn2_3', dagnn.BatchNorm('numChannels', 192), {'concat2_2'}, {'bn2_3'}, {'bn2_3f', 'bn2_3b', 'bn2_3m'});
net.addLayer('relu2_3', dagnn.ReLU(), {'bn2_3'}, {'relu2_3'}, {});
net.addLayer('conv2_3', dagnn.Conv('size', [1 1 192 64], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'relu2_3'}, {'conv2_3'}, {'conv2_3f' 'conv2_3b'});
net.addLayer('pool2', dagnn.PoolingInd('method', 'max', 'poolSize', [2, 2], 'stride', [2, 2], 'pad', [0 0 0 0]), {'conv2_3'}, {'pool2', 'pool_indices_2', 'sizes_pre_pool_2', 'sizes_post_pool_2'}, {});
% Dense Encoder 3
net.addLayer('bn3_1', dagnn.BatchNorm('numChannels', 64), {'pool2'}, {'bn3_1'}, {'bn3_1f', 'bn3_1b', 'bn3_1m'});
net.addLayer('relu3_1', dagnn.ReLU(), {'bn3_1'}, {'relu3_1'}, {});
net.addLayer('conv3_1', dagnn.Conv('size', [5 5 64 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'relu3_1'}, {'conv3_1'}, {'conv3_1f' 'conv3_1b'});
net.addLayer('concat3_1', dagnn.Concat('dim',3), {'pool2','conv3_1'}, {'concat3_1'});
net.addLayer('bn3_2', dagnn.BatchNorm('numChannels', 128), {'concat3_1'}, {'bn3_2'}, {'bn3_2f', 'bn3_2b', 'bn3_2m'});
net.addLayer('relu3_2', dagnn.ReLU(), {'bn3_2'}, {'relu3_2'}, {});
net.addLayer('conv3_2', dagnn.Conv('size', [5 5 128 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'relu3_2'}, {'conv3_2'}, {'conv3_2f' 'conv3_2b'});
net.addLayer('concat3_2', dagnn.Concat('dim',3), {'pool2','conv3_1', 'conv3_2'}, {'concat3_2'});
net.addLayer('bn3_3', dagnn.BatchNorm('numChannels', 192), {'concat3_2'}, {'bn3_3'}, {'bn3_3f', 'bn3_3b', 'bn3_3m'});
net.addLayer('relu3_3', dagnn.ReLU(), {'bn3_3'}, {'relu3_3'}, {});
net.addLayer('conv3_3', dagnn.Conv('size', [1 1 192 64], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'relu3_3'}, {'conv3_3'}, {'conv3_3f' 'conv3_3b'});
net.addLayer('pool3', dagnn.PoolingInd('method', 'max', 'poolSize', [2, 2], 'stride', [2, 2], 'pad', [0 0 0 0]), {'conv3_3'}, {'pool3', 'pool_indices_3', 'sizes_pre_pool_3', 'sizes_post_pool_3'}, {});
% Dense Encoder 4
net.addLayer('bn4_1', dagnn.BatchNorm('numChannels', 64), {'pool3'}, {'bn4_1'}, {'bn4_1f', 'bn4_1b', 'bn4_1m'});
net.addLayer('relu4_1', dagnn.ReLU(), {'bn4_1'}, {'relu4_1'}, {});
net.addLayer('conv4_1', dagnn.Conv('size', [5 5 64 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'relu4_1'}, {'conv4_1'}, {'conv4_1f' 'conv4_1b'});
net.addLayer('concat4_1', dagnn.Concat('dim',3), {'pool3','conv4_1'}, {'concat4_1'});
net.addLayer('bn4_2', dagnn.BatchNorm('numChannels', 128), {'concat4_1'}, {'bn4_2'}, {'bn4_2f', 'bn4_2b', 'bn4_2m'});
net.addLayer('relu4_2', dagnn.ReLU(), {'bn4_2'}, {'relu4_2'}, {});
net.addLayer('conv4_2', dagnn.Conv('size', [5 5 128 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'relu4_2'}, {'conv4_2'}, {'conv4_2f' 'conv4_2b'});
net.addLayer('concat4_2', dagnn.Concat('dim',3), {'pool3','conv4_1', 'conv4_2'}, {'concat4_2'});
net.addLayer('bn4_3', dagnn.BatchNorm('numChannels', 192), {'concat4_2'}, {'bn4_3'}, {'bn4_3f', 'bn4_3b', 'bn4_3m'});
net.addLayer('relu4_3', dagnn.ReLU(), {'bn4_3'}, {'relu4_3'}, {});
net.addLayer('conv4_3', dagnn.Conv('size', [1 1 192 64], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'relu4_3'}, {'conv4_3'}, {'conv4_3f' 'conv4_3b'});
net.addLayer('pool4', dagnn.PoolingInd('method', 'max', 'poolSize', [2, 2], 'stride', [2, 2], 'pad', [0 0 0 0]), {'conv4_3'}, {'pool4', 'pool_indices_4', 'sizes_pre_pool_4', 'sizes_post_pool_4'}, {});
% BottleNeck Layers
net.addLayer('conv5', dagnn.Conv('size', [5 5 64 64], 'hasBias', true, 'stride', [1, 1], 'pad', [2 2 2 2]), {'pool4'}, {'conv5'}, {'conv5f' 'conv5b'});
net.addLayer('bn5', dagnn.BatchNorm('numChannels', 64), {'conv5'}, {'bn5'}, {'bn5f', 'bn5b', 'bn5m'});
% Dense Decoder 4
net.addLayer('unpool4x', dagnn.Unpooling(), {'bn5', 'pool_indices_4', 'sizes_pre_pool_4', 'sizes_post_pool_4'}, {'unpool4x'}, {});
net.addLayer('concat4x', dagnn.Concat('dim',3), {'unpool4x','conv4_3'}, {'concat4x'});
net.addLayer('bn4_1x', dagnn.BatchNorm('numChannels', 128), {'concat4x'}, {'bn4_1x'}, {'bn4_1fx', 'bn4_1bx', 'bn4_1mx'});
net.addLayer('relu4_1x', dagnn.ReLU(), {'bn4_1x'}, {'relu4_1x'}, {});
net.addLayer('deconv4_1x', dagnn.Conv('size', [5 5 128 64], 'hasBias', true, 'stride', [1,1], 'pad', [2 2 2 2]), {'relu4_1x'}, {'deconv4_1x'}, {'deconv4_1fx' 'deconv4_1bx'});
net.addLayer('concat4_1x', dagnn.Concat('dim',3), {'concat4x','deconv4_1x'}, {'concat4_1x'});
net.addLayer('bn4_2x', dagnn.BatchNorm('numChannels', 192), {'concat4_1x'}, {'bn4_2x'}, {'bn4_2fx', 'bn4_2bx', 'bn4_2mx'});
net.addLayer('relu4_2x', dagnn.ReLU(), {'bn4_2x'}, {'relu4_2x'}, {});
net.addLayer('deconv4_2x', dagnn.Conv('size', [5 5 192 64], 'hasBias', true, 'stride', [1,1], 'pad', [2 2 2 2]), {'relu4_2x'}, {'deconv4_2x'}, {'deconv4_2fx' 'deconv4_2bx'});
net.addLayer('concat4_2x', dagnn.Concat('dim',3), {'concat4x','deconv4_1x','deconv4_2x'}, {'concat4_2x'});
net.addLayer('bn4_3x', dagnn.BatchNorm('numChannels', 256), {'concat4_2x'}, {'bn4_3x'}, {'bn4_3fx', 'bn4_3bx', 'bn4_3mx'});
net.addLayer('relu4_3x', dagnn.ReLU(), {'bn4_3x'}, {'relu4_3x'}, {});
net.addLayer('deconv4_3x', dagnn.Conv('size', [1 1 256 64], 'hasBias', true, 'stride', [1,1], 'pad', [0 0 0 0]), {'relu4_3x'}, {'deconv4_3x'}, {'deconv4_3fx' 'deconv4_3bx'});
% Dense Decoder 3
net.addLayer('unpool3x', dagnn.Unpooling(), {'deconv4_3x', 'pool_indices_3', 'sizes_pre_pool_3', 'sizes_post_pool_3'}, {'unpool3x'}, {});
net.addLayer('concat3x', dagnn.Concat('dim',3), {'unpool3x','conv3_3'}, {'concat3x'});
net.addLayer('bn3_1x', dagnn.BatchNorm('numChannels', 128), {'concat3x'}, {'bn3_1x'}, {'bn3_1fx', 'bn3_1bx', 'bn3_1mx'});
net.addLayer('relu3_1x', dagnn.ReLU(), {'bn3_1x'}, {'relu3_1x'}, {});
net.addLayer('deconv3_1x', dagnn.Conv('size', [5 5 128 64], 'hasBias', true, 'stride', [1,1], 'pad', [2 2 2 2]), {'relu3_1x'}, {'deconv3_1x'}, {'deconv3_1fx' 'deconv3_1bx'});
net.addLayer('concat3_1x', dagnn.Concat('dim',3), {'concat3x','deconv3_1x'}, {'concat3_1x'});
net.addLayer('bn3_2x', dagnn.BatchNorm('numChannels', 192), {'concat3_1x'}, {'bn3_2x'}, {'bn3_2fx', 'bn3_2bx', 'bn3_2mx'});
net.addLayer('relu3_2x', dagnn.ReLU(), {'bn3_2x'}, {'relu3_2x'}, {});
net.addLayer('deconv3_2x', dagnn.Conv('size', [5 5 192 64], 'hasBias', true, 'stride', [1,1], 'pad', [2 2 2 2]), {'relu3_2x'}, {'deconv3_2x'}, {'deconv3_2fx' 'deconv3_2bx'});
net.addLayer('concat3_2x', dagnn.Concat('dim',3), {'concat3x','deconv3_1x','deconv3_2x'}, {'concat3_2x'});
net.addLayer('bn3_3x', dagnn.BatchNorm('numChannels', 256), {'concat3_2x'}, {'bn3_3x'}, {'bn3_3fx', 'bn3_3bx', 'bn3_3mx'});
net.addLayer('relu3_3x', dagnn.ReLU(), {'bn3_3x'}, {'relu3_3x'}, {});
net.addLayer('deconv3_3x', dagnn.Conv('size', [1 1 256 64], 'hasBias', true, 'stride', [1,1], 'pad', [0 0 0 0]), {'relu3_3x'}, {'deconv3_3x'}, {'deconv3_3fx' 'deconv3_3bx'});
% Dense Decoder 2
net.addLayer('unpool2x', dagnn.Unpooling(), {'deconv3_3x', 'pool_indices_2', 'sizes_pre_pool_2', 'sizes_post_pool_2'}, {'unpool2x'}, {});
net.addLayer('concat2x', dagnn.Concat('dim',3), {'unpool2x','conv2_3'}, {'concat2x'});
net.addLayer('bn2_1x', dagnn.BatchNorm('numChannels', 128), {'concat2x'}, {'bn2_1x'}, {'bn2_1fx', 'bn2_1bx', 'bn2_1mx'});
net.addLayer('relu2_1x', dagnn.ReLU(), {'bn2_1x'}, {'relu2_1x'}, {});
net.addLayer('deconv2_1x', dagnn.Conv('size', [5 5 128 64], 'hasBias', true, 'stride', [1,1], 'pad', [2 2 2 2]), {'relu2_1x'}, {'deconv2_1x'}, {'deconv2_1fx' 'deconv2_1bx'});
net.addLayer('concat2_1x', dagnn.Concat('dim',3), {'concat2x','deconv2_1x'}, {'concat2_1x'});
net.addLayer('bn2_2x', dagnn.BatchNorm('numChannels', 192), {'concat2_1x'}, {'bn2_2x'}, {'bn2_2fx', 'bn2_2bx', 'bn2_2mx'});
net.addLayer('relu2_2x', dagnn.ReLU(), {'bn2_2x'}, {'relu2_2x'}, {});
net.addLayer('deconv2_2x', dagnn.Conv('size', [5 5 192 64], 'hasBias', true, 'stride', [1,1], 'pad', [2 2 2 2]), {'relu2_2x'}, {'deconv2_2x'}, {'deconv2_2fx' 'deconv2_2bx'});
net.addLayer('concat2_2x', dagnn.Concat('dim',3), {'concat2x','deconv2_1x','deconv2_2x'}, {'concat2_2x'});
net.addLayer('bn2_3x', dagnn.BatchNorm('numChannels', 256), {'concat2_2x'}, {'bn2_3x'}, {'bn2_3fx', 'bn2_3bx', 'bn2_3mx'});
net.addLayer('relu2_3x', dagnn.ReLU(), {'bn2_3x'}, {'relu2_3x'}, {});
net.addLayer('deconv2_3x', dagnn.Conv('size', [1 1 256 64], 'hasBias', true, 'stride', [1,1], 'pad', [0 0 0 0]), {'relu2_3x'}, {'deconv2_3x'}, {'deconv2_3fx' 'deconv2_3bx'});
% Dense Decoder 1
net.addLayer('unpool1x', dagnn.Unpooling(), {'deconv2_3x', 'pool_indices_1', 'sizes_pre_pool_1', 'sizes_post_pool_1'}, {'unpool1x'}, {});
net.addLayer('concat1x', dagnn.Concat('dim',3), {'unpool1x','conv1_3'}, {'concat1x'});
net.addLayer('bn1_1x', dagnn.BatchNorm('numChannels', 128), {'concat1x'}, {'bn1_1x'}, {'bn1_1fx', 'bn1_1bx', 'bn1_1mx'});
net.addLayer('relu1_1x', dagnn.ReLU(), {'bn1_1x'}, {'relu1_1x'}, {});
net.addLayer('deconv1_1x', dagnn.Conv('size', [5 5 128 64], 'hasBias', true, 'stride', [1,1], 'pad', [2 2 2 2]), {'relu1_1x'}, {'deconv1_1x'}, {'deconv1_1fx' 'deconv1_1bx'});
net.addLayer('concat1_1x', dagnn.Concat('dim',3), {'concat1x','deconv1_1x'}, {'concat1_1x'});
net.addLayer('bn1_2x', dagnn.BatchNorm('numChannels', 192), {'concat1_1x'}, {'bn1_2x'}, {'bn1_2fx', 'bn1_2bx', 'bn1_2mx'});
net.addLayer('relu1_2x', dagnn.ReLU(), {'bn1_2x'}, {'relu1_2x'}, {});
net.addLayer('deconv1_2x', dagnn.Conv('size', [5 5 192 64], 'hasBias', true, 'stride', [1,1], 'pad', [2 2 2 2]), {'relu1_2x'}, {'deconv1_2x'}, {'deconv1_2fx' 'deconv1_2bx'});
net.addLayer('concat1_2x', dagnn.Concat('dim',3), {'concat1x','deconv1_1x','deconv1_2x'}, {'concat1_2x'});
net.addLayer('bn1_3x', dagnn.BatchNorm('numChannels', 256), {'concat1_2x'}, {'bn1_3x'}, {'bn1_3fx', 'bn1_3bx', 'bn1_3mx'});
net.addLayer('relu1_3x', dagnn.ReLU(), {'bn1_3x'}, {'relu1_3x'}, {});
net.addLayer('deconv1_3x', dagnn.Conv('size', [1 1 256 64], 'hasBias', true, 'stride', [1,1], 'pad', [0 0 0 0]), {'relu1_3x'}, {'deconv1_3x'}, {'deconv1_3fx' 'deconv1_3bx'});
% Classifier and Losses
net.addLayer('classifier', dagnn.Conv('size', [1 1 64 16], 'hasBias', true, 'stride', [1, 1], 'pad', [0 0 0 0]), {'deconv1_3x'}, {'classifier'}, {'classf' 'classb'});
net.addLayer('prob', dagnn.SoftMax(), {'classifier'}, {'prob'}, {});
net.addLayer('objective1', dagnn.LossSemantic('weights', 1), {'prob','label'}, 'objective1');
net.addLayer('objective2', dagnn.Loss_TVReg('weights', 0), {'prob','label'}, 'objective2');
net.addLayer('objective3', dagnn.LossDice('weights', 1), {'prob','label'}, 'objective3');
% -- end of the network
% do the training!
initNet(net, netF);
net.conserveMemory = false;
info = trainer(net, imdb, @(i,b) getBatch(bopts,i,b), opts.train, 'train', trainData, 'val', valData) ;
end
% function on charge of creating a batch of images + labels
function inputs = getBatch(opts, imdb, batch)
if imdb.images.set(batch(1))==1, % training
sz0 = size(imdb.images.augData);
sz = size(imdb.images.data);
loc = [randi(sz0(1)-sz(1)+1) randi(sz0(2)-sz(2)+1)];
images = imdb.images.augData(loc(1):loc(1)+sz(1)-1, ...
loc(2):loc(2)+sz(2)-1, :, batch);
labels = imdb.images.augLabels(loc(1):loc(1)+sz(1)-1, ...
loc(2):loc(2)+sz(2)-1, :, batch);
% Id = imdb.images.label(:,:,1,:)==13;
% imdb.images.label(:,:,2,:) = single(imdb.images.label(:,:,2,:) + 5.*Id);
else % validating / testing
images = imdb.images.data(:,:,:,batch);
labels = imdb.images.label(:,:,:,batch);
end
if opts.useGpu > 0
images = gpuArray(images);
labels = gpuArray(labels);
end
inputs = {'input', images, 'label', labels} ;
end
function initNet(net, netF)
net.initParams();
% He Initialization for New Layers
for k=1:length(net.layers)
% is a convolution layer?
if(strcmp(class(net.layers(k).block), 'dagnn.Conv'))
f_ind = net.layers(k).paramIndexes(1);
b_ind = net.layers(k).paramIndexes(2);
[h,w,in,out] = size(net.params(f_ind).value);
He_gain = 0.7*sqrt(2/(size(net.params(f_ind).value,1)*size(net.params(f_ind).value,2)*size(net.params(f_ind).value,3))); % sqrt(2/fan_in)
net.params(f_ind).value = He_gain*randn(size(net.params(f_ind).value), 'single');
net.params(f_ind).learningRate = 1;
net.params(f_ind).weightDecay = 1;
net.params(b_ind).value = zeros(size(net.params(b_ind).value), 'single');
net.params(b_ind).learningRate = 0.5;
net.params(b_ind).weightDecay = 1;
end
end
end
|
github
|
ai-med/QuickNATv2-master
|
freezeColors.m
|
.m
|
QuickNATv2-master/QuickNAT_Networks/freezeColors.m
| 9,815 |
utf_8
|
2068d7a4f7a74d251e2519c4c5c1c171
|
function freezeColors(varargin)
% freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3)
%
% Problem: There is only one colormap per figure. This function provides
% an easy solution when plots using different colomaps are desired
% in the same figure.
%
% freezeColors freezes the colors of graphics objects in the current axis so
% that subsequent changes to the colormap (or caxis) will not change the
% colors of these objects. freezeColors works on any graphics object
% with CData in indexed-color mode: surfaces, images, scattergroups,
% bargroups, patches, etc. It works by converting CData to true-color rgb
% based on the colormap active at the time freezeColors is called.
%
% The original indexed color data is saved, and can be restored using
% unfreezeColors, making the plot once again subject to the colormap and
% caxis.
%
%
% Usage:
% freezeColors applies to all objects in current axis (gca),
% freezeColors(axh) same, but works on axis axh.
%
% Example:
% subplot(2,1,1); imagesc(X); colormap hot; freezeColors
% subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc...
%
% Note: colorbars must also be frozen. Due to Matlab 'improvements' this can
% no longer be done with freezeColors. Instead, please
% use the function CBFREEZE by Carlos Adrian Vargas Aguilera
% that can be downloaded from the MATLAB File Exchange
% (http://www.mathworks.com/matlabcentral/fileexchange/24371)
%
% h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar)
%
% For additional examples, see test/test_main.m
%
% Side effect on render mode: freezeColors does not work with the painters
% renderer, because Matlab doesn't support rgb color data in
% painters mode. If the current renderer is painters, freezeColors
% changes it to zbuffer. This may have unexpected effects on other aspects
% of your plots.
%
% See also unfreezeColors, freezeColors_pub.html, cbfreeze.
%
%
% John Iversen ([email protected]) 3/23/05
%
% Changes:
% JRI ([email protected]) 4/19/06 Correctly handles scaled integer cdata
% JRI 9/1/06 should now handle all objects with cdata: images, surfaces,
% scatterplots. (v 2.1)
% JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded)
% JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3)
% JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it.
% JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf)
% JRI 4/7/10 Change documentation for colorbars
% Hidden option for NaN colors:
% Missing data are often represented by NaN in the indexed color
% data, which renders transparently. This transparency will be preserved
% when freezing colors. If instead you wish such gaps to be filled with
% a real color, add 'nancolor',[r g b] to the end of the arguments. E.g.
% freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]),
% where [r g b] is a color vector. This works on images & pcolor, but not on
% surfaces.
% Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes
% attributed in the code.
% Free for all uses, but please retain the following:
% Original Author:
% John Iversen, 2005-10
% [email protected]
appdatacode = 'JRI__freezeColorsData';
[h, nancolor] = checkArgs(varargin);
%gather all children with scaled or indexed CData
cdatah = getCDataHandles(h);
%current colormap
cmap = colormap;
nColors = size(cmap,1);
cax = caxis;
% convert object color indexes into colormap to true-color data using
% current colormap
for hh = cdatah',
g = get(hh);
%preserve parent axis clim
parentAx = getParentAxes(hh);
originalClim = get(parentAx, 'clim');
% Note: Special handling of patches: For some reason, setting
% cdata on patches created by bar() yields an error,
% so instead we'll set facevertexcdata instead for patches.
if ~strcmp(g.Type,'patch'),
cdata = g.CData;
else
cdata = g.FaceVertexCData;
end
%get cdata mapping (most objects (except scattergroup) have it)
if isfield(g,'CDataMapping'),
scalemode = g.CDataMapping;
else
scalemode = 'scaled';
end
%save original indexed data for use with unfreezeColors
siz = size(cdata);
setappdata(hh, appdatacode, {cdata scalemode});
%convert cdata to indexes into colormap
if strcmp(scalemode,'scaled'),
%4/19/06 JRI, Accommodate scaled display of integer cdata:
% in MATLAB, uint * double = uint, so must coerce cdata to double
% Thanks to O Yamashita for pointing this need out
idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors);
else %direct mapping
idx = cdata;
%10/8/09 in case direct data is non-int (e.g. image;freezeColors)
% (Floor mimics how matlab converts data into colormap index.)
% Thanks to D Armyr for the catch
idx = floor(idx);
end
%clamp to [1, nColors]
idx(idx<1) = 1;
idx(idx>nColors) = nColors;
%handle nans in idx
nanmask = isnan(idx);
idx(nanmask)=1; %temporarily replace w/ a valid colormap index
%make true-color data--using current colormap
realcolor = zeros(siz);
for i = 1:3,
c = cmap(idx,i);
c = reshape(c,siz);
c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified)
realcolor(:,:,i) = c;
end
%apply new true-color color data
%true-color is not supported in painters renderer, so switch out of that
if strcmp(get(gcf,'renderer'), 'painters'),
set(gcf,'renderer','zbuffer');
end
%replace original CData with true-color data
if ~strcmp(g.Type,'patch'),
set(hh,'CData',realcolor);
else
set(hh,'faceVertexCData',permute(realcolor,[1 3 2]))
end
%restore clim (so colorbar will show correct limits)
if ~isempty(parentAx),
set(parentAx,'clim',originalClim)
end
end %loop on indexed-color objects
% ============================================================================ %
% Local functions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getCDataHandles -- get handles of all descendents with indexed CData
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hout = getCDataHandles(h)
% getCDataHandles Find all objects with indexed CData
%recursively descend object tree, finding objects with indexed CData
% An exception: don't include children of objects that themselves have CData:
% for example, scattergroups are non-standard hggroups, with CData. Changing
% such a group's CData automatically changes the CData of its children,
% (as well as the children's handles), so there's no need to act on them.
error(nargchk(1,1,nargin,'struct'))
hout = [];
if isempty(h),return;end
ch = get(h,'children');
for hh = ch'
g = get(hh);
if isfield(g,'CData'), %does object have CData?
%is it indexed/scaled?
if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1,
hout = [hout; hh]; %#ok<AGROW> %yes, add to list
end
else %no CData, see if object has any interesting children
hout = [hout; getCDataHandles(hh)]; %#ok<AGROW>
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% getParentAxes -- return handle of axes object to which a given object belongs
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hAx = getParentAxes(h)
% getParentAxes Return enclosing axes of a given object (could be self)
error(nargchk(1,1,nargin,'struct'))
%object itself may be an axis
if strcmp(get(h,'type'),'axes'),
hAx = h;
return
end
parent = get(h,'parent');
if (strcmp(get(parent,'type'), 'axes')),
hAx = parent;
else
hAx = getParentAxes(parent);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% checkArgs -- Validate input arguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [h, nancolor] = checkArgs(args)
% checkArgs Validate input arguments to freezeColors
nargs = length(args);
error(nargchk(0,3,nargs,'struct'))
%grab handle from first argument if we have an odd number of arguments
if mod(nargs,2),
h = args{1};
if ~ishandle(h),
error('JRI:freezeColors:checkArgs:invalidHandle',...
'The first argument must be a valid graphics handle (to an axis)')
end
% 4/2010 check if object to be frozen is a colorbar
if strcmp(get(h,'Tag'),'Colorbar'),
if ~exist('cbfreeze.m'),
warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',...
['You seem to be attempting to freeze a colorbar. This no longer'...
'works. Please read the help for freezeColors for the solution.'])
else
cbfreeze(h);
return
end
end
args{1} = [];
nargs = nargs-1;
else
h = gca;
end
%set nancolor if that option was specified
nancolor = [nan nan nan];
if nargs == 2,
if strcmpi(args{end-1},'nancolor'),
nancolor = args{end};
if ~all(size(nancolor)==[1 3]),
error('JRI:freezeColors:checkArgs:badColorArgument',...
'nancolor must be [r g b] vector');
end
nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0;
else
error('JRI:freezeColors:checkArgs:unrecognizedOption',...
'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1})
end
end
|
github
|
ai-med/QuickNATv2-master
|
cnn_train_dag_seg.m
|
.m
|
QuickNATv2-master/QuickNAT_Networks/cnn_train_dag_seg.m
| 9,984 |
utf_8
|
19b10231e19b45b03a993325ecd97fba
|
function [net,stats] = cnn_train_dag_seg(net, imdb, getBatch, varargin)
%CNN_TRAIN_DAG Demonstrates training a CNN using the DagNN wrapper
% CNN_TRAIN_DAG() is similar to CNN_TRAIN(), but works with
% the DagNN wrapper instead of the SimpleNN wrapper.
% Copyright (C) 2014-15 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
% Todo: save momentum with checkpointing (a waste?)
% -------------------------------------------------------------------------
% Generate options
% -------------------------------------------------------------------------
opts = generate_default_opts();
opts = vl_argparse(opts, varargin);
% -------------------------------------------------------------------------
% Initialization
% -------------------------------------------------------------------------
state.getBatch = getBatch ;
evaluateMode = isempty(opts.train) ;
if ~evaluateMode
if isempty(opts.derOutputs)
error('DEROUTPUTS must be specified when training.\n') ;
end
end
stats = [] ;
% setup GPUs
numGpus = numel(opts.gpus) ;
if numGpus > 1
if isempty(gcp('nocreate')),
parpool('local',numGpus) ;
spmd, gpuDevice(opts.gpus(labindex)), end
end
if exist(opts.memoryMapFile)
delete(opts.memoryMapFile) ;
end
elseif numGpus == 1
gpuDevice(opts.gpus)
end
% -------------------------------------------------------------------------
% Train and validate
% -------------------------------------------------------------------------
modelPath = @(ep) fullfile(opts.expDir, sprintf('net-epoch-%d.mat', ep));
modelFigPath = fullfile(opts.expDir, 'net-train.pdf') ;
start = opts.continue * findLastCheckpoint(opts.expDir) ;
if start >= 1
fprintf('resuming by loading epoch %d\n', start) ;
[net, stats] = loadState(modelPath(start)) ;
net.conserveMemory = false;
end
for epoch=start+1:opts.numEpochs
% train one epoch
save('epochNum.mat','epoch');
state.epoch = epoch ;
state.learningRate = opts.learningRate(min(epoch, numel(opts.learningRate))) ;
state.train = opts.train(randperm(numel(opts.train))) ; % shuffle
state.val = opts.val ;
state.imdb = imdb ;
if numGpus <= 1
stats.train(epoch) = process_epoch(net, state, opts, 'train') ;
stats.val(epoch) = process_epoch(net, state, opts, 'val') ;
else
savedNet = net.saveobj() ;
spmd
net_ = dagnn.DagNN.loadobj(savedNet) ;
stats_.train = process_epoch(net_, state, opts, 'train') ;
stats_.val = process_epoch(net_, state, opts, 'val') ;
if labindex == 1, savedNet_ = net_.saveobj() ; end
end
net = dagnn.DagNN.loadobj(savedNet_{1}) ;
stats__ = accumulateStats(stats_) ;
stats.train(epoch) = stats__.train ;
stats.val(epoch) = stats__.val ;
clear net_ stats_ stats__ savedNet_ ;
end
if ~evaluateMode
saveState(modelPath(epoch), net, stats) ;
end
% -------------------------------------------------------------------------
% Visualize results & save
% -------------------------------------------------------------------------
stats.epoch = epoch;
opts.fcn_visualize(stats, imdb, net, opts);
end
% -------------------------------------------------------------------------
function stats = process_epoch(net, state, opts, mode)
% -------------------------------------------------------------------------
if strcmp(mode,'train')
state.momentum = num2cell(zeros(1, numel(net.params))) ;
end
numGpus = numel(opts.gpus) ;
if numGpus >= 1
net.move('gpu') ;
if strcmp(mode,'train')
sate.momentum = cellfun(@gpuArray,state.momentum,'UniformOutput',false) ;
end
end
if numGpus > 1
mmap = map_gradients(opts.memoryMapFile, net, numGpus) ;
else
mmap = [] ;
end
stats.time = 0 ;
stats.num = 0 ;
stats.num_batches = 0;
subset = state.(mode) ;
start = tic ;
num = 0 ;
for t=1:opts.batchSize:numel(subset)
batchSize = min(opts.batchSize, numel(subset) - t + 1) ;
for s=1:opts.numSubBatches
% get this image batch and prefetch the next
batchStart = t + (labindex-1) + (s-1) * numlabs ;
batchEnd = min(t+opts.batchSize-1, numel(subset)) ;
batch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
inputs = state.getBatch(state.imdb, batch) ;
if opts.prefetch
if s == opts.numSubBatches
batchStart = t + (labindex-1) + opts.batchSize ;
batchEnd = min(t+2*opts.batchSize-1, numel(subset)) ;
else
batchStart = batchStart + numlabs ;
end
nextBatch = subset(batchStart : opts.numSubBatches * numlabs : batchEnd) ;
state.getBatch(state.imdb, nextBatch) ;
end
if strcmp(mode, 'train')
net.mode = 'normal' ;
net.accumulateParamDers = (s ~= 1) ;
net.eval(inputs, opts.derOutputs) ;
else
net.mode = 'test' ;
net.eval(inputs) ;
end
end
% extract learning stats
stats.num_batches = stats.num_batches + 1;
stats = opts.extractStatsFn(net, stats) ;
% accumulate gradient
if strcmp(mode, 'train')
if ~isempty(mmap)
write_gradients(mmap, net) ;
labBarrier() ;
end
state = accumulate_gradients(state, net, opts, batchSize, mmap) ;
end
% print learning statistics
time = toc(start) ;
stats.num = num ;
stats.time = toc(start) ;
fprintf('%s:\t epoch %02d: %3d/%3d: %.1f Hz', mode, state.epoch, fix(t/opts.batchSize)+1, ceil(numel(subset)/opts.batchSize), stats.num/stats.time * max(numGpus, 1));
fprintf('\t[obj-loss = %.3f,\t overall acc.=%.3f%%,\t perclass acc.=%.3f%%]', stats.objective, stats.overall, stats.perclass);
fprintf('\n') ;
end
net.reset() ;
net.move('cpu') ;
% -------------------------------------------------------------------------
function state = accumulate_gradients(state, net, opts, batchSize, mmap)
% -------------------------------------------------------------------------
for p=1:numel(net.params)
% bring in gradients from other GPUs if any
if ~isempty(mmap)
numGpus = numel(mmap.Data) ;
tmp = zeros(size(mmap.Data(labindex).(net.params(p).name)), 'single') ;
for g = setdiff(1:numGpus, labindex)
tmp = tmp + mmap.Data(g).(net.params(p).name) ;
end
net.params(p).der = net.params(p).der + tmp ;
else
numGpus = 1 ;
end
switch net.params(p).trainMethod
case 'average' % mainly for batch normalization
thisLR = net.params(p).learningRate ;
net.params(p).value = ...
(1 - thisLR) * net.params(p).value + ...
(thisLR/batchSize) * net.params(p).der ;
case 'gradient'
thisDecay = opts.weightDecay * net.params(p).weightDecay ;
thisLR = state.learningRate * net.params(p).learningRate ;
state.momentum{p} = opts.momentum * state.momentum{p} ...
- thisDecay * net.params(p).value ...
- (1 / batchSize) * net.params(p).der ;
net.params(p).value = net.params(p).value + thisLR * state.momentum{p} ;
case 'otherwise'
error('Unknown training method ''%s'' for parameter ''%s''.', ...
net.params(p).trainMethod, ...
net.params(p).name) ;
end
end
% -------------------------------------------------------------------------
function mmap = map_gradients(fname, net, numGpus)
% -------------------------------------------------------------------------
format = {} ;
for i=1:numel(net.params)
format(end+1,1:3) = {'single', size(net.params(i).value), net.params(i).name} ;
end
format(end+1,1:3) = {'double', [3 1], 'errors'} ;
if ~exist(fname) && (labindex == 1)
f = fopen(fname,'wb') ;
for g=1:numGpus
for i=1:size(format,1)
fwrite(f,zeros(format{i,2},format{i,1}),format{i,1}) ;
end
end
fclose(f) ;
end
labBarrier() ;
mmap = memmapfile(fname, 'Format', format, 'Repeat', numGpus, 'Writable', true) ;
% -------------------------------------------------------------------------
function write_gradients(mmap, net)
% -------------------------------------------------------------------------
for i=1:numel(net.params)
mmap.Data(labindex).(net.params(i).name) = gather(net.params(i).der) ;
end
% -------------------------------------------------------------------------
function stats = accumulateStats(stats_)
% -------------------------------------------------------------------------
stats = struct() ;
for s = {'train', 'val'}
s = char(s) ;
total = 0 ;
for g = 1:numel(stats_)
stats__ = stats_{g} ;
num__ = stats__.(s).num ;
total = total + num__ ;
for f = setdiff(fieldnames(stats__.(s))', 'num')
f = char(f) ;
if g == 1
stats.(s).(f) = 0 ;
end
stats.(s).(f) = stats.(s).(f) + stats__.(s).(f) * num__ ;
if g == numel(stats_)
stats.(s).(f) = stats.(s).(f) / total ;
end
end
end
stats.(s).num = total ;
end
% -------------------------------------------------------------------------
function saveState(fileName, net, stats)
% -------------------------------------------------------------------------
net_ = net ;
net = net_.saveobj() ;
save(fileName, 'net', 'stats') ;
% -------------------------------------------------------------------------
function [net, stats] = loadState(fileName)
% -------------------------------------------------------------------------
load(fileName, 'net', 'stats') ;
net = dagnn.DagNN.loadobj(net) ;
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(modelDir)
% -------------------------------------------------------------------------
list = dir(fullfile(modelDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
|
github
|
ai-med/QuickNATv2-master
|
visualize_segmentation.m
|
.m
|
QuickNATv2-master/QuickNAT_Networks/visualize_segmentation.m
| 5,328 |
utf_8
|
af65e066d1b43e32c0f7df354dda79ff
|
function visualize_segmentation(stats, imdb, net, opts)
epoch = stats.epoch;
plotErrors(opts, epoch, stats, false);
drawConfusionMatrix(opts, stats);
showImages(imdb, net, opts);
% print to disk
if(opts.savePlots)
print(opts.vis.hnd_loss, sprintf('%s/summary.pdf',opts.expDir), '-dpdf');
print(opts.vis.hand_examples, sprintf('%s/examples.pdf',opts.expDir), '-dpdf');
print(opts.vis.hand_conf, sprintf('%s/confm.pdf',opts.expDir), '-dpdf');
end
end
function drawConfusionMatrix(opts, stats)
change_current_figure(opts.vis.hand_conf); clf;
confT = stats.train(end).confM;
save('confT.mat','confT');
% confJac = stats.train(end).confJac;
% confJac = confJac;
for l=1:size(confT, 1)
confT(l, :) = confT(l, :) / (sum(confT(l, :))+eps);
% confJac(l, :) = confJac(l, :) / (sum(confJac(l, :))+eps);
end
confV = stats.val(end).confM;
for l=1:size(confV, 1)
confV(l, :) = confV(l, :) / (sum(confV(l, :))+eps);
end
% save('confJac.mat','confJac');
subplot(2,1,1);
imagesc(confT);
colormap(jet);
caxis([0, 1])
textstr=num2str(confT(:),'%0.2f');
textstr=strtrim(cellstr(textstr));
L = size(confT, 1);
[x,y]=meshgrid(1:L);
hstrg=text(x(:),y(:),textstr(:), 'FontWeight','bold', 'HorizontalAlignment','center','FontSize',8,'FontName','Times New Roman');
midvalue=mean(get(gca,'Clim'));
textColors=repmat([1, 1, 1], numel(confT), 1);
set(hstrg,{'color'},num2cell(textColors,2));
set(gca,'XTick',1:L,'XTickLabel',opts.classesNames,'YTick',1:L,'YTickLabel',opts.classesNames,'TickLength',[0,0],'FontSize',6,'FontName','Times New Roman', 'FontWeight','bold');
colorbar;
xlabel('Predicted class');
ylabel('True class');
title('Training');
subplot(2,1,2);
imagesc(confV);
colormap(jet);
caxis([0, 1])
textstr=num2str(confV(:),'%0.2f');
textstr=strtrim(cellstr(textstr));
L = size(confV, 1);
[x,y]=meshgrid(1:L);
hstrg=text(x(:),y(:),textstr(:), 'FontWeight','bold', 'HorizontalAlignment','center','FontSize',8,'FontName','Times New Roman');
midvalue=mean(get(gca,'Clim'));
textColors=repmat([1, 1, 1], numel(confV), 1);
set(hstrg,{'color'},num2cell(textColors,2));
set(gca,'XTick',1:L,'XTickLabel',opts.classesNames,'YTick',1:L,'YTickLabel',opts.classesNames,'TickLength',[0,0],'FontSize',6,'FontName','Times New Roman', 'FontWeight','bold');
colorbar;
xlabel('Predicted class');
ylabel('True class');
title('Validation');
end
%--------------------------------------------------------------------------
function plotErrors(opts, epoch, stats, evaluateMode)
% -------------------------------------------------------------------------
expDir = opts.expDir;
opts = opts.vis;
change_current_figure(opts.hnd_loss); clf;
sets = {'train', 'val'};
% plot for the objective
subplot(1,2,1);
if ~evaluateMode
semilogy(1:epoch, gather([stats.train.objective])./[stats.train.num_batches], '.-', 'linewidth', 2);
hold on;
end
semilogy(1:epoch, gather([stats.val.objective])./[stats.val.num_batches], '.--');
xlabel('training epoch'); ylabel('energy');
grid on ;
h=legend(sets) ;
set(h,'color','none');
title('objective') ;
t_overalls = [stats.train.overall_global];
t_perclasses = [stats.train.perclass_global];
v_overalls = [stats.val.overall_global];
v_perclasses = [stats.val.perclass_global];
subplot(1,2,2) ; leg = {} ;
if ~evaluateMode
plot(1:epoch, 100-[t_overalls', t_perclasses'], '.-', 'linewidth', 2) ;
hold on ;
leg = {'train. overall', 'train. perclass'} ;
end
plot(1:epoch, 100-[v_overalls', v_perclasses'], '.--') ;
leg{end+1} = 'val. overall';
leg{end+1} = 'val. perclass' ;
set(legend(leg{:}),'color','none') ;
grid on ;
xlabel('training epoch') ; ylabel('error') ;
title('error') ;
drawnow ;
% if(exist(opts.modelFigPath, 'file'))
% delete(opts.modelFigPath);
% end
% print(opts.hnd_loss, sprintf('%s/summary.pdf',expDir), '-dpdf') ;
end
function showImages(imdb, net, opts)
change_current_figure(opts.vis.hand_examples);
colorMapEst = opts.colorMapEst;
colorMapGT = opts.colorMapGT;
indices = opts.exampleIndices;
% create inputs
images = imdb.images.data(:,:,:, indices) ;
labels = imdb.images.label(:, :, 1, indices) ;
if numel(opts.gpus) > 0
images = gpuArray(images);
net.move('gpu') ;
end
inputs = {'input', images, 'label', labels};
% run net
net.conserveMemory = true;
net.eval({'input', images});
net.conserveMemory = false;
% obtain the CNN otuput
scores = net.vars(net.getVarIndex('prob')).value;
scores = squeeze(gather(scores));
[outW, outL] = max(scores, [], 3);
for i=1:length(indices)
subplot(length(indices), 3, (3*i)-2);
im = imdb.images.data(:, :, :, indices(i));
min_im = min(im(:));
max_im = max(im(:));
im = (im - min_im) / (max_im - min_im + 1);
imshow(im);
title('RGB');
subplot(length(indices), 3, (3*i)-1);
imshow(squeeze(outL(:,:,:,i)), colorMapEst);
freezeColors;
title('Estimated labels');
subplot(length(indices), 3, 3*i);
imshow(squeeze(labels(:,:,:,i))+1, colorMapGT);
title('Ground truth');
end
refreshdata;
drawnow;
end
function change_current_figure(h)
set(0,'CurrentFigure',h)
end
|
github
|
ai-med/QuickNATv2-master
|
visualize_classification.m
|
.m
|
QuickNATv2-master/QuickNAT_Networks/visualize_classification.m
| 750 |
utf_8
|
ca5b11eb689c2b637f5a6c2d98baae44
|
function visualize_classification(opts)
change_current_figure(opts.hand); clf;
stats = opts.stats;
epoch = opts.epoch;
plots = setdiff(cat(2, fieldnames(stats.train)', fieldnames(stats.val)'), {'num', 'time'}) ;
for p = plots
p = char(p) ;
values = zeros(0, epoch) ;
leg = {} ;
for f = {'train', 'val'}
f = char(f) ;
if isfield(stats.(f), p)
tmp = [stats.(f).(p)] ;
values(end+1,:) = tmp(1,:)' ;
leg{end+1} = f ;
end
end
subplot(1,numel(plots),find(strcmp(p,plots))) ;
plot(1:epoch, values','o-') ;
xlabel('epoch') ;
title(p) ;
legend(leg{:}) ;
grid on ;
end
drawnow ;
% save stats
print(1, opts.modelFigPath, '-dpdf') ;
end
function change_current_figure(h)
set(0,'CurrentFigure',h)
end
|
github
|
SMARTlab-Purdue/robotarium-rendezvous-RSSDOA-master
|
minboundcircle.m
|
.m
|
robotarium-rendezvous-RSSDOA-master/includes/minboundcircle.m
| 7,297 |
utf_8
|
280633840d9df9f6cdb804beceb0a493
|
function [center,radius] = minboundcircle(x,y,hullflag)
% minboundcircle: Compute the minimum radius enclosing circle of a set of (x,y) pairs
% usage: [center,radius] = minboundcircle(x,y,hullflag)
% "A suite of minimal bounding objects" by John D'Errico (v1.2 23 May 2014) in Mathworks File Exchange.
%
% arguments: (input)
% x,y - vectors of points, describing points in the plane as
% (x,y) pairs. x and y must be the same size. If x and y
% are arrays, they will be unrolled to vectors.
%
% hullflag - boolean flag - allows the user to disable the
% call to convhulln. This will allow older releases of
% matlab to use this code, with a possible time penalty.
% It also allows minboundellipse to call this code
% efficiently.
%
% hullflag = false --> do not use the convex hull
% hullflag = true --> use the convex hull for speed
%
% default: true
%
%
% arguments: (output)
% center - 1x2 vector, contains the (x,y) coordinates of the
% center of the minimum radius enclosing circle
%
% radius - scalar - denotes the radius of the minimum
% enclosing circle
%
%
% Example usage:
% x = randn(50000,1);
% y = randn(50000,1);
% tic,[c,r] = minboundcircle(x,y);toc
%
% Elapsed time is 0.171178 seconds.
%
% c: [-0.2223 0.070526]
% r: 4.6358
%
%
% See also: minboundrect
%
%
% Author: John D'Errico
% E-mail: [email protected]
% Release: 1.0
% Release date: 1/10/07
% default for hullflag
if (nargin<3) || isempty(hullflag)
hullflag = true;
elseif ~islogical(hullflag) && ~ismember(hullflag,[0 1])
error 'hullflag must be true or false if provided'
end
% preprocess data
x=x(:);
y=y(:);
% not many error checks to worry about
n = length(x);
if n~=length(y)
error 'x and y must be the same sizes'
end
% start out with the convex hull of the points to
% reduce the problem dramatically. Note that any
% points in the interior of the convex hull are
% never needed.
if hullflag && (n>3)
edges = convhulln([x,y]);
% list of the unique points on the convex hull itself
% convhulln returns them as edges
edges = unique(edges(:));
% exclude those points inside the hull as not relevant
x = x(edges);
y = y(edges);
end
% now we must find the enclosing circle of those that
% remain.
n = length(x);
% special case small numbers of points. If we trip any
% of these cases, then we are done, so return.
switch n
case 0
% empty begets empty
center = [];
radius = [];
return
case 1
% with one point, the center has radius zero
center = [x,y];
radius = 0;
return
case 2
% only two points. center is at the midpoint
center = [mean(x),mean(y)];
radius = norm([x(1),y(1)] - center);
return
case 3
% exactly 3 points
[center,radius] = enc3(x,y);
return
end
% more than 3 points.
% Use an active set strategy.
aset = 1:3; % arbitrary, but quite adequate
iset = 4:n;
% pick a tolerance
tol = 10*eps*(max(abs(mean(x) - x)) + max(abs(mean(y) - y)));
% Keep a list of old sets as tried to trap any cycles. we don't need to
% retain a huge list of sets, but only a few of the best ones. Any cycle
% must hit one of these sets. Really, I could have used a smaller list,
% but this is a small enough size that who cares? Almost always we will
% never even fill up this list anyway.
old.sets = NaN(10,3);
old.rads = inf(10,1);
old.centers = NaN(10,2);
flag = true;
while flag
% have we seen this set before? If so, then we have entered a cycle
aset = sort(aset);
if ismember(aset,old.sets,'rows')
% we have seen it before, so trap out
center = old.centers(1,:);
%radius = old.radius(1);
% just reset flag then continue, and the while loop will terminate
flag = false;
continue
end
% get the enclosing circle for the current set
[center,radius] = enc3(x(aset),y(aset));
% is this better than something from the retained sets?
if radius < old.rads(end)
old.sets(end,:) = sort(aset);
old.rads(end) = radius;
old.centers(end,:) = center;
% sort them in increasing order of the circle radii
[old.rads,tags] = sort(old.rads,'ascend');
old.sets = old.sets(tags,:);
old.centers = old.centers(tags,:);
end
% are all the inactive set points inside the circle?
r = sqrt((x(iset) - center(1)).^2 + (y(iset) - center(2)).^2);
[rmax,k] = max(r);
if (rmax - radius) <= tol
% the active set enclosing circle also enclosed
% all of the inactive points.
flag = false;
else
% it must be true that we can replace one member of aset
% with iset(k). Which one?
s1 = [aset([2 3]),iset(k)];
[c1,r1] = enc3(x(s1),y(s1));
if (norm(c1 - [x(aset(1)),y(aset(1))]) <= r1)
center = c1;
radius = r1;
% update the active/inactive sets
swap = aset(1);
aset = [iset(k),aset([2 3])];
iset(k) = swap;
% bounce out to the while loop
continue
end
s1 = [aset([1 3]),iset(k)];
[c1,r1] = enc3(x(s1),y(s1));
if (norm(c1 - [x(aset(2)),y(aset(2))]) <= r1)
center = c1;
radius = r1;
% update the active/inactive sets
swap = aset(2);
aset = [iset(k),aset([1 3])];
iset(k) = swap;
% bounce out to the while loop
continue
end
s1 = [aset([1 2]),iset(k)];
[c1,r1] = enc3(x(s1),y(s1));
if (norm(c1 - [x(aset(3)),y(aset(3))]) <= r1)
center = c1;
radius = r1;
% update the active/inactive sets
swap = aset(3);
aset = [iset(k),aset([1 2])];
iset(k) = swap;
% bounce out to the while loop
continue
end
% if we get through to this point, then something went wrong.
% Active set problem. Increase tol, then try again.
tol = 2*tol;
end
end
% =======================================
% begin subfunction
% =======================================
function [center,radius] = enc3(X,Y)
% minimum radius enclosing circle for exactly 3 points
%
% x, y are 3x1 vectors
% convert to complex
xy = X + sqrt(-1)*Y;
% just in case the points are collinear or nearly so, get
% the interpoint distances, and test the farthest pair
% to see if they work.
Dij = @(XY,i,j) abs(XY(i) - XY(j));
D12 = Dij(xy,1,2);
D13 = Dij(xy,1,3);
D23 = Dij(xy,2,3);
% Find the most distant pair. Test if their circumcircle
% also encloses the third point.
if (D12>=D13) && (D12>=D23)
center = (xy(1) + xy(2))/2;
radius = D12/2;
if abs(center - xy(3)) <= radius
center = [real(center),imag(center)];
return
end
elseif (D13>=D12) && (D13>=D23)
center = (xy(1) + xy(3))/2;
radius = D13/2;
if abs(center - xy(2)) <= radius
center = [real(center),imag(center)];
return
end
elseif (D23>=D12) && (D23>=D13)
center = (xy(2) + xy(3))/2;
radius = D23/2;
if abs(center - xy(1)) <= radius
center = [real(center),imag(center)];
return
end
end
% if we drop down to here, then the points cannot
% be collinear, so the resulting 2x2 linear system
% of equations will not be singular.
A = 2*[X(2)-X(1), Y(2)-Y(1); X(3)-X(1), Y(3)-Y(1)];
rhs = [X(2)^2 - X(1)^2 + Y(2)^2 - Y(1)^2; ...
X(3)^2 - X(1)^2 + Y(3)^2 - Y(1)^2];
center = (A\rhs)';
radius = norm(center - [X(1),Y(1)]);
|
github
|
cssjcai/hihca-master
|
getBatchFn.m
|
.m
|
hihca-master/codes/getBatchFn.m
| 1,445 |
utf_8
|
94781a69ec2a8881b4f3a081f5b0aa8c
|
function fn = getBatchFn(opts, meta)
% -------------------------------------------------------------------------
useGpu = numel(opts.gpus) > 0 ;
bopts.numThreads = opts.numFetchThreads ;
bopts.imageSize = meta.normalization.imageSize ;
bopts.border = meta.normalization.border ;
bopts.averageImage = meta.normalization.averageImage ;
bopts.rgbVariance = meta.augmentation.rgbVariance ;
bopts.transformation = meta.augmentation.transformation ;
bopts.numAugments = meta.augmentation.numAugments;
fn = @(imdb,batch) getDagNNBatch(bopts,useGpu,imdb,batch) ;
function inputs = getDagNNBatch(opts, useGpu, imdb, batch)
% -------------------------------------------------------------------------
images = strcat([imdb.imageDir filesep], imdb.images.name(batch)) ;
%isVal = ~isempty(batch) && imdb.images.set(batch(1)) ~= 1 ;
% if ~isVal
% % training
% im = cnn_imagenet_get_batch(images, opts, ...
% 'prefetch', nargout == 0) ;
% else
% % validation: disable data augmentation
% im = cnn_imagenet_get_batch(images, opts, ...
% 'prefetch', nargout == 0, ...
% 'transformation', 'none') ;
% end
im = cnn_imagenet_get_batch(images, opts);
labels = imdb.images.label(batch) ;
labels = reshape(repmat(labels, opts.numAugments, 1), 1, size(im,4));
if nargout > 0
if useGpu
im = gpuArray(im) ;
end
inputs = {'input', im, 'label', labels} ;
end
|
github
|
cssjcai/hihca-master
|
hihca_model_hed.m
|
.m
|
hihca-master/codes/hihca_model_hed.m
| 7,816 |
utf_8
|
08e0aa399fe39c930e6d494350d27a0f
|
function net = hihca_model_hed(net, imdb, opts)
%% hed-based integration
% ------------------------------------------------------------------------------------
assert(numel(opts.hieLayerName)==numel(opts.rescaleLayerFactor),...
'You must assign scaling factors for all layers !');
hca_inputs = cell(1, numel(opts.hieLayerName));
hca_layer_names = cell(1, numel(opts.hieLayerName));
hca_fdims = cell(1, numel(opts.hieLayerName));
for l = 1:numel(opts.hieLayerName)
% layer scaling
ca_input = net.layers(opts.hieLayerIDX(l)).outputs;
sca_output = ['sc_',num2str(l)];
layer_name = ['scale_',num2str(l)];
param_name = ['scalar_',num2str(l)];
param_value = single(opts.rescaleLayerFactor(l));
net.addLayer(layer_name, dagnn.Scale('hasBias', false), ca_input, sca_output, {param_name});
var_idx = net.getParamIndex(param_name);
net.params(var_idx).value = param_value;
net.params(var_idx).learningRate = 10;
% degree-1
input = sca_output;
output = ['l', num2str(l), '_', 'pm1'];
layer_name = ['layer_', num2str(l), '_', 'polymod_1'];
net.addLayer(layer_name, dagnn.Pooling('poolSize', ...
opts.imageScale*[opts.whc(1,l), opts.whc(2,l)], 'method', 'avg'), input, output);
% degree-r
hi_input = {output};
hi_layer_names = {layer_name};
hi_fdims = opts.whc(3,l);
if opts.kernelDegree > 1
pm_dims = opts.num1x1Filter .* ones(1, opts.kernelDegree-1);
for d = 2 : opts.kernelDegree
input = sca_output;
output = ['l', num2str(l), '_', 'pm',num2str(d)];
layer_name = ['layer_', num2str(l), '_', 'polymod_', num2str(d)];
switch opts.init1x1Filter
case 'rad'
if(~exist(opts.init1x1FilterDir, 'dir'))
mkdir(opts.init1x1FilterDir);
end
if exist(fullfile(opts.init1x1FilterDir, ['l', num2str(l), '_', 'd', num2str(d), '_', 'radW.mat']), 'file') == 2
fprintf('loading Rademacher weight from saved file.\n');
load(fullfile(opts.init1x1FilterDir, ['l', num2str(l), '_', 'd', num2str(d), '_', 'radW.mat']));
else
factor=1.0/sqrt(pm_dims(d-1));
fprintf('generating new Rademacher weight\n');
init_1x1Filters = cell(1,d);
for s = 1:d
init_1x1Filters{s} = single(factor*(randi(2,opts.whc(3,l), pm_dims(d-1))*2-3));
end
savefast(fullfile(opts.init1x1FilterDir, ['l', num2str(l), '_', 'd', num2str(d), '_', 'radW.mat']), 'init_1x1Filters');
end
case 'random'
if(~exist(opts.init1x1FilterDir, 'dir'))
mkdir(opts.init1x1FilterDir);
end
if exist(fullfile(opts.init1x1FilterDir, ['d', num2str(d), '_', 'ramW.mat']), 'file') == 2
fprintf('loading Random weight from saved file.\n');
load(fullfile(opts.init1x1FilterDir, ['d', num2str(d), '_', 'ramW.mat']));
else
factor = 1.0/sqrt(pm_dims(d-1)); %0.001
fprintf('generating new Random weight\n');
init_1x1Filters = cell(1,d);
for s = 1:d
init_1x1Filters{s} = single(factor *randn(opts.whc(3,l), pm_dims(d-1)));
end
savefast(fullfile(opts.init1x1FilterDir, ['l', num2str(l), '_', 'd', num2str(d), '_', 'radW.mat']), 'init_1x1Filters');
end
end
hi_param_names = {};
for s = 1:d
param_name = ['l', num2str(l), 'conv_d',num2str(d),'fm',num2str(s)];
hi_param_names = cat(2, hi_param_names, param_name);
end
net.addLayer(layer_name, Polymd(), input, output, hi_param_names);
for s = 1:d,
var_idx = net.getParamIndex(hi_param_names{s});
param_value = init_1x1Filters{s};
net.params(var_idx).value = param_value;
switch opts.init1x1Filter
case 'rad'
net.params(var_idx).learningRate = 1;
case 'ramdom'
net.params(var_idx).learningRate = 10;
end
end
hi_input = cat(2, hi_input, {output});
hi_layer_names = cat(2, hi_layer_names, {layer_name});
hi_fdims = [hi_fdims, pm_dims(d-1)];
end
end
hca_inputs{l} = hi_input;
hca_layer_names{l} = hi_layer_names;
hca_fdims{l} = hi_fdims;
end
hca_input = {};
fdim = 0;
for l = 1:numel(opts.hieLayerName)
if opts.kernelDegree > 1 && opts.homoKernel
hi_output = ['l', num2str(l), '_', 'pm',num2str(opts.kernelDegree)];
net.removeLayer(hca_layer_names{l}(1:end-1));
ca_fdim = hca_fdims{l}(end);
elseif opts.kernelDegree > 1
% degree concatenation
input = hca_inputs{l};
hi_output = ['l', num2str(l), '_', 'dcat'];
layer_name = ['layer', '_', num2str(l), '_', 'dconcat'];
net.addLayer(layer_name, dagnn.Concat(), input, hi_output);
ca_fdim = sum(hca_fdims{l});
else
hi_output = hca_inputs{1};
ca_fdim = sum(hca_fdims{l});
end
hca_input = cat(2, hca_input, {hi_output});
fdim = fdim + ca_fdim;
end
opts.fdim = fdim;
% layer concatenation
if numel(opts.hieLayerName) > 1
hca_output = 'lcat';
layer_name = 'layer_concat';
net.addLayer(layer_name, dagnn.Concat(), hca_input, hca_output);
else
hca_output = hca_input;
end
%% normalization layers
% ------------------------------------------------------------------------------------
% square-root
input = hca_output;
output = 'sqrt';
layer_name = 'sqrt';
net.addLayer(layer_name, SquareRoot(), input, output);
% l2
input = output;
output = 'l2norm';
layer_name = 'l2norm';
net.addLayer(layer_name, L2Norm(), input, output);
%% classification layer
% ------------------------------------------------------------------------------------
fc_params_init = getInitFCParams(net, imdb, opts);
input = output;
output = 'score';
layer_name = 'classifier';
fc_param_names = {'convclass_f', 'convclass_b'};
net.addLayer(layer_name, dagnn.Conv(), input, output, fc_param_names);
varId = net.getParamIndex(fc_param_names{1});
net.params(varId).value = fc_params_init{1};
net.params(varId).learningRate = 1;
varId = net.getParamIndex(fc_param_names{2});
net.params(varId).value = fc_params_init{2};
net.params(varId).learningRate = 1;
% loss functions
net.addLayer('loss', dagnn.Loss('loss', 'softmaxlog'), {'score','label'}, 'objective');
net.addLayer('error', dagnn.Loss('loss', 'classerror'), {'score','label'}, 'top1error');
net.addLayer('top5e', dagnn.Loss('loss', 'topkerror'), {'score','label'}, 'top5error');
for name = dagFindLayersOfType(net, 'dagnn.Conv')
l = net.getLayerIndex(char(name)) ;
net.layers(l).block.opts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit};
end
function layers = dagFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = [] ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, type)
layers{1,end+1} = net.layers(l).name ;
end
end
|
github
|
cssjcai/hihca-master
|
hihca_visualization.m
|
.m
|
hihca-master/codes/hihca_visualization.m
| 5,397 |
utf_8
|
2c5b82be9ec5d683e10770eb002466c5
|
function hihca_visualization(imdb, opts)
% using homogeneous kernel for better visualization of higher-order part
% with specific degree
epochIDX = ['net-epoch-',num2str(opts.netIDX),'.mat'];
snet = load(fullfile(opts.modelTrainDir, epochIDX), 'net', 'stats');
net = dagnn.DagNN.loadobj(snet.net);
net.removeLayer({'sqrt','l2norm','classifier','loss','error','top5e'});
U = cell(1,opts.kernelDegree);
for d = 1:opts.kernelDegree
pIDX = net.getParamIndex(['conv_d',num2str(opts.kernelDegree),'fm',num2str(d)]);
U{d} = net.params(pIDX).value;
end
convIDX = net.getLayerIndex(opts.hieLayerName{end});
lnames_r = dagFindRemovedLayerNames(net, convIDX);
net.removeLayer(lnames_r);
if ~exist(opts.trainedFeaturemapDir)
mkdir(opts.trainedFeaturemapDir)
end
if exist(fullfile(opts.modelTrainDir, 'fc_svm_trained.mat'))
load(fullfile(opts.modelTrainDir, 'fc_svm_trained.mat'));
w = fc_params_trained{1};
else
fprintf('You need to run testing first then visualization !\n');
return
end
vis_set = find(ismember(imdb.images.set, [1 2]));
vis_classIDX = [1]; % vis_classIDX = [1:size(w,2)];
vis_topK = 3;
for c = vis_classIDX
trainedFeaturemapClassDir = fullfile(opts.trainedFeaturemapDir, imdb.classes.name{c});
if ~exist(trainedFeaturemapClassDir)
mkdir(trainedFeaturemapClassDir)
end
[~, wIDX] = sort(abs(w(:,c)),'descend');
wIDX_topK = wIDX(1:vis_topK);
chIDX = cell(1, vis_topK);
for i = 1:vis_topK
uuT = U{1}(:,wIDX_topK(i))*U{2}(:,wIDX_topK(i))';
if opts.kernelDegree > 2
for d = 3:opts.kernelDegree
uuT = kron(uuT,U{d}(:,wIDX_topK(i))');
end
uuT = reshape(uuT, size(U{1},1)*ones(1, opts.kernelDegree));
end
ind = find(uuT==max(uuT(:)));
% for degree-2
[ch1,ch2] = ind2sub(size(U{1},1)*ones(1,opts.kernelDegree), ind);
chIDX{i} = [ch1,ch2];
% for degree-3
%[ch1,ch2,ch3] = ind2sub(size(U{1},1)*ones(1,opts.kernelDegree), ind);
%chIDX{i} = [ch1,ch2,ch3];
end
vis_set_c = vis_set(imdb.images.label==c);
meta = net.meta;
meta.augmentation.transformation = 'none' ;
meta.augmentation.rgbVariance = [];
meta.augmentation.numAugments = 1;
batchSizeFC = floor(opts.batchSizeFC / 4*meta.augmentation.numAugments);
fn_trainFC = getBatchFn(opts, meta) ;
for t=1:batchSizeFC:numel(vis_set_c)
fprintf(['Visualizating for ', imdb.classes.name{c}, ' : extracting feature maps of batch',' %d/%d\n'], ceil(t/batchSizeFC), ceil(numel(vis_set_c)/batchSizeFC));
batch = vis_set_c(t:min(numel(vis_set_c), t+batchSizeFC-1));
inputs = fn_trainFC(imdb, batch) ;
if opts.gpus
net.move('gpu') ;
end
net.mode = 'test' ;
net.conserveMemory = false;
net.eval(inputs(1:2));
hcaMaps = [];
for l = 1:numel(opts.hieLayerName)
lIdx = net.getLayerIndex(opts.hieLayerName(l));
fIdx = net.getVarIndex(net.layers(lIdx).outputs);
caMaps = net.vars(fIdx).value;
caMaps = squeeze(gather(caMaps));
hcaMaps = cat(3, hcaMaps, caMaps);
end
for i=1:numel(batch)
image_name = {fullfile(imdb.imageDir,imdb.images.name{batch(i)})};
vopts.imageSize = meta.normalization.imageSize ;
vopts.border = meta.normalization.border;
image = cnn_imagenet_get_batch(image_name, vopts);
image = double(image)/255;
for id = 1:numel(chIDX)
chMaps = hcaMaps(:,:,chIDX{id},i);
image_partMap_all = [];
for p = 1:numel(chIDX{id})
partMap = chMaps(:,:,p);
[X,Y] = meshgrid(1:size(partMap,2), 1:size(partMap,1));
[Xq,Yq] = meshgrid(1:0.01:size(partMap,2), 1:0.01:size(partMap,1));
partMap_ = interp2(X, Y, partMap, Xq, Yq, 'linear');
partMap_ = imresize(partMap_, net.meta.normalization.imageSize(1:2));
partMap_nor = partMap_-min(partMap_(:));
partMap_nor = (partMap_nor)./max(partMap_nor(:));
partMap_nor = mat2gray(partMap_nor);
partMap_nor_gray = gray2ind(partMap_nor,256);
partMap_nor_rgb = ind2rgb(partMap_nor_gray, jet(256));
image_partMap = image*0.4 + partMap_nor_rgb*0.5;
image_partMap = padarray(image_partMap,[20 20],255,'both');
image_partMap_all = cat(2, image_partMap_all, image_partMap);
end
% imshow(image_partMap_all)
imwrite(image_partMap_all, fullfile(trainedFeaturemapClassDir, [num2str(batch(i), '%05d'),'_', 'trained_featuremaps_', num2str(id, '%02d'), '.jpg']));
end
end
end
end
function layernames = dagFindRemovedLayerNames(net, convIDX)
% -------------------------------------------------------------------------
layernames = {} ;
for l = 1:numel(net.layers(convIDX+1:end))
layernames = cat(2, layernames, {net.layers(convIDX+l).name});
end
|
github
|
cssjcai/hihca-master
|
hihca_model.m
|
.m
|
hihca-master/codes/hihca_model.m
| 1,791 |
utf_8
|
4d470a0d2fff848c46c0c6ae11c9b843
|
function pnet = hihca_model(imdb, opts)
%% load the pre-trained cnn model as base net
% ------------------------------------------------------------------------------------
bnet = load(opts.cnnModelDir);
tru_idx = simpleFindLayerIDXOfName(bnet, opts.hieLayerName{end});
bnet.layers = bnet.layers(1:tru_idx);
bnet = vl_simplenn_tidy(bnet);
bnet_info = vl_simplenn_display(bnet);
hieLayerIDX = [];
for l = 1:numel(opts.hieLayerName)
hieLayerIDX = [hieLayerIDX, simpleFindLayerIDXOfName(bnet, opts.hieLayerName{l})];
end
opts.whc = bnet_info.dataSize([1 2 3], hieLayerIDX+1);
%% transform simplenn to dagnn
% ------------------------------------------------------------------------------------
pnet = dagnn.DagNN();
pnet = pnet.fromSimpleNN(bnet, 'CanonicalNames', true);
opts.hieLayerIDX = [];
for l = 1:numel(opts.hieLayerName)
opts.hieLayerIDX = [opts.hieLayerIDX, pnet.getLayerIndex(opts.hieLayerName{l})];
end
pnet.meta.classes.name = imdb.classes.name;
pnet.meta.classes.description = imdb.classes.name;
pnet.meta.normalization.imageSize = [pnet.meta.normalization.imageSize(1:2)*opts.imageScale, pnet.meta.normalization.imageSize(3)];
pnet.meta.normalization.averageImage = imresize(pnet.meta.normalization.averageImage, opts.imageScale);
clear bnet;
%% build hihca net
% ------------------------------------------------------------------------------------
switch opts.layerFusion
case 'hc'
pnet = hihca_model_hc(pnet, imdb, opts);
case 'hed'
pnet = hihca_model_hed(pnet, imdb, opts);
otherwise
error('Unknown layer integration!') ;
end
function layers = simpleFindLayerIDXOfName(net, name)
% -------------------------------------------------------------------------
layers = find(cellfun(@(x)strcmp(x.name, name), net.layers)) ;
|
github
|
cssjcai/hihca-master
|
hihca_model_hc.m
|
.m
|
hihca-master/codes/hihca_model_hc.m
| 6,966 |
utf_8
|
6a83f6b1f0880743576304bac3950e00
|
function net = hihca_model_hc(net, imdb, opts)
%% hypercolumn-based integration
% ------------------------------------------------------------------------------------
assert(numel(opts.hieLayerName)==numel(opts.rescaleLayerFactor),...
'You must assign scaling factors for all layers !');
% layer concatenation
if numel(opts.hieLayerName) > 1
hca_input = {};
% layer scaling
for l = 1:numel(opts.hieLayerIDX)
ca_input = net.layers(opts.hieLayerIDX(l)).outputs;
sca_output = ['sc_',num2str(l)];
layer_name = ['scale_',num2str(l)];
param_name = ['scalar_',num2str(l)];
param_value = single(opts.rescaleLayerFactor(l));
net.addLayer(layer_name, dagnn.Scale('hasBias', false), ca_input, sca_output, {param_name});
var_idx = net.getParamIndex(param_name);
net.params(var_idx).value = param_value;
net.params(var_idx).learningRate = 10;
hca_input = cat(2, hca_input, {sca_output});
end
hca_output = 'lcat';
layer_name = 'layer_concat';
net.addLayer(layer_name, dagnn.Concat(), hca_input, hca_output);
else
hca_output = net.layers(opts.hieLayerIDX(end)).outputs;
end
%% polynomial modules
% ------------------------------------------------------------------------------------
% degree-1
input = hca_output;
output = 'pm_1';
layer_name = 'polymod_1';
net.addLayer(layer_name, dagnn.Pooling('poolSize', ...
opts.imageScale*[opts.whc(1,end), opts.whc(2,end)], 'method', 'avg'), input, output);
% degree-r
hi_input = {output};
hi_layer_names = {layer_name};
hi_fdims = sum(opts.whc(3,:));
if opts.kernelDegree > 1
pm_dims = opts.num1x1Filter .* ones(1, opts.kernelDegree-1);
for d = 2 : opts.kernelDegree
input = hca_output;
output = ['pm_',num2str(d)];
layer_name = ['polymod_', num2str(d)];
switch opts.init1x1Filter
case 'rad'
if(~exist(opts.init1x1FilterDir, 'dir'))
mkdir(opts.init1x1FilterDir);
end
if exist(fullfile(opts.init1x1FilterDir, ['d', num2str(d), '_', 'radW.mat']), 'file') == 2
fprintf('loading Rademacher weight from saved file.\n');
load(fullfile(opts.init1x1FilterDir, ['d', num2str(d), '_', 'radW.mat']));
else
factor = 1.0/sqrt(pm_dims(d-1));
fprintf('generating new Rademacher weight\n');
init_1x1Filters = cell(1,d);
for s = 1:d
init_1x1Filters{s} = single(factor*(randi(2,sum(opts.whc(3,:)), pm_dims(d-1))*2-3));
end
savefast(fullfile(opts.init1x1FilterDir, ['d', num2str(d), '_', 'radW.mat']), 'init_1x1Filters');
end
case 'random'
if(~exist(opts.init1x1FilterDir, 'dir'))
mkdir(opts.init1x1FilterDir);
end
if exist(fullfile(opts.init1x1FilterDir, ['d', num2str(d), '_', 'ramW.mat']), 'file') == 2
fprintf('loading Random weight from saved file.\n');
load(fullfile(opts.init1x1FilterDir, ['d', num2str(d), '_', 'ramW.mat']));
else
factor = 1.0/sqrt(pm_dims(d-1)); % 0.001
fprintf('generating new Random weight\n');
init_1x1Filters = cell(1,d);
for s = 1:d
init_1x1Filters{s} = single(factor*randn(sum(opts.whc(3,:)), pm_dims(d-1)));
end
savefast(fullfile(opts.init1x1FilterDir, ['d', num2str(d), '_', 'ramW.mat']), 'init_1x1Filters');
end
end
hi_param_names = {};
for s = 1:d
param_name = ['conv_d',num2str(d),'fm',num2str(s)];
hi_param_names = cat(2, hi_param_names, param_name);
end
net.addLayer(layer_name, Polymd(), input, output, hi_param_names);
for s = 1:d,
var_idx = net.getParamIndex(hi_param_names{s});
param_value = init_1x1Filters{s};
net.params(var_idx).value = param_value;
switch opts.init1x1Filter
case 'rad'
net.params(var_idx).learningRate = 1;
case 'ramdom'
net.params(var_idx).learningRate = 10;
end
end
hi_input = cat(2, hi_input, {output});
hi_layer_names = cat(2, hi_layer_names, {layer_name});
hi_fdims = [hi_fdims, pm_dims(d-1)];
end
end
% degree concatenation
if opts.kernelDegree > 1 && opts.homoKernel
hi_output = ['pm_',num2str(opts.kernelDegree)];
net.removeLayer(hi_layer_names(1:end-1));
opts.fdim = hi_fdims(end);
elseif opts.kernelDegree > 1
input = hi_input;
hi_output = 'dcat';
layer_name = 'dconcat';
net.addLayer(layer_name, dagnn.Concat(), input, hi_output);
opts.fdim = sum(hi_fdims);
else
hi_output = hi_input;
opts.fdim = sum(hi_fdims);
end
%% normalization layers
% ------------------------------------------------------------------------------------
% square-root
input = hi_output;
output = 'sqrt';
layer_name = 'sqrt';
net.addLayer(layer_name, SquareRoot(), input, output);
% l2
input = output;
output = 'l2norm';
layer_name = 'l2norm';
net.addLayer(layer_name, L2Norm(), input, output);
%% classification layer
% ------------------------------------------------------------------------------------
fc_params_init = getInitFCParams(net, imdb, opts);
input = output;
output = 'score';
layer_name = 'classifier';
fc_param_names = {'convclass_f', 'convclass_b'};
net.addLayer(layer_name, dagnn.Conv(), input, output, fc_param_names);
varId = net.getParamIndex(fc_param_names{1});
net.params(varId).value = fc_params_init{1};
net.params(varId).learningRate = 1;
varId = net.getParamIndex(fc_param_names{2});
net.params(varId).value = fc_params_init{2};
net.params(varId).learningRate = 1;
% loss functions
net.addLayer('loss', dagnn.Loss('loss', 'softmaxlog'), {'score','label'}, 'objective');
net.addLayer('error', dagnn.Loss('loss', 'classerror'), {'score','label'}, 'top1error');
net.addLayer('top5e', dagnn.Loss('loss', 'topkerror'), {'score','label'}, 'top5error');
for name = dagFindLayersOfType(net, 'dagnn.Conv')
l = net.getLayerIndex(char(name)) ;
net.layers(l).block.opts = {'CudnnWorkspaceLimit', opts.cudnnWorkspaceLimit};
end
function layers = dagFindLayersOfType(net, type)
% -------------------------------------------------------------------------
layers = [] ;
for l = 1:numel(net.layers)
if isa(net.layers(l).block, type)
layers{1,end+1} = net.layers(l).name ;
end
end
|
github
|
cssjcai/hihca-master
|
hihca_test.m
|
.m
|
hihca-master/codes/hihca_test.m
| 3,105 |
utf_8
|
4553a79130a1909b40ca694519b39f00
|
function hihca_test(imdb, opts)
epochidx = ['net-epoch-',num2str(opts.netIDX),'.mat'];
snet = load(fullfile(opts.modelTrainDir, epochidx), 'net', 'stats');
net = dagnn.DagNN.loadobj(snet.net);
net.removeLayer({'classifier','loss','error','top5e'});
train = find(ismember(imdb.images.set, [1 2]));
if ~exist(opts.trainedPolyfeatDir)
mkdir(opts.trainedPolyfeatDir)
end
trainedPolyfeatList = dir(fullfile(opts.trainedPolyfeatDir, '/*.mat'));
if numel(trainedPolyfeatList) == 0
meta = net.meta;
meta.augmentation.transformation = 'f2';
meta.augmentation.rgbVariance = [];
meta.augmentation.numAugments = 2;
batchSizeFC = floor(opts.batchSizeFC / meta.augmentation.numAugments);
fn_trainFC = getBatchFn(opts, meta);
for t=1:batchSizeFC:numel(train)
fprintf('Testing: extracting polynomial features of batch %d/%d\n', ceil(t/batchSizeFC), ceil(numel(train)/batchSizeFC));
batch = train(t:min(numel(train), t+batchSizeFC-1));
inputs = fn_trainFC(imdb, batch);
if opts.gpus
net.move('gpu');
end
net.mode = 'test' ;
net.eval(inputs(1:2));
fIdx = net.getVarIndex('l2norm');
polyFea = net.vars(fIdx).value;
polyFea = squeeze(gather(polyFea));
for i=1:numel(batch)
fea_p = polyFea(:,meta.augmentation.numAugments*(i-1)+1:meta.augmentation.numAugments*i);
savefast(fullfile(opts.trainedPolyfeatDir, ['trained_polyfeats_', num2str(batch(i), '%05d')]), 'fea_p');
end
end
% move back to cpu
if opts.gpus
net.move('cpu');
end
end
% lr learning
polydb = imdb;
tempStr = sprintf('%05d\t', train);
tempStr = textscan(tempStr, '%s', 'delimiter', '\t');
polydb.images.name = strcat('trained_polyfeats_', tempStr{1}');
polydb.images.id = polydb.images.id(train);
polydb.images.label = polydb.images.label(train);
polydb.images.set = polydb.images.set(train);
polydb.imageDir = opts.trainedPolyfeatDir;
polydb.numAugments = 2;
[trainFV, trainY, valFV, valY] = load_polyfea_fromdisk(polydb);
[w, b, acc, map, scores]= train_test_vlfeat('SVM', trainFV, trainY, valFV, valY);
fc_params_trained{1} = w;
fc_params_trained{2} = b;
save(fullfile(opts.modelTrainDir, 'fc_svm_trained.mat'), 'fc_params_trained', '-v7.3') ;
function [trainFV, trainY, valFV, valY] = load_polyfea_fromdisk(polydb)
% -------------------------------------------------------------------------
train = find(polydb.images.set==1);
trainFV = cell(1, numel(train));
for i = 1:numel(train)
load(fullfile(polydb.imageDir, polydb.images.name{train(i)}));
trainFV{i} = fea_p;
end
trainFV = cat(2,trainFV{:});
%trainFV = trainFV(:,2:2:end);
trainY = polydb.images.label(train)';
trainY = reshape(repmat(trainY,1, polydb.numAugments)', [], 1);
val = find(polydb.images.set==2);
valFV = cell(1, numel(val));
for i = 1:numel(val)
load(fullfile(polydb.imageDir, polydb.images.name{val(i)}));
valFV{i} = fea_p;
end
valFV = cat(2,valFV{:});
valFV = valFV(:,1:2:end);
valY = polydb.images.label(val)';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.