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
marthawhite/reverse-prediction-master
Experiments.m
.m
reverse-prediction-master/algs/competitors/MR/Experiments.m
6,532
utf_8
c85e0eefba2b31d72d55b85c86163f4d
function results=Experiments(dataset,NN,SIGMA,gamma_A,gamma_I,DEGREE,M) % [err_svm,err_rlsc]=Experiments(dataset) % dataset.mat should have matrices % X (n x d training data matrix, n examples, d features) % Xt (test data matrix) (if available) % training labels Y % test labels Yt (if available) % % NN: number of nearest neighbors for graph laplacian computation % SIGMA: width of RBF kernel % gamma_A,gamma_I: the extrinsic and intrinsic regularization parameters % DEGREE: power of the graph Laplacian to use as the graph regularizer % M: Precomputed grah regularizer if available (n x n matrix). % % This code generates the mean results training and testing on data % splits. % % Data splits are specified as follows -- % folds: a n x R matrix with 0 or 1 values; each column indicates which % examples are to be considered labeled (1) or unlabeled (0). % Alternatively, one can specify by a collection of indices in R x l matrix % idxLabs where each row gives the l indices for labeled examples. % % For experiments in the paper "Beyond the Point Cloud", run e.g., % % Experiments('USPST'); % USPST.mat contains all the options % % Vikas Sindhwani ([email protected]) load(dataset); C=unique(Y); if length(C)==2 C=[1 -1]; nclassifiers=1; else nclassifiers=length(C); end % options contains the optimal parameter settings for the data options=make_options; options.NN=NN; options.Kernel='rbf'; options.KernelParam=SIGMA; options.gamma_A=gamma_A; options.gamma_I=gamma_I; options.GraphWeights='heat'; options.GraphWeightParam=SIGMA; options.LaplacianDegree=DEGREE; options if ~exist('M','var') M=laplacian(options,X); end M=M^options.LaplacianDegree; tic; % construct and deform the kernel % K contains the gram matrix of the warped data-dependent semi-supervised kernel G=calckernel(options,X); r=options.gamma_I/options.gamma_A; % the deformed kernel matrix evaluated over test data fprintf(1,'Deforming Kernel\n'); if exist('Xt','var') Gt=calckernel(options,X,Xt); [K, Kt]=Deform(r,G,M,Gt); else K=Deform(r,G,M); end % run over the random splits if exist('folds','var') number_runs=size(folds,2); else number_runs=size(idxLabs,1); end for R=1:number_runs if exist('folds','var') L=find(folds(:,R)); else L=idxLabs(R,:); end U=(1:size(K,1))'; U(L)=[]; data.K=K(L,L); data.X=X(L,:); fsvm=[]; frlsc=[]; fsvm_t=[]; frlsc_t=[]; for c=1:nclassifiers if nclassifiers>1 fprintf(1,'Class %d versus rest\n',C(c)); end data.Y=(Y(L)==C(c))-(Y(L)~=C(c)); % labeled data classifier_svm=svm(options,data); classifier_rlsc=rlsc(options,data); fsvm(:,c)=K(U,L(classifier_svm.svs))*classifier_svm.alpha-classifier_svm.b; frlsc(:,c)=K(U,L(classifier_rlsc.svs))*classifier_rlsc.alpha-classifier_rlsc.b; if exist('bias','var') [fsvm(:,c),classifier_svm.b] = adjustbias(fsvm(:,c)+classifier_svm.b, bias); [frlsc(:,c),classifier_rlsc.b] = adjustbias(frlsc(:,c)+classifier_rlsc.b,bias); end results(R).fsvm(:,c)=fsvm(:,c); results(R).frlsc(:,c)=frlsc(:,c); yu=(Y(U)==C(c))-(Y(U)~=C(c)); if exist('Xt','var') fsvm_t(:,c)=Kt(:,L(classifier_svm.svs))*classifier_svm.alpha-classifier_svm.b; frlsc_t(:,c)=Kt(:,L(classifier_rlsc.svs))*classifier_rlsc.alpha-classifier_rlsc.b; results(R).fsvm_t(:,c)=fsvm_t(:,c); results(R).frlsc_t(:,c)=frlsc_t(:,c); yt=(Yt==C(c))-(Yt~=C(c)); end end if nclassifiers==1 fsvm=sign(results(R).fsvm); frlsc=sign(results(R).frlsc); if exist('Xt','var') fsvm_t=sign(results(R).fsvm_t); frlsc_t=sign(results(R).frlsc_t); end else [e,fsvm]=max(results(R).fsvm,[],2); fsvm=C(fsvm); [e,frlsc]=max(results(R).frlsc,[],2); frlsc=C(frlsc); if exist('Xt','var') [e,fsvm_t]=max(results(R).fsvm_t,[],2); fsvm_t=C(fsvm_t); [e,frlsc_t]=max(results(R).frlsc_t,[],2); frlsc_t=C(frlsc_t); end end cm=confusion(fsvm,Y(U)); results(R).cm_svm=cm; results(R).err_svm=100*(1-sum(diag(cm))/sum(cm(:))); cm=confusion(frlsc,Y(U)); results(R).cm_rlsc=cm; results(R).err_rlsc=100*(1-sum(diag(cm))/sum(cm(:))); if exist('Xt','var') cm=confusion(fsvm_t,Yt); results(R).cm_svm_t=cm; results(R).err_svm_t=100*(1-sum(diag(cm))/sum(cm(:))); cm=confusion(frlsc_t,Yt); results(R).cm_rlsc_t=cm; results(R).err_rlsc_t=100*(1-sum(diag(cm))/sum(cm(:))); end fprintf(1,'split=%d LapSVM (transduction) err = %f \n',R, results(R).err_svm); fprintf(1,'split=%d LapRLS (transduction) err = %f \n',R, results(R).err_rlsc); if exist('Xt','var') fprintf(1,'split=%d LapSVM (out-of-sample) err = %f\n',R, results(R).err_svm_t); fprintf(1,'split=%d LapRLS (out-of-sample) err = %f\n',R, results(R).err_rlsc_t); end end fprintf(1,'\n\n'); disp('LapSVM (transduction) mean confusion matrix'); disp(round(mean(reshape(vertcat(results.cm_svm)',[size(results(1).cm_svm,1) size(results(1).cm_svm,1) length(results)]),3))); disp('LapRLS (transduction) mean confusion matrix'); disp(round(mean(reshape(vertcat(results.cm_rlsc)',[size(results(1).cm_rlsc,1) size(results(1).cm_rlsc,1) length(results)]),3))); fprintf(1,'LapSVM (transduction mean(std)) err = %f (%f) \n',mean(vertcat(results.err_svm)),std(vertcat(results.err_svm))); fprintf(1,'LapRLS (transduction mean(std)) err = %f (%f) \n',mean(vertcat(results.err_rlsc)),std(vertcat(results.err_rlsc))); if exist('Xt','var') fprintf(1,'\n\n'); disp('LapSVM (out-of-sample) mean confusion matrix'); disp(round(mean(reshape(vertcat(results.cm_svm_t)',[size(results(1).cm_svm_t,1) size(results(1).cm_svm_t,1) length(results)]),3))); disp('LapRLS (out-of-sample) mean confusion matrix'); disp(round(mean(reshape(vertcat(results.cm_rlsc_t)',[size(results(1).cm_rlsc_t,1) size(results(1).cm_rlsc_t,1) length(results)]),3))); fprintf(1,'LapSVM (out-of-sample mean(std)) err = %f (%f)\n',mean(vertcat(results.err_svm_t)), std(vertcat(results.err_svm_t))); fprintf(1,'LapRLS (out-of-sample mean(std)) err = %f (%f)\n',mean(vertcat(results.err_rlsc_t)),std(vertcat(results.err_rlsc_t))); end function [f1,b]=adjustbias(f,bias) jj=ceil((1-bias)*length(f)); g=sort(f); b=0.5*(g(jj)+g(jj+1)); f1=f-b;
github
marthawhite/reverse-prediction-master
classifier_evaluation.m
.m
reverse-prediction-master/algs/competitors/MR/classifier_evaluation.m
1,742
utf_8
1bb871f0399589f4ce43c27091513ad2
% Classifier Evaluation Routine % This code provides different methods to evaluate binary classifiers. % % Basic Usage : % [maxthreshold,maxobj,maxcm]=classifier_evaluation(outputs,labels,func) % outputs is a vector of real-valued outputs on a test set % labels are corresponding true labels % func : function of the type func(totalpositive,totalnegative, falsepositive,falsenegative) % func = f1 | r1 | acc (accuracy) | info (information) % maxthreshold-- threshold point at which func maximizes % maxobj - the maximum function value at this point % maxcm - the confusion matrix at maxthreshold % % Written by Jason Rennie <[email protected]> % Last modified: Thu Feb 19 13:19:32 2004 % % Modified by Vikas Sindhwani % 09/24/2004 % % function [maxthresh,maxobj,maxcm] = classifier_evaluation(outputs,labels,func) n = length(outputs); if n ~= length(labels) error('length of outputs and labels must match') end np = sum(labels>0); nn = sum(labels<0); fp = nn; fn = 0; maxobj = feval(func,np,nn,fp,fn); [tmp,idx] = sort(outputs); so = outputs(idx); sl = labels(idx); maxthresh = so(1)-1; maxcm=[np-fn fn; fp nn-fp]; for i=1:length(so)-1 if sl(i) < 0 fp = fp - 1; else fn = fn + 1; end if so(i) == so(i+1) continue end obj = feval(func,np,nn,fp,fn); if obj > maxobj maxobj = obj; maxthresh = (so(i)+so(i+1))/2; maxcm=[np-fn fn; fp nn-fp]; end end if sl(n) < 0 fp = fp - 1; else fn = fn + 1; end obj = feval(func,np,nn,fp,fn); if obj > maxobj maxobj = obj; maxthresh = so(n)+1; maxcm=[np-fn fn; fp nn-fp]; end function h=info(np,nn,fp,fn) cm=[nn-fp fp; fn np-fn]; h=information(cm);
github
marthawhite/reverse-prediction-master
ExperimentsWebKB.m
.m
reverse-prediction-master/algs/competitors/MR/ExperimentsWebKB.m
2,244
utf_8
40e03bf590e307651ba73996f60b46b1
function [prbep_svm,prbep_rlsc]=ExperimentsWebKB(mode,joint) %% For binary classification on LINK.mat PAGE.mat PAGE+LINK.mat %% mode='link' | 'page' | 'page+link' %% link=0 or 1. Put 1 if you want to use a %% joint regularizer (multi-view learning). Otherwise ignore this argument or put joint=0. %% e.g [prbep_svm,prbep_rlsc]=ExperimentsWebKB('link') %% or [prbep_svm,prbep_rlsc]=ExperimentsWebKB('link',1) %% options are in the mat file %% %% %% Returns the PRBEP performance over the 100 splits %% if ~exist('joint','var') joint=0; end if joint==1 load LINK.mat; L1=laplacian(options,X); load PAGE.mat; L2=laplacian(options,X); load PAGELINK.mat; L3=laplacian(options,X); options.gamma_A=0.01; options.gamma_I=0.1; L=(L1+L2+L3)/3; clear L1 L2 L3; end switch mode case 'link' load LINK.mat; case 'page' load PAGE.mat case 'page+link' load PAGELINK.mat end if joint==0 L=laplacian(options,X); end tic; % construct the semi-supervised kernel by deforming a linear kernel with % the graph regularizer % K contains the gram matrix of the new data-dependent semi-supervised kernel K=Deform(options.gamma_I/options.gamma_A,calckernel(options,X),L^options.LaplacianDegree); % run over the random splits for R=1:size(idxLabs,1) L=idxLabs(R,:); U=1:size(K,1); U(L)=[]; data.K=K(L,L); data.X=X(L,:); data.Y=Y(L); % labeled data classifier_svm=svm(options,data); classifier_rlsc=rlsc(options,data); testdata.K=K(U,L); prbep_svm(R)=test_prbep(classifier_svm,testdata.K,Y(U)); prbep_rlsc(R)=test_prbep(classifier_rlsc,testdata.K,Y(U)); disp(['Laplacian SVM Performance on split ' num2str(R) ': ' num2str(prbep_svm(R))]); disp(['Laplacian RLS Performance on split ' num2str(R) ': ' num2str(prbep_rlsc(R))]); end fprintf(1,'\n\n'); disp(['Mean (std dev) Laplacian SVM PRBEP : ' num2str(mean(prbep_svm)) ' ( ' num2str(std(prbep_svm)) ' )']); disp(['Mean (std dev) Laplacian RLS PRBEP ' num2str(mean(prbep_rlsc)) ' ( ' num2str(std(prbep_rlsc)) ' )']); function prbep=test_prbep(classifier,K,Y); f=K(:,classifier.svs)*classifier.alpha-classifier.b; [m,n,maxcm]=classifier_evaluation(f,Y,'pre_rec_equal'); prbep=100*(maxcm(1,1)/(maxcm(1,1)+maxcm(1,2)));
github
marthawhite/reverse-prediction-master
make_options.m
.m
reverse-prediction-master/algs/competitors/MR/make_options.m
6,396
utf_8
e86f6b554bd5088e376b275341142d5a
function options = make_options(varargin) % ML_OPTIONS - Generate/alter options structure for training classifiers % ----------------------------------------------------------------------------------------% % options = ml_options('PARAM1',VALUE1,'PARAM2',VALUE2,...) % % Creates an options structure "options" in which the named parameters % have the specified values. Any unspecified parameters are set to % default values specified below. % options = ml_options (with no input arguments) creates an options structure % "options" where all the fields are set to default values specified below. % % Example: % options=ml_options('Kernel','rbf','KernelParam',0.5,'NN',6); % % "options" structure is as follows: % % Field Name: Description : default % ------------------------------------------------------------------------------------- % 'Kernel': 'linear' | 'rbf' | 'poly' : 'linear' % 'KernelParam': -- | sigma | degree : 1 % 'NN': number of nearest neighbor : 6 %'GraphDistanceFuncion': distance function for graph: 'euclidean' | 'cosine' : 'euclidean' % 'GraphWeights': 'binary' | 'distance' | 'heat' : 'binary' % 'GraphWeightParam': e.g For heat kernel, width to use : 1 % 'GraphNormalize': Use normalized Graph laplacian (1) or not (0) : 1 % 'ClassEdges': Disconnect Edges across classes:yes(1) no (0) : 0 % 'gamma_A': RKHS norm regularization parameter (Ambient) : 1 % 'gamma_I': Manifold regularization parameter (Intrinsic) : 1 % mu': Class-based Fully Supervised Laplacian Parameter : 0.5 % 'LaplacianDegree' : Degree of Iterated Laplacian : 1 % k : Regularized Spectral Representation Paramter : 2 % ------------------------------------------------------------------------------------- % % Acknowledgement: Adapted from Anton Schwaighofer's software: % http://www.cis.tugraz.at/igi/aschwaig/software.html % % Author: Vikas Sindhwani ([email protected]) % June 2004 % ----------------------------------------------------------------------------------------% % options default values options = struct('Kernel','linear', ... 'KernelParam',1, ... 'NN',6,... 'k' , 2, ... 'GraphDistanceFunction','euclidean',... 'GraphWeights', 'binary', ... 'GraphWeightParam',1, ... 'GraphNormalize',1, ... 'ClassEdges',0,... 'LaplacianDegree',1, ... 'gamma_A',1.0,... 'gamma_I',1.0, ... 'mu',0.5); numberargs = nargin; if numberargs==0 return; end Names = fieldnames(options); [m,n] = size(Names); names = lower(Names); i = 1; while i <= numberargs arg = varargin{i}; if isstr(arg) break; end if ~isempty(arg) if ~isa(arg,'struct') error(sprintf('Expected argument %d to be a string parameter name or an options structure.', i)); end for j = 1:m if any(strcmp(fieldnames(arg),Names{j,:})) val = getfield(arg, Names{j,:}); else val = []; end if ~isempty(val) [valid, errmsg] = checkfield(Names{j,:},val); if valid options = setfield(options, Names{j,:},val); else error(errmsg); end end end end i = i + 1; end % A finite state machine to parse name-value pairs. if rem(numberargs-i+1,2) ~= 0 error('Arguments must occur in name-value pairs.'); end expectval = 0; while i <= numberargs 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) error(sprintf('Unrecognized parameter name ''%s''.', arg)); elseif length(j) > 1 % 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 '(' Names{j(1),:}]; for k = j(2:length(j))' msg = [msg ', ' Names{k,:}]; end msg = sprintf('%s).', msg); error(msg); end end expectval = 1; else [valid, errmsg] = checkfield(Names{j,:}, arg); if valid options = setfield(options, Names{j,:}, arg); else error(errmsg); end expectval = 0; end i = i + 1; end function [valid, errmsg] = checkfield(field,value) % CHECKFIELD Check validity of structure field contents. % [VALID, MSG] = CHECKFIELD('field',V) checks the contents of the specified % value V to be valid for the field 'field'. % valid = 1; errmsg = ''; if isempty(value) return end isFloat = length(value==1) & isa(value, 'double'); isPositive = isFloat & (value>=0); isString = isa(value, 'char'); range = []; requireInt = 0; switch field case 'NN' requireInt = 1; range=[1 Inf]; case 'k' requireInt=1; range=[1 Inf]; case 'GraphNormalize' requireInt = 1; range=[0 1]; case 'LaplacianDegree' requireInt = 1; range=[1 Inf]; case 'ClassEdges' requireInt = 1; range=[0 1]; case {'Kernel', 'GraphWeights', 'GraphDistanceFunction'} if ~isString, valid = 0; errmsg = sprintf('Invalid value for %s parameter: Must be a string', field); end case {'gamma_A', 'gamma_I','GraphWeightParam'} range = [0 Inf]; case {'mu'} range = [0 1]; case 'KernelParam' valid = 1; otherwise valid = 0; error('Unknown field name for Options structure.') end if ~isempty(range), if (value<range(1)) | (value>range(2)), valid = 0; errmsg = sprintf('Invalid value for %s parameter: Must be scalar in the range [%g..%g]', ... field, range(1), range(2)); end end if requireInt & ((value-round(value))~=0), valid = 0; errmsg = sprintf('Invalid value for %s parameter: Must be integer', ... field); end
github
marthawhite/reverse-prediction-master
Lfor_log.m
.m
reverse-prediction-master/loss/Lfor_log.m
1,069
utf_8
305b0fbfa01210acb7adbbd9a41331d2
function [f,g,log_constraint_opts] = Lfor_log(X,W,Y) % assumes 0 <= X, because f^-1(YU) = exp(YU) = X % f(z) = log(z), F(z) = [ln(z) - 1]^T z^T % f = D_F(XW||f^*(Y)) = sum((ln(XW) - 1).*(XW)) - YW^T X^T) % g = X^T(f(XW) - Y) = X^T(log(XW) - Y) % NOTE: FUNCTION VALUES CAN BE LESS THAN ZERO BECAUSE WE ARE % NOT WRITING DOWN THE ENTIRE D_F* (BECAUSE ARE ONLY MINIIZING PART % WITH Y AND U) if any(any(X <= 0)) X(X <= 0) = 1e-5; end t = size(Y,1); Zhat = X*W; Yhat = log(Zhat); f = sum(sum((Yhat-Y-ones(size(Y))).*Zhat)); if nargout > 1 g = X'*(Yhat-Y); end %persistent log_constraint_opts; log_constraint_opts = []; %if isempty(log_constraint_opts) % [log_constraint_opts.A, log_constraint_opts.b] = Lconst_log(X); %end % XW >= 0 % So need to put X on blkdiagonal since W will been linearized % This constrant only needs to be computed once, so save as persistent variables function [A,b] = Lconst_log(X) Acell = []; for i = 1:k Acell = [Acell {X}]; end A = blkdiag(Acell{:}); b = zeros(size(A,1),1); end end
github
zhujiagang/gating-ConvNet-code-master
classification_demo.m
.m
gating-ConvNet-code-master/caffe-action/matlab/demo/classification_demo.m
5,466
utf_8
45745fb7cfe37ef723c307dfa06f1b97
function [scores, maxlabel] = classification_demo(im, use_gpu) % [scores, maxlabel] = classification_demo(im, use_gpu) % % Image classification demo using BVLC CaffeNet. % % IMPORTANT: before you run this demo, you should download BVLC CaffeNet % from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html) % % **************************************************************************** % For detailed documentation and usage on Caffe's Matlab interface, please % refer to the Caffe Interface Tutorial at % http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab % **************************************************************************** % % input % im color image as uint8 HxWx3 % use_gpu 1 to use the GPU, 0 to use the CPU % % output % scores 1000-dimensional ILSVRC score vector % maxlabel the label of the highest score % % You may need to do the following before you start matlab: % $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64 % $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6 % Or the equivalent based on where things are installed on your system % and what versions are installed. % % Usage: % im = imread('../../examples/images/cat.jpg'); % scores = classification_demo(im, 1); % [score, class] = max(scores); % Five things to be aware of: % caffe uses row-major order % matlab uses column-major order % caffe uses BGR color channel order % matlab uses RGB color channel order % images need to have the data mean subtracted % Data coming in from matlab needs to be in the order % [width, height, channels, images] % where width is the fastest dimension. % Here is the rough matlab code for putting image data into the correct % format in W x H x C with BGR channels: % % permute channels from RGB to BGR % im_data = im(:, :, [3, 2, 1]); % % flip width and height to make width the fastest dimension % im_data = permute(im_data, [2, 1, 3]); % % convert from uint8 to single % im_data = single(im_data); % % reshape to a fixed size (e.g., 227x227). % im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % % subtract mean_data (already in W x H x C with BGR channels) % im_data = im_data - mean_data; % If you have multiple images, cat them with cat(4, ...) % Add caffe/matlab to your Matlab search PATH in order to use matcaffe if exist('../+caffe', 'dir') addpath('..'); else error('Please run this demo from caffe/matlab/demo'); end % Set caffe mode if exist('use_gpu', 'var') && use_gpu caffe.set_mode_gpu(); gpu_id = 0; % we will use the first gpu in this demo caffe.set_device(gpu_id); else caffe.set_mode_cpu(); end % Initialize the network using BVLC CaffeNet for image classification % Weights (parameter) file needs to be downloaded from Model Zoo. model_dir = '../../models/bvlc_reference_caffenet/'; net_model = [model_dir 'deploy.prototxt']; net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel']; phase = 'test'; % run with phase test (so that dropout isn't applied) if ~exist(net_weights, 'file') error('Please download CaffeNet from Model Zoo before you run this demo'); end % Initialize a network net = caffe.Net(net_model, net_weights, phase); if nargin < 1 % For demo purposes we will use the cat image fprintf('using caffe/examples/images/cat.jpg as input image\n'); im = imread('../../examples/images/cat.jpg'); end % prepare oversampled input % input_data is Height x Width x Channel x Num tic; input_data = {prepare_image(im)}; toc; % do forward pass to get scores % scores are now Channels x Num, where Channels == 1000 tic; % The net forward function. It takes in a cell array of N-D arrays % (where N == 4 here) containing data of input blob(s) and outputs a cell % array containing data from output blob(s) scores = net.forward(input_data); toc; scores = scores{1}; scores = mean(scores, 2); % take average scores over 10 crops [~, maxlabel] = max(scores); % call caffe.reset_all() to reset caffe caffe.reset_all(); % ------------------------------------------------------------------------ function crops_data = prepare_image(im) % ------------------------------------------------------------------------ % caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that % is already in W x H x C with BGR channels d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat'); mean_data = d.mean_data; IMAGE_DIM = 256; CROPPED_DIM = 227; % Convert an image returned by Matlab's imread to im_data in caffe's data % format: W x H x C with BGR channels im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR im_data = permute(im_data, [2, 1, 3]); % flip width and height im_data = single(im_data); % convert from uint8 to single im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR) % oversample (4 corners, center, and their x-axis flips) crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single'); indices = [0 IMAGE_DIM-CROPPED_DIM] + 1; n = 1; for i = indices for j = indices crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :); crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n); n = n + 1; end end center = floor(indices(2) / 2) + 1; crops_data(:,:,:,5) = ... im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:); crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
github
uncledickHe/EMBED-master
FISTA.m
.m
EMBED-master/src/FISTA.m
1,679
utf_8
cabc593990ccf7c5cf75d5d5b9048e57
function [x,info] = FISTA(fun, PSF, b, x0, maxit) % FISTA FAST ITERATIVE SHRINKAGE-THRESHOLDING ALGORITHM % % Usage: [x,info] = FISTA(@fun, PSF, b, x0, maxit) % % Input: % @fun: Function handle with objective function and gradient % PSF: Point-spread function % b : Beamformer map % x0: Starting vector % maxit: Maximum number of iterations % % % Output: % x: Source distribution for all iterations % info: Struct with info about % .obj: Objective function values as a function of iterations % .time: Total time of algorithm % % Author: Oliver Lylloff % Date: 25/9/14 % Latest revision: 25/9/14 % % % Reference: % Beck, Amir, and Marc Teboulle. 2009. % 'A Fast Iterative Shrinkage-Thresholding Algorithm for Linear Inverse Problems.' % SIAM Journal on Imaging Sciences 2 (1) (January): 183-202. % start_time = tic; % Initialize variables x = x0; xold = x; y = x; t = 1; % Precompute fft of PSF Fps = fft2(PSF); FpsT = fft2(rot90(PSF,2)); % Evaluate f(x0) fgx = @(x) fun(PSF,b,x,Fps,FpsT); % Compute Lipschitz constant L = lipschitz(PSF,Fps); % For n = 1 [fy,grady] = fgx(y); info.obj(1) = fy; % Start iteration n = 0; while n < maxit n = n+1; x = max(0,y - (1/L)*grady); tnew = (1+sqrt(1+4*t*t))/2; y = x + ((t-1)/tnew)*(x-xold); [fy,grady] = fgx(y); xold = x; t = tnew; info.obj(n+1) = fy; end info.time = toc(start_time); end function L = lipschitz(PSF,Fps) % Estimate Lipschitz constant by power iteration x = rand(size(PSF)); for k = 1:10 x = fftshift(ifft2(fft2(x).*Fps))/norm(x,'fro'); end L = norm(x,'fro')^2; % lambda(A'A) Assuming a symmetric matric A end
github
vildenst/3D-heart-models-master
meshIntersectImage.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Meshes/meshIntersectImage.m
3,242
utf_8
1f67da0fd88c98728ce085baf3a959e4
function flag = meshIntersectImage(meshIn, imageIn, varargin) % returns true if the mesh and the image intersect at voxels where the % image is nonzero n=1/2; dbg=false; i=1; while (i <= size(varargin,2)) if (strcmp( varargin{i} , 'debug')) dbg= true; elseif (strcmp( varargin{i} , 'thickness')) n = varargin{i+1}; i=i+1; end i = i+1; end % build AABB tree tree= AABB_tree(meshIn); tree.BuildTree(); % input bounds % For each leave of the tree, only if it its BB intersects with the BB of % the input image, rasterize flag = find_intersection(tree.rootNode, imageIn,n); end function flag = find_intersection(node, imageIn,n) % This function iterated and does "something" for all the nodes % of the other tree which lay inside the current tree flag=0; bb = imageIn.GetBounds(); bb=bb(:); if (node.intersectBB(bb)) % current node intersects with image, continue in this branch if (numel(node.leftNodes)) % if there are branches on the left flag = find_intersection(node.leftNodes, imageIn,n); if flag return; end end if (numel(node.rightNodes)) % if there are branches on the right flag = find_intersection(node.rightNodes, imageIn,n); if flag return; end end if (~numel(node.rightNodes) && ~numel(node.rightNodes)) % It is a leaf node: compute intersection %intersection = obj.intersectNodeWithNode(obj.rootNode, otherNode); flag = find_intersection_node(node, imageIn,n); end end end function flag = find_intersection_node(currentNode, imageIn,n) flag = false; ntriangles = currentNode.mesh.ntriangles; if (ntriangles > 1) disp('ERROR: at the end of the branch there should be only one triangle!') return ; end if (currentNode.mesh.npoints < 3) disp('ERROR: This triangle has less than 3 points!') return ; end % Find coordinate system of the triangle normal = currentNode.mesh.GetTriangleNormal(1); [x y ] = vtkMathPerpendiculars(normal(:),pi/2); M = [x y normal(:)]; % convert nonzero imagePoints to the trangle plane nonzero_indices = find(abs(imageIn.data)>0); if ~numel(nonzero_indices) return ; end [x y z] = ind2sub(imageIn.size',nonzero_indices); imagePoints = imageIn.GetPosition([x(:) y(:) z(:)]'); imagePoints_transformed = M \ imagePoints; % see if the points are in the triangle triangleCorners = currentNode.mesh.points(currentNode.mesh.triangles(1,:),:)'; triangleCorners_transformed = M \ triangleCorners; fl = PointInTriangle(imagePoints_transformed(1:2,:) , triangleCorners_transformed(1:2,1),triangleCorners_transformed(1:2,2),triangleCorners_transformed(1:2,3),'maxChunkSize',150); %pointsCloser = abs(imagePoints_transformed(3,:)-triangleCorners_transformed(3,1))<imageIn.spacing(3); pointsCloser = abs(imagePoints_transformed(3,:)-triangleCorners_transformed(3,1))<n*norm(imageIn.spacing); pointsInTriangle = fl & pointsCloser; flag = numel(nonzeros(pointsInTriangle))>0; end
github
vildenst/3D-heart-models-master
meshBinarize.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Meshes/meshBinarize.m
5,378
utf_8
68a9f0e757ca5428555ce4c31170603c
function imageOut = meshBinarize(meshIn, imageIn, varargin) % converts a mesh into a binary image (rasterization), on the grid defined % % Options: % 'thickness' , n -> n is the number of voxel sizes at each size of % the mesh that will be painted (by default, n=1/2) n=1/2; dbg=false; i=1; enlarge=0; MAX_CHUNK_SIZE = 50; while (i <= size(varargin,2)) if (strcmp( varargin{i} , 'thickness')) n= varargin{i+1}; i = i+1; elseif (strcmp( varargin{i} , 'enlarge')) enlarge= varargin{i+1}; i = i+1; elseif(strcmp( varargin{i} , 'debug')) dbg= true; elseif (strcmp(varargin{i},'maxChunkSize')) MAX_CHUNK_SIZE = varargin{i+1}; i=i+1; end i = i+1; end % build AABB tree meshOut = MeshType(meshIn); meshOut.triangles =meshIn.triangles; imageOut = ImageType(imageIn); if enlarge centerpoint = mean(meshIn.points); if enlarge <0 % this only works for planes! Compute intersection of bounding box % and plane plane.normal = meshIn.GetNormalAtFaces(1); plane.origin = meshIn.points(meshIn.triangles(1),:); % transform positions to align with normal [x y] = vtkMathPerpendiculars(plane.normal',pi/2); M = [x y plane.normal(:); 0 0 0]; M = [M [plane.origin(:) ; 1] ]; NCHUNKS = ceil(imageIn.size/MAX_CHUNK_SIZE); chunked_size = ceil(imageIn.size./NCHUNKS)'; [ix iy iz]= ndgrid(0:NCHUNKS(1)-1,0:NCHUNKS(2)-1,0:NCHUNKS(3)-1); intervals = [ix(:) iy(:) iz(:)]; clear ix iy iz; for i=1:size(intervals,1) ranges([1 3 5]) = intervals(i,:).*chunked_size+1; ranges([2 4 6]) = min([(intervals(i,:)+[1 1 1]).*chunked_size ; imageIn.size']); ranges_size = ranges([2 4 6])-ranges([1 3 5])+[1 1 1]; % generate all the indexes of the target image [x y z] = ndgrid( ranges(1):ranges(2),ranges(3):ranges(4),ranges(5):ranges(6)); positions = imageIn.GetPosition([x(:) y(:) z(:)]'); clear x y z; tx_positions = M \ [positions ; ones(1,size(positions,2)) ]; imageOut.data(ranges(1):ranges(2),ranges(3):ranges(4),ranges(5):ranges(6)) = reshape(abs(tx_positions(3,:)')<n,ranges_size); end return; else for i=1:meshIn.npoints meshOut.points(i,:)=(meshIn.points(i,:)-centerpoint)*enlarge+ centerpoint; end end else meshOut.points=meshIn.points; end tree= AABB_tree(meshOut); tree.BuildTree(); % input bounds % For each leave of the tree, only if it its BB intersects with the BB of % the input image, rasterize imageOut = rasterize(tree.rootNode, imageOut,n); end function imageOut = rasterize(node, imageIn,n) % This function iterated and does "something" for all the nodes % of the other tree which lay inside the current tree imageOut = ImageType(imageIn); imageOut.data = imageIn.data; bb = imageIn.GetBounds(); if (node.intersectBB(bb)) % current node intersects with image, continue in this branch if (numel(node.leftNodes)) % if there are branches on the left imageOut = rasterize(node.leftNodes, imageOut,n); end if (numel(node.rightNodes)) % if there are branches on the right imageOut = rasterize(node.rightNodes, imageOut,n); end if (~numel(node.rightNodes) && ~numel(node.rightNodes)) % It is a leaf node: compute intersection %intersection = obj.intersectNodeWithNode(obj.rootNode, otherNode); imageOut = rasterizeNode(node, imageOut,n); end end end function imageOut = rasterizeNode(currentNode, imageIn,n) % rasterize the current node into the image imageOut = ImageType(imageIn); imageOut.data = imageIn.data; ntriangles = currentNode.mesh.ntriangles; if (ntriangles > 1) disp('ERROR: at the end of the branch there should be only one triangle!') return ; end if (currentNode.mesh.npoints < 3) disp('ERROR: This triangle has less than 3 points!') return ; end % Find coordinate system of the triangle normal = currentNode.mesh.GetTriangleNormal(1); [x y ] = vtkMathPerpendiculars(normal(:),pi/2); M = [x y normal(:)]; % convert imagePoints to the trangle plane [x y z] = ndgrid(1:imageIn.size(1), 1:imageIn.size(2), 1:imageIn.size(3)); imagePoints = imageIn.GetPosition([x(:) y(:) z(:)]'); imagePoints_transformed = M \ imagePoints; % see if the points are in the triangle triangleCorners = currentNode.mesh.points(currentNode.mesh.triangles(1,:),:)'; triangleCorners_transformed = M \ triangleCorners; flag = PointInTriangle(imagePoints_transformed(1:2,:) , triangleCorners_transformed(1:2,1),triangleCorners_transformed(1:2,2),triangleCorners_transformed(1:2,3),'maxChunkSize',150); %pointsCloser = abs(imagePoints_transformed(3,:)-triangleCorners_transformed(3,1))<imageIn.spacing(3); pointsCloser = abs(imagePoints_transformed(3,:)-triangleCorners_transformed(3,1))<n*norm(imageIn.spacing); pointsInTriangle = flag & pointsCloser; pointsInTriangle = reshape(pointsInTriangle, imageIn.size' ); imageOut.data(pointsInTriangle)=1; end
github
vildenst/3D-heart-models-master
meshClip.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Meshes/meshClip.m
3,132
utf_8
3114d4f956c33fad0ccaee6c15e99104
function imageOut = meshClip(meshIn, meshStencil, varargin) % Clips the input mesh, meshIn, using another mesh as a stencil % % Options: % none dbg=false; i=1; while (i <= size(varargin,2)) if (strcmp( varargin{i} , 'thickness')) %n= varargin{i+2}; %i = i+1; elseif(strcmp( varargin{i} , 'debug')) dbg= true; end i = i+1; end % build AABB tree tree= AABB_tree(meshIn); tree.BuildTree(); % input bounds inputBounds = imageIn.GetBounds(); imageOut = ImageType(imageIn); % For each leave of the tree, only if it its BB intersects with the BB of % the input image, rasterize imageOut = rasterize(tree.rootNode, imageOut,n); end function imageOut = rasterize(node, imageIn,n) % This function iterated and does "something" for all the nodes % of the other tree which lay inside the current tree imageOut = ImageType(imageIn); imageOut.data = imageIn.data; bb = imageIn.GetBounds(); if (node.intersectBB(bb)) % current node intersects with image, continue in this branch if (numel(node.leftNodes)) % if there are branches on the left imageOut = rasterize(node.leftNodes, imageOut,n); end if (numel(node.rightNodes)) % if there are branches on the right imageOut = rasterize(node.rightNodes, imageOut,n); end if (~numel(node.rightNodes) && ~numel(node.rightNodes)) % It is a leaf node: compute intersection %intersection = obj.intersectNodeWithNode(obj.rootNode, otherNode); imageOut = rasterizeNode(node, imageOut,n); end end end function imageOut = rasterizeNode(currentNode, imageIn,n) % rasterize the current node into the image imageOut = ImageType(imageIn); imageOut.data = imageIn.data; ntriangles = currentNode.mesh.ntriangles; if (ntriangles > 1) disp('ERROR: at the end of the branch there should be only one triangle!') return ; end % Find coordinate system of the triangle normal = currentNode.mesh.GetTriangleNormal(1); [x y ] = vtkMathPerpendiculars(normal,pi/2); M = [x y normal(:)]; % convert imagePoints to the trangle plane [x y z] = ndgrid(1:imageIn.size(1), 1:imageIn.size(2), 1:imageIn.size(3)); imagePoints = imageIn.GetPosition([x(:) y(:) z(:)]'); imagePoints_transformed = M \ imagePoints; % see if the points are in the triangle triangleCorners = currentNode.mesh.points(currentNode.mesh.triangles(1,:),:)'; triangleCorners_transformed = M \ triangleCorners; flag = PointInTriangle(imagePoints_transformed(1:2,:) , triangleCorners_transformed(1:2,1),triangleCorners_transformed(1:2,2),triangleCorners_transformed(1:2,3)); %pointsCloser = abs(imagePoints_transformed(3,:)-triangleCorners_transformed(3,1))<imageIn.spacing(3); pointsCloser = abs(imagePoints_transformed(3,:)-triangleCorners_transformed(3,1))<n*norm(imageIn.spacing); pointsInTriangle = flag & pointsCloser; pointsInTriangle = reshape(pointsInTriangle, imageIn.size' ); imageOut.data(pointsInTriangle)=1; end
github
vildenst/3D-heart-models-master
PointInTriangle.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Geometry/PointInTriangle.m
1,429
utf_8
1e0294774d58c2ff4462665e17eee244
function flag = PointInTriangle(p, a,b,c,varargin) % returns true if the point p is inside the triangle defined by a,b,c (in 2D) % p, a b and c are column points MAX_CHUNK_SIZE = 50; for i=1:size(varargin,2) if (strcmp(varargin{i},'maxChunkSize')) MAX_CHUNK_SIZE = varargin{i+1}; i=i+1; end end NCHUNKS = ceil(size(p,2)/MAX_CHUNK_SIZE.^3); chunked_size = ceil(size(p,2)./NCHUNKS); intervals = 0:(NCHUNKS-1); flag = zeros(1,size(p,2)); if norm(a-c)<1E-10 || norm(a-b)<1E-10 return; end for i=1:numel(intervals) range(1) = intervals(i)*chunked_size+1; range(2) = min([(intervals(i)+1)*chunked_size size(p,2)]); flag(range(1):range(2)) = SameSide(p(:,range(1):range(2)),a, b,c) .* SameSide(p(:,range(1):range(2)),b, a,c) .* SameSide(p(:,range(1):range(2)),c, a,b); end end function flag = SameSide(p1,p2, a,b) % This function and the next one are taken from http://www.blackpawn.com/texts/pointinpoly/default.html npts = size(p1,2); p1 = [p1; zeros(1,npts)]; %p2Large = p2*ones(1,npts); aLarge = [a; 0]*ones(1,npts); bLarge = [b; 0]*ones(1,npts); cp1 = cross(bLarge-aLarge, p1-aLarge,1); cp2 = cross([b-a; 0], [p2; 0]-[a; 0],1); cp2Large = cp2*ones(1,npts); epsilon = 10^-10; flag = dot(cp1,cp2Large,1) >= (0-epsilon); end
github
vildenst/3D-heart-models-master
quatToRMat_igtl.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Geometry/quatToRMat_igtl.m
695
utf_8
9e936dfbc7128a6485d398ecf10859e1
% Converts a quaternion to a 3quat(1)3 rotation matriquat(1) function RMat = quatToRMat_igtl(quat) quat = quat / norm(quat); q00 = quat(1) * quat(1)*2; % xx q0x = quat(1) * quat(2)*2; % xy q0y = quat(1) * quat(3)*2; % xz q0z = quat(1) * quat(4)*2; % xw qxx = quat(2) * quat(2)*2; % yy qxy = quat(2) * quat(3)*2; % yz qxz = quat(2) * quat(4)*2; % yw qyy = quat(3) * quat(3)*2; % zz qyz = quat(3) * quat(4)*2; % zw qzz = quat(4) * quat(4)*2; % ww RMat(1,1) = 1.0 - (qxx + qyy); RMat(1,2) =q0x -qyz; RMat(1,3) =q0y + qxz; RMat(2,1) = q0x + qyz; RMat(2,2) = 1.0 -(q00 +qyy); RMat(2,3) = qxy - q0z; RMat(3,1) = q0y - qxz; RMat(3,2) = qxy + q0z; RMat(3,3) = 1.0 -(q00 + qxx); end
github
vildenst/3D-heart-models-master
quatToRMat.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Geometry/quatToRMat.m
663
utf_8
80939c0da0ee48fa73fe3cb23860ca2a
% Converts a quaternion to a 3x3 rotation matrix function RMat = quatToRMat(quat) quat = quat / norm(quat); q00 = quat(1) * quat(1); q0x = quat(1) * quat(2); q0y = quat(1) * quat(3); q0z = quat(1) * quat(4); qxx = quat(2) * quat(2); qxy = quat(2) * quat(3); qxz = quat(2) * quat(4); qyy = quat(3) * quat(3); qyz = quat(3) * quat(4); qzz = quat(4) * quat(4); RMat = zeros(3,3); RMat(1,1) = q00 + qxx - qyy - qzz; RMat(1,2) = 2 * (qxy - q0z); RMat(1,3) = 2 * (qxz + q0y); RMat(2,1) = 2 * (qxy + q0z); RMat(2,2) = q00 - qxx + qyy - qzz; RMat(2,3) = 2 * (qyz - q0x); RMat(3,1) = 2 * (qxz - q0y); RMat(3,2) = 2 * (qyz + q0x); RMat(3,3) = q00 - qxx - qyy + qzz; end
github
vildenst/3D-heart-models-master
PointInFrustum.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Geometry/PointInFrustum.m
1,559
utf_8
c0f77e35cf25a5d0459538a974dc4342
function flag = PointInFrustum(p, frustum,varargin) % returns true if the point p is inside the frustum (in 3D) % p are column points MAX_CHUNK_SIZE = 50; for i=1:size(varargin,2) if (strcmp(varargin{i},'maxChunkSize')) MAX_CHUNK_SIZE = varargin{i+1}; i=i+1; end end NCHUNKS = ceil(size(p,2)/MAX_CHUNK_SIZE.^3); chunked_size = ceil(size(p,2)./NCHUNKS); intervals = 0:(NCHUNKS-1); flag = zeros(1,size(p,2)); for i=1:numel(intervals) range(1) = intervals(i)*chunked_size+1; range(2) = min([(intervals(i)+1)*chunked_size size(p,2)]); flag(range(1):range(2)) = isInside(p(:,range(1):range(2)),frustum) ; end end function flag = isInside(p,frustum) npts = size(p,2); flag = ones(1,npts); M = [frustum.directions frustum.centre(:) ; 0 0 0 1]; points_in_frustum_coordinates = M\p; radiuses = norm(points_in_frustum_coordinates(1:3,:)); flag(radiuses<frustum.radiuses(1))=0; flag(radiuses>frustum.radiuses(2))=0; theta_frustum = [atan2(points_in_frustum_coordinates(1,:),points_in_frustum_coordinates(3,:)) atan2(points_in_frustum_coordinates(2,:),points_in_frustum_coordinates(3,:))]*180/pi; % first row: angle1, second row: angle2 a1 = angleInRange(theta_frustum(1,:),frustum.angles([1 2]),1E-03); a2 = angleInRange(theta_frustum(2,:),frustum.angles([3 4]),1E-03); inAngle = intersect(a1,a2); outAngle = setdiff(1:npts,inAngle); flag(outAngle)=0; end
github
vildenst/3D-heart-models-master
PointInTriangle3D.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Geometry/PointInTriangle3D.m
773
utf_8
1efcaba15df43c2b2d0af1658acb24de
function flag = PointInTriangle3D(p, a,b,c) % returns true if the point p is inside the triangle defined by a,b,c (in 3D) % p, a b and c are column points flag = SameSide(p,a, b,c) .* SameSide(p,b, a,c) .* SameSide(p,c, a,b); end function flag = SameSide(p1,p2, a,b) % This function and the next one are taken from http://www.blackpawn.com/texts/pointinpoly/default.html npts = size(p1,2); p1 = [p1; zeros(1,npts)]; %p2Large = p2*ones(1,npts); aLarge = [a; 0]*ones(1,npts); bLarge = [b; 0]*ones(1,npts); cp1 = cross(bLarge-aLarge, p1-aLarge,1); cp2 = cross([b-a; 0], [p2; 0]-[a; 0],1); cp2Large = cp2*ones(1,npts); epsilon = 10^-10; flag = dot(cp1,cp2Large,1) >= (0-epsilon); end
github
vildenst/3D-heart-models-master
coneImage.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Sources/coneImage.m
1,756
utf_8
6b9f19b1dc5ee1977b18d4b71c43b972
% test_generateCone function out = coneImage(points_axis, points_side, ref_im) %% parameters out = ImageType(ref_im); th = sqrt(sum(ref_im.spacing.^2))/2; %th=48; npieces=1; %% get the apex of the cone Up = (points_axis(:,2)-points_axis(:,1))/norm(points_axis(:,2)-points_axis(:,1)); Uq = (points_side(:,2)-points_side(:,1))/norm(points_side(:,2)-points_side(:,1)); P0 = points_axis(:,1); Q0 = points_side(:,1); b = -1*[(P0-Q0)'*Up; (P0-Q0)'*Uq]; A = [ Up'*Up -Uq'*Up; Up'*Uq -Uq'*Uq]; lambda = A\b; P1 = P0 + lambda(1)*Up; %Q1 = Q0 + lambda(2)*Uq; apex = P1; %% Get distance to the cone [ x y z] = ndgrid(1:ref_im.size(1), 1:ref_im.size(2), 1:ref_im.size(3)); positions = ref_im.GetPosition([x(:) y(:) z(:)]'); vectors = positions - apex*ones(1,size(positions,2)); vectors_norm = sqrt(vectors(1,:).^2+vectors(2,:).^2+vectors(3,:).^2); vectors(1,:)=vectors(1,:)./vectors_norm; vectors(2,:)=vectors(2,:)./vectors_norm; vectors(3,:)=vectors(3,:)./vectors_norm; angle_with_coneAxis = acos(abs(dot(vectors,(Up*ones(1,size(vectors,2))),1))); cone_angle= acos(abs(dot(Uq,Up))); distance_from_point_to_cone = vectors_norm .* sin(cone_angle*ones(1,size(angle_with_coneAxis,2)) -angle_with_coneAxis); %distance_from_point_to_cone = abs(angle_with_coneAxis-cone_angle*ones(1,size(angle_with_coneAxis,2))); %distance_from_point_to_cone(distance_from_point_to_cone<0)=0; out.data = reshape(abs(distance_from_point_to_cone)<th,out.size'); %out.data = reshape(distance_from_point_to_cone,out.size'); %out.data = reshape(angle_with_coneAxis*180/pi,out.size'); % out2=VectorImageType(ref_im); % out2.datax = reshape(vectors(1,:),out2.size'); % out2.datay = reshape(vectors(2,:),out2.size'); % out2.dataz = reshape(vectors(3,:),out2.size'); end
github
vildenst/3D-heart-models-master
prismImage.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Sources/prismImage.m
2,348
utf_8
eaaddbc7ba27025ae9971ac325dc7ba5
% test_generateCone function out = prismImage(roi_file, ref_im,varargin) % generate a prism from a roi, using the roi as base section and extruding % along the normal to the roi plane %% parameters MAX_CHUNK_SIZE = 50; MAX_CHUNK_SIZE = 50; for i=1:size(varargin,2) if (strcmp(varargin{i},'debug')) dbg = true; elseif (strcmp(varargin{i},'maxChunkSize')) MAX_CHUNK_SIZE = varargin{i+1}; i=i+1; end end out = ImageType(ref_im); th = sqrt(sum(ref_im.spacing.^2))/2; npieces=1; %% Read roi % ------------------------------------------- read roi [roinormal roiorigin points] = read_roi(roi_file); roi.normal = roinormal; roi.origin = roiorigin; [x y]=vtkMathPerpendiculars(roi.normal,pi/2); M=eye(4); M(1:3,1:3) = [x(:) y(:) roi.normal(:)]; M(1:3,4) = roi.origin; npoints = size(points,2); %% The image will be filled in NCHUNKS = ceil(ref_im.size/MAX_CHUNK_SIZE); chunked_size = ceil(ref_im.size./NCHUNKS)'; [ix iy iz]= ndgrid(0:NCHUNKS(1)-1,0:NCHUNKS(2)-1,0:NCHUNKS(3)-1); intervals = [ix(:) iy(:) iz(:)]; clear ix iy iz; for i=1:size(intervals,1) ranges([1 3 5]) = intervals(i,:).*chunked_size+1; ranges([2 4 6]) = min([(intervals(i,:)+[1 1 1]).*chunked_size ; ref_im.size']); ranges_size = ranges([2 4 6])-ranges([1 3 5])+[1 1 1]; % generate all the indexes of the target image [x y z] = ndgrid( ranges(1):ranges(2),ranges(3):ranges(4),ranges(5):ranges(6)); ref_positions = ref_im.GetPosition([x(:) y(:) z(:)]'); clear x y z; ref_positions_2D = M \ [ref_positions; ones(1,size(ref_positions,2))]; clear ref_positions; % The origin of the system is the centroid of the points centroid = mean(points,2); % make the triangles for j=1:npoints-1 % triangle i is defined by point i, point i+1 and centroid. Seee if the % ref positions are inside it A = points(1:2,j); B = points(1:2,j+1); pointsInside = PointInTriangle(ref_positions_2D(1:2,:), A,B,centroid(1:2)); pointsInside = reshape(pointsInside,ranges_size); out.data(ranges(1):ranges(2),ranges(3):ranges(4),ranges(5):ranges(6)) = ... double(out.data(ranges(1):ranges(2),ranges(3):ranges(4),ranges(5):ranges(6)) | pointsInside>0); end clear ref_positions_2D pointsInside ; end end
github
vildenst/3D-heart-models-master
ellipsoidMesh.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Sources/ellipsoidMesh.m
5,858
utf_8
40ad36dfde772dfe5cff5b18d784b22e
function m = ellipsoidMesh(c,r,varargin) % m = ellipsoidMesh(c,r) % m = ellipsoidMesh(c,r,options) % % creates a MeshType object of a sphere of radius r (vector) and center c % % options meaning default % ------- ------- ------- % % 'resolution' sphereRes 16 % 'theta' angle [-180 180] % 'phi' angle [-90 90] % 'rotatez' angle 0 % 'rotatey' angle 0 % 'rotatex' angle 0 % 'rotationOrder' int {0} = Rx - Ry - Rz % 1 = Ry - Rx - Rz global closed; resolution = 8; % half resolution for phi than for theta theta = [-180 180]; phi = [-90 90]; rotatez = 0; rotatey = 0; rotatex = 0; rotationOrder=0; nOptions = size(varargin,2); % Argument reading if (nOptions > 0) if (rem(nOptions,2)~=0) disp('Error in the arguments, please check the option list'); return; end i=1; while(i<=nOptions) if (strcmp(varargin{i},'resolution')) resolution = varargin{i+1}; i = i+2; elseif (strcmp(varargin{i},'theta')) theta = varargin{i+1}; i = i+2; elseif (strcmp(varargin{i},'phi')) phi = varargin{i+1}; i = i+2; elseif (strcmp(varargin{i},'rotatez')) rotatez = varargin{i+1}; i = i+2; elseif (strcmp(varargin{i},'rotatey')) rotatey = varargin{i+1}; i = i+2; elseif (strcmp(varargin{i},'rotatex')) rotatex = varargin{i+1}; i = i+2; elseif (strcmp(varargin{i},'rotationOrder')) rotationOrder= varargin{i+1}; i = i+2; end end end phi(1)=max(phi(1),-90); phi(2)=min(phi(2),90); theta(1)=max(theta(1),-180); theta(2)=min(theta(2),180); %'theta',[-180 180],'phi',[-90 90] closed = true; if (theta(2)-360< theta(1)) closed = false; end % -------------------------- thetaResolution = resolution; phiResolution = resolution; numPts = phiResolution * resolution + 2; % phires * thetares +2 numPolys = phiResolution *2* resolution; % Create sphere deltaTheta = (theta(2)-theta(1))/thetaResolution; deltaPhi = (phi(2)-phi(1))/phiResolution; t = theta(1):deltaTheta:theta(2); p = (phi(1):deltaPhi:phi(2))'; % Create conectivity polygons = []; points = []; numpoles = 0; poleNorthFound = false; poleSouthFound = false; for phi_=p'; for theta_=t; % north pole if (~poleNorthFound && ~phi_) poleNorthFound = true; numpoles = numpoles+1; for i=1:thetaResolution vertex1 = i+1; vertex2 = cyclicNext((vertex1),[2 thetaResolution+numpoles]); vertex3 = 1; % the pole polygons = [polygons ; vertex1 vertex2 vertex3]; end x = r(1)*cosd(phi_)*cosd(theta_); y = r(2)*cosd(phi_)*sind(theta_); z = r(3)*sind(phi_); points = [points; [x y z]+c']; end % north pole if (~poleSouthFound && phi_>=90) poleSouthFound = true; numpoles = numpoles+1; for i=1:thetaResolution vertex1 = size(points,1)-thetaResolution+i; vertex2 = cyclicNext((vertex1),[size(points,1)+1-thetaResolution size(points,1)]); vertex3 = size(points,1)+1; % the pole polygons = [polygons ; vertex1 vertex2 vertex3]; end x = r(1)*cosd(phi_)*cosd(theta_); y = r(2)*cosd(phi_)*sind(theta_); z = r(3)*sind(phi_); points = [points; [x y z]+c']; end if (phi_ && phi_<90 && theta_ < t(end)) x = r(1)*cosd(phi_)*cosd(theta_); y = r(2)*cosd(phi_)*sind(theta_); z = r(3)*sind(phi_); points = [points; [x y z]+c']; end end end % band conectivity for i=2:(phiResolution-1); for j=1:(thetaResolution) % conectivity vertex1 = (i-2)*thetaResolution+j+1; vertex2 = cyclicNext(vertex1,[(i-2)*thetaResolution+2 (i-2)*thetaResolution+thetaResolution+1]); vertex3 = cyclicNext(vertex1+thetaResolution-1,[(i-1)*thetaResolution+2 (i-1)*thetaResolution+thetaResolution+1]); polygons = [polygons ; vertex1 vertex2 vertex3]; vertex1 = (i-2)*thetaResolution+j+1; vertex3 = cyclicNext(vertex1+thetaResolution-1,[(i-1)*thetaResolution+2 (i-1)*thetaResolution+thetaResolution+1]); vertex2 = cyclicPrevious(vertex3,[(i-1)*thetaResolution+2 (i-1)*thetaResolution+thetaResolution+1]); polygons = [polygons ; vertex1 vertex2 vertex3]; end end Rx = eye(3); Ry = eye(3); Rz = eye(3); if (rotatex~=0) Rx = [1 0 0 0 cos(rotatex) -sin(rotatex) 0 sin(rotatex) cos(rotatex)]; end if (rotatey~=0) Ry = [cos(rotatey) 0 sin(rotatey) 0 1 0 -sin(rotatey) 0 cos(rotatey)]; end if (rotatez~=0) Rz = [cos(rotatez) -sin(rotatez) 0 sin(rotatez) cos(rotatez) 0 0 0 1]; end switch (rotationOrder) case 0 M = Rz * Ry * Rx; case 1 M = Rz * Rx * Ry; end for i=1:size(points,1) points(i,:) = (M * (points(i,:)'-c(:)) +c(:))'; end % create mesh m = MeshType(size(points,1),size(polygons,1)); m.points =points; m.triangles = polygons; % just for testing end function n = cyclicNext(a,b) global closed; % a index % b=[b1 b2] min and max index % if (a<b(1)) % a=b(1); % end n = a+1; if (n>b(2)) if (closed) n = b(1); else n=a; end end end function n = cyclicPrevious(a,b) global closed; % a index n = a-1; if (n<b(1)) if (closed) n = b(2); else n=a; end end end
github
vildenst/3D-heart-models-master
planeImage.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Sources/planeImage.m
1,886
utf_8
79304dd1339002b3779451aceb18423f
function out = planeImage(p, n, ref_im,varargin) %lets say that the plane is defined by the point p and the %normal vector n. skeletonize_plane=false; MAX_CHUNK_SIZE = 50; for i=1:size(varargin,2) if (strcmp(varargin{i},'debug')) dbg = true; elseif (strcmp(varargin{i},'skeletonize')) skeletonize_plane= true; i=i+1; elseif (strcmp(varargin{i},'maxChunkSize')) MAX_CHUNK_SIZE = varargin{i+1}; i=i+1; end end %% parameters out = ImageType(ref_im); th = sqrt(sum(ref_im.spacing.^2))/2; NCHUNKS = ceil(out.size/MAX_CHUNK_SIZE); chunked_size = ceil(out.size./NCHUNKS)'; [ix iy iz]= ndgrid(0:NCHUNKS(1)-1,0:NCHUNKS(2)-1,0:NCHUNKS(3)-1); intervals = [ix(:) iy(:) iz(:)]; clear ix iy iz; for i=1:size(intervals,1) ranges([1 3 5]) = intervals(i,:).*chunked_size+1; ranges([2 4 6]) = min([(intervals(i,:)+[1 1 1]).*chunked_size ; out.size']); ranges_size = ranges([2 4 6])-ranges([1 3 5])+[1 1 1]; % generate all the indexes of the target image [x y z] = ndgrid( ranges(1):ranges(2),ranges(3):ranges(4),ranges(5):ranges(6)); %[ x y z] = ndgrid(1:out.size(1), 1:out.size(2), 1:out.size(3)); positions = out.GetPosition([x(:) y(:) z(:)]'); clear x y z; planeToPoint = p*ones(1,size(positions,2)) - positions; clear positions; distancesToPlane = abs(n'*planeToPoint); clear planeToPoint; distance_th = sqrt(sum(ref_im.spacing.^2))/2; % world coordinates outputValues = double(distancesToPlane < distance_th ); clear distancesToPlane; %out.data(distancesToPlane<distance_th)=1; out.data(ranges(1):ranges(2),ranges(3):ranges(4),ranges(5):ranges(6)) = reshape(outputValues,ranges_size); clear outputValues; end bounds = out.GetBounds(0.9,true); out = cropImage(out,bounds); if (skeletonize_plane) out.data = skeletonize3D(out.data); end end
github
vildenst/3D-heart-models-master
cylinderImage.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Sources/cylinderImage.m
1,760
utf_8
68ba9dd0b57b2de7f1309fb205a41b9e
% test_generateCone function out = cylinderImage(points_axis, points_side, ref_im) %% parameters out = ImageType(ref_im); th = sqrt(sum(ref_im.spacing.^2))/2; %th=48; npieces=1; %% get the apex of the cone Up = (points_axis(:,2)-points_axis(:,1))/norm(points_axis(:,2)-points_axis(:,1)); Uq = (points_side(:,2)-points_side(:,1))/norm(points_side(:,2)-points_side(:,1)); P0 = points_axis(:,1); Q0 = points_side(:,1); b = -1*[(P0-Q0)'*Up; (P0-Q0)'*Uq]; A = [ Up'*Up -Uq'*Up; Up'*Uq -Uq'*Uq]; lambda = A\b; P1 = P0 + lambda(1)*Up; %Q1 = Q0 + lambda(2)*Uq; apex = P1; %% Get distance to the cone [ x y z] = ndgrid(1:ref_im.size(1), 1:ref_im.size(2), 1:ref_im.size(3)); positions = ref_im.GetPosition([x(:) y(:) z(:)]'); vectors = positions - apex*ones(1,size(positions,2)); vectors_norm = sqrt(vectors(1,:).^2+vectors(2,:).^2+vectors(3,:).^2); vectors(1,:)=vectors(1,:)./vectors_norm; vectors(2,:)=vectors(2,:)./vectors_norm; vectors(3,:)=vectors(3,:)./vectors_norm; angle_with_coneAxis = acos(abs(dot(vectors,(Up*ones(1,size(vectors,2))),1))); cone_angle= acos(abs(dot(Uq,Up))); distance_from_point_to_cone = vectors_norm .* sin(cone_angle*ones(1,size(angle_with_coneAxis,2)) -angle_with_coneAxis); %distance_from_point_to_cone = abs(angle_with_coneAxis-cone_angle*ones(1,size(angle_with_coneAxis,2))); %distance_from_point_to_cone(distance_from_point_to_cone<0)=0; out.data = reshape(abs(distance_from_point_to_cone)<th,out.size'); %out.data = reshape(distance_from_point_to_cone,out.size'); %out.data = reshape(angle_with_coneAxis*180/pi,out.size'); % out2=VectorImageType(ref_im); % out2.datax = reshape(vectors(1,:),out2.size'); % out2.datay = reshape(vectors(2,:),out2.size'); % out2.dataz = reshape(vectors(3,:),out2.size'); end
github
vildenst/3D-heart-models-master
gradientBinaryImage.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Basic/gradientBinaryImage.m
2,165
utf_8
69f6baceb835769d25fc803e1dce1151
function out = gradientBinaryImage(im,varargin) % out = gradientImage(im) % % Fast gradient of a binary image % Works for ImageType % difforder = 1; binary=false; dbg=false; for i=1:size(varargin,2) if (strcmp(varargin{i},'dbg')) dbg=true; elseif (strcmp(varargin{i},'order')) difforder=varargin{1}; elseif (strcmp(varargin{i},'binary')) binary=true; end end %---------------------------- out=[]; % maybe something wrong: the transpose matlab shit % Using the derivative of a Gaussian to guarantee smoothness filter_size = 7; sigma = 1.5; % in pixels for d=1:im.ndimensions [d_gaussian_kernel,d_gaussian_plain] = derivativeOfGaussian(filter_size, sigma, d, im.ndimensions, im.spacing); %d_gaussian_kernel = d_gaussian_kernel/sum(abs(d_gaussian_kernel(:))); d_gaussian_kernel = d_gaussian_kernel/sum(d_gaussian_plain(:).^2); dx = convn(im.data,d_gaussian_kernel,'same');%/im.spacing(d); out = cat(im.ndimensions+1,out,dx); end end function [d_gaussian_kernel_derivative,d_gaussian_kernel] = derivativeOfGaussian(filter_size, sigma_, d, ndimensions, spacing) % example of inputs: %filter_size = 5; %sigma = 3; % in pixels % d=2 (direction along which we do the derivative) filter_radius = floor(filter_size/2); sigma = sigma_ * spacing(d); % Below will give me the gaussian function along direction d. For example, % for a 3D image and along direction y: %d_gaussian_func_2 =@(x,y,z) exp(-(x.^2)/(2*sigma^2)).*-y/(sigma^2).*exp(-(y.^2)/(2*sigma^2)).*exp(-(z.^2)/(2*sigma^2)); str1=''; str2=''; str3 =''; str4 = ''; for i=1:ndimensions str2=[str2 'x' num2str(i) ',']; if i==d str1 = [str1 '-x' num2str(i) '/(sigma^2).*exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; else str1 = [str1 'exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; end str3 = [str3 'exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; str4 = [str4 '(-filter_radius:filter_radius)*spacing(' num2str(i) '),']; end eval([ '[' str2(1:end-1) ']=ndgrid(' str4(1:end-1) ');']); eval(['d_gaussian_kernel_derivative= ' str1(1:end-2) ';']); eval(['d_gaussian_kernel= ' str3(1:end-2) ';']); end
github
vildenst/3D-heart-models-master
gradientImage.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Basic/gradientImage.m
3,508
utf_8
e7bc4b29c506c5b31a86029b9080bd4b
function out = gradientImage(im,varargin) % out = gradientImage(im) % % Fast gradient of an image % Works for ImageType % difforder = 1; binary=false; dbg=false; for i=1:size(varargin,2) if (strcmp(varargin{i},'dbg')) dbg=true; elseif (strcmp(varargin{i},'order')) difforder=varargin{1}; elseif (strcmp(varargin{i},'binary')) binary=true; end end %---------------------------- out=[]; % maybe something wrong: the transpose matlab shit % Using the derivative of a Gaussian to guarantee smoothness filter_size = 7; sigma = 1.5; % in pixels for d=1:im.ndimensions if binary d_gaussian_kernel =derivativeKernel(filter_size, d, ndimensions); else [d_gaussian_kernel,d_gaussian_plain] = derivativeOfGaussian(filter_size, sigma, d, im.ndimensions, im.spacing); %d_gaussian_kernel = d_gaussian_kernel/sum(abs(d_gaussian_kernel(:))); d_gaussian_kernel = d_gaussian_kernel/sum(d_gaussian_plain(:).^2); end dx = convn(im.data,d_gaussian_kernel,'same');%/im.spacing(d); out = cat(im.ndimensions+1,out,dx); end end function [d_gaussian_kernel_derivative,d_gaussian_kernel] = derivativeOfGaussian(filter_size, sigma_, d, ndimensions, spacing) % example of inputs: %filter_size = 5; %sigma = 3; % in pixels % d=2 (direction along which we do the derivative) filter_radius = floor(filter_size/2); sigma = sigma_ * spacing(d); % Below will give me the gaussian function along direction d. For example, % for a 3D image and along direction y: %d_gaussian_func_2 =@(x,y,z) exp(-(x.^2)/(2*sigma^2)).*-y/(sigma^2).*exp(-(y.^2)/(2*sigma^2)).*exp(-(z.^2)/(2*sigma^2)); str1=''; str2=''; str3 =''; str4 = ''; for i=1:ndimensions str2=[str2 'x' num2str(i) ',']; if i==d str1 = [str1 '-x' num2str(i) '/(sigma^2).*exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; else str1 = [str1 'exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; end str3 = [str3 'exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; str4 = [str4 '(-filter_radius:filter_radius)*spacing(' num2str(i) '),']; end eval([ '[' str2(1:end-1) ']=ndgrid(' str4(1:end-1) ');']); eval(['d_gaussian_kernel_derivative= ' str1(1:end-2) ';']); eval(['d_gaussian_kernel= ' str3(1:end-2) ';']); end function d_derivative = derivativeKernel(filter_size, d, ndimensions) % example of inputs: %filter_size = 5; % d=2 (direction along which we do the derivative) filter_radius = floor(filter_size/2); d_derivative = [1 0 -1]'*([1:filter_radius filter_radius+1 filter_radius:-1:1]); d_derivative = repmat(d_derivative,1,1); % Below will give me the gaussian function along direction d. For example, % for a 3D image and along direction y: %d_gaussian_func_2 =@(x,y,z) exp(-(x.^2)/(2*sigma^2)).*-y/(sigma^2).*exp(-(y.^2)/(2*sigma^2)).*exp(-(z.^2)/(2*sigma^2)); str1=''; str2=''; str3 =''; str4 = ''; for i=1:ndimensions str2=[str2 'x' num2str(i) ',']; if i==d str1 = [str1 '-x' num2str(i) '/(sigma^2).*exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; else str1 = [str1 'exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; end str3 = [str3 'exp(-(x' num2str(i) '.^2)/(2*sigma^2)).*']; str4 = [str4 '(-filter_radius:filter_radius)*spacing(' num2str(i) '),']; end eval([ '[' str2(1:end-1) ']=ndgrid(' str4(1:end-1) ');']); eval(['d_gaussian_kernel_derivative= ' str1(1:end-2) ';']); eval(['d_gaussian_kernel= ' str3(1:end-2) ';']); end
github
vildenst/3D-heart-models-master
gaussianBlurImage.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/Basic/gaussianBlurImage.m
1,858
utf_8
e77041b544d680c3bd86e18ebf395faa
function out = gaussianBlurImage(im,varargin) % out = gaussianBlurImage(im) % % Fast gaussian blur % Works for ImageType % filter_size = 5; sigma = 1.5; dbg = false; for i=1:size(varargin,2) if (strcmp(varargin{i},'dbg')) dbg=true; elseif (strcmp(varargin{i},'kernelSize')) filter_size=varargin{i+1}; elseif (strcmp(varargin{i},'kernelSigma')) sigma=varargin{i+1}; end end %---------------------------- % maybe something wrong: the transpose matlab % Using the derivative of a Gaussian to guarantee smoothness d_gaussian_plain = kernelOfGaussian(filter_size, sigma, im.ndimensions, im.spacing); %d_gaussian_kernel = d_gaussian_plain/sum(abs(d_gaussian_plain(:))); d_gaussian_plain = d_gaussian_plain/sum(d_gaussian_plain(:).^2); out = convn(im.data,d_gaussian_plain,'same');%/im.spacing(d); end function d_gaussian_kernel = kernelOfGaussian(filter_size, sigma_, ndimensions, spacing) % example of inputs: %filter_size = 5; %sigma = 3; % in pixels filter_radius = floor(filter_size/2); sigma = sigma_; if numel(filter_radius)==1 filter_radius = filter_radius*ones(ndimensions,1); end if numel(sigma)==1 sigma = sigma*ones(ndimensions,1); end % Below will give me the gaussian function along direction d. For example, % for a 3D image and along direction y: %d_gaussian_func_2 =@(x,y,z) exp(-(x.^2)/(2*sigma^2)).*-y/(sigma^2).*exp(-(y.^2)/(2*sigma^2)).*exp(-(z.^2)/(2*sigma^2)); str2=''; str3 =''; str4 = ''; for i=1:ndimensions str2=[str2 'x' num2str(i) ',']; str3 = [str3 'exp(-(x' num2str(i) '.^2)/(2*(sigma(' num2str(i) ')*spacing(' num2str(i) '))^2)).*']; str4 = [str4 '(-filter_radius(' num2str(i) '):filter_radius(' num2str(i) '))*spacing(' num2str(i) '),']; end eval([ '[' str2(1:end-1) ']=ndgrid(' str4(1:end-1) ');']); eval(['d_gaussian_kernel= ' str3(1:end-2) ';']); end
github
vildenst/3D-heart-models-master
read_gipl2.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_gipl2.m
4,167
utf_8
cc6279c2867274e206d8a231128307b0
function [V, sizes, origin,scales] =read_gipl2(filename) % function for reading header of Guys Image Processing Lab (Gipl) volume file % % [V, sizes, origin,scales] = gipl_read_header(filename); % % % Copied from the package ReadData3D_version1h fid=fopen(filename,'rb','ieee-be'); %fid=fopen(filename,'r','native'); if(fid<0) fprintf('could not open file %s\n',filename); return end trans_type{1}='binary'; trans_type{7}='char'; trans_type{8}='uchar'; trans_type{15}='short'; trans_type{16}='ushort'; trans_type{31}='uint'; trans_type{32}='int'; trans_type{64}='float';trans_type{65}='double'; trans_type{144}='C_short';trans_type{160}='C_int'; trans_type{192}='C_float'; trans_type{193}='C_double'; trans_type{200}='surface'; trans_type{201}='polygon'; trans_orien{0+1}='UNDEFINED'; trans_orien{1+1}='UNDEFINED_PROJECTION'; trans_orien{2+1}='AP_PROJECTION'; trans_orien{3+1}='LATERAL_PROJECTION'; trans_orien{4+1}='OBLIQUE_PROJECTION'; trans_orien{8+1}='UNDEFINED_TOMO'; trans_orien{9+1}='AXIAL'; trans_orien{10+1}='CORONAL'; trans_orien{11+1}='SAGITTAL'; trans_orien{12+1}='OBLIQUE_TOMO'; offset=256; % header size %get the file size fseek(fid,0,'eof'); fsize = ftell(fid); fseek(fid,0,'bof'); sizes=fread(fid,4,'ushort')'; if(sizes(4)==1), maxdim=3; else maxdim=4; end sizes=sizes(1:maxdim); image_type=fread(fid,1,'ushort'); scales=fread(fid,4,'float')'; scales=scales(1:maxdim); patient=fread(fid,80, 'uint8=>char')'; matrix=fread(fid,20,'float')'; orientation=fread(fid,1, 'uint8')'; par2=fread(fid,1, 'uint8')'; voxmin=fread(fid,1,'double'); voxmax=fread(fid,1,'double'); origin=fread(fid,4,'double')'; origin=origin(1:maxdim); pixval_offset=fread(fid,1,'float'); pixval_cal=fread(fid,1,'float'); interslicegap=fread(fid,1,'float'); user_def2=fread(fid,1,'float'); magic_number= fread(fid,1,'uint32'); %if (magic_number~=4026526128), error('file corrupt - or not big endian'); end fclose('all'); info.Filename=filename; info.FileSize=fsize; info.Dimensions=sizes; info.PixelDimensions=scales; info.ImageType=image_type; info.Patient=patient; info.Matrix=matrix; info.Orientation=orientation; info.VoxelMin=voxmin; info.VoxelMax=voxmax; info.Origing=origin; info.PixValOffset=pixval_offset; info.PixValCal=pixval_cal; info.InterSliceGap=interslicegap; info.UserDef2=user_def2; info.Par2=par2; info.Offset=offset; V = gipl_read_volume(info); end function V = gipl_read_volume(info) % function for reading volume of Guys Image Processing Lab (Gipl) volume file % % volume = gipl_read_volume(file-header) % % examples: % 1: info = gipl_read_header() % V = gipl_read_volume(info); % imshow(squeeze(V(:,:,round(end/2))),[]); % % 2: V = gipl_read_volume('test.gipl'); if(~isstruct(info)) info=gipl_read_header(info); end % Open gipl file fid=fopen(info.Filename','rb','ieee-be'); % Seek volume data start if(info.ImageType==1), voxelbits=1; end if(info.ImageType==7||info.ImageType==8), voxelbits=8; end if(info.ImageType==15||info.ImageType==16), voxelbits=16; end if(info.ImageType==31||info.ImageType==32||info.ImageType==64), voxelbits=32; end if(info.ImageType==65), voxelbits=64; end datasize=prod(info.Dimensions)*(voxelbits/8); fsize=info.FileSize; fseek(fid,fsize-datasize,'bof'); % Read Volume data volsize(1:3)=info.Dimensions; if(info.ImageType==1), V = logical(fread(fid,datasize,'bit1')); end if(info.ImageType==7), V = int8(fread(fid,datasize,'char')); end if(info.ImageType==8), V = uint8(fread(fid,datasize,'uchar')); end if(info.ImageType==15), V = int16(fread(fid,datasize,'short')); end if(info.ImageType==16), V = uint16(fread(fid,datasize,'ushort')); end if(info.ImageType==31), V = uint32(fread(fid,datasize,'uint')); end if(info.ImageType==32), V = int32(fread(fid,datasize,'int')); end if(info.ImageType==64), V = single(fread(fid,datasize,'float')); end if(info.ImageType==65), V = double(fread(fid,datasize,'double')); end fclose(fid); % Reshape the volume data to the right dimensions V = reshape(V,volsize); end
github
vildenst/3D-heart-models-master
read_parrec2DFlow.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_parrec2DFlow.m
18,394
utf_8
cb03377888f70ad72f5bdb0b5da050ff
function [outphase, outanatomy, patientdata] = read_parrec2DFlow(filename) par_survey = parread(filename ); rec_survey = readrec([filename(1:end-3) 'REC' ]); % Split the 5D 2Dflow data data_mag = rec_survey(:,:,:,1,1); if ndims(rec_survey)>3 && size(rec_survey,4)>1 data_oth = rec_survey(:,:,:,2,1); % ? else data_oth =data_mag; end if ndims(rec_survey)>4 && size(rec_survey,5)>1 data_phs = rec_survey(:,:,:,2,2); else data_phs = data_mag; end % calculate velocity values max_ph = max(data_phs(:)); p = nextpow2(max_ph); venc = max(par_survey.PhaseEncodingVelocity); data_phs = data_phs - (2^p)/2; data_phs = data_phs./((2^p)/2); data_phs = data_phs.*(venc); % (division by 100 because cm/s?) % Orientantion AFRtoLPS = [0 0 1; 1 0 0; 0 1 0]; magicmatrix = [-1 0 0; 0 0 1; 0 -1 0]; TRA = [0 1 0; -1 0 0; 0 0 -1]; SAG = [-1 0 0; 0 0 1; 0 -1 0]; COR = [0 1 0; 0 0 1; -1 0 0]; switch (par_survey.ImageInformation.SliceOrientation(1)) case 1 Torientation = TRA; case 2 Torientation = SAG; case 3 Torientation = COR; otherwise Torientation = eye(3); end ap = par_survey.AngulationMidslice(1)* pi / 180.0; fh = par_survey.AngulationMidslice(2)* pi / 180.0; rl = par_survey.AngulationMidslice(3)* pi / 180.0; Tap = [1 0 0; 0 cos(ap) -sin(ap); 0 sin(ap) cos(ap)]; Tfh = [cos(fh) 0 sin(fh); 0 1 0; -sin(fh) 0 cos(fh)]; Trl = [cos(rl) -sin(rl) 0; sin(rl) cos(rl) 0; 0 0 1]; orientation_matrix = AFRtoLPS * Trl * Tap * Tfh * magicmatrix' * Torientation'; % c++ version s = size(data_phs)'; s_ = [s(1:2) ;1 ;s(3)]; % ORIGIN ---------------------------------------------------- if par_survey.ImageInformation.CardiacFrequency(1)==0 tmax=1; else tmax = 60/par_survey.ImageInformation.CardiacFrequency(1); end %extent = AFRtoLPS * par_survey.FOV'; extent = abs(Torientation * magicmatrix * par_survey.FOV'); % I am not sure exactly why I have to use the abs spacing = [extent ; tmax]./s_; midoffset = spacing(1:3) .* (s(1:3)- ones(3,1)) ./2.0; midoffset = orientation_matrix * midoffset; origin = par_survey.OffCentreMidslice'; origin = AFRtoLPS * origin; origin = origin - midoffset; M = eye(4); M(1:3,1:3)=orientation_matrix; outphase = ImageType(s_,[origin ; 0],spacing,M); outphase.data = reshape(data_phs, s_'); outanatomy = ImageType(s_,[origin ; 0],spacing,M); outanatomy.data = reshape(data_mag, s_'); patientdata.type = '3DCDI'; %params.type = 'other'; patientdata.heart_rate = par_survey.ImageInformation.CardiacFrequency(1); patientdata.frame_rate=s_(end)/(60/par_survey.ImageInformation.CardiacFrequency(1)); patientdata.trigger_delay = 0; patientdata.venc = venc; end function values = parread(filename) %PARREAD reads Philips .par file % PARREAD(FILENAME) reads the .par file and returns a struct % whose fields contain all parameters. PARREAD can handle all % versions of .par files % % The field ImageInformation in the output struct is a struct % itself and contains the parameters which correspond to the % lower part of the .par file. % % The fields of the output struct can be accessed by a . % Example: % values = parread('My_Parfile') % reads the .par file and returns the output struct % % values.RepetitionTime % returns the repetition time % % values.ImageInformation.SliceNumber % returns the slice order in the .rec file fid = fopen(filename); if fid == -1 filename = [filename(1:end-3),'par']; fid = fopen(filename); if fid == -1 filename = [filename(1:end-3),'PAR']; fid = fopen(filename); if fid == -1 error(['The .par file ',filename,' does not exist']) return end end end values = read_upper_part(fid); values = read_lower_part(fid, values); fclose(fid); end %--------- function for reading the upper part of the .par file ---------- function values = read_upper_part(fid) %------------------------------------------------------------------------- parameters = read_parameters(fid); struct_names = format_parameters(parameters); no_parameters = size(parameters,1); values = struct; h = waitbar(0,'Read header I'); for i = 1:no_parameters waitbar(i/no_parameters); values_temp = []; fseek(fid,0,-1); while ~feof(fid) s = fgetl(fid); s_index = findstr(parameters{i},s); if ~isempty(s_index) s_index = findstr(':', s); % s_index = s_index(1)+4; s_index = s_index(1)+1; if isempty(str2num(s(s_index:length(s)))) values_temp = s(s_index:length(s)); else values_temp = str2num(s(s_index:length(s))); end values = setfield(values, struct_names{i},values_temp); s_index=s_index+1; end end end close(h); end %--------- function for reading the lower part of the .par file ---------- function values = read_lower_part(fid, values) %------------------------------------------------------------------------- [image_information_legend,image_information_length] = read_image_information_parameters(fid); if ~isempty(image_information_legend) image_information_legend = format_parameters(image_information_legend); fseek(fid,0,-1); loop =1; while ~feof(fid) s = fgetl(fid); s_index = strmatch('# === IMAGE INFORMATION ==',s); if ~isempty(s_index) fgetl(fid); fgetl(fid); while ~feof(fid) s = fgetl(fid); if length(str2num(s)) ~= 0 h(loop,:) = str2num(s); end loop = loop+1; end end end if ~isempty(s_index) ImageInformation = struct; k = 1; for i = 1:length(image_information_legend) ImageInformation = setfield(ImageInformation,image_information_legend{i},h(:,k:k+image_information_length(i)-1)); k = k+image_information_length(i); end values = setfield(values, 'ImageInformation',ImageInformation); end end end %-- Check which parameters are stored in the upper part of the .par file -- function parameters = read_parameters(fid); %-------------------------------------------------------------------------- fseek(fid,0,-1); loop = 1; while ~feof(fid) s = fgetl(fid); s_index = strmatch('# === GENERAL INFORMATION',s); if ~isempty(s_index) fgetl(fid); while ~feof(fid) s = fgetl(fid); if isempty(s) | ~strcmp(s(1),'.') break end ind = findstr(s,':'); s = s(2:ind-1); parameters{loop} = strtrim(s); loop = loop +1; end end end parameters = parameters'; end %-- Format parameter names such that they can be given as struct fields -- function struct_names = format_parameters(parameters) %-------------------------------------------------------------------------- h = waitbar(0,'Read header II'); for i = 1:length(parameters) waitbar(i/length(parameters)); s = parameters{i}; ind1 = strfind(s,'('); ind2 = strfind(s,'['); ind3 = strfind(s,'<'); ind = [ind1,ind2,ind3]; if ~isempty(ind) ind = min(ind); s = s(1:ind-1); end s = strrep(s,'.',' '); s = strrep(s,'/',' '); s = strrep(s,'_',' '); s = strrep(s,'-',' '); s = deblank(s); ind = strfind(s,' '); s(ind+1) = upper(s(ind+1)); s(1) = upper(s(1)); s(ind)=[]; struct_names{i} = s; end close(h); struct_names = struct_names'; end %-- Check which parameters are stored in the lower part of the .par file -- function [image_information_legend,image_information_length] = read_image_information_parameters(fid); %-------------------------------------------------------------------------- fseek(fid,0,-1); loop = 1; image_information_legend = []; image_information_length = []; while ~feof(fid) s = fgetl(fid); s_index = strmatch('# === IMAGE INFORMATION DEFINITION',s); if ~isempty(s_index) fgetl(fid); fgetl(fid); while ~feof(fid) s = fgetl(fid); if length(s) < 5 break end ind = max(findstr(s,'(')); l = str2double(s(ind+1)); s = s(2:ind-1); image_information_legend{loop} = strtrim(s); if isnan(l) | imag(l)~=0 image_information_length(loop) = 1; else image_information_length(loop) = l; end loop = loop +1; end end end if ~isempty(image_information_legend) image_information_legend = image_information_legend'; end end function data = readrec(fn, read_params, v) %------------------------------------------------------ % fReadrec: reads a rec-file % % Input: fn name of the rec-file % read_params optional input. Specifies the images to be % read. read_params is a struct created % by the function create_read_param_struct % v Parameter struct created by parread % % Output: out_pics dataset as a 3D-matrix %------------------------------------------------------ parfile = [fn(1:end-3),'PAR']; if nargin == 1 [read_params, v, DataFormat] = ReadParameterFile(fn); elseif nargin == 2 v = parread(parfile); end if isfield(v,'ReconResolution') size1 = v.ReconResolution(1); size2 = v.ReconResolution(2); else size1 = v.ImageInformation.ReconResolution(1); size2 = v.ImageInformation.ReconResolution(2); end fid=fopen(fn,'r','l'); if (fid<0) fid=fopen([fn(1:end-3) lower(fn(end-2:end))],'r','l'); end % l means little ended data = zeros(size1,size2,length(read_params.kz),length(read_params.echo),length(read_params.dyn),length(read_params.card),length(read_params.typ), length(read_params.mix),'single'); h = waitbar(0,'Read image data'); for sl = 1:length(read_params.kz) waitbar(sl/length(read_params.kz)); for ec = 1:length(read_params.echo) for dy = 1:length(read_params.dyn) for ph = 1:length(read_params.card) for ty = 1:length(read_params.typ) for mi = 1:length(read_params.mix) ind{1} = find(v.ImageInformation.SliceNumber == read_params.kz(sl)); ind{2} = find(v.ImageInformation.EchoNumber == read_params.echo(ec)); ind{3} = find(v.ImageInformation.DynamicScanNumber == read_params.dyn(dy)); ind{4} = find(v.ImageInformation.CardiacPhaseNumber == read_params.card(ph)); ind{5} = find(v.ImageInformation.ImageTypeMr == read_params.typ(ty)); ind{6} = find(v.ImageInformation.ScanningSequence == read_params.mix(mi)); im_ind = ind{1}; for i = 2:6 im_ind = intersect(im_ind,ind{i}); end offset = v.ImageInformation.IndexInRECFile(im_ind)*size1*size2*2; if isempty(offset) continue % error('Some parameters specified are not valid') end fseek(fid,offset,-1); im = fread(fid,size1*size2,'uint16'); data(:,:,sl,ec,dy,ph,ty,mi) = reshape(im,size1,size2)'; end end end end end end close(h); data = squeeze(data); end function [Parameter2read, Parameter, DataFormat, Filenames] = ReadParameterFile(file) dotind = findstr(file,'.'); if ~isempty(dotind) dotind = dotind(end); ending = lower(file(dotind(end)+1:end)); else ending = 'raw'; end switch ending case {'rec', 'par'} parfile = [file(1:dotind),'par']; Parameter = parread(parfile); DataFormat = 'Rec'; Filenames.DataFile = [file(1:dotind),'rec']; Filenames.ParameterFile = parfile; Parameter2read.kz = unique(Parameter.ImageInformation.SliceNumber); Parameter2read.echo = unique(Parameter.ImageInformation.EchoNumber); Parameter2read.dyn = unique(Parameter.ImageInformation.DynamicScanNumber); Parameter2read.card = unique(Parameter.ImageInformation.CardiacPhaseNumber); Parameter2read.typ = unique(Parameter.ImageInformation.ImageTypeMr); Parameter2read.mix = unique(Parameter.ImageInformation.ScanningSequence); Parameter2read.aver = []; Parameter2read.rtop = []; Parameter2read.ky = []; Parameter2read.loca = []; Parameter2read.chan = []; Parameter2read.extr1 = []; Parameter2read.extr2 = []; case 'cpx' Parameter = read_cpx_header(file,'no'); DataFormat = 'Cpx'; Filenames.DataFile = file; Filenames.ParameterFile = file; Parameter2read.loca = unique(Parameter(:,1))+1; Parameter2read.kz = unique(Parameter(:,2))+1; Parameter2read.chan = unique(Parameter(:,3))+1; Parameter2read.card = unique(Parameter(:,4))+1; Parameter2read.echo = unique(Parameter(:,5))+1; Parameter2read.dyn = unique(Parameter(:,6))+1; Parameter2read.extr1 = unique(Parameter(:,7))+1; Parameter2read.extr2 = unique(Parameter(:,18))+1; Parameter2read.aver = []; Parameter2read.rtop = []; Parameter2read.typ = []; Parameter2read.mix = []; Parameter2read.ky = []; case {'data', 'list'} t = 'TEHROA'; DataFormat = 'ExportedRaw'; listfile = [file(1:dotind),'list']; Parameter = listread(listfile); Filenames.DataFile = [file(1:dotind),'data']; Filenames.ParameterFile = listfile; typ = unique(Parameter.Index.typ(:,2)); for i = 1:length(typ) numtyp(i) = findstr(typ(i),t); end Parameter2read.typ = sort(numtyp); Parameter2read.mix = unique(Parameter.Index.mix); Parameter2read.dyn = unique(Parameter.Index.dyn); Parameter2read.card = unique(Parameter.Index.card); Parameter2read.echo = unique(Parameter.Index.echo); Parameter2read.loca = unique(Parameter.Index.loca); Parameter2read.chan = unique(Parameter.Index.chan); Parameter2read.extr1 = unique(Parameter.Index.extr1); Parameter2read.extr2 = unique(Parameter.Index.extr2); Parameter2read.ky = unique(Parameter.Index.ky); Parameter2read.kz = unique(Parameter.Index.kz); Parameter2read.aver = unique(Parameter.Index.aver); Parameter2read.rtop = unique(Parameter.Index.rtop); case {'raw', 'lab'} t = 'TEHROA'; DataFormat = 'Raw'; if isempty( dotind ) slash_ind = strfind( file, filesep )+1; if isempty( slash_ind ) slash_ind = 1; directory = ''; files = dir ; else directory = file( 1:slash_ind(end)-1 ); files = dir( directory ) ; end one_file = file( slash_ind(end):end ); ind_one_file = -1; ind_other_file = -1; for i = 1:size(files,1) if strcmp( files(i).name , one_file ) ind_one_file = i; end if strfind( files(i).name, one_file( 1:17) ) & ... isempty( strfind( files(i).name, '.' )) & ... i ~= ind_one_file ind_other_file = i; end end if ind_one_file > 0 & ind_other_file > 0 if files(ind_one_file).bytes > files(ind_other_file).bytes Filenames.DataFile = [directory, files(ind_one_file).name]; Filenames.ParameterFile = [directory, files(ind_other_file).name]; else Filenames.DataFile = [directory,files(ind_other_file).name]; Filenames.ParameterFile = [directory,files(ind_one_file).name]; end else error('data/parameter-file pair not found'); end dotind = length(Filenames.ParameterFile)+1; dotind = dotind(end); else Filenames.DataFile = [file(1:dotind),'raw']; Filenames.ParameterFile = [file(1:dotind),'lab']; end try_path = which( 'MRecon.m' ); try_path = try_path( 1:strfind( try_path, 'MRecon.m')-1); if fopen( [try_path, 'recframe.exe'],'r') == -1 cmd_str = which( 'recframe.exe' ); else cmd_str = [try_path, 'recframe.exe']; end if isempty( cmd_str ) error( 'recframe.exe not found. Please make sure that the location of recframe.exe is in the Matlab path'); end cmd_str = ['"',cmd_str, '" "', Filenames.DataFile, '" "', Filenames.ParameterFile, '" /D']; system( cmd_str ); listfile = [Filenames.ParameterFile(1:dotind-1),'.list']; Parameter = listread(listfile); typ = unique(Parameter.Index.typ(:,2)); for i = 1:length(typ) numtyp(i) = findstr(typ(i),t); end Parameter2read.typ = sort(numtyp); Parameter2read.mix = unique(Parameter.Index.mix); Parameter2read.dyn = unique(Parameter.Index.dyn); Parameter2read.card = unique(Parameter.Index.card); Parameter2read.echo = unique(Parameter.Index.echo); Parameter2read.loca = unique(Parameter.Index.loca); Parameter2read.chan = unique(Parameter.Index.chan); Parameter2read.extr1 = unique(Parameter.Index.extr1); Parameter2read.extr2 = unique(Parameter.Index.extr2); Parameter2read.ky = unique(Parameter.Index.ky); Parameter2read.kz = unique(Parameter.Index.kz); Parameter2read.aver = unique(Parameter.Index.aver); Parameter2read.rtop = unique(Parameter.Index.rtop); otherwise Parameter2read = []; Parameter = []; DataFormat = []; end end
github
vildenst/3D-heart-models-master
read_mhd.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_mhd.m
10,497
utf_8
1e583e41a4ab0481210876d95b95b93b
function [img, info]=read_mhd(filename) % This function is based upon "read_mhd" function from the package % ReadData3D_version1 from the matlab exchange. % Copyright (c) 2010, Dirk-Jan Kroon % [image info ] = read_mhd(filename) info = mhareadheader(filename); [path, name, extension] = fileparts(filename); if (isfield(info,'ElementNumberOfChannels')) ndims = str2num(info.ElementNumberOfChannels); else ndims = 1; end img = ImageType(); if (ndims == 1) data = read_raw([ path filesep info.DataFile ], info.Dimensions,info.DataType,'native',0,ndims, info); if (data==-1) data = read_raw([ info.DataFile ], info.Dimensions,info.DataType,'native',0,ndims); end img=ImageType(size(data),info.Offset',info.PixelDimensions',reshape(info.TransformMatrix,numel(info.PixelDimensions),numel(info.PixelDimensions))); img.data = data; elseif (ndims == 2) clear img; [datax datay] = read_raw([ path filesep info.DataFile], info.Dimensions,info.DataType,'native',0,ndims, info); img = VectorImageType(size(datax),info.Offset',info.PixelDimensions',reshape(info.TransformMatrix,numel(info.PixelDimensions),numel(info.PixelDimensions))); img.datax = datax; clear datax; img.datay=datay; clear datay; img.data = img.datax.^2+img.datay.^2; elseif (ndims == 3) clear img; [datax datay dataz] = read_raw([ path filesep info.DataFile], info.Dimensions,info.DataType,'native',0,ndims, info); img = VectorImageType(size(datax),info.Offset',info.PixelDimensions',reshape(info.TransformMatrix,numel(info.PixelDimensions),numel(info.PixelDimensions))); img.datax = datax; clear datax; img.datay=datay; clear datay; img.dataz = dataz; clear dataz; img.data = img.datax.^2+img.datay.^2+img.dataz.^2; end end function [rawData, rdy, rdz] =read_raw(filename,imSize,type,endian,skip,ndims, info) % Reads a raw file % Inputs: filename, image size, image type, byte ordering, skip % If you are using an offset to access another slice of the volume image % be sure to multiply your skip value by the number of bytes of the % type (ie. float is 4 bytes). % Inputs: filename, image size, pixel type, endian, number of values to % skip. % Output: image rdy=[]; rdz=[]; fid = fopen(filename,'rb',endian); %type='uint8'; if (fid < 0) display(['Filename ' filename ' does not exist']); rawData = -1; else if (ndims == 1) status = fseek(fid,skip,'bof'); if status == 0 rawData = fread(fid,prod(imSize),type); if strcmp(filename(end-3:end),'zraw') || strcmp(lower(info.CompressedData),'true') rawData =zlibdecode(uint8(rawData)); end fclose(fid); if prod(imSize)~=numel(rawData) disp('ERROR: Wrong data size') rawData = zeros(imSize); else rawData = reshape(rawData,imSize); end else rawData = status; end else %disp('Vector Image'); status = fseek(fid,skip,'bof'); if status == 0 r = fread(fid,prod(imSize)*3,type); fclose(fid); if length(imSize) == 2 im_size=[ 2 imSize([1 2]) ]; elseif length(imSize) == 3 im_size=[ 3 imSize([1 2 3]) ]; elseif length(imSize) == 4 im_size=[3 imSize([1 2 3 4]) ]; end r = reshape(r,im_size); else r = status; end if length(imSize) == 2 rawData=squeeze(r(1,:,:,:)); rdy=squeeze(r(2,:,:,:)); rdz=rdy*0; elseif length(imSize) == 3 rawData=squeeze(r(1,:,:,:)); rdy=squeeze(r(2,:,:,:)); rdz=squeeze(r(3,:,:,:)); elseif length(imSize) == 4 rawData=squeeze(r(1,:,:,:,:)); rdy=squeeze(r(2,:,:,:,:)); rdz=squeeze(r(3,:,:,:,:)); end end end end function info =mhareadheader(filename) % Function for reading the header of a Insight Meta-Image (.mha,.mhd) file % % info = mha_read_header(filename); % % examples: % 1, info=mha_read_header() % 2, info=mha_read_header('volume.mha'); info = []; if(exist('filename','var')==0) [filename, pathname] = uigetfile('*.mha', 'Read mha-file'); filename = [pathname filename]; end fid=fopen(filename,'rb'); if(fid<0) fprintf('could not open file %s\n',filename); return end info.Filename=filename; info.Format='MHA'; info.CompressedData='false'; info.TransformMatrix = []; info.CenterOfRotation=[]; readelementdatafile=false; while(~readelementdatafile) str=fgetl(fid); if str==-1 readelementdatafile =true; continue; end s=find(str=='=',1,'first'); if(~isempty(s)) type=str(1:s-1); data=str(s+1:end); while(type(end)==' '); type=type(1:end-1); end while(data(1)==' '); data=data(2:end); end else if strcmp(str(1),'#') if strcmp(str(2:5),'VENC') type='venc'; data = str2num(str(6:end)); elseif strcmp(str(2:5),'TXFR') type='txfr'; data = str2num(str(6:end)); elseif strcmp(str(2:6),'FORCE') type='force'; data = str(7:end); elseif strcmp(str(2:6),'ACQFR') type='acqfr'; data = str2num(str(7:end)); elseif strcmp(str(2:9),'POSITION') type='position'; data = str(10:end); elseif strcmp(str(2:10),'HEARTRATE') type='heartrate'; data = str2num(str(11:end)); elseif strcmp(str(2:11),'PERCEIVEDF') type='perceivedf'; data = str(12:end); elseif strcmp(str(2:14),'TRACKERMATRIX') type='trackermatrix'; data = str(15:end); elseif strcmp(str(2:12),'TOTALMATRIX') type='totalmatrix'; data = str(13:end); elseif numel(str) >= 26 && strcmp(str(2:26),'TIMESTAMP_DNLLAYERTIMELAG') type='timestamp_dnllayertimelag'; data = str2num(str(27:end)); elseif strcmp(str(2:14),'TIMESTAMP_DNL') type='timestamp_dnl'; data = str2num(str(15:end)); elseif strcmp(str(2:15),'REORIENTMATRIX') type='reorientmatrix'; data = str(16:end); elseif strcmp(str(2:16),'TIMESTAMP_LOCAL') type='timestamp_local'; data = str2num(str(17:end)); elseif strcmp(str(2:17),'TRANSDUCERMATRIX') type='transducermatrix'; data = str(18:end); elseif strcmp(str(2:18),'TIMESTAMP_TRACKER') type='timestamp_tracker'; data = str2num(str(19:end)); else type=''; data=str; end end end switch(lower(type)) case 'ndims' info.NumberOfDimensions=sscanf(data, '%d')'; case 'dimsize' info.Dimensions=sscanf(data, '%d')'; case 'elementspacing' info.PixelDimensions=sscanf(data, '%lf')'; case 'elementsize' info.ElementSize=sscanf(data, '%lf')'; if(~isfield(info,'PixelDimensions')) info.PixelDimensions=info.ElementSize; end case 'elementbyteordermsb' info.ByteOrder=lower(data); case 'anatomicalorientation' info.AnatomicalOrientation=data; case 'centerofrotation' info.CenterOfRotation=sscanf(data, '%lf')'; case 'offset' info.Offset=sscanf(data, '%lf')'; case 'binarydata' info.BinaryData=lower(data); case 'compresseddatasize' info.CompressedDataSize=sscanf(data, '%d')'; case 'objecttype', info.ObjectType=lower(data); case 'transformmatrix' info.TransformMatrix=sscanf(data, '%lf')'; case 'compresseddata'; info.CompressedData=lower(data); case 'binarydatabyteordermsb' info.ByteOrder=lower(data); case 'elementdatafile' info.DataFile=data; %readelementdatafile=true; case 'elementtype' info.DataType=lower(data(5:end)); case 'headersize' val=sscanf(data, '%d')'; if(val(1)>0), info.HeaderSize=val(1); end % Custom fields case 'force' info.Force=sscanf(data, '%lf')'; case 'position' info.Position=sscanf(data, '%lf')'; case 'reorientmatrix' info.ReorientMatrix=sscanf(data, '%lf')'; info.ReorientMatrix = reshape(info.ReorientMatrix,4,4); case 'transducermatrix' info.Transducermatrix=sscanf(data, '%lf')'; info.Transducermatrix = reshape(info.Transducermatrix,4,4); case 'trackermatrix' info.TrackerMatrix=sscanf(data, '%lf')'; info.TrackerMatrix = reshape(info.TrackerMatrix,4,4); case 'totalmatrix' info.TotalMatrix=sscanf(data, '%lf')'; info.TotalMatrix = reshape(info.TotalMatrix,4,4); case 'timestamp' info.Timestamp=sscanf(data, '%lf')'; case 'perceivedf' info.perceivedf=data; case '#timestamp_dnl' info.timestamp_dnl=str2num(data); case '#timestamp_local' info.timestamp_local=str2num(data); case '#timestamp_tracker' info.timestamp_tracker=str2num(data); otherwise info.(type)=data; end end if ~numel(info.TransformMatrix) info.TransformMatrix = reshape(eye(info.NumberOfDimensions), 1,info.NumberOfDimensions*info.NumberOfDimensions); end if ~numel(info.CenterOfRotation) info.CenterOfRotation = zeros(1,info.NumberOfDimensions); end switch(info.DataType) case 'char', info.BitDepth=8; case 'uchar', info.BitDepth=8; case 'short', info.BitDepth=16; case 'ushort', info.BitDepth=16; case 'int', info.BitDepth=32; case 'uint', info.BitDepth=32; case 'float', info.BitDepth=32; case 'double', info.BitDepth=64; otherwise, info.BitDepth=0; end if(~isfield(info,'HeaderSize')) info.HeaderSize=ftell(fid); end fclose(fid); end
github
vildenst/3D-heart-models-master
read_vtkSP.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_vtkSP.m
4,704
utf_8
20a96a39be48ddd9fdc98826bb15deef
function [img, info]=read_vtkSP(filename) % This function is based upon "read_mhd" function from the package % ReadData3D_version1 from the matlab exchange. % Copyright (c) 2010, Dirk-Jan Kroon % [image info ] = read_mhd(filename) info = vtkSPreadheader(filename); img = VectorImageType(info.Dimensions',info.Offset',info.PixelDimensions',reshape(info.TransformMatrix,numel(info.PixelDimensions),numel(info.PixelDimensions))); img.datax(:) = info.field1(:,1); img.datay(:) = info.field1(:,2); img.dataz(:) = info.field1(:,3); img.data = img.datax.^2+img.datay.^2+img.dataz.^2; end function info =vtkSPreadheader(filename) % Function for reading the header of a VTK legacy (.vtk) image file info = []; if(exist('filename','var')==0) [filename, pathname] = uigetfile('*.vtk', 'Read vtk-file'); filename = [pathname filename]; end fid=fopen(filename,'rb'); if(fid<0) fprintf('could not open file %s\n',filename); return end info.Filename=filename; info.Format='VTK'; info.CompressedData='false'; info.TransformMatrix = []; info.CenterOfRotation=[]; readelementdatafile=false; while(~readelementdatafile) str=fgetl(fid); if str==-1 readelementdatafile =true; continue; end if numel(str)==0 readelementdatafile =true; continue; end s=find(str==' ',1,'first'); if(~isempty(s)) type=str(1:s-1); if isempty(type) readelementdatafile =true; continue; end data=str(s+1:end); if isempty(data) readelementdatafile =true; continue; end while(type(end)==' '); type=type(1:end-1); end while(data(1)==' '); data=data(2:end); end else if strcmp(str(1),'#') if strcmp(str(2:6),'FORCE') type='force'; data = str(7:end); elseif strcmp(str(2:9),'POSITION') type='position'; data = str(10:end); elseif strcmp(str(2:10),'TIMESTAMP') type='timestamp'; data = str(11:end); elseif strcmp(str(2:11),'PERCEIVEDF') type='perceivedf'; data = str(12:end); else type='comment'; data=str; end else type=''; data=str; end end if ~numel(type) continue; end switch(lower(type)) case 'ndims' info.NumberOfDimensions=sscanf(data, '%d')'; case 'dimensions' info.Dimensions=sscanf(data, '%d')'; case 'spacing' info.PixelDimensions=sscanf(data, '%lf')'; case 'elementbyteordermsb' info.ByteOrder=lower(data); case 'point_data' info.npoints=sscanf(data, '%lf')'; case 'field' info.fielddata=sscanf(data, '%s'); info.nfielddata=str2num(info.fielddata(end)); %for i=1:info.nfielddata for i=1 str=fgetl(fid); s=find(str==' ',3,'first'); if(~isempty(s)) type=str(1:s(1)-1); ncomponents=str2num(str(s(1)+1:s(2)-1)); nvectors=str2num(str(s(2)+1:s(3)-1)); vectortype=str(s(3)+1:end); info.DataType = vectortype; else continue; end %data_read = fread(fid, [nvectors*ncomponents ],vectortype)'; data_read = fscanf(fid, '%lf', [ncomponents nvectors ]); info.(['field' num2str(i)]) = data_read'; end case 'origin' info.Offset=sscanf(data, '%lf')'; % Custom fields case 'force' info.Force=sscanf(data, '%lf')'; case 'position' info.Position=sscanf(data, '%lf')'; case 'timestamp' info.Timestamp=sscanf(data, '%lf')'; case '#' info.comment = data; case 'perceivedf' info.perceivedf=data; otherwise info.(type)=data; end end if ~numel(info.TransformMatrix) info.TransformMatrix = reshape(eye(3), 1,3*3); end if ~numel(info.CenterOfRotation) info.CenterOfRotation = zeros(1,3); end switch(info.DataType) case 'char', info.BitDepth=8; case 'uchar', info.BitDepth=8; case 'short', info.BitDepth=16; case 'ushort', info.BitDepth=16; case 'int', info.BitDepth=32; case 'uint', info.BitDepth=32; case 'float', info.BitDepth=32; case 'double', info.BitDepth=64; otherwise, info.BitDepth=0; end if(~isfield(info,'HeaderSize')) info.HeaderSize=ftell(fid); end fclose(fid); end
github
vildenst/3D-heart-models-master
read_roi.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_roi.m
2,775
utf_8
68644e9d752ab5c4857ac0a482658adf
function [roinormal, roiorigin, points2D, points3D] = read_roi(roi_file) % [roinormal, roiorigin, points2D, points3D] = read_roi(roi_file) %roi_file must be an xml file % points are wc in 2D of the roi vertices. This space can be achieved by % the matrix defined by origin and normal roi_file = char(roi_file); idx = strfind(roi_file,'xml'); roiFileTxT = [ roi_file(1:idx-1) 'txt']; planeData =dlmread(roiFileTxT); roi.normal = planeData(1,:)'; roi.origin = planeData(2,:)'; roinormal = roi.normal; roiorigin = roi.origin; [x y]=vtkMathPerpendiculars(roi.normal,pi/2); M=eye(4); M(1:3,1:3) = [x(:) y(:) roi.normal(:)]; M(1:3,4) = roi.origin; % -------------------------------- xDoc= xmlread(roi_file); children = parseChildNodes(xDoc); npoints=str2num(children.Children(2).Children(2).Attributes(2).Value); points_string = children.Children(2).Children(2).Children(6).Children(2).Children.Data; [token remain]=strtok(points_string,' '); for i=1:npoints for j=1:3 [token remain]=strtok(remain,' '); points2D{i,j}=str2num(token); end end points2D = cell2mat(points2D)'; points2D(3,:)=0.0; points3D = M * [points2D ; ones(1,size(points2D,2))]; end function children = parseChildNodes(theNode) % Recurse over node children. children = []; if theNode.hasChildNodes childNodes = theNode.getChildNodes; numChildNodes = childNodes.getLength; allocCell = cell(1, numChildNodes); children = struct( ... 'Name', allocCell, 'Attributes', allocCell, ... 'Data', allocCell, 'Children', allocCell); for count = 1:numChildNodes theChild = childNodes.item(count-1); children(count) = makeStructFromNode(theChild); end end end % ----- Subfunction MAKESTRUCTFROMNODE ----- function nodeStruct = makeStructFromNode(theNode) % Create structure of node info. nodeStruct = struct( ... 'Name', char(theNode.getNodeName), ... 'Attributes', parseAttributes(theNode), ... 'Data', '', ... 'Children', parseChildNodes(theNode)); if any(strcmp(methods(theNode), 'getData')) nodeStruct.Data = char(theNode.getData); else nodeStruct.Data = ''; end end % ----- Subfunction PARSEATTRIBUTES ----- function attributes = parseAttributes(theNode) % Create attributes structure. attributes = []; if theNode.hasAttributes theAttributes = theNode.getAttributes; numAttributes = theAttributes.getLength; allocCell = cell(1, numAttributes); attributes = struct('Name', allocCell, 'Value', ... allocCell); for count = 1:numAttributes attrib = theAttributes.item(count-1); attributes(count).Name = char(attrib.getName); attributes(count).Value = char(attrib.getValue); end end end
github
vildenst/3D-heart-models-master
read_nifty.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_nifty.m
13,037
utf_8
fd40f3d530bce32b3eba55c19b8f5511
function [img, info]=read_nifty(filename) % [image info ] = read_nifty(filename) % Adapted from the code % "Tools for NIfTI and ANALYZE image" % by Jimmy Shen % Available at http://www.mathworks.com/matlabcentral/fileexchange/8797-tools-for-nifti-and-analyze-image if ~exist('filename','var') error('Usage: nii = load_nii(filename, [img_idx], [dim5_idx], [dim6_idx], [dim7_idx], [old_RGB], [tolerance], [preferredForm])'); end if ~exist('img_idx','var') || isempty(img_idx) img_idx = []; end if ~exist('dim5_idx','var') || isempty(dim5_idx) dim5_idx = []; end if ~exist('dim6_idx','var') || isempty(dim6_idx) dim6_idx = []; end if ~exist('dim7_idx','var') || isempty(dim7_idx) dim7_idx = []; end if ~exist('old_RGB','var') || isempty(old_RGB) old_RGB = 0; end if ~exist('tolerance','var') || isempty(tolerance) tolerance = 0.1; % 10 percent end if ~exist('preferredForm','var') || isempty(preferredForm) preferredForm= 's'; % Jeff end v = version; % Check file extension. If .gz, unpack it into temp folder % if length(filename) > 2 && strcmp(filename(end-2:end), '.gz') if ~strcmp(filename(end-6:end), '.img.gz') && ... ~strcmp(filename(end-6:end), '.hdr.gz') && ... ~strcmp(filename(end-6:end), '.nii.gz') error('Please check filename.'); end if str2num(v(1:3)) < 7.1 || ~usejava('jvm') error('Please use MATLAB 7.1 (with java) and above, or run gunzip outside MATLAB.'); elseif strcmp(filename(end-6:end), '.img.gz') filename1 = filename; filename2 = filename; filename2(end-6:end) = ''; filename2 = [filename2, '.hdr.gz']; tmpDir = tempname; mkdir(tmpDir); gzFileName = filename; filename1 = gunzip(filename1, tmpDir); filename2 = gunzip(filename2, tmpDir); filename = char(filename1); % convert from cell to string elseif strcmp(filename(end-6:end), '.hdr.gz') filename1 = filename; filename2 = filename; filename2(end-6:end) = ''; filename2 = [filename2, '.img.gz']; tmpDir = tempname; mkdir(tmpDir); gzFileName = filename; filename1 = gunzip(filename1, tmpDir); filename2 = gunzip(filename2, tmpDir); filename = char(filename1); % convert from cell to string elseif strcmp(filename(end-6:end), '.nii.gz') tmpDir = tempname; mkdir(tmpDir); gzFileName = filename; filename = gunzip(filename, tmpDir); filename = char(filename); % convert from cell to string end end % Read the dataset header % [nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename); % Read the header extension % % nii.ext = load_nii_ext(filename); % Read the dataset body % [nii.img,nii.hdr] = load_nii_img(nii.hdr,nii.filetype,nii.fileprefix, ... nii.machine,img_idx,dim5_idx,dim6_idx,dim7_idx,old_RGB); % Perform some of sform/qform transform % nii = xform_nii(nii, tolerance, preferredForm); % Clean up after gunzip % if exist('gzFileName', 'var') % fix fileprefix so it doesn't point to temp location % nii.fileprefix = gzFileName(1:end-7); rmdir(tmpDir,'s'); end N = nii.hdr.dime.dim(1); sz = nii.hdr.dime.dim(2:2+N-1)'; spc = nii.hdr.dime.pixdim(2:2+N-1)'; ori = nii.hdr.dime.pixdim((2:2+N-1)+1+N)'; ma = eye(N); img = ImageType(sz, ori, spc, ma); img.data = nii.img; info = []; end % internal function % - Jimmy Shen ([email protected]) function [hdr, filetype, fileprefix, machine] = load_nii_hdr(fileprefix) if ~exist('fileprefix','var'), error('Usage: [hdr, filetype, fileprefix, machine] = load_nii_hdr(filename)'); end machine = 'ieee-le'; new_ext = 0; if findstr('.nii',fileprefix) & strcmp(fileprefix(end-3:end), '.nii') new_ext = 1; fileprefix(end-3:end)=''; end if findstr('.hdr',fileprefix) & strcmp(fileprefix(end-3:end), '.hdr') fileprefix(end-3:end)=''; end if findstr('.img',fileprefix) & strcmp(fileprefix(end-3:end), '.img') fileprefix(end-3:end)=''; end if new_ext fn = sprintf('%s.nii',fileprefix); if ~exist(fn) msg = sprintf('Cannot find file "%s.nii".', fileprefix); error(msg); end else fn = sprintf('%s.hdr',fileprefix); if ~exist(fn) msg = sprintf('Cannot find file "%s.hdr".', fileprefix); error(msg); end end fid = fopen(fn,'r',machine); if fid < 0, msg = sprintf('Cannot open file %s.',fn); error(msg); else fseek(fid,0,'bof'); if fread(fid,1,'int32') == 348 hdr = read_header(fid); fclose(fid); else fclose(fid); % first try reading the opposite endian to 'machine' % switch machine, case 'ieee-le', machine = 'ieee-be'; case 'ieee-be', machine = 'ieee-le'; end fid = fopen(fn,'r',machine); if fid < 0, msg = sprintf('Cannot open file %s.',fn); error(msg); else fseek(fid,0,'bof'); if fread(fid,1,'int32') ~= 348 % Now throw an error % msg = sprintf('File "%s" is corrupted.',fn); error(msg); end hdr = read_header(fid); fclose(fid); end end end if strcmp(hdr.hist.magic, 'n+1') filetype = 2; elseif strcmp(hdr.hist.magic, 'ni1') filetype = 1; else filetype = 0; end return % load_nii_hdr end %--------------------------------------------------------------------- function [ dsr ] = read_header(fid) % Original header structures % struct dsr % { % struct header_key hk; /* 0 + 40 */ % struct image_dimension dime; /* 40 + 108 */ % struct data_history hist; /* 148 + 200 */ % }; /* total= 348 bytes*/ dsr.hk = header_key(fid); dsr.dime = image_dimension(fid); dsr.hist = data_history(fid); % For Analyze data format % if ~strcmp(dsr.hist.magic, 'n+1') & ~strcmp(dsr.hist.magic, 'ni1') dsr.hist.qform_code = 0; dsr.hist.sform_code = 0; end return % read_header end %--------------------------------------------------------------------- function [ hk ] = header_key(fid) fseek(fid,0,'bof'); % Original header structures % struct header_key /* header key */ % { /* off + size */ % int sizeof_hdr /* 0 + 4 */ % char data_type[10]; /* 4 + 10 */ % char db_name[18]; /* 14 + 18 */ % int extents; /* 32 + 4 */ % short int session_error; /* 36 + 2 */ % char regular; /* 38 + 1 */ % char dim_info; % char hkey_un0; /* 39 + 1 */ % }; /* total=40 bytes */ % % int sizeof_header Should be 348. % char regular Must be 'r' to indicate that all images and % volumes are the same size. v6 = version; if str2num(v6(1))<6 directchar = '*char'; else directchar = 'uchar=>char'; end hk.sizeof_hdr = fread(fid, 1,'int32')'; % should be 348! hk.data_type = deblank(fread(fid,10,directchar)'); hk.db_name = deblank(fread(fid,18,directchar)'); hk.extents = fread(fid, 1,'int32')'; hk.session_error = fread(fid, 1,'int16')'; hk.regular = fread(fid, 1,directchar)'; hk.dim_info = fread(fid, 1,'uchar')'; return % header_key end %--------------------------------------------------------------------- function [ dime ] = image_dimension(fid) % Original header structures % struct image_dimension % { /* off + size */ % short int dim[8]; /* 0 + 16 */ % /* % dim[0] Number of dimensions in database; usually 4. % dim[1] Image X dimension; number of *pixels* in an image row. % dim[2] Image Y dimension; number of *pixel rows* in slice. % dim[3] Volume Z dimension; number of *slices* in a volume. % dim[4] Time points; number of volumes in database % */ % float intent_p1; % char vox_units[4]; /* 16 + 4 */ % float intent_p2; % char cal_units[8]; /* 20 + 4 */ % float intent_p3; % char cal_units[8]; /* 24 + 4 */ % short int intent_code; % short int unused1; /* 28 + 2 */ % short int datatype; /* 30 + 2 */ % short int bitpix; /* 32 + 2 */ % short int slice_start; % short int dim_un0; /* 34 + 2 */ % float pixdim[8]; /* 36 + 32 */ % /* % pixdim[] specifies the voxel dimensions: % pixdim[1] - voxel width, mm % pixdim[2] - voxel height, mm % pixdim[3] - slice thickness, mm % pixdim[4] - volume timing, in msec % ..etc % */ % float vox_offset; /* 68 + 4 */ % float scl_slope; % float roi_scale; /* 72 + 4 */ % float scl_inter; % float funused1; /* 76 + 4 */ % short slice_end; % float funused2; /* 80 + 2 */ % char slice_code; % float funused2; /* 82 + 1 */ % char xyzt_units; % float funused2; /* 83 + 1 */ % float cal_max; /* 84 + 4 */ % float cal_min; /* 88 + 4 */ % float slice_duration; % int compressed; /* 92 + 4 */ % float toffset; % int verified; /* 96 + 4 */ % int glmax; /* 100 + 4 */ % int glmin; /* 104 + 4 */ % }; /* total=108 bytes */ dime.dim = fread(fid,8,'int16')'; dime.intent_p1 = fread(fid,1,'float32')'; dime.intent_p2 = fread(fid,1,'float32')'; dime.intent_p3 = fread(fid,1,'float32')'; dime.intent_code = fread(fid,1,'int16')'; dime.datatype = fread(fid,1,'int16')'; dime.bitpix = fread(fid,1,'int16')'; dime.slice_start = fread(fid,1,'int16')'; dime.pixdim = fread(fid,8,'float32')'; dime.vox_offset = fread(fid,1,'float32')'; dime.scl_slope = fread(fid,1,'float32')'; dime.scl_inter = fread(fid,1,'float32')'; dime.slice_end = fread(fid,1,'int16')'; dime.slice_code = fread(fid,1,'uchar')'; dime.xyzt_units = fread(fid,1,'uchar')'; dime.cal_max = fread(fid,1,'float32')'; dime.cal_min = fread(fid,1,'float32')'; dime.slice_duration = fread(fid,1,'float32')'; dime.toffset = fread(fid,1,'float32')'; dime.glmax = fread(fid,1,'int32')'; dime.glmin = fread(fid,1,'int32')'; return % image_dimension end %--------------------------------------------------------------------- function [ hist ] = data_history(fid) % Original header structures % struct data_history % { /* off + size */ % char descrip[80]; /* 0 + 80 */ % char aux_file[24]; /* 80 + 24 */ % short int qform_code; /* 104 + 2 */ % short int sform_code; /* 106 + 2 */ % float quatern_b; /* 108 + 4 */ % float quatern_c; /* 112 + 4 */ % float quatern_d; /* 116 + 4 */ % float qoffset_x; /* 120 + 4 */ % float qoffset_y; /* 124 + 4 */ % float qoffset_z; /* 128 + 4 */ % float srow_x[4]; /* 132 + 16 */ % float srow_y[4]; /* 148 + 16 */ % float srow_z[4]; /* 164 + 16 */ % char intent_name[16]; /* 180 + 16 */ % char magic[4]; % int smin; /* 196 + 4 */ % }; /* total=200 bytes */ v6 = version; if str2num(v6(1))<6 directchar = '*char'; else directchar = 'uchar=>char'; end hist.descrip = deblank(fread(fid,80,directchar)'); hist.aux_file = deblank(fread(fid,24,directchar)'); hist.qform_code = fread(fid,1,'int16')'; hist.sform_code = fread(fid,1,'int16')'; hist.quatern_b = fread(fid,1,'float32')'; hist.quatern_c = fread(fid,1,'float32')'; hist.quatern_d = fread(fid,1,'float32')'; hist.qoffset_x = fread(fid,1,'float32')'; hist.qoffset_y = fread(fid,1,'float32')'; hist.qoffset_z = fread(fid,1,'float32')'; hist.srow_x = fread(fid,4,'float32')'; hist.srow_y = fread(fid,4,'float32')'; hist.srow_z = fread(fid,4,'float32')'; hist.intent_name = deblank(fread(fid,16,directchar)'); hist.magic = deblank(fread(fid,4,directchar)'); fseek(fid,253,'bof'); hist.originator = fread(fid, 5,'int16')'; return % data_history end
github
vildenst/3D-heart-models-master
read_meshMesh.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_meshMesh.m
2,725
utf_8
f44abbb2b7d5527f563591bcc2b210a5
function mesh =read_meshMesh(filename) % Function for reading a mesh in a Visualization Toolkit (VTK) format % % mesh = read_vtkMesh(filename); % % examples: % mesh=read_vtkMesh('volume.vtk'); % mesh would be of the class MeshType %from vtkCellType.h keywordList={'MeshVersionFormatted','Dimension','Vertices','Triangles','Quadrilaterals','Tetrahedra',... 'Hexahedra','Normals','Tangents','Corners','Edges','Ridges','End'}; if(exist('filename','var')==0) [filename, pathname] = uigetfile('*.vtk', 'Read vtk-file'); filename = [pathname filename]; end fid=fopen(filename,'rb'); if(fid<0) fprintf('could not open file %s\n',filename); return end mesh=MeshType(); isEnd=false; dimension=-1; nvertices=-1; vertices=[]; ntriangles=-1; triangles=[]; while ~isEnd kw = nextKeyword(fid,keywordList); switch kw{1} case keywordList{1} % This is currently ignored. states wether is float or double case keywordList{2} kw = nextKeyword(fid,keywordList); dimension = str2num(kw{1}); case keywordList{3} kw = nextKeyword(fid,keywordList); nvertices= str2num(kw{1}); vertices=fscanf(fid,'%f %f %f %f',[dimension+1 nvertices ]); vertices = vertices(1:3,:)'; mesh.npoints = nvertices; mesh.points=vertices; case keywordList{4} kw = nextKeyword(fid,keywordList); ntriangles= str2num(kw{1}); triangles=fscanf(fid,'%f %f %f %f',[dimension+1 ntriangles]); triangles = triangles(1:3,:)'; mesh.ntriangles = ntriangles; mesh.triangles=triangles; case keywordList{5} % quadrilaterals kw = nextKeyword(fid,keywordList); ntriangles= str2num(kw{1}); quadrilaterals=fscanf(fid,'%d %d %d %d %d',[dimension+2 ntriangles]); quadrilaterals= quadrilaterals(1:4,:)'; % convert each cuadrilateral into 2 triangles triangles = [quadrilaterals(:,1:3) ; quadrilaterals(:,[3 4 1])]; mesh.ntriangles = size(triangles,1); mesh.triangles=triangles; case keywordList{end} %disp(['Finished ']) isEnd=true; otherwise %disp(['Unknown field ' kw{1}]) end end end function kw = nextKeyword(fid,keywordList) str = fgetl(fid); if strcmp(str,keywordList{end}) kw=keywordList{end}; return; end [a1,a2]=strtok(str); while strcmp(a1,'#') str = fgetl(fid); [a1,a2]=strtok(str); end kw{1}=a1; kw{2}=a2; end
github
vildenst/3D-heart-models-master
read_MITKPoints.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_MITKPoints.m
4,015
utf_8
e5e60717ca44a830094c042e96c77277
function out=read_MITKPoints(filename) global bounds; global points; bounds = zeros(6,1); points = []; out = []; try tree = xmlread(filename); catch error('Failed to read XML file %s.',filename); end % Recurse over child nodes. This could run into problems % with very deeply nested trees. try theStruct = parseChildNodes(tree); catch error('Unable to parse XML file %s.',filename); end out.bounds = bounds; out.points = points; end % ----- Local function PARSECHILDNODES ----- function children = parseChildNodes(theNode) % Recurse over node children. global bounds; global points; children = []; if theNode.hasChildNodes childNodes = theNode.getChildNodes; numChildNodes = childNodes.getLength; allocCell = cell(1, numChildNodes); children = struct( ... 'Name', allocCell, 'Attributes', allocCell, ... 'Data', allocCell, 'Children', allocCell); for count = 1:numChildNodes theChild = childNodes.item(count-1); children(count) = makeStructFromNode(theChild); if strcmp( children(count).Name,'Bounds') for i=1:numel(children(count).Children) ch = children(count).Children(i); if strcmp( ch.Name,'Min') bounds(1) = str2num(ch.Attributes(2).Value); bounds(3) = str2num(ch.Attributes(3).Value); bounds(5) = str2num(ch.Attributes(4).Value); elseif strcmp( ch.Name,'Max') bounds(2) = str2num(ch.Attributes(2).Value); bounds(4) = str2num(ch.Attributes(3).Value); bounds(6) = str2num(ch.Attributes(4).Value); end end elseif strcmp( children(count).Name,'point') for i=1:numel(children(count).Children) ch = children(count).Children(i); if strcmp(ch.Name,'id') chch = ch.Children; id = str2num(chch.Data); npts = numel(points); points(npts+1).id = id; elseif strcmp( ch.Name,'specification') chch = ch.Children; npts = numel(points); points(npts).tag = chch.Data; elseif strcmp( ch.Name,'x') chch = ch.Children; npts = numel(points); points(npts).coordinates(1) = str2num(chch.Data); elseif strcmp( ch.Name,'y') chch = ch.Children; npts = numel(points); points(npts).coordinates(2) = str2num(chch.Data); elseif strcmp( ch.Name,'z') chch = ch.Children; npts = numel(points); points(npts).coordinates(3) = str2num(chch.Data); end end end end end end % ----- Local function MAKESTRUCTFROMNODE ----- function nodeStruct = makeStructFromNode(theNode) % Create structure of node info. nodeStruct = struct( ... 'Name', char(theNode.getNodeName), ... 'Attributes', parseAttributes(theNode), ... 'Data', '', ... 'Children', parseChildNodes(theNode)); if any(strcmp(methods(theNode), 'getData')) nodeStruct.Data = char(theNode.getData); else nodeStruct.Data = ''; end end % ----- Local function PARSEATTRIBUTES ----- function attributes = parseAttributes(theNode) % Create attributes structure. attributes = []; if theNode.hasAttributes theAttributes = theNode.getAttributes; numAttributes = theAttributes.getLength; allocCell = cell(1, numAttributes); attributes = struct('Name', allocCell, 'Value', ... allocCell); for count = 1:numAttributes attrib = theAttributes.item(count-1); attributes(count).Name = char(attrib.getName); attributes(count).Value = char(attrib.getValue); end end end
github
vildenst/3D-heart-models-master
read_gipl.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/processing/IO/read_gipl.m
4,261
utf_8
b7e0a24be25a0a04a0c57e59ed2ca44f
function out =read_gipl(filename) % function for reading header of Guys Image Processing Lab (Gipl) volume file % % out = gipl_read_header(filename); % % returns an ImageType % % Copied from the package ReadData3D_version1h fid=fopen(filename,'rb','ieee-be'); %fid=fopen(filename,'r','native'); if(fid<0) fprintf('could not open file %s\n',filename); return end trans_type{1}='binary'; trans_type{7}='char'; trans_type{8}='uchar'; trans_type{15}='short'; trans_type{16}='ushort'; trans_type{31}='uint'; trans_type{32}='int'; trans_type{64}='float';trans_type{65}='double'; trans_type{144}='C_short';trans_type{160}='C_int'; trans_type{192}='C_float'; trans_type{193}='C_double'; trans_type{200}='surface'; trans_type{201}='polygon'; trans_orien{0+1}='UNDEFINED'; trans_orien{1+1}='UNDEFINED_PROJECTION'; trans_orien{2+1}='AP_PROJECTION'; trans_orien{3+1}='LATERAL_PROJECTION'; trans_orien{4+1}='OBLIQUE_PROJECTION'; trans_orien{8+1}='UNDEFINED_TOMO'; trans_orien{9+1}='AXIAL'; trans_orien{10+1}='CORONAL'; trans_orien{11+1}='SAGITTAL'; trans_orien{12+1}='OBLIQUE_TOMO'; offset=256; % header size %get the file size fseek(fid,0,'eof'); fsize = ftell(fid); fseek(fid,0,'bof'); mn = 719555000; sizes=fread(fid,4,'ushort')'; if(sizes(4)==1), maxdim=3; else maxdim=4; end sizes=sizes(1:maxdim); image_type=fread(fid,1,'ushort'); scales=fread(fid,4,'float')'; scales=scales(1:maxdim); patient=fread(fid,80, 'uint8=>char')'; matrix=fread(fid,20,'float')'; orientation=fread(fid,1, 'uint8')'; par2=fread(fid,1, 'uint8')'; voxmin=fread(fid,1,'double'); voxmax=fread(fid,1,'double'); origin=fread(fid,4,'double')'; origin=origin(1:maxdim); pixval_offset=fread(fid,1,'float'); pixval_cal=fread(fid,1,'float'); interslicegap=fread(fid,1,'float'); user_def2=fread(fid,1,'float'); magic_number= fread(fid,1,'uint32'); %if (magic_number~=4026526128), error('file corrupt - or not big endian'); end fclose('all'); info.Filename=filename; info.FileSize=fsize; info.Dimensions=sizes; info.PixelDimensions=scales; info.ImageType=image_type; info.Patient=patient; info.Matrix=matrix; info.Orientation=orientation; info.VoxelMin=voxmin; info.VoxelMax=voxmax; info.Origing=origin; info.PixValOffset=pixval_offset; info.PixValCal=pixval_cal; info.InterSliceGap=interslicegap; info.UserDef2=user_def2; info.Par2=par2; info.Offset=offset; out = ImageType(sizes(:), origin(:),scales(:),eye(numel(sizes))); out.data = gipl_read_volume(info); end function V = gipl_read_volume(info) % function for reading volume of Guys Image Processing Lab (Gipl) volume file % % volume = gipl_read_volume(file-header) % % examples: % 1: info = gipl_read_header() % V = gipl_read_volume(info); % imshow(squeeze(V(:,:,round(end/2))),[]); % % 2: V = gipl_read_volume('test.gipl'); if(~isstruct(info)) info=gipl_read_header(info); end % Open gipl file fid=fopen(info.Filename','rb','ieee-be'); % Seek volume data start if(info.ImageType==1), voxelbits=1; end if(info.ImageType==7||info.ImageType==8), voxelbits=8; end if(info.ImageType==15||info.ImageType==16), voxelbits=16; end if(info.ImageType==31||info.ImageType==32||info.ImageType==64), voxelbits=32; end if(info.ImageType==65), voxelbits=64; end datasize=prod(info.Dimensions)*(voxelbits/8); fsize=info.FileSize; fseek(fid,fsize-datasize,'bof'); % Read Volume data volsize(1:numel(info.Dimensions))=info.Dimensions; if(info.ImageType==1), V = logical(fread(fid,datasize,'bit1')); end if(info.ImageType==7), V = int8(fread(fid,datasize,'char')); end if(info.ImageType==8), V = uint8(fread(fid,datasize,'uchar')); end if(info.ImageType==15), V = int16(fread(fid,datasize,'short')); end if(info.ImageType==16), V = uint16(fread(fid,datasize,'ushort')); end if(info.ImageType==31), V = uint32(fread(fid,datasize,'uint')); end if(info.ImageType==32), V = int32(fread(fid,datasize,'int')); end if(info.ImageType==64), V = single(fread(fid,datasize,'float')); end if(info.ImageType==65), V = double(fread(fid,datasize,'double')); end fclose(fid); % Reshape the volume data to the right dimensions V = reshape(V,volsize); end
github
vildenst/3D-heart-models-master
MeshType.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/class_mesh/MeshType.m
58,137
utf_8
42bb608b029763866937bbd8bd41223d
classdef MeshType < handle % This class defines a trinagulated mesh % by Alberto Gomez, 2011 % properties(GetAccess = 'public', SetAccess = 'public') npoints=0; ntriangles=0; points=[];% npointsx3 matrix triangles=[];%ntrianglesx3 matrix bounds = [0 0 0 0 0 0]; attributes = AttributeType(); % for labels, luts, etc end methods(Access = public) %constructor function obj = MeshType(npoints,ntriangles) if(nargin > 0) if(nargin ==1 ) % copy constructor obj.npoints = npoints.npoints; obj.ntriangles = npoints.ntriangles; obj.points = npoints.points; obj.triangles = npoints.triangles; for i=1:numel(npoints.attributes) obj.attributes(i)=AttributeType(npoints.attributes(i)); end else obj.npoints = npoints; obj.ntriangles = ntriangles; obj.points = zeros(npoints,3); obj.triangles = zeros(ntriangles,3); obj.attributes(1)=AttributeType(obj.npoints); end end end function b = ComputeBounds(obj) b([1 3 5])=min(obj.points,[],1); b([2 4 6])=max(obj.points,[],1); obj.bounds = b; end function v = GetVolume(obj) normals = obj.GetNormalAtFaces(1:obj.ntriangles); [~,areas]= obj.GetTriangleNormal(1:obj.ntriangles); p1 = obj.points(obj.triangles(:,1),:); p2 = obj.points(obj.triangles(:,2),:); p3 = obj.points(obj.triangles(:,3),:); pts = cat(3,p1,p2,p3); barycentres = mean(pts ,3); v = nansum(dot(barycentres,normals,2).*areas)/3; end function P = GetVertexCoordinates(obj, index) % get the position of a vertex at index "index", an integer P = obj.points(index,:); end function P = GetTriangleVertices(obj, index) % get the vertices composing the triangle at the index P = obj.triangles(index,:); end function [P, area] = GetTriangleNormal(obj,index) % get the normal to the surface of a triangle triang = obj.triangles(index,:); v1 = obj.points(triang(:,2),:) - obj.points(triang(:,1),:); v2 = obj.points(triang(:,3),:) - obj.points(triang(:,1),:); cp = cross(v1,v2); area = sqrt(sum(cp.^2,2))/2; P = cp./([area area area]*2); %P = P(:)'; end %% function out = laplacianSmoothing(obj) ignoreOrientation = true; out = MeshType(obj); h = waitbar(0,'Applying laplacian smooth'); for i =1:obj.npoints nn = obj.GetVertexNeighbours(i); positions = obj.points(nn,:); out.points(i,:)=mean(positions); waitbar(i/obj.npoints); end close(h); end function normal = GetNormalAtVertex(obj,index, varargin) % get normal to a vertex % normal is computed as linear combination of the normals to % faces. % % the weigting factor for the average can be chosen by the % user, Gouraud being default: % options : % mode = 'Gouraud' (w=1) % 'area' (w=area) index_of_att = obj.find_attribute('normalVectors'); if index_of_att >0 normal= obj.attributes(index_of_att).attribute_array(index,:); return end normal = [0 0 0]; ignoreOrientation=false; center=[]; % a point inside (convex geometry) to be able to define a positicve orientation mode = 'Gouraud'; % w = 1 for i=1:size(varargin,2) if (strcmp(varargin{i},'mode')) mode =varargin{i+1}; elseif (strcmp(varargin{i},'ignoreOrientation')) ignoreOrientation = varargin{i+1}; elseif (strcmp(varargin{i},'insidePoint')) center= varargin{i+1}; end end nn = obj.GetVertexNeighboursSorted(index,ignoreOrientation); w = ones(size(nn,1),1); % weightings % compute normals to the neighbor faces normals = zeros(length(nn),3); areas = zeros(length(nn),1); for i = 1:length(nn) v1 = obj.points(nn(i),:)-obj.points(index,:); v2 = obj.points(nn(cyclicNext(i,length(nn))),:)-obj.points(index,:); areas(i)=norm(cross(v1,v2))/2; normals(i,:) = cross(v1,v2)/areas(i)*2; end if (strcmp(mode,'Gouraud')) % w is all ones normal = sum((w*ones(1,3)).*normals,1)/sum(w); normal = normal/norm(normal); elseif (strcmp(mode,'area')) normal = sum((areas*ones(1,3)).*normals,1)/sum(areas); normal = normal/norm(normal); else normal = normals(1,:); normal = normal/norm(normal); %display('Using default mode: Gouraud'); end if (numel(center)) vector = obj.points(index,:)-center; if vector*normal'<0 normal=-1*normal; end end end %% function normal = GetNormalAtFaces(obj,index) % get normal to faces. % get first edge v1 = obj.points(obj.triangles(index,2),:)-obj.points(obj.triangles(index,1),:); v2 = obj.points(obj.triangles(index,3),:)-obj.points(obj.triangles(index,1),:); normal = cross(v1,v2,2); % normalize result magnitude = sqrt(normal(:,1).^2 + normal(:,2).^2 + normal(:,3).^2); for i=1:3 normal(:,i) = normal(:,i)./magnitude; end end %% function P = GetForwardVertexNeighbours(obj, index) % Returns neighbours as oriented subcession of 2 neighbours [r, c]=find(obj.triangles==index); extended_triangles = [obj.triangles(r,:) obj.triangles(r,:)]; P=[]; for i=1:numel(r) c = find(extended_triangles(i,:)==index,1,'first'); P =[P; extended_triangles(i,(c+1):(c+2))]; end end %% function P = GetBackwardVertexNeighbours(obj, index) % Returns neighbours as oriented subcession of 2 neighbours [r, c]=find(obj.triangles==index); extended_triangles = [obj.triangles(r,:) obj.triangles(r,:)]; P=[]; for i=1:numel(r) c = find(extended_triangles(i,:)==index,1,'last'); P =[P; extended_triangles(i,(c-1):(c-2))]; end end %% function P = GetVertexNeighbours(obj,index) % get a column vector with the neighbours to a vertex (excludes the vertex itself) [r, c]=find(obj.triangles==index); tri = obj.triangles(r,:); tri_reshaped = unique(reshape(tri,3*size(r,1),1)); % remove repeated elements P = zeros(length(tri_reshaped)-1,1); i=1; for j=1:length(tri_reshaped) if (tri_reshaped(j)~=index) P(i)=tri_reshaped(j); i = i+1; end end end %% function sorted_neighbours = GetVertexNeighboursSorted(obj,index, varargin) % get a column vector with the neighbours to a vertex (excludes the vertex itself) % the neighbours are given in couter-clockwise order ignoreOrientation=false; if (size(varargin,2)>0) ignoreOrientation = varargin{1}; end [r_, c_]=find(obj.triangles==index); triangles = obj.triangles(r_,:); trianglesExtended = [triangles triangles]; all_neighbours = unique(triangles); all_neighbours(all_neighbours ==index)=[]; added_neighbours = 0; current_neighbour = trianglesExtended(1,find(trianglesExtended(1,:)==index ,1,'first')+1); % we start courter clockwise sorted_neighbours = zeros(numel(all_neighbours),1); added_neighbours=added_neighbours+1; sorted_neighbours(added_neighbours)=current_neighbour; while(numel(nonzeros(sorted_neighbours))<numel(all_neighbours)) [r_, c_] = find(triangles==current_neighbour); candidate_found=false; for i = 1:numel(r_) c_2 = find(trianglesExtended(r_(i),:)==current_neighbour,1,'first'); if (ignoreOrientation) candidate = [ trianglesExtended(r_(i),c_2+1) trianglesExtended(r_(i),c_2+2)]; candidate(candidate==index)=[]; else candidate = trianglesExtended(r_(i),c_2+1); end if numel(candidate) && ~numel(find(sorted_neighbours==candidate)) && candidate~=index current_neighbour=candidate; added_neighbours=added_neighbours+1; sorted_neighbours(added_neighbours)=current_neighbour; candidate_found=true; break; end end if ~candidate_found disp('No candidate found. Check the surface orientation') sorted_neighbours=[]; return end end end %% function ring = Get1Ring(obj,i) % i is the vertex index for which the ring is required % If there is only one triangle, this is a corner point, return % its triangle [r_, c_]=find(obj.triangles==i); if numel(r_)==1 ring =r_; return; end % Now we assume the triangle is ordered ring=r_(1); r_(1)=[]; while(numel(r_)) vertices = obj.triangles(ring(end),[1 2 3 1 2]); centre_idx=find(vertices==i,1,'first'); % Add next triangle next_vertex=vertices(centre_idx+2); triangles = obj.triangles(r_,:); next_triangle = find(sum(triangles==i | triangles==next_vertex,2)==2,1,'first'); if numel(next_triangle) ring = [ring r_(next_triangle)]; r_(next_triangle)=[]; end % Add previous triangle vertices = obj.triangles(ring(1),[1 2 3 1 2]); centre_idx=find(vertices==i,1,'first'); prev_vertex=vertices(centre_idx+1); triangles = obj.triangles(r_,:); prev_triangle = find(sum(triangles==i | triangles==prev_vertex,2)==2,1,'first'); if numel(prev_triangle) ring = [ r_(prev_triangle) ring]; r_(prev_triangle)=[]; end end end %% function e = edges(obj) % This function returns a listof the edges tmp = [obj.triangles(:,[1 2]) ; obj.triangles(:,[2 3]) ; obj.triangles(:,[3 1])]; % remove duplicates e=unique(sort(tmp,2),'rows'); end %% function [ring,tri_sorted] = GetRingOrdered(obj,i) % This function returns the one ring required by the paper: % M. Desbrun, M. Meyer, and P. Alliez, "Intrinsic Parametrization of % Surface Meshes", Eurographics 2002 % Arguments: % i - central vertex % The ring is ordered so that every triangle starts with the i % vertex % This function will also correct for the orientation [r_, c_]=find(obj.triangles==i); ring=r_(1); r_(1)=[]; vertices = obj.triangles(ring(end),[1 2 3 1 2]); tri_sorted = vertices([c_(1) c_(1)+1 c_(1)+2]); c_(1)=[]; while(numel(r_)) vertices = obj.triangles(ring(end),[1 2 3 1 2]); centre_idx=find(vertices==i,1,'first'); % Add next triangle next_vertex=vertices(centre_idx+2); added=0; triangles = obj.triangles(r_,:); next_triangle = find(sum(triangles==i | triangles==next_vertex,2)==2,1,'first'); if numel(next_triangle) ring = [ring r_(next_triangle)]; vertices_ = obj.triangles(r_(next_triangle),[1 2 3 1 2]); r_(next_triangle)=[]; tri_sorted = [tri_sorted ; vertices_([c_(next_triangle) c_(next_triangle)+1 c_(next_triangle)+2]) ]; c_(next_triangle)=[]; added=added+1; end % Add previous triangle vertices = obj.triangles(ring(1),[1 2 3 1 2]); centre_idx=find(vertices==i,1,'first'); prev_vertex=vertices(centre_idx+1); triangles = obj.triangles(r_,:); prev_triangle = find(sum(triangles==i | triangles==prev_vertex,2)==2,1,'first'); if numel(prev_triangle) ring = [ r_(prev_triangle) ring]; vertices_ = obj.triangles(r_(prev_triangle),[1 2 3 1 2]); r_(prev_triangle)=[]; tri_sorted = [ vertices_([c_(prev_triangle) c_(prev_triangle)+1 c_(prev_triangle)+2]) ; tri_sorted]; c_(prev_triangle)=[]; added=added+1; end if added==0 % one of the remaining triangles is badly ordered disp(['WARNING: The input mesh does not have consistent orientation at node ' num2str(i) ]) elseif added==2 % Check that orientation is good %disp(['WARNING: The input mesh does not have consistent orientation at node ' num2str(i) ]) if tri_sorted(1,3)~=tri_sorted(2,2) tri_sorted(1,2)=tri_sorted(1,3); tri_sorted(1,3)=tri_sorted(2,2); obj.triangles(ring(1),:) = obj.triangles(ring(1),[1 3 2]); end if tri_sorted(end,2)~=tri_sorted(end-1,3) tri_sorted(end,3)=tri_sorted(end,2); tri_sorted(end,2)=tri_sorted(end-1,3); obj.triangles(ring(end),:) = obj.triangles(ring(end),[1 3 2]); end end end end %% function out = GetValue(obj,attribute_name,positions) % positions must be an array of row vectors ind = obj.find_attribute(attribute_name); if (ind <= 0) disp([ 'Attribute ' attribute_name ' was not found ']) out=[]; return; end out = zeros(size(positions,1),1); bt = obj.ComputeBounds(); extent = bt(2:2:end)-bt(1:2:end); nodim = find(extent==0); availabledims = setdiff(1:numel(extent),nodim); DT= delaunayTriangulation(obj.points(:,availabledims)); triangle_idx = DT.pointLocation(positions); valid_points = find(triangle_idx==triangle_idx); invalues = obj.attributes(ind).attribute_array; % out(valid_points) = invalues(valid_points); % this works fine! bary_coords = DT.cartesianToBarycentric(triangle_idx(valid_points),positions(valid_points,:)); %vertices = obj.triangles(triangle_idx(valid_points),:); vertices = DT.ConnectivityList(triangle_idx(valid_points),:); values_at_vertices = invalues(vertices); interpolated_values = sum(values_at_vertices.*bary_coords,2); out(valid_points)=interpolated_values; end %% function normals=ComputeNormals(obj,varargin) % add normals as another attribute ignoreOrientation=false; center=[]; if (size(varargin,2)>0) ignoreOrientation= varargin{1}; end if (size(varargin,2)>1) center= varargin{2}; end n_attributes = numel(obj.attributes); at = AttributeType(); at.attribute='normals'; at.name='normalVectors'; at.numComp=3; % between 1 and 4 at.type='float'; at.nelements=obj.npoints; %number of tuples for i=1:at.nelements at.attribute_array(i,:) = obj.GetNormalAtVertex(i,'ignoreOrientation', ignoreOrientation,'insidePoint',center); end ind = obj.find_attribute(at.name); if (ind > 0) obj.attributes(ind)=at; else n_attributes = numel(obj.attributes); obj.attributes(n_attributes+1)=at; end normals = at.attribute_array; end function AddScalarAttributeToVertices(obj,arr,name) at = AttributeType(); at.attribute='scalars'; at.name=name; at.numComp=1; % between 1 and 4 at.type='float'; at.nelements=obj.npoints; %number of tuples at.attribute_array = arr(:); ind = obj.find_attribute(at.name); if (ind > 0) obj.attributes(ind)=at; else n_attributes = numel(obj.attributes); obj.attributes(n_attributes+1)=at; end end function ComputeNormalsToFaces(obj) % add normals as another attribute ind = obj.find_attribute('normalVectorsFaces'); if (ind > 0) return; end at = AttributeType(); at.attribute='normals'; at.name='normalVectorsFaces'; at.numComp=3; % between 1 and 4 at.type='float'; at.nelements=obj.ntriangles; %number of tuples for i=1:at.nelements at.attribute_array(i,:) = obj.GetNormalAtFaces(i); end ind = obj.find_attribute(at.name); if (ind > 0) obj.attributes(ind)=at; else n_attributes = numel(obj.attributes); obj.attributes(n_attributes+1)=at; end end function Mesh = ExtractSurface(obj, n_attribute, value) % This function returns a new mesh which corresponds to the % sub-surface of vertex whos attribute #n_attribute have the % value #value % This function leaves the original points and attribute list % unchanged % 1. Check that there is the same number of points in the % scalar field and in the mesh scalar_array = obj.attributes(n_attribute).attribute_array; if (size(scalar_array,1)~=size(obj.points,1)) disp('Error: associated field has too few points') Mesh = []; return; end index = find(scalar_array == value); % remove all triangles which contain a triangle not in index triangles_to_add=[]; for i=1:numel(index) [x y]=find(obj.triangles==index(i)); triangles_to_add = [triangles_to_add; x]; end triangles_to_add= unique(triangles_to_add); tri= obj.triangles(triangles_to_add,:); Mesh = MeshType(); Mesh.npoints = obj.npoints; Mesh.points = obj.points; Mesh.triangles = tri; Mesh.ntriangles = size(tri,1); Mesh.attributes= obj.attributes; end function closedMesh= closeMesh(obj) % this function closes the mesh by adding 1 point. % IMPORTANT: it will only work if there is 1 single hole closedMesh = MeshType(); closedMesh.npoints = obj.npoints; closedMesh.points = obj.points; closedMesh.ntriangles = obj.ntriangles; closedMesh.triangles = obj.triangles; closedMesh.attributes = obj.attributes; [borders,borderPaths]= obj.detectBorders(); nholes = numel(borderPaths); for i=1:nholes b=zeros(size(borders)); b(unique(borderPaths{i}(:))')=1; bindex = find(b==1); borderPoints = obj.points(b==1,:); nborderPoints = size(borderPoints,1); if (nborderPoints>0) %add the centroid as a new point centroid = sum(borderPoints)/nborderPoints; closedMesh.npoints = closedMesh.npoints+1; closedMesh.points(closedMesh.npoints,:)=centroid; % Build new triangles remainingPoints = bindex; currentPoint = remainingPoints(1); while (numel(remainingPoints)>1) %try to look for the closest neighbor clockwise minDistance = 999999999999999999; % very big number for candidate=remainingPoints(:)' if (currentPoint~=candidate) vector = closedMesh.points(currentPoint,:)-closedMesh.points(candidate,:); distance = norm(vector); if (distance<minDistance ) minDistance = distance; neighbor = candidate; end end end %remove the currentPoint from the list indexOfCurrentPoint = find(remainingPoints==currentPoint); if (indexOfCurrentPoint ==1) remainingPoints = remainingPoints(2:end); elseif (indexOfCurrentPoint ==numel(remainingPoints)) remainingPoints = remainingPoints(1:(end-1)); else remainingPoints = remainingPoints([1:(indexOfCurrentPoint-1) (indexOfCurrentPoint+1):end]); end %build triangle tri = [currentPoint neighbor closedMesh.npoints] ; closedMesh.triangles = [closedMesh.triangles ; tri]; currentPoint = neighbor; end tri = [remainingPoints(1) bindex(1) closedMesh.npoints]; closedMesh.triangles = [closedMesh.triangles ; tri]; closedMesh.ntriangles = size(closedMesh.triangles,1); end end end function flag = addVertex(obj,pointIn) % Adds a vertex (or vertices) to current mesh, updating the % triangulations accordingly. If there is any problem returns % an error code. % TODO: test mesh flag=1; % 1. Find the closest triangle indicesClosestTriangle = obj.findClosestTriangle(pointIn); trianglePointIndices = [ obj.triangles(indicesClosestTriangle,:) ((obj.npoints+1):(obj.npoints+size(pointIn,1)))' ]; newTopology = [1 2 4 2 3 4 3 1 4]; % this will have to be reshaped newTriangles = trianglePointIndices(:,newTopology); % Now reshape 'newTriangles' so that from each row we get 3 % rows. newTriangles = [newTriangles(:,1:3);newTriangles(:,4:6);newTriangles(:,7:9)]; % Remove old triangles and add new ones obj.triangles(indicesClosestTriangle,:)=[]; obj.triangles = [obj.triangles; newTriangles]; obj.ntriangles = size(obj.triangles,1); % add new points obj.points = [ obj.points; pointIn]; obj.npoints = size(obj.points,1); end function outMesh = removeVertex(obj,index,varargin) % Removes a vertex (or vertices) to current mesh, updating the % triangulations accordingly. % % This code (still to be written) can be designed to do two % things: % % a) Remove the point and all triangles where this point was % (this will of course produce a hole) [default] % % b) Remove a point and re-triangulate neighbors. This will % avoid holes (option 'noholes') % mode = 'holes'; % w = 1 if (size(varargin,2)>0) mode = varargin{1}; end outMesh = MeshType(obj); outMesh.triangles = obj.triangles; outMesh.points = obj.points; if (strcmp('holes',mode)) pointsToRemove = index; % remove all triangles containing any of the points to be % removed nPointsRemoved = 0; trianglesRemoved=[]; while(numel(index)>0) [r, c]= find(outMesh.triangles==index(1)); outMesh.triangles(r,:)=[]; trianglesRemoved = [trianglesRemoved; r]; % point per point, remove the index to the triangle list outMesh.points(index(1),:)=[]; outMesh.triangles(outMesh.triangles>index(1))=outMesh.triangles(outMesh.triangles>index(1))-1; nPointsRemoved = nPointsRemoved+1; index = index-1; index(1)=[]; end % update attributes for i=1:numel(obj.attributes) if (numel(obj.attributes(i).attribute_array)==outMesh.npoints) outMesh.attributes(i).attribute_array(pointsToRemove)=[]; elseif (numel(obj.attributes(i).attribute_array)==outMesh.ntriangles) outMesh.attributes(i).attribute_array(trianglesRemoved)=[]; end end outMesh.npoints = size(outMesh.points,1); outMesh.ntriangles = size(outMesh.triangles,1); elseif (strcmp('noholes',mode)) disp(['Mode ' mode ' is not implemented yet']) ; else disp(['ERROR: ' mode ' is not a valid option']); end end function outMesh = removeTriangle(obj,index,varargin) % Removes a triangle (or triangles) to current mesh, updating the % triangulations accordingly. % % This code (still to be written) can be designed to do two % things: % % a) Remove the triangle and leave a hole [default] % % b) Remove a triangle and re-triangulate neighbors. This will % avoid holes (option 'noholes') % mode = 'holes'; % w = 1 if (size(varargin,2)>0) mode = varargin{1}; end outMesh = MeshType(obj); outMesh.triangles = obj.triangles; outMesh.points = obj.points; if (strcmp('holes',mode)) outMesh.triangles(index,:)=[]; pointsToRemove = setdiff(unique(obj.triangles(:)),unique(outMesh.triangles(:))); nPointsRemoved = 0; while(numel(pointsToRemove )>0) % point per point, remove the index to the triangle list outMesh.points(pointsToRemove(1),:)=[]; outMesh.triangles(outMesh.triangles>pointsToRemove(1))=outMesh.triangles(outMesh.triangles>pointsToRemove(1))-1; nPointsRemoved = nPointsRemoved+1; pointsToRemove = pointsToRemove-1; pointsToRemove(1)=[]; end % update attributes for i=1:numel(obj.attributes) if (numel(obj.attributes(i).attribute_array)==outMesh.npoints) outMesh.attributes(i).attribute_array(pointsToRemove)=[]; elseif (numel(obj.attributes(i).attribute_array)==outMesh.ntriangles) if max(outMesh.triangles(:))>=numel(outMesh.points) %outMesh.attributes(i).attribute_array(trianglesRemoved)=[]; disp('MeshType: this has to be implemented') end end end outMesh.npoints = size(outMesh.points,1); outMesh.ntriangles = size(outMesh.triangles,1); elseif (strcmp('noholes',mode)) disp(['Mode ' mode ' is not implemented yet']) ; else disp(['ERROR: ' mode ' is not a valid option']); end end function invertOrientation(obj) % This function inverts the orientation of all triangles in a % mesh. This might be useful for example if the mesh is negative % oriented and one wants it positive oriented and vv. if size(obj.triangles,2)~=3 disp('MeshType::invertOrientation -- ERROR: this method only works on triangular meshes' ); return; end obj.triangles = obj.triangles(:,[1 3 2]); end %% function n= GetTriangleNeighbours(obj,i) % n gives the neighbours triangles vertices = obj.triangles(i,:); [r1,~]= find(obj.triangles==vertices(1)); [r2,~]= find(obj.triangles==vertices(2)); [r3,~]= find(obj.triangles==vertices(3)); isfound = zeros(obj.ntriangles,3); isfound(r1,1)=1; isfound(r2,2)=1; isfound(r3,3)=1; n = find(sum(isfound,2)==2); end %% function imposeConsistentOrientation(obj) % This funtion imposes the same orientation to all triangloes % in a mesh. This orientation is the one of the first triangle, % thus arbitrary, and not necessarily positive. is_oriented = false(obj.ntriangles,1); is_oriented(1)=true; %set(0,'RecursionLimit',obj.ntriangles); not_oriented = 2:obj.ntriangles; already_oriented_fathers = []; while numel(not_oriented) oriented = find(is_oriented)'; oriented = setdiff(oriented,already_oriented_fathers); if ~numel(oriented) break; end for i = oriented for j=obj.triangles(i,1) is_oriented = obj.orientNeighbourTriangles(j,is_oriented); end already_oriented_fathers = [already_oriented_fathers i]; end oriented = find(is_oriented); not_oriented = setdiff(not_oriented,oriented); disp([ 'There remain ' num2str(numel(not_oriented)) ]) end end function imposeConsistentOrientationFlatMesh(obj) % This funtion imposes the same orientation to all triangles % in a mesh. This orientation is the one of the first triangle, % thus arbitrary, and not necessarily positive. % The underlying work of this method is to reorient triangles % with negative area. side1 = obj.points(obj.triangles(:,1),:); side2 = obj.points(obj.triangles(:,2),:); side3 = obj.points(obj.triangles(:,3),:); vector1 = side2-side1; vector2 = side3-side1; cp = cross(vector1,vector2); %dt = dot(vector1,vector2,2); %area = sum(cp.^2,2); %ang = acos(dt); not_oriented = find(cp(:,3)<0); obj.triangles(not_oriented,:) = obj.triangles(not_oriented,[1 3 2]); end function is_oriented = orientNeighbourTriangles(obj,i,is_oriented) % assuming the triangle i is oriented, set the same orientation % in its neighbours and propagate triangle_neighbours = obj.GetTriangleNeighbours(i); % triangles that share at least one edge neighbours_not_oriented = ~is_oriented(triangle_neighbours); remaining_neghbours = triangle_neighbours(neighbours_not_oriented); if ~numel(remaining_neghbours ) return; end vertices = obj.triangles(i,[1 2 3 1 2]); for r = remaining_neghbours(:)' if is_oriented(r) continue; end vertices_r = obj.triangles(r,[1 2 3]); for common_vertex=1:2 idx = find(vertices==vertices_r(common_vertex),1,'first'); if ~numel(idx) continue; end if vertices_r(common_vertex)==vertices(idx+1) % realign it obj.triangles(r,:)=obj.triangles(r,[1 3 2]); end break; end is_oriented(r)=true; % is_oriented = obj.orientNeighbourTriangles(r,is_oriented); end end %% function nnonpos = imposePositiveOrientation(obj) % This function reorganises topology do that every facet has a % positive orientation. This orientation is required by many % algorithms and is in general desirable. % Functionning is only guaranteed if the gravity center of the % shape lays inside the mesh centre = mean(obj.points,1); normals = obj.GetNormalAtFaces(1:obj.ntriangles); inwardsVector = ones(obj.ntriangles,1)*centre - obj.points(obj.triangles(:,1),:); isNotPositiveOriented = dot(normals,inwardsVector,2)>0; % take the ones not positively oriented and reorder (it suffice to swa cols 2 and 3) nnonpos = numel(nonzeros(isNotPositiveOriented)); obj.triangles(isNotPositiveOriented,[2 3]) = obj.triangles(isNotPositiveOriented,[3 2]); end function flag = isInside(obj,points) % Returns a boolean indicating whether tha input point(s) is inside or outside the closed mesh % points should be a N x 3 matrix. tree = AABB_tree(obj); tree.BuildTree(); obj.ComputeBounds(); n_points = size(points,1); flag = zeros(n_points,1); % do a quick bounds check values_out = find( (points(:,1) < obj.bounds(1)) | (points(:,1) > obj.bounds(2)) |... (points(:,2) < obj.bounds(3)) | (points(:,2) > obj.bounds(4)) |... (points(:,3) < obj.bounds(5)) | (points(:,3) > obj.bounds(6)) ); values_in = setdiff(1:n_points,values_out); % K = 2*norm(obj.bounds([2 4 6])-obj.bounds([1 3 5])); direction = [0 -1 0]; % any random direction would do tree.computedIntersections = zeros(numel(values_in),1); tree.intersect_ray(tree.rootNode,points(values_in,:), direction); nintersections1 = tree.computedIntersections==1; % only inside points intersect once flag(values_in)=nintersections1(:)'; end function [p indicesClosestTriangle] = findClosestSurfacePoint(obj, pointIn) % Finds the closest point on the surface to a point (or points) % which in general is not a vertex. %1. Find closest triangle % THIS HAS TO BE REDONE disp('WARNING: findClosestSurfacePoint is inaccurate') pointsOfTriangles = cat(3,obj.points(obj.triangles(:,1),:),obj.points(obj.triangles(:,2),:),obj.points(obj.triangles(:,3),:)); medicenters = mean(pointsOfTriangles,3); errorx = medicenters(:,1)*ones(1,size(pointIn,1)) - ones(obj.ntriangles,1) * pointIn(:,1)'; errory = medicenters(:,2)*ones(1,size(pointIn,1)) - ones(obj.ntriangles,1) * pointIn(:,2)'; errorz = medicenters(:,3)*ones(1,size(pointIn,1)) - ones(obj.ntriangles,1) * pointIn(:,3)'; totalError = errorx.^2+errory.^2+errorz.^2; [dummy indicesClosestTriangle] = min(totalError,[],1); medicenters = medicenters(indicesClosestTriangle,:); [indicesClosestTriangle pointInTriangle]= obj.findClosestTriangle(pointIn); % get normals to faces normals = obj.GetNormalAtFaces(indicesClosestTriangle); p = pointIn + normals.*(dot(pointInTriangle-pointIn,normals,2) * ones(1,3)); end function [indicesClosestTriangle medicenters]= findClosestTriangle(obj, pointIn) % Find the closest triangle to a point (or points). This is % usefull if for example the triangularization needs to be % changed % compute medicenters pointsOfTriangles = cat(3,obj.points(obj.triangles(:,1),:),obj.points(obj.triangles(:,2),:),obj.points(obj.triangles(:,3),:)); medicenters = mean(pointsOfTriangles,3); errorx = medicenters(:,1)*ones(1,size(pointIn,1)) - ones(obj.ntriangles,1) * pointIn(:,1)'; errory = medicenters(:,2)*ones(1,size(pointIn,1)) - ones(obj.ntriangles,1) * pointIn(:,2)'; errorz = medicenters(:,3)*ones(1,size(pointIn,1)) - ones(obj.ntriangles,1) * pointIn(:,3)'; totalError = errorx.^2+errory.^2+errorz.^2; [dummy indicesClosestTriangle] = min(totalError,[],1); medicenters = medicenters(indicesClosestTriangle,:); end function indicesNclosestPoints = findNClosestVertices(obj, pointIn,N) % Finds the N closest vertices to a point (or points) % PointIn has to be a N x 3 array of points % Note that this does not necessarily give the three vertex of % the closest triangle! errorx = obj.points(:,1)*ones(1,size(pointIn,1)) - ones(obj.npoints,1) * pointIn(:,1)'; errory = obj.points(:,2)*ones(1,size(pointIn,1)) - ones(obj.npoints,1) * pointIn(:,2)'; errorz = obj.points(:,3)*ones(1,size(pointIn,1)) - ones(obj.npoints,1) * pointIn(:,3)'; totalError = errorx.^2+errory.^2+errorz.^2; [totalErrorSorted IX] = sort(totalError,1); indicesNclosestPoints = IX(1:N,:); end function [p distance] = findClosestVertex(obj, pointIn) % Finds the closest vertex to a point (or points) % PointIn has to be a N x 3 array of points errorx = obj.points(:,1)*ones(1,size(pointIn,1)) - ones(obj.npoints,1) * pointIn(:,1)'; errory = obj.points(:,2)*ones(1,size(pointIn,1)) - ones(obj.npoints,1) * pointIn(:,2)'; errorz = obj.points(:,3)*ones(1,size(pointIn,1)) - ones(obj.npoints,1) * pointIn(:,3)'; totalError = errorx.^2+errory.^2+errorz.^2; [distance p] = min(totalError); end function p = find_attribute(obj,at_name) % returns the index of the attribute if found, -1 otherwise. n_attributes = numel(obj.attributes); p=-1; for i=1:n_attributes if (strcmp(at_name, obj.attributes(i).name)) p = i; return; end end end function at = addVertexAttribute(obj, array,name) at = AttributeType(); at.attribute='field'; at.name=name; at.numComp=1; % between 1 and 4 at.type='float'; at.nelements=obj.npoints; %number of vertex at.attribute_array = array; % ovewrite if already exists ind = obj.find_attribute(at.name); if (ind > 0) obj.attributes(ind)=at; else n_attributes = numel(obj.attributes); obj.attributes(n_attributes+1)=at; end end % Cleanup the points function removeDuplicatedPoints(obj) % This function removes duplicated points from the mesh and updates topology accordingly [nodup_points, m, n] = unique(obj.points,'rows'); clear nodup_points; m_sorted = sort(m); obj.points = obj.points(m_sorted ,:); old_m_sorted = 1:obj.npoints; points_to_be_removed = setdiff(old_m_sorted , m_sorted'); replacements = m(n(points_to_be_removed))'; % Remove duplicated labels for i=1:numel(obj.attributes) if (size(obj.attributes(i).attribute_array,1)==obj.npoints) obj.attributes(i).attribute_array =obj.attributes(i).attribute_array(m_sorted,:); end end % Replace indices with duplicateds for i=1:numel(points_to_be_removed) obj.triangles(obj.triangles == points_to_be_removed(i))=replacements(i); end % remove points and update topology while(numel(points_to_be_removed)) obj.triangles(obj.triangles>points_to_be_removed(1))=obj.triangles(obj.triangles>points_to_be_removed(1))-1; points_to_be_removed(1)=[]; points_to_be_removed=points_to_be_removed-1; end obj.npoints = size(obj.points,1); end function propagateLabel(obj, ind, varargin) % This function will need some morphomat operations on meshes. % Then we will do a reconstruction. The seed for the % reconstruction can be the first point inside the region. This % should be easy to get since edges are oriented % the neighbouring vertices. For this, only vertices which lie % on the positive side of a labelled edge (edge containing two labelled % vertices) are labelled. Positive means on the sense of the % cross product of the oriented edge with the face normal. % % the label is supposed to be binary! disp('ERRROR: STILL HAS TO BE IMPLEMENTED') center= []; for i=1:size(varargin,2) if (strcmp(varargin{i},'insidePoint')) center=varargin{i+1}; end end old_labelledVertices = find(obj.attributes(ind).attribute_array); % figure; viewMesh(obj,'wireframeSurface','color',[0 0 1],'labelColor',2) % hold on; plot3(obj.points(old_labelledVertices,1),obj.points(old_labelledVertices,2), obj.points(old_labelledVertices,3),'.g','MarkerSize',25 ); hold off % hold on; text(obj.points(:,1),obj.points(:,2), obj.points(:,3),num2str((1:obj.npoints)'),'FontSize',15 ); hold off for vert=old_labelledVertices' % get labelled neighbours neighbours = obj.GetForwardVertexNeighbours(vert); % this is already positively oriented for n = 1:size(neighbours,1) if obj.attributes(ind).attribute_array(neighbours(n,1)) obj.attributes(ind).attribute_array(neighbours(n,2))=1; end end end labelledVertices = find(obj.attributes(ind).attribute_array); % figure; viewMesh(obj,'wireframeSurface','color',[0 0 1],'labelColor',2) %hold on; plot3(obj.points(labelledVertices,1),obj.points(labelledVertices,2), obj.points(labelledVertices,3),'.g','MarkerSize',25 ); hold off end % function propagateLabel(obj, ind, varargin) % % This function propagates the label indicated by ind towards % % the neighbouring vertices. For this, only vertices which % lie % % on the positive side of a labelled edge (edge containing two labelled % % vertices) are labelled. Positive means on the sense of the % % cross product of the oriented edge with the face normal. % % % % the label is supposed to be binary! % % % center= []; % % for i=1:size(varargin,2) % if (strcmp(varargin{i},'insidePoint')) % center=varargin{i+1}; % end % % end % % old_labelledVertices = find(obj.attributes(ind).attribute_array); % figure; viewMesh(obj,'wireframeSurface','color',[0 0 1],'labelColor',2) % hold on; plot3(obj.points(labelledVertices,1),obj.points(labelledVertices,2), obj.points(labelledVertices,3),'.g','MarkerSize',25 ); hold off % hold on; text(obj.points(:,1),obj.points(:,2), obj.points(:,3),num2str((1:obj.npoints)'),'FontSize',15 ); hold off % for vert=labelledVertices' % % get labelled neighbours % neighbours = obj.GetForwardVertexNeighbours(vert); % this is already positively oriented % for n = 1:size(neighbours,1) % if obj.attributes(ind).attribute_array(neighbours(n,1)) % obj.attributes(ind).attribute_array(neighbours(n,2))=1; % end % end % % end % labelledVertices = find(obj.attributes(ind).attribute_array); % figure; viewMesh(obj,'wireframeSurface','color',[0 0 1],'labelColor',2) % hold on; plot3(obj.points(labelledVertices,1),obj.points(labelledVertices,2), obj.points(labelledVertices,3),'.g','MarkerSize',25 ); hold off % end % function [isBorder,borderPaths] = detectBorders(obj) % This function returns wether an vertex is a border or not obj.removeDuplicatedPoints(); isBorder = zeros(obj.npoints,1); borderPaths=[]; pointlist = reshape(obj.triangles,obj.ntriangles*3,1); pointlist = unique(pointlist); edges = []; for i=pointlist(:)' % get all triangles in which this point appears [x, ~]=find(obj.triangles == i); if numel(x>0) neighbors = obj.triangles(x,:); neighbors = neighbors(:)'; for j=unique(neighbors) if nnz(neighbors==j)<2 isBorder(i,:)=1; if i~=j [f1,~] = find(edges==j); [f2,~] = find(edges==i); if ~numel(intersect(f1,f2)) edges = [edges; i j]; end end end end end end edges = unique(edges,'rows'); % add attribute at = AttributeType(); at.attribute='field'; at.name='border'; at.numComp=1; % between 1 and 4 at.type='short'; at.nelements=obj.npoints; %number of tuples for i=1:at.nelements at.attribute_array(i,:) = isBorder(i); end ind = obj.find_attribute(at.name); if (ind > 0) obj.attributes(ind)=at; else n_attributes = numel(obj.attributes); obj.attributes(n_attributes+1)=at; end % get the borderPaths borderPoints = find(isBorder); npaths = 0; while numel(edges ); npaths = npaths+1; borderPaths{npaths} = []; currentIndex=1; finish=false; while ~finish if ~numel(currentIndex) finish=true; continue; end current = edges(currentIndex,:); edges(currentIndex,:)=[]; if numel(borderPaths{npaths}) && borderPaths{npaths}(end)==current(2) current = current([2 1]); end extremum = current(2); borderPaths{npaths} = [ borderPaths{npaths} ;current]; % find neighbours (border edges) [tri,~]=find(edges==extremum); if ~numel(tri) % turn around starting from the other end borderPaths{npaths}(:) = borderPaths{npaths}(end:-1:1); current = borderPaths{npaths}(end,:); [tri,~]=find(edges==current(2)); if ~numel(tri) finish=true; %npaths = npaths-1; %borderPaths={borderPaths{1:npaths}}; continue; end end % find the edge that follows e = edges(tri,:); % see if we have finished if numel(borderPaths{npaths})>2 && current(1)~=borderPaths{npaths}(2) && nnz(e==borderPaths{npaths}(1)) finish=true; if e(2)==borderPaths{npaths}(end) && e(1)==borderPaths{npaths}(1) || ... e(1)==borderPaths{npaths}(end) && e(2)==borderPaths{npaths}(1) % this is the connecting edge - just remove it edges(tri,:)=[]; end else neighbour = setdiff(e(:) ,borderPaths{npaths}(:)); if numel(neighbour) > 1 disp('MeshType::ERROR: more than one neighbour'); return; elseif numel(neighbour)<1 disp('MeshType::ERROR: less than one neighbour'); return; end [tri1,~]=find(edges==neighbour); [tri2,~]=find(edges==current(2)); currentIndex = intersect(tri1,tri2); end end end % borderPoints = find(isBorder); % npaths = 0; % while numel(edges ); % npaths = npaths+1; % borderPaths{npaths} = []; % % currentIndex=1; % finish=false; % while ~finish % if ~numel(currentIndex) % finish=true; % continue; % end % current = edges(currentIndex,:); % edges(currentIndex,:)=[]; % borderPaths{npaths} = [ borderPaths{npaths} ;current]; % % % find neighbours (border edges) % [tri,~]=find(edges==current(2)); % if ~numel(tri) % finish=true; % %npaths = npaths-1; % %borderPaths={borderPaths{1:npaths}}; % continue; % end % % find the edge that follows % e = edges(tri,:); % % see if we have finished % if numel(borderPaths{npaths})>2 && current(1)~=borderPaths{npaths}(2) && nnz(e==borderPaths{npaths}(1)) % finish=true; % else % neighbour = setdiff(e(:) ,borderPaths{npaths}(:)); % if numel(neighbour) > 1 % disp('MeshType::ERROR: more than one neighbour'); % return; % elseif numel(neighbour)<1 % disp('MeshType::ERROR: less than one neighbour'); % return; % end % % [tri1,~]=find(edges==neighbour); % [tri2,~]=find(edges==current(2)); % currentIndex = intersect(tri1,tri2); % end % end % % % end end end % methods end function n = cyclicNext(a,b) n = a+1; if (n>b) n = 1; end end
github
vildenst/3D-heart-models-master
QuadMeshType.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/class_mesh/QuadMeshType.m
3,222
utf_8
9b6dfff51ad7cca91802f4c03b1ce3a5
classdef QuadMeshType < handle % This class defines a trinagulated mesh % by Alberto Gomez, 2011 % properties(GetAccess = 'public', SetAccess = 'public') end methods(Access = public) %constructor function obj = QuadMeshType(npoints,ncells) if(nargin > 0) if(nargin ==1 ) % copy constructor obj.npoints = npoints.npoints; obj.ncells = npoints.ncells; obj.points = npoints.points; obj.cells = npoints.cells; for i=1:numel(npoints.attributes) obj.attributes(i)=AttributeType(npoints.attributes(i)); end else obj.npoints = npoints; obj.ncells = ncells; obj.points = zeros(npoints,3); obj.cells = zeros(ncells,10); % this is quadratic meshes! obj.attributes(1)=AttributeType(obj.npoints); end end end function p = find_attribute(obj,at_name) % returns the index of the attribute if found, -1 otherwise. n_attributes = numel(obj.attributes); p=-1; for i=1:n_attributes if (strcmp(at_name, obj.attributes(i).name)) p = i; return; end end end % Cleanup the points function removeDuplicatedPoints(obj) % This function removes duplicated points from the mesh and updates topology accordingly [nodup_points, m, n] = unique(obj.points,'rows'); clear nodup_points; m_sorted = sort(m); obj.points = obj.points(m_sorted ,:); old_m_sorted = 1:obj.npoints; points_to_be_removed = setdiff(old_m_sorted , m_sorted'); replacements = m(n(points_to_be_removed))'; % Remove duplicated labels for i=1:numel(obj.attributes) if (size(obj.attributes(i).attribute_array,1)==obj.npoints) obj.attributes(i).attribute_array =obj.attributes(i).attribute_array(m_sorted,:); end end % Replace indices with duplicateds for i=1:numel(points_to_be_removed) obj.cells(obj.cells == points_to_be_removed(i))=replacements(i); end % remove points and update topology while(numel(points_to_be_removed)) obj.cells(obj.cells>points_to_be_removed(1))=obj.cells(obj.cells>points_to_be_removed(1))-1; points_to_be_removed(1)=[]; points_to_be_removed=points_to_be_removed-1; end obj.npoints = size(obj.points,1); end end % methods end function n = cyclicNext(a,b) n = a+1; if (n>b) n = 1; end end
github
vildenst/3D-heart-models-master
QuadTetMeshType.m
.m
3D-heart-models-master/Medical_Image_Processing_Toolbox/code/MedicalImageProcessingToolbox/class_mesh/QuadTetMeshType.m
3,422
utf_8
75ac3909ac15eac80a176b58cdf3d2cf
classdef QuadTetMeshType < handle % This class defines a trinagulated mesh % by Alberto Gomez, 2011 % properties(GetAccess = 'public', SetAccess = 'public') npoints=0; ncells=0; points=[];% npointsx3 matrix cells=[];%ntrianglesx3 matrix bounds = [0 0 0 0 0 0]; attributes = AttributeType(); % for labels, luts, etc end methods(Access = public) %constructor function obj = QuadMeshType(npoints,ncells) if(nargin > 0) if(nargin ==1 ) % copy constructor obj.npoints = npoints.npoints; obj.ncells = npoints.ncells; obj.points = npoints.points; obj.cells = npoints.cells; for i=1:numel(npoints.attributes) obj.attributes(i)=AttributeType(npoints.attributes(i)); end else obj.npoints = npoints; obj.ncells = ncells; obj.points = zeros(npoints,3); obj.cells = zeros(ncells,10); % this is quadratic meshes! obj.attributes(1)=AttributeType(obj.npoints); end end end function p = find_attribute(obj,at_name) % returns the index of the attribute if found, -1 otherwise. n_attributes = numel(obj.attributes); p=-1; for i=1:n_attributes if (strcmp(at_name, obj.attributes(i).name)) p = i; return; end end end % Cleanup the points function removeDuplicatedPoints(obj) % This function removes duplicated points from the mesh and updates topology accordingly [nodup_points, m, n] = unique(obj.points,'rows'); clear nodup_points; m_sorted = sort(m); obj.points = obj.points(m_sorted ,:); old_m_sorted = 1:obj.npoints; points_to_be_removed = setdiff(old_m_sorted , m_sorted'); replacements = m(n(points_to_be_removed))'; % Remove duplicated labels for i=1:numel(obj.attributes) if (size(obj.attributes(i).attribute_array,1)==obj.npoints) obj.attributes(i).attribute_array =obj.attributes(i).attribute_array(m_sorted,:); end end % Replace indices with duplicateds for i=1:numel(points_to_be_removed) obj.cells(obj.cells == points_to_be_removed(i))=replacements(i); end % remove points and update topology while(numel(points_to_be_removed)) obj.cells(obj.cells>points_to_be_removed(1))=obj.cells(obj.cells>points_to_be_removed(1))-1; points_to_be_removed(1)=[]; points_to_be_removed=points_to_be_removed-1; end obj.npoints = size(obj.points,1); end end % methods end function n = cyclicNext(a,b) n = a+1; if (n>b) n = 1; end end
github
vildenst/3D-heart-models-master
gmsh2pdetoolbox.m
.m
3D-heart-models-master/gmsh/utils/converters/matlab/gmsh2pdetoolbox.m
9,118
utf_8
50a4231a31b359c82cee0ce1c21a5567
%GMSH2PDETOOLBOX Reads a mesh in msh format, version 1 or 2 and returns the %arrays p, e and t according to the MATLAB pde toolbox syntax. Filename %refers to the .msh file. Note that only triangular 2D mesh are processed %since these are the only elements allowed in pde toolbox. % %SEE ALSO load_gmsh load_gmsh4 initmesh % % Copyright (C) 2014 Arthur Levy. https://github.com/arthurlevy/ % % This fucntion uses the routine load_gmsh4 in load_gmsh2.m: Copyright (C) % 2007 JP Moitinho de Almeida ([email protected]) and R % Lorphevre(r(point)lorphevre(at)ulg(point)ac(point)be) It is based on % load_gmsh.m supplied with gmsh-2.0 function [p, e, t] = gmsh2pdetoolbox(filename) %loads the gmsh file using JP Moitinho de Almeida ([email protected]) % and R Lorphevre(r(point)lorphevre(at)ulg(point)ac(point)be) code. mesh_structure = load_gmsh4(filename,-1); %% NODES %nodes positions disp('importing nodes'); p = mesh_structure.POS(:,1:2)'; %% EDGES disp('importing edges'); %find the edges (ie dimension 1) is_edge = (mesh_structure.ELE_INFOS(:,2)==1); %add edge data e = mesh_structure.ELE_NODES(is_edge,1:2)'; e(3,:) = 0; e(4,:) = 1; %tag is important for applying boundary conditions e(5,:) = mesh_structure.ELE_TAGS(is_edge,1)'; e(6,:) = 1; e(7,:) = 0; %% TRIANGLES disp('importing triangles') is_triangle = (mesh_structure.ELE_INFOS(:,2)==2); t = mesh_structure.ELE_NODES(is_triangle,1:3)'; t(4,:) = 2; function msh = load_gmsh4(filename, which) %% Reads a mesh in msh format, version 1 or 2 % % Usage: % To define all variables m.LINES, M.TRIANGLES, etc % (Warning: This creates a very large structure. Do you really need it?) % m = load_gmsh4('a.msh') % % To define only certain variables (for example TETS and HEXS) % m = load_gmsh4('a.msh', [ 5 6]) % % To define no variables (i.e. if you prefer to use m.ELE_INFOS(i,2)) % m = load_gmsh4('a.msh', -1) % m = load_gmsh4('a.msh', []) % % Copyright (C) 2007 JP Moitinho de Almeida ([email protected]) % and R Lorphevre(r(point)lorphevre(at)ulg(point)ac(point)be) % % based on load_gmsh.m supplied with gmsh-2.0 % % Structure msh always has the following elements: % % msh.MIN, msh.MAX - Bounding box % msh.nbNod - Number of nodes % msh.nbElm - Total number of elements % msh.nbType(i) - Number of elements of type i (i in 1:19) % msh.POS(i,j) - j'th coordinate of node i (j in 1:3, i in 1:msh.nbNod) % msh.ELE_INFOS(i,1) - id of element i (i in 1:msh.nbElm) % msh.ELE_INFOS(i,2) - type of element i % msh.ELE_INFOS(i,3) - number of tags for element i % msh.ELE_INFOS(i,4) - Dimension (0D, 1D, 2D or 3D) of element i % msh.ELE_TAGS(i,j) - Tags of element i (j in 1:msh.ELE_INFOS(i,3)) % msh.ELE_NODES(i,j) - Nodes of element i (j in 1:k, with % k = msh.NODES_PER_TYPE_OF_ELEMENT(msh.ELE_INFOS(i,2))) % % These elements are created if requested: % % msh.nbLines - number of 2 node lines % msh.LINES(i,1:2) - nodes of line i % msh.LINES(i,3) - tag (WHICH ?????) of line i % % msh.nbTriangles - number of 2 node triangles % msh.TRIANGLES(i,1:3) - nodes of triangle i % msh.TRIANGLES(i,4) - tag (WHICH ?????) of triangle i % % Etc % These definitions need to be updated when new elemens types are added to gmsh % % msh.Types{i}{1} Number of an element of type i % msh.Types{i}{2} Dimension (0D, 1D, 2D or 3D) of element of type i % msh.Types{i}{3} Name to add to the structure with elements of type i % msh.Types{i}{4} Name to add to the structure with the number of elements of type i % nargchk(1, 2, nargin); msh.Types = { ... { 2, 1, 'LINES', 'nbLines'}, ... % 1 { 3, 2, 'TRIANGLES', 'nbTriangles'}, ... { 4, 2, 'QUADS', 'nbQuads'}, ... { 4, 3, 'TETS', 'nbTets'}, ... { 8, 3, 'HEXAS', 'nbHexas'}, ... %5 { 6, 3, 'PRISMS', 'nbPrisms'}, ... { 5, 3, 'PYRAMIDS', 'nbPyramids'}, ... { 3, 1, 'LINES3', 'nbLines3'}, ... { 6, 2, 'TRIANGLES6', 'nbTriangles6'}, ... { 9, 2, 'QUADS9', 'nbQuads9'}, ... % 10 { 10, 3, 'TETS10', 'nbTets10'}, ... { 27, 3, 'HEXAS27', 'nbHexas27'}, ... { 18, 3, 'PRISMS18', 'nbPrisms18'}, ... { 14, 3, 'PYRAMIDS14', 'nbPyramids14'}, ... { 1, 0, 'POINTS', 'nbPoints'}, ... % 15 { 8, 3, 'QUADS8', 'nbQuads8'}, ... { 20, 3, 'HEXAS20', 'nbHexas20'}, ... { 15, 3, 'PRISMS15', 'nbPrisms15'}, ... { 13, 3, 'PYRAMIDS13', 'nbPyramids13'}, ... }; ntypes = length(msh.Types); if (nargin==1) which = 1:ntypes; else if isscalar(which) && which == -1 which = []; end end % Could check that "which" is properlly defined.... fid = fopen(filename, 'r'); fileformat = 0; % Assume wrong file tline = fgetl(fid); if (feof(fid)) disp (sprintf('Empty file: %s', filename)); msh = []; return; end %% Read mesh type if (strcmp(tline, '$NOD')) fileformat = 1; elseif (strcmp(tline, '$MeshFormat')) fileformat = 2; tline = fgetl(fid); if (feof(fid)) disp (sprintf('Syntax error (no version) in: %s', filename)); fileformat = 0; end [ form ] = sscanf( tline, '%f %d %d'); % if (form(1) ~= 2) % disp (sprintf('Unknown mesh format: %s', tline)); % fileformat = 0; % end if (form(2) ~= 0) disp ('Sorry, this program can only read ASCII format'); fileformat = 0; end fgetl(fid); % this should be $EndMeshFormat if (feof(fid)) disp (sprintf('Syntax error (no $EndMeshFormat) in: %s', filename)); fileformat = 0; end tline = fgetl(fid); % this should be $Nodes if (feof(fid)) disp (sprintf('Syntax error (no $Nodes) in: %s', filename)); fileformat = 0; end end if (~fileformat) msh = []; return end %% Read nodes if strcmp(tline, '$NOD') || strcmp(tline, '$Nodes') msh.nbNod = fscanf(fid, '%d', 1); aux = fscanf(fid, '%g', [4 msh.nbNod]); msh.POS = aux(2:4,:)'; numids = max(aux(1,:)); IDS = zeros(1, numids); IDS(aux(1,:)) = 1:msh.nbNod; % This may not be an identity msh.MAX = max(msh.POS); msh.MIN = min(msh.POS); fgetl(fid); % End previous line fgetl(fid); % Has to be $ENDNOD $EndNodes else disp (sprintf('Syntax error (no $Nodes/$NOD) in: %s', filename)); fileformat = 0; end %% Read elements tline = fgetl(fid); if strcmp(tline,'$ELM') || strcmp(tline, '$Elements') msh.nbElm = fscanf(fid, '%d', 1); % read all info about elements into aux (it is faster!) aux = fscanf(fid, '%g', inf); start = 1; msh.ELE_INFOS = zeros(msh.nbElm, 4); % 1 - id, 2 - type, 3 - ntags, 4 - Dimension msh.ELE_NODES = zeros(msh.nbElm,6); % i - Element, j - ElNodes if (fileformat == 1) ntags = 2; else ntags = 3; % just a prediction end msh.ELE_TAGS = zeros(msh.nbElm, ntags); % format 1: 1 - physical number, 2 - geometrical number % format 2: 1 - physical number, 2 - geometrical number, 3 - mesh partition number msh.nbType = zeros(ntypes,1); for I = 1:msh.nbElm if (fileformat == 2) finnish = start + 2; msh.ELE_INFOS(I, 1:3) = aux(start:finnish); ntags = aux(finnish); start = finnish + 1; finnish = start + ntags -1; msh.ELE_TAGS(I, 1:ntags) = aux(start:finnish); start = finnish + 1; else finnish = start + 1; msh.ELE_INFOS(I, 1:2) = aux(start:finnish); start = finnish + 1; % the third element is nnodes, which we get from the type msh.ELE_INFOS(I, 3) = 2; finnish = start + 1; msh.ELE_TAGS(I, 1:2) = aux(start:finnish); start = finnish + 2; end type = msh.ELE_INFOS(I, 2); msh.nbType(type) = msh.nbType(type) + 1; msh.ELE_INFOS(I, 4) = msh.Types{type}{2}; nnodes = msh.Types{type}{1}; finnish = start + nnodes - 1; msh.ELE_NODES(I, 1:nnodes) = IDS(aux(start:finnish)); start=finnish + 1; end fgetl(fid); % Has to be $ENDELM or $EndElements else disp (sprintf('Syntax error (no $Elements/$ELM) in: %s', filename)); fileformat = 0; end if (fileformat == 0) msh = []; end fclose(fid); %% This is used to create the explicit lists for types of elements for i = which if (~isempty(msh.Types{i}{3})) cmd = sprintf('msh.%s=msh.nbType(%d);', msh.Types{i}{4}, i); eval(cmd); % Dimension cmd = sprintf('msh.%s=zeros(%d,%d);', msh.Types{i}{3}, msh.nbType(i), msh.Types{i}{1}+1); eval(cmd); % Clear nbType for counting, next loop will recompute it msh.nbType(i) = 0; end end for i = 1:msh.nbElm type = msh.ELE_INFOS(i,2); if (find(which == type)) if (~isempty(msh.Types{type}{3})) msh.nbType(type) = msh.nbType(type)+1; aux=[ msh.ELE_NODES(i,1:msh.Types{type}{1}), msh.ELE_TAGS(i,1) ]; cmd = sprintf('msh.%s(%d,:)=aux;', msh.Types{type}{3}, msh.nbType(type)); eval(cmd); end end end return;
github
vildenst/3D-heart-models-master
notSliceAlignment.m
.m
3D-heart-models-master/Matlab_Process/notSliceAlignment.m
10,794
utf_8
ea94293cc4ba8101a75f2addc6b53570
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % ALIGN SLICES % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Find the center point of the point cloud representing the left or right % ventricle % Author - Eric Davenne and Kristin McLeod % SIMULA Research Laboratory % Contact - [email protected] % October 2014 % This function aligns automatically segmentation contours. Takes a SEG % structure as argument and returns a SEG structure with aligned slices. % Alignement is performed using a linear least square estimation of the % center of all slices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG_shift = sliceAlignment(SEG,RVyes,IsFullTemporal) % DO NOTHING, SLICES ARE ALREADY ALIGNED FOR THIS DATASET sizen=size(SEG.EndoX); K = sizen(1, 1); N = sizen(1, 2); S = sizen(1, 3); sizenEpi=size(SEG.EpiX); KEpi = sizenEpi(1, 1); NEpi = sizenEpi(1, 2); SEpi = sizenEpi(1, 3); if RVyes==1 sizenRV=size(SEG.RVEndoX); KRV = sizenRV(1, 1); NRV = sizenRV(1, 2); SRV = sizenRV(1, 3); zRV = (1:SRV)*SEG.SliceThickness; %XRV_avgs = mean(SEG.RVEndoX); %YRV_avgs = mean(SEG.RVEndoY); end % i = 1; for s = 1:S if s > 1 if ~isnan(endo(k,1)) i = i+1; end end for k = 1:K EndoX(:,:)=SEG.EndoX(:,1,s); EndoY(:,:)=SEG.EndoY(:,1,s); endo = sum(EndoX,2); % Remove NaN values in the array if ~isnan(endo(k,1)) tmp1(k,1) = EndoX(k,1); tmp2(k,1) = EndoY(k,1); EndoXnew(k,1,i) = tmp1(k,1); EndoYnew(k,1,i) = tmp2(k,1); end end end i = 1; for s = 1:SEpi if s > 1 if ~isnan(epi(k,1)) i = i+1; end end for k = 1:KEpi EpiX(:,:)=SEG.EpiX(:,1,s); EpiY(:,:)=SEG.EpiY(:,1,s); epi = sum(EpiX,2); % Remove NaN values in the array if ~isnan(epi(k,1)) tmp1(k,1) = EpiX(k,1); tmp2(k,1) = EpiY(k,1); EpiXnew(k,1,i) = tmp1(k,1); EpiYnew(k,1,i) = tmp2(k,1); end end end i = 1; for s = 1:SRV if s > 1 if ~isnan(rv(k,1)) i = i+1; end end for k = 1:KRV RVX(:,:)=SEG.RVEndoX(:,1,s); RVY(:,:)=SEG.RVEndoY(:,1,s); rv = sum(RVX,2); % Remove NaN values in the array if ~isnan(rv(k,1)) tmp1(k,1) = RVX(k,1); tmp2(k,1) = RVY(k,1); RVEndoXnew(k,1,i) = tmp1(k,1); RVEndoYnew(k,1,i) = tmp2(k,1); end end end SEG_shift = SEG; %clear SEG_shift.EndoX SEG_shift.EndoY SEG_shift.EpiX SEG_shift.EpiY SEG_shift.RVEndoX SEG_shift.RVEndoY SEG_shift.EndoXnew = EndoXnew; SEG_shift.EndoYnew = EndoYnew; SEG_shift.EpiXnew = EpiXnew; SEG_shift.EpiYnew = EpiYnew; SEG_shift.RVEndoXnew = RVEndoXnew; SEG_shift.RVEndoYnew = RVEndoYnew; SEG_shift.isFullTemporal = IsFullTemporal; % % % X_avgs : array cointaining the barycenters of each slice and frame % % X_avgs(1, frame, slice) % % contour barycenters are computed as the mean of all LV contour points % % in a slice % % for s = 1:S % if ~isnan(SEG.EndoX(1,1,s)) % X_avgs = 0.5*mean(SEG.EpiX + SEG.EndoX); % Y_avgs = 0.5*mean(SEG.EpiY + SEG.EndoY); % else % X_avgs = mean(SEG.EpiX); % Y_avgs = mean(SEG.EpiY); % end % end % % % zEndo = (1:S)*SEG.SliceThickness; zEpi = (1:SEpi)*SEG.SliceThickness; % % if IsFullTemporal == 1 % for n=1:N % % x = X_avgs(1, n, :); % y = Y_avgs(1, n, :); % % % Computing least squares linear regression of barycenters for both % % coordinates X and Y. % % lmX = LinearModel.fit(zEndo, x(:)); % lmY = LinearModel.fit(zEndo, y(:)); % % % estX linear least squares estimation of barycenter X coordinate % % estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zEndo; % estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zEndo; % % % Shifting each segment contour so that all barycenters are located % % on the regression lines for both X and Y coordinates. % % for s=1:S % % shiftX = x(:) - estX(s); % shiftY = y(:) - estY(s); % % SEG_shift.EndoX(:, n, s) = SEG.EndoX(:, n, s) - shiftX(s); % SEG_shift.EndoY(:, n, s) = SEG.EndoY(:, n, s) - shiftY(s); % end % end % for n = 1:N % x = X_avgs(1, n, :); % y = Y_avgs(1, n, :); % % % Computing least squares linear regression of barycenters for both % % coordinates X and Y. % % lmX = LinearModel.fit(zEpi, x(:)); % lmY = LinearModel.fit(zEpi, y(:)); % % % estX linear least squares estimation of barycenter X coordinate % % estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zEpi; % estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zEpi; % % % Shifting each segment contour so that all barycenters are located % % on the regression lines for both X and Y coordinates. % for s=1:SEpi % % shiftX = x(:) - estX(s); % shiftY = y(:) - estY(s); % % SEG_shift.EpiX(:, n, s) = SEG.EpiX(:, n, s) - shiftX(s); % SEG_shift.EpiY(:, n, s) = SEG.EpiY(:, n, s) - shiftY(s); % end % end % if RVyes == 1 % for n = 1:N % %x = XRV_avgs(1, n, :); % %y = YRV_avgs(1, n, :); % x = X_avgs(1, n, :); % y = Y_avgs(1, n, :); % % % Computing least squares linear regression of barycenters for both % % coordinates X and Y. % % lmX = LinearModel.fit(zRV, x(:)); % lmY = LinearModel.fit(zRV, y(:)); % % % estX linear least squares estimation of barycenter X coordinate % % estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zRV; % estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zRV; % % % Shifting each segment contour so that all barycenters are located % % on the regression lines for both X and Y coordinates. % for s=1:SRV % % shiftX = x(:) - estX(s); % shiftY = y(:) - estY(s); % % if SEG_shift.isFullTemporal == 1 % if n == SEG.EDT || n == SEG.EST % SEG_shift.RVEndoX(:, n, s) = SEG.RVEndoX(:, n, s) - shiftX(s); % SEG_shift.RVEndoY(:, n, s) = SEG.RVEndoY(:, n, s) - shiftY(s); % end % else % SEG_shift.RVEndoX(:, n, s) = SEG.RVEndoX(:, n, s) - shiftX(s); % SEG_shift.RVEndoY(:, n, s) = SEG.RVEndoY(:, n, s) - shiftY(s); % end % end % end % end % else for n=1 %x = X_avgs(1, n, :); %y = Y_avgs(1, n, :); % Computing least squares linear regression of barycenters for both % coordinates X and Y. %lmX = LinearModel.fit(zEndo, x(:)); %lmY = LinearModel.fit(zEndo, y(:)); % estX linear least squares estimation of barycenter X coordinate %estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zEndo; %estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zEndo; % Shifting each segment contour so that all barycenters are located % on the regression lines for both X and Y coordinates. for s=1:S %shiftX = x(:) - estX(s); %shiftY = y(:) - estY(s); SEG_shift.EndoX(:, n, s) = SEG.EndoX(:, n, s); %- shiftX(s); SEG_shift.EndoY(:, n, s) = SEG.EndoY(:, n, s); %- shiftY(s); end end for n = 1 %x = X_avgs(1, n, :); %y = Y_avgs(1, n, :); % Computing least squares linear regression of barycenters for both % coordinates X and Y. %lmX = LinearModel.fit(zEpi, x(:)); %lmY = LinearModel.fit(zEpi, y(:)); % estX linear least squares estimation of barycenter X coordinate %estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zEpi; %estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zEpi; % Shifting each segment contour so that all barycenters are located % on the regression lines for both X and Y coordinates. for s=1:SEpi %shiftX = x(:) - estX(s); %shiftY = y(:) - estY(s); SEG_shift.EpiX(:, n, s) = SEG.EpiX(:, n, s); % - shiftX(s); SEG_shift.EpiY(:, n, s) = SEG.EpiY(:, n, s); % - shiftY(s); end end if RVyes == 1 for n = 1 %x = XRV_avgs(1, n, :); %y = YRV_avgs(1, n, :); %x = X_avgs(1, n, :); %y = Y_avgs(1, n, :); % Computing least squares linear regression of barycenters for both % coordinates X and Y. %lmX = LinearModel.fit(zRV, x(:)); %lmY = LinearModel.fit(zRV, y(:)); % estX linear least squares estimation of barycenter X coordinate %estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zRV; %estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zRV; % Shifting each segment contour so that all barycenters are located % on the regression lines for both X and Y coordinates. for s=1:SRV %shiftX = x(:) - estX(s); %shiftY = y(:) - estY(s); if SEG_shift.isFullTemporal == 1 if n == SEG.EDT || n == SEG.EST SEG_shift.RVEndoX(:, n, s) = SEG.RVEndoX(:, n, s); % - shiftX(s); SEG_shift.RVEndoY(:, n, s) = SEG.RVEndoY(:, n, s); % - shiftY(s); end else SEG_shift.RVEndoX(:, n, s) = SEG.RVEndoX(:, n, s); % - shiftX(s); SEG_shift.RVEndoY(:, n, s) = SEG.RVEndoY(:, n, s); % - shiftY(s); end end end % end end
github
vildenst/3D-heart-models-master
sliceAlignmentwithBivEpi.m
.m
3D-heart-models-master/Matlab_Process/sliceAlignmentwithBivEpi.m
10,222
utf_8
7472fc9053aa8e361502b124939956d6
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % ALIGN SLICES % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Find the center point of the point cloud representing the left or right % ventricle % Author - Eric Davenne and Kristin McLeod % SIMULA Research Laboratory % Contact - [email protected] % July 2016 % This function aligns automatically segmentation contours. Takes a SEG % structure as argument and returns a SEG structure with aligned slices. % Alignement is performed using a linear least square estimation of the % center of all slices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG_shift = sliceAlignmentwithBivEpi(SEG,RVyes,IsFullTemporal) sizen=size(SEG.EndoX); K = sizen(1, 1); N = sizen(1, 2); S = sizen(1, 3); zEndo = (1:S)*SEG.SliceThickness; sizenEpi=size(SEG.EpiX); KEpi = sizenEpi(1, 1); NEpi = sizenEpi(1, 2); SEpi = sizenEpi(1, 3); zEpi = (1:SEpi)*SEG.SliceThickness; if RVyes==1 sizenRV=size(SEG.RVEndoX); KRV = sizenRV(1, 1); NRV = sizenRV(1, 2); SRV = sizenRV(1, 3); zRV = (1:SRV)*SEG.SliceThickness; sizenRVEpi=size(SEG.RVEpiX); KRVEpi = sizenRVEpi(1, 1); NRVEpi = sizenRVEpi(1, 2); SRVEpi = sizenRVEpi(1, 3); zRVEpi = (1:SRVEpi)*SEG.SliceThickness; XRV_avgs = mean(SEG.RVEndoX); YRV_avgs = mean(SEG.RVEndoY); end % X_avgs : array cointaining the barycenters of each slice and frame % X_avgs(1, frame, slice) % contour barycenters are computed as the mean of all LV contour points % in a slice for s = 1:S if ~isnan(SEG.EndoX(1,1,s)) X_avgs = 0.5*mean(SEG.EpiX + SEG.EndoX); Y_avgs = 0.5*mean(SEG.EpiY + SEG.EndoY); else X_avgs = mean(SEG.EpiX); Y_avgs = mean(SEG.EpiY); end end SEG_shift = SEG; SEG_shift.isFullTemporal = 1; for n=1:N x = X_avgs(1, n, :); y = Y_avgs(1, n, :); % Computing least squares linear regression of barycenters for both % coordinates X and Y. lmX = LinearModel.fit(zEndo, x(:)); lmY = LinearModel.fit(zEndo, y(:)); % estX linear least squares estimation of barycenter X coordinate estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zEndo; estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zEndo; % Shifting each segment contour so that all barycenters are located % on the regression lines for both X and Y coordinates. for s=1:S shiftX = x(:) - estX(s); shiftY = y(:) - estY(s); SEG_shift.EndoX(:, n, s) = SEG.EndoX(:, n, s) - shiftX(s); SEG_shift.EndoY(:, n, s) = SEG.EndoY(:, n, s) - shiftY(s); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Finding X and Y coordinates of pixels with scars [X_scar, Y_scar] = find(SEG.Scar.Result(:, :, s)); % Scar pixels, if present in the slice, shall be shifted if sum(size(X_scar)) > 1 % Calculating new scar pixels' positions X_scar = abs(round(X_scar - shiftX(s))); Y_scar = abs(round(Y_scar - shiftY(s))); dims = size(SEG_shift.Scar.Result(:,:, s)); % Providing linear indices ind = sub2ind(dims, X_scar, Y_scar); U = zeros(dims); % Creating new pixel matrix U(ind) = 1; SEG_shift.Scar.Result(:,:, s) = U; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end end for n = 1:N %x = X_avgs(1, n, :); %y = Y_avgs(1, n, :); % Computing least squares linear regression of barycenters for both % coordinates X and Y. lmX = LinearModel.fit(zEpi, x(:)); lmY = LinearModel.fit(zEpi, y(:)); % estX linear least squares estimation of barycenter X coordinate estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zEpi; estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zEpi; % Shifting each segment contour so that all barycenters are located % on the regression lines for both X and Y coordinates. for s=1:SEpi shiftX = x(:) - estX(s); shiftY = y(:) - estY(s); SEG_shift.EpiX(:, n, s) = SEG.EpiX(:, n, s) - shiftX(s); SEG_shift.EpiY(:, n, s) = SEG.EpiY(:, n, s) - shiftY(s); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % RV calignment (if included) if RVyes == 1 for n = 1:N %?? %x = XRV_avgs(1, n, :); %y = YRV_avgs(1, n, :); % x = X_avgs(1, n, :); % y = Y_avgs(1, n, :); % Computing least squares linear regression of barycenters for both % coordinates X and Y. lmX = LinearModel.fit(zRV, x(:)); lmY = LinearModel.fit(zRV, y(:)); % estX linear least squares estimation of barycenter X coordinate estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zRV; estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zRV; % Shifting each segment contour so that all barycenters are located % on the regression lines for both X and Y coordinates. for s=1:SRV shiftX = x(:) - estX(s); shiftY = y(:) - estY(s); if SEG_shift.isFullTemporal == 1 if n == SEG.EDT || n == SEG.EST SEG_shift.RVEndoX(:, n, s) = SEG.RVEndoX(:, n, s) - shiftX(s); SEG_shift.RVEndoY(:, n, s) = SEG.RVEndoY(:, n, s) - shiftY(s); end else SEG_shift.RVEndoX(:, n, s) = SEG.RVEndoX(:, n, s) - shiftX(s); SEG_shift.RVEndoY(:, n, s) = SEG.RVEndoY(:, n, s) - shiftY(s); end end end for n = 1:N %x = XRV_avgs(1, n, :); %y = YRV_avgs(1, n, :); % x = X_avgs(1, n, :); % y = Y_avgs(1, n, :); % Computing least squares linear regression of barycenters for both % coordinates X and Y. lmX = LinearModel.fit(zRVEpi, x(:)); lmY = LinearModel.fit(zRVEpi, y(:)); % estX linear least squares estimation of barycenter X coordinate estX = lmX.Coefficients.Estimate(1) + lmX.Coefficients.Estimate(2)*zRVEpi; estY = lmY.Coefficients.Estimate(1) + lmY.Coefficients.Estimate(2)*zRVEpi; % Shifting each segment contour so that all barycenters are located % on the regression lines for both X and Y coordinates. for s=1:SRVEpi shiftX = x(:) - estX(s); shiftY = y(:) - estY(s); if SEG_shift.isFullTemporal == 1 if n == SEG.EDT || n == SEG.EST SEG_shift.RVEpiX(:, n, s) = SEG.RVEpiX(:, n, s) - shiftX(s); SEG_shift.RVEpiY(:, n, s) = SEG.RVEpiY(:, n, s) - shiftY(s); end else SEG_shift.RVEpiX(:, n, s) = SEG.RVEpiX(:, n, s) - shiftX(s); SEG_shift.RVEpiY(:, n, s) = SEG.RVEpiY(:, n, s) - shiftY(s); end end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Cleaning the data i = 1; for s = 1:S if s > 1 if ~isnan(endo(k,1)) i = i+1; end end for k = 1:K EndoX(:,:)=SEG_shift.EndoX(:,:,s); EndoY(:,:)=SEG_shift.EndoY(:,:,s); endo = sum(EndoX,2); % Remove NaN values in the array if ~isnan(endo(k,1)) tmp1(k,:) = EndoX(k,:); tmp2(k,:) = EndoY(k,:); for n = 1:N EndoXnew(k,n,i) = tmp1(k,n); EndoYnew(k,n,i) = tmp2(k,n); end end end end i = 1; for s = 1:SEpi if s > 1 if ~isnan(epi(k,1)) i = i+1; end end for k = 1:KEpi EpiX(:,:)=SEG_shift.EpiX(:,:,s); EpiY(:,:)=SEG_shift.EpiY(:,:,s); epi = sum(EpiX,2); % Remove NaN values in the array if ~isnan(epi(k,1)) tmp1(k,:) = EpiX(k,:); tmp2(k,:) = EpiY(k,:); for n = 1:NEpi EpiXnew(k,n,i) = tmp1(k,n); EpiYnew(k,n,i) = tmp2(k,n); end end end end i = 1; for s = 1:SRV if s > 1 if ~isnan(rv(k,1)) i = i+1; end end for k = 1:KRV RVX(:,:)=SEG_shift.RVEndoX(:,1,s); RVY(:,:)=SEG_shift.RVEndoY(:,1,s); rv = sum(RVX,2); % Remove NaN values in the array if ~isnan(rv(k,1)) tmp1(k,:) = RVX(k,:); tmp2(k,:) = RVY(k,:); for n = 1:NRV RVEndoXnew(k,n,i) = tmp1(k,n); RVEndoYnew(k,n,i) = tmp2(k,n); end end end end i = 1; for s = 1:SRVEpi if s > 1 if ~isnan(rv(k,1)) i = i+1; end end for k = 1:KRVEpi RVX(:,:)=SEG_shift.RVEpiX(:,1,s); RVY(:,:)=SEG_shift.RVEpiY(:,1,s); rv = sum(RVX,2); % Remove NaN values in the array if ~isnan(rv(k,1)) tmp1(k,:) = RVX(k,:); tmp2(k,:) = RVY(k,:); for n = 1:NRV RVEpiXnew(k,n,i) = tmp1(k,n); RVEpiYnew(k,n,i) = tmp2(k,n); end end end end SEG_shift.EndoXnew = EndoXnew; SEG_shift.EndoYnew = EndoYnew; SEG_shift.EpiXnew = EpiXnew; SEG_shift.EpiYnew = EpiYnew; SEG_shift.RVEndoXnew = RVEndoXnew; SEG_shift.RVEndoYnew = RVEndoYnew; SEG_shift.RVEpiXnew = RVEpiXnew; SEG_shift.RVEpiYnew = RVEpiYnew; end
github
vildenst/3D-heart-models-master
pairwiseAlignmentwithBivEpi.m
.m
3D-heart-models-master/Matlab_Process/pairwiseAlignmentwithBivEpi.m
30,224
utf_8
8037aa97add81bb8bece5bc9457a8bd4
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % TRANSFORM MOVING SUBJECT TO REFERENCE % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Find the center point of the point cloud representing the left or right % ventricle % Author - Kristin Mcleod % SIMULA Research Laboratory % Contact - [email protected] % July 2016 % Takes as input the filenames of the reference subject and target subject % which should be pre-aligned and temporally resampled first using % autoAlign.m and temporalResample.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG2new = pairwiseAlignmentwithBivEpi(SEG_fixed,SEG_moving,IsFullTemporal) %% Read data % Read first filename to assign SEG1 SEG1 = SEG_fixed; sizen1 = size(SEG1.EndoXnew); sizen1epi = size(SEG1.EpiXnew); sizenRV1 = size(SEG1.RVEndoXnew); sizenRVEpi1 = size(SEG1.RVEpiXnew); K1 = sizen1(1,1); N1 = sizen1(1,2); S1 = sizen1(1,3); K1epi = sizen1epi(1,1); N1epi = sizen1epi(1,2); S1epi = sizen1epi(1,3); KRV1 = sizenRV1(1,1); NRV1 = sizenRV1(1,2); SRV1 = sizenRV1(1,3); KRVEpi1 = sizenRVEpi1(1,1); NRVEpi1 = sizenRVEpi1(1,2); SRVEpi1 = sizenRVEpi1(1,3); EndoZ1 = repmat((1-(1:SEG1.ZSize))*(SEG1.SliceThickness+SEG1.SliceGap),... [K1 1]); EpiZ1 = repmat((1-(1:SEG1.ZSize))*(SEG1.SliceThickness+SEG1.SliceGap),... [K1epi 1]); RVEndoZ1 = repmat((1-(1:SEG1.ZSize))*(SEG1.SliceThickness+SEG1.SliceGap),... [KRV1 1]); RVEpiZ1 = repmat((1-(1:SEG1.ZSize))*(SEG1.SliceThickness+SEG1.SliceGap),... [KRVEpi1 1]); % Read second filename to assign SEG2 SEG2 = SEG_moving; sizen2 = size(SEG2.EndoXnew); sizen2epi = size(SEG2.EpiXnew); sizenRV2 = size(SEG2.RVEndoXnew); sizenRVEpi2 = size(SEG2.RVEpiXnew); K2 = sizen2(1,1); N2 = sizen2(1,2); S2 = sizen2(1,3); K2epi = sizen2epi(1,1); N2epi = sizen2epi(1,2); S2epi = sizen2epi(1,3); KRV2 = sizenRV2(1,1); NRV2 = sizenRV2(1,2); SRV2 = sizenRV2(1,3); KRVEpi2 = sizenRVEpi2(1,1); NRVEpi2 = sizenRVEpi2(1,2); SRVEpi2 = sizenRVEpi2(1,3); EndoZ2 = repmat((1-(1:SEG2.ZSize))*(SEG2.SliceThickness+SEG2.SliceGap),... [K2 1]); EpiZ2 = repmat((1-(1:SEG2.ZSize))*(SEG2.SliceThickness+SEG2.SliceGap),... [K2epi 1]); RVEndoZ2 = repmat((1-(1:SEG2.ZSize))*(SEG2.SliceThickness+SEG2.SliceGap),... [KRV2 1]); RVEpiZ2 = repmat((1-(1:SEG2.ZSize))*(SEG2.SliceThickness+SEG2.SliceGap),... [KRVEpi2 1]); %% Create physical points from EndoX and EndoY for fixed patient % Move RV after voxel-size adjustment (so that LV and RV don't overlap) %%% WHAT IS THIS FOR? %%% baryCentreLVold1(1,1) = mean(mean(SEG1.EndoXnew(:,1,:))); baryCentreLVold1(1,2) = mean(mean(SEG1.EndoYnew(:,1,:))); baryCentreRVold1(1,1) = mean(mean(SEG1.RVEndoXnew(:,1,:))); baryCentreRVold1(1,2) = mean(mean(SEG1.RVEndoYnew(:,1,:))); directionBefore1 = baryCentreLVold1 - baryCentreRVold1; lengthDirectionBefore1 = sqrt(directionBefore1(1,1)^2 + directionBefore1(1,2)^2); moveInDirection1 = SEG1.ResolutionX * lengthDirectionBefore1 - lengthDirectionBefore1; %%% %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if IsFullTemporal == 1 for n = 1:N1 for s = 1:S1 for k = 1:K1 i = (s-1)*K1+k; eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.EndoXnew(k,n,s);']); eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.EndoYnew(k,n,s);']); eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,3) = EndoZ1(k,s);']); end end end % Same for Epi for n = 1:N1epi for s = 1:S1epi for k = 1:K1epi i = (s-1)*K1epi+k; eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.EpiXnew(k,n,s);']); eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.EpiYnew(k,n,s);']); eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,3) = EpiZ1(k,s);']); end end end %Same for RV endo for n = 1:NRV1 for s = 1:SRV1 for k = 1:KRV1 i = (s-1)*KRV1+k; eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.RVEndoXnew(k,n,s);']); eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.RVEndoYnew(k,n,s);']); eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ1(k,s);']); end end end %Same for RV epi for n = 1:NRVEpi1 for s = 1:SRVEpi1 for k = 1:KRVEpi1 i = (s-1)*KRVEpi1+k; eval(['SEG1.RVEpiPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.RVEpiXnew(k,n,s);']); eval(['SEG1.RVEpiPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.RVEpiYnew(k,n,s);']); eval(['SEG1.RVEpiPoints.Frame' int2str(n) '(i,3) = RVEpiZ1(k,s);']); end end end %% Create physical points from EndoX and EndoY for moving patient % Move RV after voxel-size adjustment (so that LV and RV don't overlap) baryCentreLVold2(1,1) = mean(mean(SEG2.EndoXnew(:,1,:))); baryCentreLVold2(1,2) = mean(mean(SEG2.EndoYnew(:,1,:))); %baryCentreLVold(1,3) = mean(mean(SEG_shift_resampled.ResolutionX*EndoZ)); baryCentreRVold2(1,1) = mean(mean(SEG2.RVEndoXnew(:,1,:))); baryCentreRVold2(1,2) = mean(mean(SEG2.RVEndoYnew(:,1,:))); %baryCentreRVold(1,3) = mean(mean(SEG_shift_resampled.ResolutionX*RVEndoZ)); directionBefore2 = baryCentreLVold2 - baryCentreRVold2; lengthDirectionBefore2 = sqrt(directionBefore2(1,1)^2 + directionBefore2(1,2)^2); moveInDirection2 = SEG2.ResolutionX * lengthDirectionBefore2 - lengthDirectionBefore2; for n = 1:N2 for s = 1:S2 for k = 1:K2 i = (s-1)*K2+k; eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.EndoXnew(k,n,s);']); eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.EndoYnew(k,n,s);']); eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,3) = EndoZ2(k,s);']); end end end % Same for Epi for n = 1:N2epi for s = 1:S2epi for k = 1:K2epi i = (s-1)*K2epi+k; eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.EpiXnew(k,n,s);']); eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.EpiYnew(k,n,s);']); eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,3) = EpiZ2(k,s);']); end end end % Same for RV Endo for n = 1:NRV2 for s = 1:SRV2 for k = 1:KRV2 i = (s-1)*KRV2+k; eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.RVEndoXnew(k,n,s);']); eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.RVEndoYnew(k,n,s);']); eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ2(k,s);']); end end end % Same for RV Epi for n = 1:NRVEpi2 for s = 1:SRVEpi2 for k = 1:KRVEpi2 i = (s-1)*KRVEpi2+k; eval(['SEG2.RVEpiPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.RVEpiXnew(k,n,s);']); eval(['SEG2.RVEpiPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.RVEpiYnew(k,n,s);']); eval(['SEG2.RVEpiPoints.Frame' int2str(n) '(i,3) = RVEpiZ2(k,s);']); end end end %% Compute transformation components (scaling, translation, rotation) % Compute barycentres (choose the 1st frame as the reference) baryCentreLV1(1,1) = mean(SEG1.EndoPoints.Frame1(:,1)); baryCentreLV1(1,2) = mean(SEG1.EndoPoints.Frame1(:,2)); baryCentreLV1(1,3) = mean(SEG1.EndoPoints.Frame1(:,3)); baryCentreRV1(1,1) = mean(SEG1.RVEndoPoints.Frame1(:,1)); baryCentreRV1(1,2) = mean(SEG1.RVEndoPoints.Frame1(:,2)); baryCentreRV1(1,3) = mean(SEG1.RVEndoPoints.Frame1(:,3)); baryCentreLV2(1,1) = mean(SEG2.EndoPoints.Frame1(:,1)); baryCentreLV2(1,2) = mean(SEG2.EndoPoints.Frame1(:,2)); baryCentreLV2(1,3) = mean(SEG2.EndoPoints.Frame1(:,3)); baryCentreRV2(1,1) = mean(SEG2.RVEndoPoints.Frame1(:,1)); baryCentreRV2(1,2) = mean(SEG2.RVEndoPoints.Frame1(:,2)); baryCentreRV2(1,3) = mean(SEG2.RVEndoPoints.Frame1(:,3)); % Get length of line segments joining LV centre and RV centre length1 = sqrt((abs(baryCentreLV1(1,1)-baryCentreRV1(1,1))^2 + ... abs(baryCentreLV1(1,2) - baryCentreRV1(1,2))^2 + ... abs(baryCentreLV1(1,3) - baryCentreRV1(1,3))^2)); length2 = sqrt((abs(baryCentreLV2(1,1)-baryCentreRV2(1,1))^2 + ... abs(baryCentreLV2(1,2) - baryCentreRV2(1,2))^2 + ... abs(baryCentreLV2(1,3) - baryCentreRV2(1,3))^2)); % Compute scaling factor between line segments scale = length1 / length2; % Compute translation (translate to match x-points) translation = baryCentreLV2-baryCentreLV1; %Copy to new struct SEG2new = SEG2; SEG1new = SEG1; %% Translate main axis of moving patient back to the origin for n = 1:N2 eval(['l = length(SEG2.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2.EndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Same for Epi for n = 1:N2epi eval(['l = length(SEG2.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2.EpiPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Same for RV Endo for n = 1:NRV2 eval(['l = length(SEG2.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2.RVEndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Same for RV Epi for n = 1:NRVEpi2 eval(['l = length(SEG2.RVEpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEpiPoints.Frame' int2str(n) '(i,:) = SEG2.RVEpiPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Do for fixed subject as well for n = 1:N1 eval(['l = length(SEG1.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.EndoPoints.Frame' int2str(n) '(i,:) = SEG1.EndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end % Same for Epi for n = 1:N1epi eval(['l = length(SEG1.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.EpiPoints.Frame' int2str(n) '(i,:) = SEG1.EpiPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end % Same for RV Endo for n = 1:NRV1 eval(['l = length(SEG1.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG1.RVEndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end % Same for RV Epi for n = 1:NRVEpi1 eval(['l = length(SEG1.RVEpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.RVEpiPoints.Frame' int2str(n) '(i,:) = SEG1.RVEpiPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Rotate baryCentreLV1new(1,1) = mean(SEG1new.EndoPoints.Frame1(1:80,1)); baryCentreLV1new(1,2) = mean(SEG1new.EndoPoints.Frame1(1:80,2)); baryCentreLV1new(1,3) = mean(SEG1new.EndoPoints.Frame1(1:80,3)); baryCentreRV1new(1,1) = mean(SEG1new.RVEndoPoints.Frame1(1:80,1)); baryCentreRV1new(1,2) = mean(SEG1new.RVEndoPoints.Frame1(1:80,2)); baryCentreRV1new(1,3) = mean(SEG1new.RVEndoPoints.Frame1(1:80,3)); baryCentreLV2new(1,1) = mean(SEG2new.EndoPoints.Frame1(1:80,1)); baryCentreLV2new(1,2) = mean(SEG2new.EndoPoints.Frame1(1:80,2)); baryCentreLV2new(1,3) = mean(SEG2new.EndoPoints.Frame1(1:80,3)); baryCentreRV2new(1,1) = mean(SEG2new.RVEndoPoints.Frame1(1:80,1)); baryCentreRV2new(1,2) = mean(SEG2new.RVEndoPoints.Frame1(1:80,2)); baryCentreRV2new(1,3) = mean(SEG2new.RVEndoPoints.Frame1(1:80,3)); baryCentreLV1normed = ((baryCentreRV1new-(baryCentreLV1new))); baryCentreLV2normed = ((baryCentreRV2new-(baryCentreLV2new))); % Compute angle of rotation between the line segments rotationAngle = acos((baryCentreLV1normed(1,1) * baryCentreLV2normed(1,1) + ... baryCentreLV1normed(1,2) * baryCentreLV2normed(1,2))/(... sqrt(baryCentreLV1normed(1,1)^2 + baryCentreLV1normed(1,2)^2) * ... sqrt(baryCentreLV2normed(1,1)^2 + baryCentreLV2normed(1,2)^2))); %rotationAngle = rotationAngle*180/pi; rotationMatrix = [cos(rotationAngle) sin(rotationAngle) 0; ... -sin(rotationAngle) cos(rotationAngle) 0; ... 0 0 1]; for n = 1:N2 eval(['l = length(SEG2new.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2new.EndoPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end % Same for Epi for n = 1:N2epi eval(['l = length(SEG2new.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2new.EpiPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end % Same for RV Endo for n = 1:NRV2 eval(['l = length(SEG2new.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end % Same for RV Epi for n = 1:NRVEpi2 eval(['l = length(SEG2new.RVEpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEpiPoints.Frame' int2str(n) '(i,:) = SEG2new.RVEpiPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end %% Translate to fit main axis of fixed patient for n = 1:N2 eval(['l = length(SEG2new.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2new.EndoPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end % Same for Epi for n = 1:N2epi eval(['l = length(SEG2new.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2new.EpiPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end % Same for RV Endo for n = 1:NRV2 eval(['l = length(SEG2new.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end % Same for RV Epi for n = 1:NRVEpi2 eval(['l = length(SEG2new.RVEpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEpiPoints.Frame' int2str(n) '(i,:) = SEG2new.RVEpiPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% else %if isFullTemporal %% Create physical points from EndoX and EndoY for fixed patient % Move RV after voxel-size adjustment (so that LV and RV don't overlap) %%%%%%%%%%%%% % LV Endo for n = 1 for s = 1:S1 for k = 1:K1 i = (s-1)*K1+k; SEG1.EndoPoints.Frame{n}(i,1) = SEG1.ResolutionX *... SEG1.EndoXnew(k,n,s); SEG1.EndoPoints.Frame{n}(i,2) = SEG1.ResolutionY *... SEG1.EndoYnew(k,n,s); SEG1.EndoPoints.Frame{n}(i,3) = EndoZ1(k,s); end end end %%%%%%%%%%%%% % LV Epi for n = 1 for s = 1:S1epi for k = 1:K1epi i = (s-1)*K1epi+k; SEG1.EpiPoints.Frame{n}(i,1) = SEG1.ResolutionX *... SEG1.EpiXnew(k,n,s); SEG1.EpiPoints.Frame{n}(i,2) = SEG1.ResolutionY *... SEG1.EpiYnew(k,n,s); SEG1.EpiPoints.Frame{n}(i,3) = EpiZ1(k,s); end end end %%%%%%%%%%%%% % RV endo for n = 1 for s = 1:SRV1 for k = 1:KRV1 i = (s-1)*KRV1+k; SEG1.RVEndoPoints.Frame{n}(i,1) = SEG1.ResolutionX *... SEG1.RVEndoXnew(k,n,s); SEG1.RVEndoPoints.Frame{n}(i,2) = SEG1.ResolutionY *... SEG1.RVEndoYnew(k,n,s); SEG1.RVEndoPoints.Frame{n}(i,3) = RVEndoZ1(k,s); end end end %%%%%%%%%%%%% % RV epi for n = 1 for s = 1:SRVEpi1 for k = 1:KRVEpi1 i = (s-1)*KRVEpi1+k; SEG1.RVEpiPoints.Frame{n}(i,1) = SEG1.ResolutionX *... SEG1.RVEpiXnew(k,n,s); SEG1.RVEpiPoints.Frame{n}(i,2) = SEG1.ResolutionY *... SEG1.RVEpiYnew(k,n,s); SEG1.RVEpiPoints.Frame{n}(i,3) = RVEpiZ1(k,s); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Create physical points from EndoX and EndoY for moving patient % Move RV after voxel-size adjustment (so that LV and RV don't overlap) baryCentreLVold2(1,1) = mean(mean(SEG2.EndoXnew(:,1,:))); baryCentreLVold2(1,2) = mean(mean(SEG2.EndoYnew(:,1,:))); baryCentreRVold2(1,1) = mean(mean(SEG2.RVEndoXnew(:,1,:))); baryCentreRVold2(1,2) = mean(mean(SEG2.RVEndoYnew(:,1,:))); directionBefore2 = baryCentreLVold2 - baryCentreRVold2; lengthDirectionBefore2 = sqrt(directionBefore2(1,1)^2 + ... directionBefore2(1,2)^2); moveInDirection2 = SEG2.ResolutionX * lengthDirectionBefore2 - ... lengthDirectionBefore2; %%%%%%%%%%%%% % LV Endo for n = 1 for s = 1:S2 for k = 1:K2 i = (s-1)*K2+k; SEG2.EndoPoints.Frame{n}(i,1) = SEG2.ResolutionX *... SEG2.EndoXnew(k,n,s); SEG2.EndoPoints.Frame{n}(i,2) = SEG2.ResolutionY *... SEG2.EndoYnew(k,n,s); SEG2.EndoPoints.Frame{n}(i,3) = EndoZ2(k,s); end end end %%%%%%%%%%%%% % LV Epi for n = 1 for s = 1:S2epi for k = 1:K2epi i = (s-1)*K2epi+k; SEG2.EpiPoints.Frame{n}(i,1) = SEG2.ResolutionX *... SEG2.EpiXnew(k,n,s); SEG2.EpiPoints.Frame{n}(i,2) = SEG2.ResolutionY *... SEG2.EpiYnew(k,n,s); SEG2.EpiPoints.Frame{n}(i,3) = EpiZ2(k,s); end end end %%%%%%%%%%%%% % RV Endo for n = 1 for s = 1:SRV2 for k = 1:KRV2 i = (s-1)*KRV2+k; SEG2.RVEndoPoints.Frame{n}(i,1) = SEG2.ResolutionX *... SEG2.RVEndoXnew(k,n,s); SEG2.RVEndoPoints.Frame{n}(i,2) = SEG2.ResolutionY *... SEG2.RVEndoYnew(k,n,s); SEG2.RVEndoPoints.Frame{n}(i,3) = RVEndoZ2(k,s); end end end %%%%%%%%%%%%% % RV Epi for n = 1 for s = 1:SRVEpi2 for k = 1:KRVEpi2 i = (s-1)*KRVEpi2+k; SEG2.RVEpiPoints.Frame{n}(i,1) = SEG2.ResolutionX *... SEG2.RVEpiXnew(k,n,s); SEG2.RVEpiPoints.Frame{n}(i,2) = SEG2.ResolutionY *... SEG2.RVEpiYnew(k,n,s); SEG2.RVEpiPoints.Frame{n}(i,3) = RVEpiZ2(k,s); end end end %%%%%%%%%%%%%%%%%%%%%%% SCAR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Scarmhd = []; % initZshift = SEG2.EndoPoints.Frame{1}(1,3); for s = 1:S2 [X_scar, Y_scar] = find(SEG2.Scar.Result(:, :, s)); X_scar = SEG2.ResolutionX * X_scar; Y_scar = SEG2.ResolutionY * Y_scar; Z_scar = repmat(EndoZ2(1,s),[size(X_scar),1]); % Z_scar = Z_scar + initZshift; if sum(size(X_scar)) > 1 Scartmp = [X_scar, Y_scar, Z_scar]; Scarmhd = cat(1,Scarmhd,Scartmp); end SEG2.ScarMhd = Scarmhd; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Compute transformation components (scaling, translation, rotation) % Compute barycentres (choose the 1st frame as the reference) baryCentreLV1(1,1) = mean(SEG1.EndoPoints.Frame{1}(:,1)); baryCentreLV1(1,2) = mean(SEG1.EndoPoints.Frame{1}(:,2)); baryCentreLV1(1,3) = mean(SEG1.EndoPoints.Frame{1}(:,3)); baryCentreRV1(1,1) = mean(SEG1.RVEndoPoints.Frame{1}(:,1)); baryCentreRV1(1,2) = mean(SEG1.RVEndoPoints.Frame{1}(:,2)); baryCentreRV1(1,3) = mean(SEG1.RVEndoPoints.Frame{1}(:,3)); baryCentreLV2(1,1) = mean(SEG2.EndoPoints.Frame{1}(:,1)); baryCentreLV2(1,2) = mean(SEG2.EndoPoints.Frame{1}(:,2)); baryCentreLV2(1,3) = mean(SEG2.EndoPoints.Frame{1}(:,3)); baryCentreRV2(1,1) = mean(SEG2.RVEndoPoints.Frame{1}(:,1)); baryCentreRV2(1,2) = mean(SEG2.RVEndoPoints.Frame{1}(:,2)); baryCentreRV2(1,3) = mean(SEG2.RVEndoPoints.Frame{1}(:,3)); % Get length of line segments joining LV centre and RV centre length1 = sqrt((abs(baryCentreLV1(1,1) - baryCentreRV1(1,1))^2 + ... abs(baryCentreLV1(1,2) - baryCentreRV1(1,2))^2 + ... abs(baryCentreLV1(1,3) - baryCentreRV1(1,3))^2)); length2 = sqrt((abs(baryCentreLV2(1,1) - baryCentreRV2(1,1))^2 + ... abs(baryCentreLV2(1,2) - baryCentreRV2(1,2))^2 + ... abs(baryCentreLV2(1,3) - baryCentreRV2(1,3))^2)); % Compute scaling factor between line segments scale = length1 / length2; % Compute translation (translate to match x-points) translation = baryCentreLV2-baryCentreLV1; %Copy to new struct SEG2new = SEG2; SEG1new = SEG1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Translate main axis of moving patient back to the origin %%%%%%%%%%%%% % LV Endo for n = 1 l = length(SEG2.EndoPoints.Frame{n}); for i = 1:l SEG2new.EndoPoints.Frame{n}(i,:) = SEG2.EndoPoints.Frame{n}(i,:)... - baryCentreLV2; end end %%%%%%%%%%%%%%%% SCAR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for i = 1:length(SEG2.ScarMhd) SEG2new.ScarMhd(i,:) = SEG2.ScarMhd(i,:) - baryCentreLV2; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%% % LV Epi for n = 1 l = length(SEG2.EpiPoints.Frame{n}); for i = 1:l SEG2new.EpiPoints.Frame{n}(i,:) = SEG2.EpiPoints.Frame{n}(i,:)... - baryCentreLV2; end end %%%%%%%%%%%%% % RV Endo for n = 1 l = length(SEG2.RVEndoPoints.Frame{n}); for i = 1:l SEG2new.RVEndoPoints.Frame{n}(i,:) = SEG2.RVEndoPoints.Frame{n}(i,:)... - baryCentreLV2; end end %%%%%%%%%%%%% % RV Epi for n = 1 l = length(SEG2.RVEpiPoints.Frame{n}); for i = 1:l SEG2new.RVEpiPoints.Frame{n}(i,:) = SEG2.RVEpiPoints.Frame{n}(i,:)... - baryCentreLV2; end end % %%% Do for fixed subject as well % %%%%%%%%%%%%% % LV Endo for n = 1 l = length(SEG1.EndoPoints.Frame{n}); for i = 1:l SEG1new.EndoPoints.Frame{n}(i,:) = SEG1.EndoPoints.Frame{n}(i,:)... - baryCentreLV1; end end %%%%%%%%%%%%% % LV Epi for n = 1 l = length(SEG1.EpiPoints.Frame{n}); for i = 1:l SEG1new.EpiPoints.Frame{n}(i,:) = SEG1.EpiPoints.Frame{n}(i,:)... - baryCentreLV1; end end %%%%%%%%%%%%% % RV Endo for n = 1 l = length(SEG1.RVEndoPoints.Frame{n}); for i = 1:l SEG1new.RVEndoPoints.Frame{n}(i,:) = SEG1.RVEndoPoints.Frame{n}(i,:)... - baryCentreLV1; end end %%%%%%%%%%%%% % RV Epi for n = 1 l = length(SEG1.RVEpiPoints.Frame{n}); for i = 1:l SEG1new.RVEpiPoints.Frame{n}(i,:) = SEG1.RVEpiPoints.Frame{n}(i,:)... - baryCentreLV1; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Rotate baryCentreLV1new(1,1) = mean(SEG1new.EndoPoints.Frame{1}(:,1)); baryCentreLV1new(1,2) = mean(SEG1new.EndoPoints.Frame{1}(:,2)); baryCentreLV1new(1,3) = mean(SEG1new.EndoPoints.Frame{1}(:,3)); baryCentreRV1new(1,1) = mean(SEG1new.RVEndoPoints.Frame{1}(:,1)); baryCentreRV1new(1,2) = mean(SEG1new.RVEndoPoints.Frame{1}(:,2)); baryCentreRV1new(1,3) = mean(SEG1new.RVEndoPoints.Frame{1}(:,3)); baryCentreLV2new(1,1) = mean(SEG2new.EndoPoints.Frame{1}(:,1)); baryCentreLV2new(1,2) = mean(SEG2new.EndoPoints.Frame{1}(:,2)); baryCentreLV2new(1,3) = mean(SEG2new.EndoPoints.Frame{1}(:,3)); baryCentreRV2new(1,1) = mean(SEG2new.RVEndoPoints.Frame{1}(:,1)); baryCentreRV2new(1,2) = mean(SEG2new.RVEndoPoints.Frame{1}(:,2)); baryCentreRV2new(1,3) = mean(SEG2new.RVEndoPoints.Frame{1}(:,3)); baryCentreLV1normed = ((baryCentreRV1new-(baryCentreLV1new))); baryCentreLV2normed = ((baryCentreRV2new-(baryCentreLV2new))); %Compute angle of rotation between the line segments % rotationAngle = acos((baryCentreLV1normed(1,1) * baryCentreLV2normed(1,1) + ... % baryCentreLV1normed(1,2) * baryCentreLV2normed(1,2))/(... % sqrt(baryCentreLV1normed(1,1)^2 + baryCentreLV1normed(1,2)^2) * ... % sqrt(baryCentreLV2normed(1,1)^2 + baryCentreLV2normed(1,2)^2))); rotationAngle = atan2(baryCentreLV2normed(1,2), baryCentreLV2normed(1,1)) -... atan2(baryCentreLV1normed(1,2), baryCentreLV1normed(1,1)); %rotationAngle = rotationAngle*180/pi; rotationMatrix = [cos(rotationAngle) -sin(rotationAngle) 0; ... sin(rotationAngle) cos(rotationAngle) 0; ... 0 0 1]; %%%%%%%%%%%%% % LV Endo for n = 1 l = length(SEG2new.EndoPoints.Frame{n}); for i = 1:l SEG2new.EndoPoints.Frame{n}(i,:) = SEG2new.EndoPoints.Frame{n}(i,:)... * rotationMatrix; end end %%%%%%%%%%%%%%%% SCAR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for i = 1:length(SEG2.ScarMhd) SEG2new.ScarMhd(i,:) = SEG2new.ScarMhd(i,:) * rotationMatrix; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%% % LV Epi for n = 1 l = length(SEG2new.EpiPoints.Frame{n}); for i = 1:l SEG2new.EpiPoints.Frame{n}(i,:) = SEG2new.EpiPoints.Frame{n}(i,:)... * rotationMatrix; end end %%%%%%%%%%%%% % RV Endo for n = 1 l = length(SEG2new.RVEndoPoints.Frame{n}); for i = 1:l SEG2new.RVEndoPoints.Frame{n}(i,:) = SEG2new.RVEndoPoints.Frame{n}(i,:)... * rotationMatrix; end end disp(['Difference:', int2str(mean(SEG1new.RVEndoPoints.Frame{1}(1:160,1)) - ... mean(SEG2new.RVEndoPoints.Frame{1}(:,1)))]); %%%%%%%%%%%%% % RV Epi for n = 1 l = length(SEG2new.RVEpiPoints.Frame{n}); for i = 1:l SEG2new.RVEpiPoints.Frame{n}(i,:) = SEG2new.RVEpiPoints.Frame{n}(i,:)... * rotationMatrix; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Translate to fit main axis of fixed patient %%%%%%%%%%%%% % LV Endo for n = 1 l = length(SEG2new.EndoPoints.Frame{n}); for i = 1:l SEG2new.EndoPoints.Frame{n}(i,:) = SEG2new.EndoPoints.Frame{n}(i,:)... + baryCentreLV1; end end %%%%%%%%%%%%%%%% SCAR %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for i = 1:length(SEG2.ScarMhd) SEG2new.ScarMhd(i,:) = SEG2new.ScarMhd(i,:) + baryCentreLV1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%% % LV Epi for n = 1 l = length(SEG2new.EpiPoints.Frame{n}); for i = 1:l SEG2new.EpiPoints.Frame{n}(i,:) = SEG2new.EpiPoints.Frame{n}(i,:)... + baryCentreLV1; end end %%%%%%%%%%%%% % RV Endo for n = 1 l = length(SEG2new.RVEndoPoints.Frame{n}); for i = 1:l SEG2new.RVEndoPoints.Frame{n}(i,:) = SEG2new.RVEndoPoints.Frame{n}(i,:)... + baryCentreLV1; end end %%%%%%%%%%%%% % RV Endo for n = 1 l = length(SEG2new.RVEpiPoints.Frame{n}); for i = 1:l SEG2new.RVEpiPoints.Frame{n}(i,:) = SEG2new.RVEpiPoints.Frame{n}(i,:)... + baryCentreLV1; end end end % if isFullTemporal end
github
vildenst/3D-heart-models-master
ChangeReswithBivEpi.m
.m
3D-heart-models-master/Matlab_Process/ChangeReswithBivEpi.m
4,216
utf_8
3f0d69d6a6e13c8e079b28012d7909ce
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % %%% Change Resolution % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG_NewRes = ChangeReswithBivEpi(SEG) %% Account for voxel size for SEG1 % Account for voxel size SEG.EndoXold = SEG.EndoXnew; SEG.EndoYold = SEG.EndoYnew; SEG.EpiXold = SEG.EpiXnew; SEG.EpiYold = SEG.EpiYnew; SEG.RVEndoXold = SEG.RVEndoXnew; SEG.RVEndoYold = SEG.RVEndoYnew; SEG.RVEpiXold = SEG.RVEpiXnew; SEG.RVEpiYold = SEG.RVEpiYnew; %% Move EndoLV points % sizenEndo=size(SEG.EndoXnew); KEndo = sizenEndo(1, 1); %No. of points (default 80) NEndo = sizenEndo(1, 2); %No. of time frames SEndo = sizenEndo(1, 3); %No. of slices EndoZ = repmat((1-(1:SEG.ZSize))*(SEG.SliceThickness+SEG.SliceGap),... [KEndo 1]); % Create physical points for the fixed reference for n = 1:NEndo for s = 1:SEndo for k = 1:KEndo i = (s-1)*KEndo+k; SEG.EndoPoints.Frame{n}(i,1) = SEG.ResolutionX *... SEG.EndoXnew(k,n,s); SEG.EndoPoints.Frame{n}(i,2) = SEG.ResolutionY *... SEG.EndoYnew(k,n,s); SEG.EndoPoints.Frame{n}(i,3) = EndoZ(k,s); end end end sizenEpi=size(SEG.EpiXnew); KEpi = sizenEpi(1, 1); %No. of points (default 80) NEpi = sizenEpi(1, 2); %No. of time frames SEpi = sizenEpi(1, 3); %No. of slices EpiZ = repmat((1-(1:SEG.ZSize))*(SEG.SliceThickness+SEG.SliceGap),... [KEpi 1]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Move EpiLV points for n = 1:NEpi for s = 1:SEpi for k = 1:KEpi i = (s-1)*KEpi+k; SEG.EpiPoints.Frame{n}(i,1) = SEG.ResolutionX *... SEG.EpiXnew(k,n,s); SEG.EpiPoints.Frame{n}(i,2) = SEG.ResolutionY *... SEG.EpiYnew(k,n,s); SEG.EpiPoints.Frame{n}(i,3) = EpiZ(k,s); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Move EndoRV points sizenRV=size(SEG.RVEndoXnew); KRV = sizenRV(1, 1); %No. of points (default 80) NRV = sizenRV(1, 2); %No. of time frames SRV = sizenRV(1, 3); %No. of slices RVEndoZ = repmat((1-(1:SEG.ZSize))*(SEG.SliceThickness+SEG.SliceGap),... [KRV 1]); for n = 1:NRV for s = 1:SRV for k = 1:KRV i = (s-1)*KRV+k; SEG.RVEndoPoints.Frame{n}(i,1) = SEG.ResolutionX *... SEG.RVEndoXnew(k,n,s); SEG.RVEndoPoints.Frame{n}(i,2) = SEG.ResolutionY *... SEG.RVEndoYnew(k,n,s); SEG.RVEndoPoints.Frame{n}(i,3) = RVEndoZ(k,s); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Move EpiRV points sizenRVEpi=size(SEG.RVEpiXnew); KRVEpi = sizenRVEpi(1, 1); %No. of points (default 80) NRVEpi = sizenRVEpi(1, 2); %No. of time frames SRVEpi = sizenRVEpi(1, 3); %No. of slices RVEpiZ = repmat((1-(1:SEG.ZSize))*(SEG.SliceThickness+SEG.SliceGap),... [KRVEpi 1]); for n = 1:NRVEpi for s = 1:SRVEpi for k = 1:KRVEpi i = (s-1)*KRVEpi+k; SEG.RVEpiPoints.Frame{n}(i,1) = SEG.ResolutionX *... SEG.RVEpiXnew(k,n,s); SEG.RVEpiPoints.Frame{n}(i,2) = SEG.ResolutionY *... SEG.RVEpiYnew(k,n,s); SEG.RVEpiPoints.Frame{n}(i,3) = RVEpiZ(k,s); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Change Res for scar Scarmhd = []; initZshift = SEG.EndoPoints.Frame{1}(1,3); for s = 1:SEndo [X_scar, Y_scar] = find(SEG.Scar.Result(:, :, s)); X_scar = SEG.ResolutionX * X_scar; Y_scar = SEG.ResolutionY * Y_scar; Z_scar = repmat(EndoZ(1,s),[size(X_scar),1]); Z_scar = Z_scar + initZshift; if sum(size(X_scar)) > 1 Scartmp = [X_scar, Y_scar, Z_scar]; Scarmhd = cat(1,Scarmhd,Scartmp); end SEG.ScarMhd = Scarmhd; end SEG_NewRes = SEG;
github
vildenst/3D-heart-models-master
SaveMhd.m
.m
3D-heart-models-master/Matlab_Process/SaveMhd.m
1,925
utf_8
50fa3ebe9a24a82d93a42d24d4e56a4e
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % %%% SAVE .MHD FILE IN PROPER FORMAT %%% % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SIMULA Research Laboratory % For TOF and MI patients at ED only (bi-ventricle) % Contact - [email protected], [email protected] % July 2016 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SaveMhd(subjNo, filen) global SEG % Comes from global workspace localSEG = SEG{subjNo}; % For further processing purposes, values are changed to maximum 8-bit value % Preparing binary array % resVector = [localSEG.ResolutionX localSEG.ResolutionY 1]; pixSize = int16([localSEG.XSize, localSEG.YSize, localSEG.ZSize]);%.*resVector); pix=zeros(pixSize); %Finding slices with scar pixels temp=round(localSEG.ScarMhd/[localSEG.ResolutionX 0 0; 0 localSEG.ResolutionY 0;... 0 0 1]); temp(:)=temp(:); z=max(temp(:,3)); for i=1:localSEG.ZSize temp1=find(temp(:,3)==z); [c,~]=size(temp1); for j=1:c x=temp(temp1(j),1); y=temp(temp1(j),2); pix(x,y,i)=255; end z = z-localSEG.SliceThickness; end % Information for .mhd file. pixImage(:,:,1,:) = uint8(pix); orig = [0 0 -localSEG.EndoPoints.Frame{1}(1,3);]'; sp = [localSEG.ResolutionX localSEG.ResolutionY localSEG.SliceGap+... localSEG.SliceThickness]'; orient = eye(3); image = ImageType(size(squeeze(pixImage))', orig, sp, orient); image.data = squeeze(pixImage); % Saving image [~,name,~] = fileparts(filen); fileName=['Data/ScarImages/MetaImages/' name '.mhd']; write_mhd(fileName, image, 'elementtype', 'uint8');
github
vildenst/3D-heart-models-master
notTemporalResampleAlignmentwithBivEpi.m
.m
3D-heart-models-master/Matlab_Process/notTemporalResampleAlignmentwithBivEpi.m
3,955
utf_8
c5714f1fe5c3d01c8d180ae4fa8d5133
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % TEMPORAL RESAMPLING OF POINT CLOUD WITH TEMPORAL ALIGNMENT TO ES PHASE % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Resample point cloud to have 30 frames using interpolation between points % Author - Kristin Mcleod % SIMULA Research Laboratory % Contact - [email protected], [email protected] % July 2016 % Takes as input SEG_shift from sliceAlignment.m, and the number of desired % time points N %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG_shift_resampled = notTemporalResampleAlignment(SEG_shift_clean,RVyes) SEG_shift_resampled = SEG_shift_clean; % Pre-assign output SEG_shift = SEG_shift_clean; SEG_shift_resampled.EndoXnew = []; SEG_shift_resampled.EndoYnew = []; SEG_shift_resampled.EpiXnew = []; SEG_shift_resampled.EpiYnew = []; sizen=size(SEG_shift.EndoXnew); K = sizen(1, 1); %No. of points (default 80) S = sizen(1, 3); %No. of slices sizenEpi=size(SEG_shift.EpiXnew); KEpi = sizenEpi(1, 1); %No. of points (default 80) SEpi = sizenEpi(1, 3); %No. of slices if RVyes == 1 SEG_shift_resampled.RVEndoXnew = []; SEG_shift_resampled.RVEndoYnew = []; SEG_shift_resampled.RVEpiXnew = []; SEG_shift_resampled.RVEpiYnew = []; sizenRV=size(SEG_shift.RVEndoXnew); KRV = sizenRV(1, 1); %No. of points (default 80) SRV = sizenRV(1, 3); %No. of slices sizenRVEpi=size(SEG_shift.RVEpiXnew); KRVEpi = sizenRVEpi(1, 1); %No. of points (default 80) SRVEpi = sizenRVEpi(1, 3); %No. of slices end for s = 1:S for k = 1:K EndoX(:,:)=SEG_shift.EndoXnew(:,:,s); EndoY(:,:)=SEG_shift.EndoYnew(:,:,s); endo = sum(EndoX,2); % Remove NaN values in the array if ~isnan(endo(k,1)) tmp1(k,:) = EndoX(k,:); tmp2(k,:) = EndoY(k,:); for n = 1 SEG_shift_resampled.EndoXnew(k,n,s) = tmp1(k,n); SEG_shift_resampled.EndoYnew(k,n,s) = tmp2(k,n); end end end end for s = 1:SEpi for k = 1:KEpi EpiX(:,:)=SEG_shift.EpiXnew(:,:,s); EpiY(:,:)=SEG_shift.EpiYnew(:,:,s); epi = sum(EpiX,2); % Remove NaN values in the array if ~isnan(epi(k,1)) tmp1(k,:) = EpiX(k,:); tmp2(k,:) = EpiY(k,:); for n = 1 SEG_shift_resampled.EpiXnew(k,n,s) = tmp1(k,n); SEG_shift_resampled.EpiYnew(k,n,s) = tmp2(k,n); end end end end if RVyes == 1 for s = 1:SRV for k = 1:KRV RVEndoX(:,:)=SEG_shift.RVEndoXnew(:,:,s); RVEndoY(:,:)=SEG_shift.RVEndoYnew(:,:,s); rv = sum(RVEndoX,2); % Remove NaN values in the array if ~isnan(rv(k,1)) tmp1(k,:) = RVEndoX(k,:); tmp2(k,:) = RVEndoY(k,:); for n = 1 SEG_shift_resampled.RVEndoXnew(k,n,s) = tmp1(k,n); SEG_shift_resampled.RVEndoYnew(k,n,s) = tmp2(k,n); end end end end for s = 1:SRVEpi for k = 1:KRVEpi RVEpiX(:,:)=SEG_shift.RVEpiXnew(:,:,s); RVEpiY(:,:)=SEG_shift.RVEpiYnew(:,:,s); rv = sum(RVEpiX,2); % Remove NaN values in the array if ~isnan(rv(k,1)) tmp1(k,:) = RVEpiX(k,:); tmp2(k,:) = RVEpiY(k,:); for n = 1 SEG_shift_resampled.RVEpiXnew(k,n,s) = tmp1(k,n); SEG_shift_resampled.RVEpiYnew(k,n,s) = tmp2(k,n); end end end end end clear EndoX EndoY EpiX EpiY RVEndoX RVEndoY RVEpiX RVEpiY tmp1 tmp2 end
github
vildenst/3D-heart-models-master
pairwiseAlignment.m
.m
3D-heart-models-master/Matlab_Process/pairwiseAlignment.m
23,419
utf_8
de84214a29b38cb85a4942827379071f
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % TRANSFORM MOVING SUBJECT TO REFERENCE % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Find the center point of the point cloud representing the left or right % ventricle % Author - Kristin Mcleod % SIMULA Research Laboratory % Contact - [email protected] % May 2016 % Takes as input the filenames of the reference subject and target subject % which should be pre-aligned and temporally resampled first using % autoAlign.m and temporalResample.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG2new = pairwiseAlignment1(SEG_fixed,SEG_moving,IsFullTemporal) %% Read data % Read first filename to assign SEG1 SEG1 = SEG_fixed; sizen1 = size(SEG1.EndoXnew); sizen1epi = size(SEG1.EpiXnew); sizenRV1 = size(SEG1.RVEndoXnew); K1 = sizen1(1,1); N1 = sizen1(1,2); S1 = sizen1(1,3); K1epi = sizen1epi(1,1); N1epi = sizen1epi(1,2); S1epi = sizen1epi(1,3); KRV1 = sizenRV1(1,1); NRV1 = sizenRV1(1,2); SRV1 = sizenRV1(1,3); EndoZ1 = repmat((1-(1:SEG1.ZSize))*(SEG1.SliceThickness+SEG1.SliceGap),... [K1 1]); EpiZ1 = repmat((1-(1:SEG1.ZSize))*(SEG1.SliceThickness+SEG1.SliceGap),... [K1epi 1]); RVEndoZ1 = repmat((1-(1:SEG1.ZSize))*(SEG1.SliceThickness+SEG1.SliceGap),... [KRV1 1]); % Read second filename to assign SEG2 SEG2 = SEG_moving; sizen2 = size(SEG2.EndoXnew); sizen2epi = size(SEG2.EpiXnew); sizenRV2 = size(SEG2.RVEndoXnew); K2 = sizen2(1,1); N2 = sizen2(1,2); S2 = sizen2(1,3); K2epi = sizen2epi(1,1); N2epi = sizen2epi(1,2); S2epi = sizen2epi(1,3); KRV2 = sizenRV2(1,1); NRV2 = sizenRV2(1,2); SRV2 = sizenRV2(1,3); EndoZ2 = repmat((1-(1:SEG2.ZSize))*(SEG2.SliceThickness+SEG2.SliceGap),... [K2 1]); EpiZ2 = repmat((1-(1:SEG2.ZSize))*(SEG2.SliceThickness+SEG2.SliceGap),... [K2epi 1]); RVEndoZ2 = repmat((1-(1:SEG2.ZSize))*(SEG2.SliceThickness+SEG2.SliceGap),... [KRV2 1]); %% Create physical points from EndoX and EndoY for fixed patient % Move RV after voxel-size adjustment (so that LV and RV don't overlap) baryCentreLVold1(1,1) = mean(mean(SEG1.EndoXnew(:,1,:))); baryCentreLVold1(1,2) = mean(mean(SEG1.EndoYnew(:,1,:))); baryCentreRVold1(1,1) = mean(mean(SEG1.RVEndoXnew(:,1,:))); directionBefore1 = baryCentreLVold1 - baryCentreRVold1; lengthDirectionBefore1 = sqrt(directionBefore1(1,1)^2 + directionBefore1(1,2)^2); moveInDirection1 = SEG1.ResolutionX * lengthDirectionBefore1 - lengthDirectionBefore1; if IsFullTemporal == 1 for n = 1:N1 for s = 1:S1 for k = 1:K1 i = (s-1)*K1+k; eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.EndoXnew(k,n,s);']); eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.EndoYnew(k,n,s);']); eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,3) = EndoZ1(k,s);']); end end end % Same for Epi for n = 1:N1epi for s = 1:S1epi for k = 1:K1epi i = (s-1)*K1epi+k; eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.EpiXnew(k,n,s);']); eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.EpiYnew(k,n,s);']); eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,3) = EpiZ1(k,s);']); end end end %Same for RV endo for n = 1:NRV1 for s = 1:SRV1 for k = 1:KRV1 i = (s-1)*KRV1+k; eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.RVEndoXnew(k,n,s);']); eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.RVEndoYnew(k,n,s);']); eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ1(k,s);']); end end end %% Create physical points from EndoX and EndoY for moving patient % Move RV after voxel-size adjustment (so that LV and RV don't overlap) baryCentreLVold2(1,1) = mean(mean(SEG2.EndoXnew(:,1,:))); baryCentreLVold2(1,2) = mean(mean(SEG2.EndoYnew(:,1,:))); %baryCentreLVold(1,3) = mean(mean(SEG_shift_resampled.ResolutionX*EndoZ)); baryCentreRVold2(1,1) = mean(mean(SEG2.RVEndoXnew(:,1,:))); baryCentreRVold2(1,2) = mean(mean(SEG2.RVEndoYnew(:,1,:))); %baryCentreRVold(1,3) = mean(mean(SEG_shift_resampled.ResolutionX*RVEndoZ)); directionBefore2 = baryCentreLVold2 - baryCentreRVold2; lengthDirectionBefore2 = sqrt(directionBefore2(1,1)^2 + directionBefore2(1,2)^2); moveInDirection2 = SEG2.ResolutionX * lengthDirectionBefore2 - lengthDirectionBefore2; for n = 1:N2 for s = 1:S2 for k = 1:K2 i = (s-1)*K2+k; eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.EndoXnew(k,n,s);']); eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.EndoYnew(k,n,s);']); eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,3) = EndoZ2(k,s);']); end end end % Same for Epi for n = 1:N2epi for s = 1:S2epi for k = 1:K2epi i = (s-1)*K2epi+k; eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.EpiXnew(k,n,s);']); eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.EpiYnew(k,n,s);']); eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,3) = EpiZ2(k,s);']); end end end % Same for RV Endo for n = 1:NRV2 for s = 1:SRV2 for k = 1:KRV2 i = (s-1)*KRV2+k; eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.RVEndoXnew(k,n,s);']); eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.RVEndoYnew(k,n,s);']); eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ2(k,s);']); end end end %% Compute transformation components (scaling, translation, rotation) % Compute barycentres (choose the 1st frame as the reference) baryCentreLV1(1,1) = mean(SEG1.EndoPoints.Frame1(:,1)); baryCentreLV1(1,2) = mean(SEG1.EndoPoints.Frame1(:,2)); baryCentreLV1(1,3) = mean(SEG1.EndoPoints.Frame1(:,3)); baryCentreRV1(1,1) = mean(SEG1.RVEndoPoints.Frame1(:,1)); baryCentreRV1(1,2) = mean(SEG1.RVEndoPoints.Frame1(:,2)); baryCentreRV1(1,3) = mean(SEG1.RVEndoPoints.Frame1(:,3)); baryCentreLV2(1,1) = mean(SEG2.EndoPoints.Frame1(:,1)); baryCentreLV2(1,2) = mean(SEG2.EndoPoints.Frame1(:,2)); baryCentreLV2(1,3) = mean(SEG2.EndoPoints.Frame1(:,3)); baryCentreRV2(1,1) = mean(SEG2.RVEndoPoints.Frame1(:,1)); baryCentreRV2(1,2) = mean(SEG2.RVEndoPoints.Frame1(:,2)); baryCentreRV2(1,3) = mean(SEG2.RVEndoPoints.Frame1(:,3)); % Get length of line segments joining LV centre and RV centre length1 = sqrt((abs(baryCentreLV1(1,1)-baryCentreRV1(1,1))^2 + ... abs(baryCentreLV1(1,2) - baryCentreRV1(1,2))^2 + ... abs(baryCentreLV1(1,3) - baryCentreRV1(1,3))^2)); length2 = sqrt((abs(baryCentreLV2(1,1)-baryCentreRV2(1,1))^2 + ... abs(baryCentreLV2(1,2) - baryCentreRV2(1,2))^2 + ... abs(baryCentreLV2(1,3) - baryCentreRV2(1,3))^2)); % Compute scaling factor between line segments scale = length1 / length2; % Compute translation (translate to match x-points) translation = baryCentreLV2-baryCentreLV1; %Copy to new struct SEG2new = SEG2; SEG1new = SEG1; %% Translate main axis of moving patient back to the origin for n = 1:N2 eval(['l = length(SEG2.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2.EndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Same for Epi for n = 1:N2epi eval(['l = length(SEG2.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2.EpiPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Same for RV Endo for n = 1:NRV2 eval(['l = length(SEG2.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2.RVEndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Do for fixed subject as well for n = 1:N1 eval(['l = length(SEG1.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.EndoPoints.Frame' int2str(n) '(i,:) = SEG1.EndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end % Same for Epi for n = 1:N1epi eval(['l = length(SEG1.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.EpiPoints.Frame' int2str(n) '(i,:) = SEG1.EpiPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end % Same for RV Endo for n = 1:NRV1 eval(['l = length(SEG1.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG1.RVEndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end %% Rotate baryCentreLV1new(1,1) = mean(SEG1new.EndoPoints.Frame1(1:80,1)); baryCentreLV1new(1,2) = mean(SEG1new.EndoPoints.Frame1(1:80,2)); baryCentreLV1new(1,3) = mean(SEG1new.EndoPoints.Frame1(1:80,3)); baryCentreRV1new(1,1) = mean(SEG1new.RVEndoPoints.Frame1(1:80,1)); baryCentreRV1new(1,2) = mean(SEG1new.RVEndoPoints.Frame1(1:80,2)); baryCentreRV1new(1,3) = mean(SEG1new.RVEndoPoints.Frame1(1:80,3)); baryCentreLV2new(1,1) = mean(SEG2new.EndoPoints.Frame1(1:80,1)); baryCentreLV2new(1,2) = mean(SEG2new.EndoPoints.Frame1(1:80,2)); baryCentreLV2new(1,3) = mean(SEG2new.EndoPoints.Frame1(1:80,3)); baryCentreRV2new(1,1) = mean(SEG2new.RVEndoPoints.Frame1(1:80,1)); baryCentreRV2new(1,2) = mean(SEG2new.RVEndoPoints.Frame1(1:80,2)); baryCentreRV2new(1,3) = mean(SEG2new.RVEndoPoints.Frame1(1:80,3)); baryCentreLV1normed = ((baryCentreRV1new-(baryCentreLV1new))); baryCentreLV2normed = ((baryCentreRV2new-(baryCentreLV2new))); % Compute angle of rotation between the line segments rotationAngle = acos((baryCentreLV1normed(1,1) * baryCentreLV2normed(1,1) + ... baryCentreLV1normed(1,2) * baryCentreLV2normed(1,2))/(... sqrt(baryCentreLV1normed(1,1)^2 + baryCentreLV1normed(1,2)^2) * ... sqrt(baryCentreLV2normed(1,1)^2 + baryCentreLV2normed(1,2)^2))); %rotationAngle = rotationAngle*180/pi; rotationMatrix = [cos(rotationAngle) sin(rotationAngle) 0; ... -sin(rotationAngle) cos(rotationAngle) 0; ... 0 0 1]; for n = 1:N2 eval(['l = length(SEG2new.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2new.EndoPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end % Same for Epi for n = 1:N2epi eval(['l = length(SEG2new.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2new.EpiPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end % Same for RV Endo for n = 1:NRV2 eval(['l = length(SEG2new.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end %% Translate to fit main axis of fixed patient for n = 1:N2 eval(['l = length(SEG2new.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2new.EndoPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end % Same for Epi for n = 1:N2epi eval(['l = length(SEG2new.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2new.EpiPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end % Same for RV Endo for n = 1:NRV2 eval(['l = length(SEG2new.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end else for n = 1 for s = 1:S1 for k = 1:K1 i = (s-1)*K1+k; eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.EndoXnew(k,n,s);']); eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.EndoYnew(k,n,s);']); eval(['SEG1.EndoPoints.Frame' int2str(n) '(i,3) = EndoZ1(k,s);']); end end end % Same for Epi for n = 1 for s = 1:S1epi for k = 1:K1epi i = (s-1)*K1epi+k; eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.EpiXnew(k,n,s);']); eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.EpiYnew(k,n,s);']); eval(['SEG1.EpiPoints.Frame' int2str(n) '(i,3) = EpiZ1(k,s);']); end end end %Same for RV endo for n = 1 for s = 1:SRV1 for k = 1:KRV1 i = (s-1)*KRV1+k; eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG1.ResolutionX*SEG1.RVEndoXnew(k,n,s);']); eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG1.ResolutionY*SEG1.RVEndoYnew(k,n,s);']); eval(['SEG1.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ1(k,s);']); end end end %% Create physical points from EndoX and EndoY for moving patient % Move RV after voxel-size adjustment (so that LV and RV don't overlap) baryCentreLVold2(1,1) = mean(mean(SEG2.EndoXnew(:,1,:))); baryCentreLVold2(1,2) = mean(mean(SEG2.EndoYnew(:,1,:))); baryCentreRVold2(1,1) = mean(mean(SEG2.RVEndoXnew(:,1,:))); baryCentreRVold2(1,2) = mean(mean(SEG2.RVEndoYnew(:,1,:))); directionBefore2 = baryCentreLVold2 - baryCentreRVold2; lengthDirectionBefore2 = sqrt(directionBefore2(1,1)^2 + directionBefore2(1,2)^2); moveInDirection2 = SEG2.ResolutionX * lengthDirectionBefore2 - lengthDirectionBefore2; for n = 1 for s = 1:S2 for k = 1:K2 i = (s-1)*K2+k; eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.EndoXnew(k,n,s);']); eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.EndoYnew(k,n,s);']); eval(['SEG2.EndoPoints.Frame' int2str(n) '(i,3) = EndoZ2(k,s);']); end end end % Same for Epi for n = 1 for s = 1:S2epi for k = 1:K2epi i = (s-1)*K2epi+k; eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.EpiXnew(k,n,s);']); eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.EpiYnew(k,n,s);']); eval(['SEG2.EpiPoints.Frame' int2str(n) '(i,3) = EpiZ2(k,s);']); end end end % Same for RV Endo for n = 1 for s = 1:SRV2 for k = 1:KRV2 i = (s-1)*KRV2+k; eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG2.ResolutionX*SEG2.RVEndoXnew(k,n,s);']); eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG2.ResolutionY*SEG2.RVEndoYnew(k,n,s);']); eval(['SEG2.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ2(k,s);']); end end end %% Compute transformation components (scaling, translation, rotation) % Compute barycentres (choose the 1st frame as the reference) baryCentreLV1(1,1) = mean(SEG1.EndoPoints.Frame1(:,1)); baryCentreLV1(1,2) = mean(SEG1.EndoPoints.Frame1(:,2)); baryCentreLV1(1,3) = mean(SEG1.EndoPoints.Frame1(:,3)); baryCentreRV1(1,1) = mean(SEG1.RVEndoPoints.Frame1(:,1)); baryCentreRV1(1,2) = mean(SEG1.RVEndoPoints.Frame1(:,2)); baryCentreRV1(1,3) = mean(SEG1.RVEndoPoints.Frame1(:,3)); baryCentreLV2(1,1) = mean(SEG2.EndoPoints.Frame1(:,1)); baryCentreLV2(1,2) = mean(SEG2.EndoPoints.Frame1(:,2)); baryCentreLV2(1,3) = mean(SEG2.EndoPoints.Frame1(:,3)); baryCentreRV2(1,1) = mean(SEG2.RVEndoPoints.Frame1(:,1)); baryCentreRV2(1,2) = mean(SEG2.RVEndoPoints.Frame1(:,2)); baryCentreRV2(1,3) = mean(SEG2.RVEndoPoints.Frame1(:,3)); % Get length of line segments joining LV centre and RV centre length1 = sqrt((abs(baryCentreLV1(1,1)-baryCentreRV1(1,1))^2 + ... abs(baryCentreLV1(1,2) - baryCentreRV1(1,2))^2 + ... abs(baryCentreLV1(1,3) - baryCentreRV1(1,3))^2)); length2 = sqrt((abs(baryCentreLV2(1,1)-baryCentreRV2(1,1))^2 + ... abs(baryCentreLV2(1,2) - baryCentreRV2(1,2))^2 + ... abs(baryCentreLV2(1,3) - baryCentreRV2(1,3))^2)); % Compute scaling factor between line segments scale = length1 / length2; % Compute translation (translate to match x-points) translation = baryCentreLV2-baryCentreLV1; %Copy to new struct SEG2new = SEG2; SEG1new = SEG1; %% Translate main axis of moving patient back to the origin for n = 1 eval(['l = length(SEG2.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2.EndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Same for Epi for n = 1 eval(['l = length(SEG2.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2.EpiPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Same for RV Endo for n = 1 eval(['l = length(SEG2.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2.RVEndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV2;']); end end % Do for fixed subject as well for n = 1 eval(['l = length(SEG1.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.EndoPoints.Frame' int2str(n) '(i,:) = SEG1.EndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end % Same for Epi for n = 1 eval(['l = length(SEG1.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.EpiPoints.Frame' int2str(n) '(i,:) = SEG1.EpiPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end % Same for RV Endo for n = 1 eval(['l = length(SEG1.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG1new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG1.RVEndoPoints.Frame' int2str(n) '(i,:) - baryCentreLV1;']); end end %% Rotate baryCentreLV1new(1,1) = mean(SEG1new.EndoPoints.Frame1(1:80,1)); baryCentreLV1new(1,2) = mean(SEG1new.EndoPoints.Frame1(1:80,2)); baryCentreLV1new(1,3) = mean(SEG1new.EndoPoints.Frame1(1:80,3)); baryCentreRV1new(1,1) = mean(SEG1new.RVEndoPoints.Frame1(1:80,1)); baryCentreRV1new(1,2) = mean(SEG1new.RVEndoPoints.Frame1(1:80,2)); baryCentreRV1new(1,3) = mean(SEG1new.RVEndoPoints.Frame1(1:80,3)); baryCentreLV2new(1,1) = mean(SEG2new.EndoPoints.Frame1(1:80,1)); baryCentreLV2new(1,2) = mean(SEG2new.EndoPoints.Frame1(1:80,2)); baryCentreLV2new(1,3) = mean(SEG2new.EndoPoints.Frame1(1:80,3)); baryCentreRV2new(1,1) = mean(SEG2new.RVEndoPoints.Frame1(1:80,1)); baryCentreRV2new(1,2) = mean(SEG2new.RVEndoPoints.Frame1(1:80,2)); baryCentreRV2new(1,3) = mean(SEG2new.RVEndoPoints.Frame1(1:80,3)); baryCentreLV1normed = ((baryCentreRV1new-(baryCentreLV1new))); baryCentreLV2normed = ((baryCentreRV2new-(baryCentreLV2new))); % Compute angle of rotation between the line segments rotationAngle = acos((baryCentreLV1normed(1,1) * baryCentreLV2normed(1,1) + ... baryCentreLV1normed(1,2) * baryCentreLV2normed(1,2))/(... sqrt(baryCentreLV1normed(1,1)^2 + baryCentreLV1normed(1,2)^2) * ... sqrt(baryCentreLV2normed(1,1)^2 + baryCentreLV2normed(1,2)^2))); %rotationAngle = rotationAngle*180/pi; rotationMatrix = [cos(rotationAngle) sin(rotationAngle) 0; ... -sin(rotationAngle) cos(rotationAngle) 0; ... 0 0 1]; for n = 1 eval(['l = length(SEG2new.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2new.EndoPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end % Same for Epi for n = 1 eval(['l = length(SEG2new.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2new.EpiPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end % Same for RV Endo for n = 1 eval(['l = length(SEG2new.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) * rotationMatrix;']); end end %% Translate to fit main axis of fixed patient for n = 1 eval(['l = length(SEG2new.EndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EndoPoints.Frame' int2str(n) '(i,:) = SEG2new.EndoPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end % Same for Epi for n = 1 eval(['l = length(SEG2new.EpiPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.EpiPoints.Frame' int2str(n) '(i,:) = SEG2new.EpiPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end % Same for RV Endo for n = 1 eval(['l = length(SEG2new.RVEndoPoints.Frame' int2str(n) ');']); for i = 1:l eval(['SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) = SEG2new.RVEndoPoints.Frame' int2str(n) '(i,:) + baryCentreLV1;']); end end end end
github
vildenst/3D-heart-models-master
cleanPointIndices.m
.m
3D-heart-models-master/Matlab_Process/cleanPointIndices.m
15,343
utf_8
c948ac7359010a8aadb16886e9176014
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % CLEAN POINT INDEXING % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Clean point indexing to make nicer meshes % Author - Kristin Mcleod (following from Eric Davennes work) % SIMULA Research Laboratory % Contact - [email protected] % October 2014 % Takes as input SEG_shift_resampled from temporalResample.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG_shift_clean = cleanPointIndices(SEG_shift,RVyes,IsFullTemporal) %% Get size info SEG_shift_clean = SEG_shift; sizen = size(SEG_shift.EndoXnew); K = sizen(1,1); %number of points in a segment contour N = sizen(1,2); %number of frames S = sizen(1,3); %number of slices sizenEpi = size(SEG_shift.EpiXnew); KEpi = sizenEpi(1,1); %number of points in a segment contour NEpi = sizenEpi(1,2); %number of frames SEpi = sizenEpi(1,3); %number of slices LVdist21Endo = zeros(1,K); LVdist21Epi = zeros(1,KEpi); if RVyes == 1 sizenRV = size(SEG_shift.RVEndoXnew); KRV = sizenRV(1,1); %number of points in a segment contour NRV = sizenRV(1,2); SRV = sizenRV(1,3); %number of slices RVEndoZ = repmat((1-(1:SRV))*(SEG_shift.SliceThickness+SEG_shift.SliceGap),... [KRV 1]); RVdist21Endo = zeros(1,KRV); end % SEG_shift_clean.EndoXnew = SEG_shift.EndoXnew; % SEG_shift_clean.EndoYnew = SEG_shift.EndoYnew; % SEG_shift_clean.EpiXnew = SEG_shift.EpiX; % SEG_shift_clean.EpiYnew = SEG_shift.EpiY; %% Compute squared distances and rearrange points %if IsFullTemporal == 1 refEndo = 1; % LV Endo for n=1:N % if n>1 % for j = 1:K % TestIndPrevFrameEndo(j) = (SEG_shift.EndoX(j, n, s) - SEG_shift.EndoX(refEndo, n-1, s))^2 + (SEG_shift.EndoY(j, n, s) - SEG_shift.EndoY(refEndo, n-1, s))^2; % end % [YTestEndo , indTestEndo] = min(TestIndPrevFrameEndo); % refEndo = indTestEndo; % end for s=S:-1:2 for k=1:K LVdist21Endo(k) = (SEG_shift.EndoXnew(refEndo, n, s) - SEG_shift.EndoXnew(k, n, s - 1))^2 + (SEG_shift.EndoYnew(refEndo, n, s) - SEG_shift.EndoYnew(k, n, s - 1))^2; end [YEndo , indEndo] = min(LVdist21Endo); indexEndo = indEndo; refEndo = indEndo; for l=1:K indexEndo = mod(indexEndo, K) + 1; SEG_shift_clean.EndoXnew(l, n, s-1) = SEG_shift.EndoXnew(indexEndo, n, s-1); SEG_shift_clean.EndoYnew(l, n, s-1) = SEG_shift.EndoYnew(indexEndo, n, s-1); end end end % LV Epi refEpi = 1; for n=1:NEpi % if n>1 % for j = 1:K % TestIndPrevFrameEpi(j) = (SEG_shift.EpiX(j, n, s) - SEG_shift.EpiX(refEpi, n-1, s))^2 + (SEG_shift.EpiY(j, n, s) - SEG_shift.EpiY(refEpi, n-1, s))^2; % end % [YTestEpi , indTestEpi] = min(TestIndPrevFrameEpi); % refEpi = indTestEpi; % end for s=SEpi:-1:2 for k=1:KEpi LVdist21Epi(k) = (SEG_shift.EpiXnew(refEpi, n, s) - SEG_shift.EpiXnew(k, n, s - 1))^2 + (SEG_shift.EpiYnew(refEpi, n, s) - SEG_shift.EpiYnew(k, n, s - 1))^2; end [YEpi , indEpi] = min(LVdist21Epi); indexEpi = indEpi; refEpi = indEpi; for l=1:KEpi indexEpi = mod(indexEpi, K) + 1; SEG_shift_clean.EpiXnew(l, n, s-1) = SEG_shift.EpiXnew(indexEpi, n, s-1); SEG_shift_clean.EpiYnew(l, n, s-1) = SEG_shift.EpiYnew(indexEpi, n, s-1); end end end % % To account for the irregular shape of the RV, start the cleaning from the % % centre and adjust indexing above then below % halfSliceRVED = round(SRV/2); % %RV ED % refRVED = 1; % for s=halfSliceRVED:-1:2 % for k=1:KRV % RVdist21EndoED(k) = (SEG_shift_resampled.RVEndoXED(refRVED, s) - SEG_shift_resampled.RVEndoXED(k, s-1))^2 + (SEG_shift_resampled.RVEndoYED(refRVED, s) - SEG_shift_resampled.RVEndoYED(k, s-1))^2; % end % [YRVED , indRVED] = min(RVdist21EndoED); % indexRVED = indRVED; % refRVED = indRVED; % for l=1:KRV % SEG_shift_clean.RVEndoXED(l, s-1) = SEG_shift_resampled.RVEndoXED(indexRVED, s-1); % SEG_shift_clean.RVEndoYED(l, s-1) = SEG_shift_resampled.RVEndoYED(indexRVED, s-1); % indexRVED = mod(indexRVED,KRV) + 1; % end % end % refRVED = 1; % for s=halfSliceRVED:SRV-1 % for k=1:KRV % RVdist21EndoED(k) = (SEG_shift_resampled.RVEndoXED(refRVED, s) - SEG_shift_resampled.RVEndoXED(k, s+1))^2 + (SEG_shift_resampled.RVEndoYED(refRVED, s) - SEG_shift_resampled.RVEndoYED(k, s+1))^2; % end % [YRVED , indRVED] = min(RVdist21EndoED); % indexRVED = indRVED; % refRVED = indRVED; % for l=1:KRV % SEG_shift_clean.RVEndoXED(l, s+1) = SEG_shift_resampled.RVEndoXED(indexRVED, s+1); % SEG_shift_clean.RVEndoYED(l, s+1) = SEG_shift_resampled.RVEndoYED(indexRVED, s+1); % indexRVED = mod(indexRVED,KRV) + 1; % end % end %RV if RVyes ==1 refRV = 1; for n = 1:NRV % if n>1 % for j = 1:K % TestIndPrevFrameRV(j) = (SEG_shift.RVEndoX(j, n, s) - SEG_shift.RVEndoX(refRV, n-1, s))^2 + (SEG_shift.RVEndoY(j, n, s) - SEG_shift.RVEndoY(refRV, n-1, s))^2; % end % [YTestRV , indTestRV] = min(TestIndPrevFrameRV); % refRV = indTestRV; % end for s=SRV:-1:2 for k=1:KRV RVdist21Endo(k) = (SEG_shift.RVEndoXnew(refRV, n, s) - SEG_shift.RVEndoXnew(k, n, s-1))^2 + (SEG_shift.RVEndoYnew(refRV, n, s) - SEG_shift.RVEndoYnew(k, n, s-1))^2; end [YRV , indRV] = min(RVdist21Endo); indexRV = indRV; refRV = indRV; for l=1:KRV SEG_shift_clean.RVEndoXnew(l, n, s-1) = SEG_shift.RVEndoXnew(indexRV, n, s-1); SEG_shift_clean.RVEndoYnew(l, n, s-1) = SEG_shift.RVEndoYnew(indexRV, n, s-1); indexRV = mod(indexRV,KRV) + 1; end end end end % %RV ES % refRVES = 1; % for s=SRVES:-1:2 % for k=1:KRVES % RVdist21EndoES(k) = (SEG_shift_resampled.RVEndoXES(refRVES, s) - SEG_shift_resampled.RVEndoXES(k, s-1))^2 + (SEG_shift_resampled.RVEndoYES(refRVES, s) - SEG_shift_resampled.RVEndoYES(k, s-1))^2; % end % [YRVES , indRVES] = min(RVdist21EndoES); % indexRVES = indRVES; % refRVES = indRVES; % for l=1:KRVES % SEG_shift_clean.RVEndoXES(l, s-1) = SEG_shift_resampled.RVEndoXES(indexRVES, s-1); % SEG_shift_clean.RVEndoYES(l, s-1) = SEG_shift_resampled.RVEndoYES(indexRVES, s-1); % indexRVES = mod(indexRVES,KRVES) + 1; % end % end % n = SEG_shift_clean.EDT; % for s = 1:SRV % for k = 1:KRV % i = (s-1)*KRV+k; % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG_shift_clean.RVEndoXED(k,s);']); % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG_shift_clean.RVEndoYED(k,s);']); % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ(k,s);']); % end % end % n = SEG_shift_clean.EST; % for s = 1:SRV % for k = 1:KRV % i = (s-1)*KRV+k; % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG_shift_clean.RVEndoXES(k,s);']); % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG_shift_clean.RVEndoYES(k,s);']); % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZES(k,s);']); % end % end % else % refEndo = 1; % % LV Endo % for n=1 % % if n>1 % % for j = 1:K % % TestIndPrevFrameEndo(j) = (SEG_shift.EndoX(j, n, s) - SEG_shift.EndoX(refEndo, n-1, s))^2 + (SEG_shift.EndoY(j, n, s) - SEG_shift.EndoY(refEndo, n-1, s))^2; % % end % % [YTestEndo , indTestEndo] = min(TestIndPrevFrameEndo); % % refEndo = indTestEndo; % % end % for s=S:-1:2 % for k=1:K % LVdist21Endo(k) = (SEG_shift.EndoX(refEndo, n, s) - SEG_shift.EndoX(k, n, s - 1))^2 + (SEG_shift.EndoY(refEndo, n, s) - SEG_shift.EndoY(k, n, s - 1))^2; % end % [YEndo , indEndo] = min(LVdist21Endo); % indexEndo = indEndo; % refEndo = indEndo; % for l=1:K % indexEndo = mod(indexEndo, K) + 1; % SEG_shift_clean.EndoXnew(l, n, s-1) = SEG_shift.EndoX(indexEndo, n, s-1); % SEG_shift_clean.EndoYnew(l, n, s-1) = SEG_shift.EndoY(indexEndo, n, s-1); % end % end % end % % % LV Epi % refEpi = 1; % for n=1 % % if n>1 % % for j = 1:K % % TestIndPrevFrameEpi(j) = (SEG_shift.EpiX(j, n, s) - SEG_shift.EpiX(refEpi, n-1, s))^2 + (SEG_shift.EpiY(j, n, s) - SEG_shift.EpiY(refEpi, n-1, s))^2; % % end % % [YTestEpi , indTestEpi] = min(TestIndPrevFrameEpi); % % refEpi = indTestEpi; % % end % for s=SEpi:-1:2 % for k=1:KEpi % LVdist21Epi(k) = (SEG_shift.EpiX(refEpi, n, s) - SEG_shift.EpiX(k, n, s - 1))^2 + (SEG_shift.EpiY(refEpi, n, s) - SEG_shift.EpiY(k, n, s - 1))^2; % end % [YEpi , indEpi] = min(LVdist21Epi); % indexEpi = indEpi; % refEpi = indEpi; % for l=1:KEpi % indexEpi = mod(indexEpi, K) + 1; % SEG_shift_clean.EpiXnew(l, n, s-1) = SEG_shift.EpiX(indexEpi, n, s-1); % SEG_shift_clean.EpiYnew(l, n, s-1) = SEG_shift.EpiY(indexEpi, n, s-1); % end % end % end % % % % To account for the irregular shape of the RV, start the cleaning from the % % % centre and adjust indexing above then below % % halfSliceRVED = round(SRV/2); % % %RV ED % % refRVED = 1; % % for s=halfSliceRVED:-1:2 % % for k=1:KRV % % RVdist21EndoED(k) = (SEG_shift_resampled.RVEndoXED(refRVED, s) - SEG_shift_resampled.RVEndoXED(k, s-1))^2 + (SEG_shift_resampled.RVEndoYED(refRVED, s) - SEG_shift_resampled.RVEndoYED(k, s-1))^2; % % end % % [YRVED , indRVED] = min(RVdist21EndoED); % % indexRVED = indRVED; % % refRVED = indRVED; % % for l=1:KRV % % SEG_shift_clean.RVEndoXED(l, s-1) = SEG_shift_resampled.RVEndoXED(indexRVED, s-1); % % SEG_shift_clean.RVEndoYED(l, s-1) = SEG_shift_resampled.RVEndoYED(indexRVED, s-1); % % indexRVED = mod(indexRVED,KRV) + 1; % % end % % end % % refRVED = 1; % % for s=halfSliceRVED:SRV-1 % % for k=1:KRV % % RVdist21EndoED(k) = (SEG_shift_resampled.RVEndoXED(refRVED, s) - SEG_shift_resampled.RVEndoXED(k, s+1))^2 + (SEG_shift_resampled.RVEndoYED(refRVED, s) - SEG_shift_resampled.RVEndoYED(k, s+1))^2; % % end % % [YRVED , indRVED] = min(RVdist21EndoED); % % indexRVED = indRVED; % % refRVED = indRVED; % % for l=1:KRV % % SEG_shift_clean.RVEndoXED(l, s+1) = SEG_shift_resampled.RVEndoXED(indexRVED, s+1); % % SEG_shift_clean.RVEndoYED(l, s+1) = SEG_shift_resampled.RVEndoYED(indexRVED, s+1); % % indexRVED = mod(indexRVED,KRV) + 1; % % end % % end % % %RV % if RVyes ==1 % refRV = 1; % for n = 1 % % if n>1 % % for j = 1:K % % TestIndPrevFrameRV(j) = (SEG_shift.RVEndoX(j, n, s) - SEG_shift.RVEndoX(refRV, n-1, s))^2 + (SEG_shift.RVEndoY(j, n, s) - SEG_shift.RVEndoY(refRV, n-1, s))^2; % % end % % [YTestRV , indTestRV] = min(TestIndPrevFrameRV); % % refRV = indTestRV; % % end % for s=SRV:-1:2 % for k=1:KRV % RVdist21Endo(k) = (SEG_shift.RVEndoX(refRV, n, s) - SEG_shift.RVEndoX(k, n, s-1))^2 + (SEG_shift.RVEndoY(refRV, n, s) - SEG_shift.RVEndoY(k, n, s-1))^2; % end % [YRV , indRV] = min(RVdist21Endo); % indexRV = indRV; % refRV = indRV; % for l=1:KRV % SEG_shift_clean.RVEndoXnew(l, n, s-1) = SEG_shift.RVEndoX(indexRV, n, s-1); % SEG_shift_clean.RVEndoYnew(l, n, s-1) = SEG_shift.RVEndoY(indexRV, n, s-1); % indexRV = mod(indexRV,KRV) + 1; % end % end % end % end % % %RV ES % % refRVES = 1; % % for s=SRVES:-1:2 % % for k=1:KRVES % % RVdist21EndoES(k) = (SEG_shift_resampled.RVEndoXES(refRVES, s) - SEG_shift_resampled.RVEndoXES(k, s-1))^2 + (SEG_shift_resampled.RVEndoYES(refRVES, s) - SEG_shift_resampled.RVEndoYES(k, s-1))^2; % % end % % [YRVES , indRVES] = min(RVdist21EndoES); % % indexRVES = indRVES; % % refRVES = indRVES; % % for l=1:KRVES % % SEG_shift_clean.RVEndoXES(l, s-1) = SEG_shift_resampled.RVEndoXES(indexRVES, s-1); % % SEG_shift_clean.RVEndoYES(l, s-1) = SEG_shift_resampled.RVEndoYES(indexRVES, s-1); % % indexRVES = mod(indexRVES,KRVES) + 1; % % end % % end % % % n = SEG_shift_clean.EDT; % % for s = 1:SRV % % for k = 1:KRV % % i = (s-1)*KRV+k; % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG_shift_clean.RVEndoXED(k,s);']); % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG_shift_clean.RVEndoYED(k,s);']); % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ(k,s);']); % % end % % end % % n = SEG_shift_clean.EST; % % for s = 1:SRV % % for k = 1:KRV % % i = (s-1)*KRV+k; % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG_shift_clean.RVEndoXES(k,s);']); % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG_shift_clean.RVEndoYES(k,s);']); % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZES(k,s);']); % % end % % end %end clear n s k j i N S K NEpi SEpi KEpi SRV KRV SRVES KRVES YRV YEpi YEndo YTestEpi YTestEndo YTestRV end
github
vildenst/3D-heart-models-master
notTemporalResampleAlignment.m
.m
3D-heart-models-master/Matlab_Process/notTemporalResampleAlignment.m
3,203
utf_8
fe8bca106d0f1d6f62541ffb47586dc0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % TEMPORAL RESAMPLING OF POINT CLOUD WITH TEMPORAL ALIGNMENT TO ES PHASE % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Resample point cloud to have 30 frames using interpolation between points % Author - Kristin Mcleod % SIMULA Research Laboratory % Contact - [email protected] % October 2014 % Takes as input SEG_shift from sliceAlignment.m, and the number of desired % time points N %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG_shift_resampled = notTemporalResampleAlignment(SEG_shift_clean,RVyes) SEG_shift_resampled = SEG_shift_clean; % Pre-assign output SEG_shift = SEG_shift_clean; SEG_shift_resampled.EndoXnew = []; SEG_shift_resampled.EndoYnew = []; SEG_shift_resampled.EpiXnew = []; SEG_shift_resampled.EpiYnew = []; if RVyes == 1 SEG_shift_resampled.RVEndoXnew = []; SEG_shift_resampled.RVEndoYnew = []; sizenRV=size(SEG_shift.RVEndoXnew); KRV = sizenRV(1, 1); %No. of points (default 80) SRV = sizenRV(1, 3); %No. of slices end sizen=size(SEG_shift.EndoXnew); K = sizen(1, 1); %No. of points (default 80) S = sizen(1, 3); %No. of slices sizenEpi=size(SEG_shift.EpiXnew); KEpi = sizenEpi(1, 1); %No. of points (default 80) SEpi = sizenEpi(1, 3); %No. of slices for s = 1:S for k = 1:K EndoX(:,:)=SEG_shift.EndoXnew(:,:,s); EndoY(:,:)=SEG_shift.EndoYnew(:,:,s); endo = sum(EndoX,2); % Remove NaN values in the array if ~isnan(endo(k,1)) tmp1(k,:) = EndoX(k,:); tmp2(k,:) = EndoY(k,:); for n = 1 SEG_shift_resampled.EndoXnew(k,n,s) = tmp1(k,n); SEG_shift_resampled.EndoYnew(k,n,s) = tmp2(k,n); end end end end for s = 1:SEpi for k = 1:KEpi EpiX(:,:)=SEG_shift.EpiXnew(:,:,s); EpiY(:,:)=SEG_shift.EpiYnew(:,:,s); epi = sum(EpiX,2); % Remove NaN values in the array if ~isnan(epi(k,1)) tmp1(k,:) = EpiX(k,:); tmp2(k,:) = EpiY(k,:); for n = 1 SEG_shift_resampled.EpiXnew(k,n,s) = tmp1(k,n); SEG_shift_resampled.EpiYnew(k,n,s) = tmp2(k,n); end end end end if RVyes == 1 for s = 1:SRV for k = 1:KRV RVEndoX(:,:)=SEG_shift.RVEndoXnew(:,:,s); RVEndoY(:,:)=SEG_shift.RVEndoYnew(:,:,s); rv = sum(RVEndoX,2); % Remove NaN values in the array if ~isnan(rv(k,1)) tmp1(k,:) = RVEndoX(k,:); tmp2(k,:) = RVEndoY(k,:); for n = 1 SEG_shift_resampled.RVEndoXnew(k,n,s) = tmp1(k,n); SEG_shift_resampled.RVEndoYnew(k,n,s) = tmp2(k,n); end end end end end clear EndoX EndoY EpiX EpiY RVEndoX RVEndoY tmp1 tmp2 end
github
vildenst/3D-heart-models-master
cleanPointIndiceswithBivEpi.m
.m
3D-heart-models-master/Matlab_Process/cleanPointIndiceswithBivEpi.m
17,540
utf_8
0b35d1c10b75c3d2ecd05bcb56ca1db5
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % CLEAN POINT INDEXING % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Clean point indexing to make nicer meshes % Author - Kristin Mcleod (following from Eric Davennes work) % SIMULA Research Laboratory % Contact - [email protected], [email protected] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function SEG_shift_clean = cleanPointIndiceswithBivEpi(SEG_shift,RVyes,IsFullTemporal) %% Get size info SEG_shift_clean = SEG_shift; sizen = size(SEG_shift.EndoXnew); K = sizen(1,1); %number of points in a segment contour N = sizen(1,2); %number of frames S = sizen(1,3); %number of slices sizenEpi = size(SEG_shift.EpiXnew); KEpi = sizenEpi(1,1); %number of points in a segment contour NEpi = sizenEpi(1,2); %number of frames SEpi = sizenEpi(1,3); %number of slices LVdist21Endo = zeros(1,K); LVdist21Epi = zeros(1,KEpi); if RVyes == 1 sizenRV = size(SEG_shift.RVEndoXnew); KRV = sizenRV(1,1); %number of points in a segment contour NRV = sizenRV(1,2); SRV = sizenRV(1,3); %number of slices sizenRVEpi = size(SEG_shift.RVEpiXnew); KRVEpi = sizenRVEpi(1,1); %number of points in a segment contour NRVEpi = sizenRVEpi(1,2); SRVEpi = sizenRVEpi(1,3); %number of slices RVdist21Endo = zeros(1,KRV); RVdist21Epi = zeros(1,KRVEpi); % RVEndoZ = repmat((1-(1:SRV))*(SEG_shift.SliceThickness+SEG_shift.SliceGap),... % [KRV 1]); % RVEpiZ = repmat((1-(1:SRVEpi))*(SEG_shift.SliceThickness+SEG_shift.SliceGap),... % [KRVEpi 1]); end % SEG_shift_clean.EndoXnew = SEG_shift.EndoXnew; % SEG_shift_clean.EndoYnew = SEG_shift.EndoYnew; % SEG_shift_clean.EpiXnew = SEG_shift.EpiX; % SEG_shift_clean.EpiYnew = SEG_shift.EpiY; %% Compute squared distances and rearrange points %if IsFullTemporal == 1 % EndoLV refEndo = 1; for n=1:N % if n>1 % for j = 1:K % TestIndPrevFrameEndo(j) = (SEG_shift.EndoX(j, n, s) - SEG_shift.EndoX(refEndo, n-1, s))^2 + (SEG_shift.EndoY(j, n, s) - SEG_shift.EndoY(refEndo, n-1, s))^2; % end % [YTestEndo , indTestEndo] = min(TestIndPrevFrameEndo); % refEndo = indTestEndo; % end for s=S:-1:2 for k=1:K LVdist21Endo(k) = (SEG_shift.EndoXnew(refEndo, n, s) - ... SEG_shift.EndoXnew(k, n, s - 1))^2 + ... (SEG_shift.EndoYnew(refEndo, n, s) - ... SEG_shift.EndoYnew(k, n, s - 1))^2; end [~, indEndo] = min(LVdist21Endo); indexEndo = indEndo; refEndo = indEndo; for l=1:K indexEndo = mod(indexEndo, K) + 1; SEG_shift_clean.EndoXnew(l, n, s-1) = ... SEG_shift.EndoXnew(indexEndo, n, s-1); SEG_shift_clean.EndoYnew(l, n, s-1) = ... SEG_shift.EndoYnew(indexEndo, n, s-1); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % EpiLV refEpi = 1; for n=1:NEpi % if n>1 % for j = 1:K % TestIndPrevFrameEpi(j) = (SEG_shift.EpiX(j, n, s) - SEG_shift.EpiX(refEpi, n-1, s))^2 + (SEG_shift.EpiY(j, n, s) - SEG_shift.EpiY(refEpi, n-1, s))^2; % end % [YTestEpi , indTestEpi] = min(TestIndPrevFrameEpi); % refEpi = indTestEpi; % end for s=SEpi:-1:2 for k=1:KEpi LVdist21Epi(k) = (SEG_shift.EpiXnew(refEpi, n, s) -... SEG_shift.EpiXnew(k, n, s - 1))^2 + ... (SEG_shift.EpiYnew(refEpi, n, s) - ... SEG_shift.EpiYnew(k, n, s - 1))^2; end [~, indEpi] = min(LVdist21Epi); indexEpi = indEpi; refEpi = indEpi; for l=1:KEpi indexEpi = mod(indexEpi, K) + 1; SEG_shift_clean.EpiXnew(l, n, s-1) = ... SEG_shift.EpiXnew(indexEpi, n, s-1); SEG_shift_clean.EpiYnew(l, n, s-1) = ... SEG_shift.EpiYnew(indexEpi, n, s-1); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % To account for the irregular shape of the RV, start the cleaning from the % % centre and adjust indexing above then below % halfSliceRVED = round(SRV/2); % %RV ED % refRVED = 1; % for s=halfSliceRVED:-1:2 % for k=1:KRV % RVdist21EndoED(k) = (SEG_shift_resampled.RVEndoXED(refRVED, s) - SEG_shift_resampled.RVEndoXED(k, s-1))^2 + (SEG_shift_resampled.RVEndoYED(refRVED, s) - SEG_shift_resampled.RVEndoYED(k, s-1))^2; % end % [YRVED , indRVED] = min(RVdist21EndoED); % indexRVED = indRVED; % refRVED = indRVED; % for l=1:KRV % SEG_shift_clean.RVEndoXED(l, s-1) = SEG_shift_resampled.RVEndoXED(indexRVED, s-1); % SEG_shift_clean.RVEndoYED(l, s-1) = SEG_shift_resampled.RVEndoYED(indexRVED, s-1); % indexRVED = mod(indexRVED,KRV) + 1; % end % end % refRVED = 1; % for s=halfSliceRVED:SRV-1 % for k=1:KRV % RVdist21EndoED(k) = (SEG_shift_resampled.RVEndoXED(refRVED, s) - SEG_shift_resampled.RVEndoXED(k, s+1))^2 + (SEG_shift_resampled.RVEndoYED(refRVED, s) - SEG_shift_resampled.RVEndoYED(k, s+1))^2; % end % [YRVED , indRVED] = min(RVdist21EndoED); % indexRVED = indRVED; % refRVED = indRVED; % for l=1:KRV % SEG_shift_clean.RVEndoXED(l, s+1) = SEG_shift_resampled.RVEndoXED(indexRVED, s+1); % SEG_shift_clean.RVEndoYED(l, s+1) = SEG_shift_resampled.RVEndoYED(indexRVED, s+1); % indexRVED = mod(indexRVED,KRV) + 1; % end % end % EndoRV if RVyes ==1 refRV = 1; for n = 1:NRV % if n>1 % for j = 1:K % TestIndPrevFrameRV(j) = (SEG_shift.RVEndoX(j, n, s) - SEG_shift.RVEndoX(refRV, n-1, s))^2 + (SEG_shift.RVEndoY(j, n, s) - SEG_shift.RVEndoY(refRV, n-1, s))^2; % end % [YTestRV , indTestRV] = min(TestIndPrevFrameRV); % refRV = indTestRV; % end for s=SRV:-1:2 for k=1:KRV RVdist21Endo(k) = (SEG_shift.RVEndoXnew(refRV, n, s) - ... SEG_shift.RVEndoXnew(k, n, s-1))^2 + ... (SEG_shift.RVEndoYnew(refRV, n, s) - ... SEG_shift.RVEndoYnew(k, n, s-1))^2; end [~, indRV] = min(RVdist21Endo); indexRV = indRV; refRV = indRV; for l=1:KRV SEG_shift_clean.RVEndoXnew(l, n, s-1) = ... SEG_shift.RVEndoXnew(indexRV, n, s-1); SEG_shift_clean.RVEndoYnew(l, n, s-1) = ... SEG_shift.RVEndoYnew(indexRV, n, s-1); indexRV = mod(indexRV,KRV) + 1; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % EpiRV refRVEpi = 1; for n = 1:NRVEpi % if n>1 % for j = 1:K % TestIndPrevFrameRV(j) = (SEG_shift.RVEndoX(j, n, s) - SEG_shift.RVEndoX(refRV, n-1, s))^2 + (SEG_shift.RVEndoY(j, n, s) - SEG_shift.RVEndoY(refRV, n-1, s))^2; % end % [YTestRV , indTestRV] = min(TestIndPrevFrameRV); % refRV = indTestRV; % end for s=SRVEpi:-1:2 for k=1:KRVEpi RVdist21Epi(k) = (SEG_shift.RVEpiXnew(refRVEpi, n, s) - ... SEG_shift.RVEpiXnew(k, n, s-1))^2 + ... (SEG_shift.RVEpiYnew(refRVEpi, n, s) - ... SEG_shift.RVEpiYnew(k, n, s-1))^2; end [~, indRVEpi] = min(RVdist21Epi); indexRVEpi = indRVEpi; refRVEpi = indRVEpi; for l=1:KRVEpi SEG_shift_clean.RVEpiXnew(l, n, s-1) = ... SEG_shift.RVEpiXnew(indexRVEpi, n, s-1); SEG_shift_clean.RVEpiYnew(l, n, s-1) = ... SEG_shift.RVEpiYnew(indexRVEpi, n, s-1); indexRVEpi = mod(indexRVEpi,KRVEpi) + 1; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end % %RV ES % refRVES = 1; % for s=SRVES:-1:2 % for k=1:KRVES % RVdist21EndoES(k) = (SEG_shift_resampled.RVEndoXES(refRVES, s) - SEG_shift_resampled.RVEndoXES(k, s-1))^2 + (SEG_shift_resampled.RVEndoYES(refRVES, s) - SEG_shift_resampled.RVEndoYES(k, s-1))^2; % end % [YRVES , indRVES] = min(RVdist21EndoES); % indexRVES = indRVES; % refRVES = indRVES; % for l=1:KRVES % SEG_shift_clean.RVEndoXES(l, s-1) = SEG_shift_resampled.RVEndoXES(indexRVES, s-1); % SEG_shift_clean.RVEndoYES(l, s-1) = SEG_shift_resampled.RVEndoYES(indexRVES, s-1); % indexRVES = mod(indexRVES,KRVES) + 1; % end % end % n = SEG_shift_clean.EDT; % for s = 1:SRV % for k = 1:KRV % i = (s-1)*KRV+k; % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG_shift_clean.RVEndoXED(k,s);']); % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG_shift_clean.RVEndoYED(k,s);']); % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ(k,s);']); % end % end % n = SEG_shift_clean.EST; % for s = 1:SRV % for k = 1:KRV % i = (s-1)*KRV+k; % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG_shift_clean.RVEndoXES(k,s);']); % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG_shift_clean.RVEndoYES(k,s);']); % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZES(k,s);']); % end % end % else % refEndo = 1; % % LV Endo % for n=1 % % if n>1 % % for j = 1:K % % TestIndPrevFrameEndo(j) = (SEG_shift.EndoX(j, n, s) - SEG_shift.EndoX(refEndo, n-1, s))^2 + (SEG_shift.EndoY(j, n, s) - SEG_shift.EndoY(refEndo, n-1, s))^2; % % end % % [YTestEndo , indTestEndo] = min(TestIndPrevFrameEndo); % % refEndo = indTestEndo; % % end % for s=S:-1:2 % for k=1:K % LVdist21Endo(k) = (SEG_shift.EndoX(refEndo, n, s) - SEG_shift.EndoX(k, n, s - 1))^2 + (SEG_shift.EndoY(refEndo, n, s) - SEG_shift.EndoY(k, n, s - 1))^2; % end % [YEndo , indEndo] = min(LVdist21Endo); % indexEndo = indEndo; % refEndo = indEndo; % for l=1:K % indexEndo = mod(indexEndo, K) + 1; % SEG_shift_clean.EndoXnew(l, n, s-1) = SEG_shift.EndoX(indexEndo, n, s-1); % SEG_shift_clean.EndoYnew(l, n, s-1) = SEG_shift.EndoY(indexEndo, n, s-1); % end % end % end % % % LV Epi % refEpi = 1; % for n=1 % % if n>1 % % for j = 1:K % % TestIndPrevFrameEpi(j) = (SEG_shift.EpiX(j, n, s) - SEG_shift.EpiX(refEpi, n-1, s))^2 + (SEG_shift.EpiY(j, n, s) - SEG_shift.EpiY(refEpi, n-1, s))^2; % % end % % [YTestEpi , indTestEpi] = min(TestIndPrevFrameEpi); % % refEpi = indTestEpi; % % end % for s=SEpi:-1:2 % for k=1:KEpi % LVdist21Epi(k) = (SEG_shift.EpiX(refEpi, n, s) - SEG_shift.EpiX(k, n, s - 1))^2 + (SEG_shift.EpiY(refEpi, n, s) - SEG_shift.EpiY(k, n, s - 1))^2; % end % [YEpi , indEpi] = min(LVdist21Epi); % indexEpi = indEpi; % refEpi = indEpi; % for l=1:KEpi % indexEpi = mod(indexEpi, K) + 1; % SEG_shift_clean.EpiXnew(l, n, s-1) = SEG_shift.EpiX(indexEpi, n, s-1); % SEG_shift_clean.EpiYnew(l, n, s-1) = SEG_shift.EpiY(indexEpi, n, s-1); % end % end % end % % % % To account for the irregular shape of the RV, start the cleaning from the % % % centre and adjust indexing above then below % % halfSliceRVED = round(SRV/2); % % %RV ED % % refRVED = 1; % % for s=halfSliceRVED:-1:2 % % for k=1:KRV % % RVdist21EndoED(k) = (SEG_shift_resampled.RVEndoXED(refRVED, s) - SEG_shift_resampled.RVEndoXED(k, s-1))^2 + (SEG_shift_resampled.RVEndoYED(refRVED, s) - SEG_shift_resampled.RVEndoYED(k, s-1))^2; % % end % % [YRVED , indRVED] = min(RVdist21EndoED); % % indexRVED = indRVED; % % refRVED = indRVED; % % for l=1:KRV % % SEG_shift_clean.RVEndoXED(l, s-1) = SEG_shift_resampled.RVEndoXED(indexRVED, s-1); % % SEG_shift_clean.RVEndoYED(l, s-1) = SEG_shift_resampled.RVEndoYED(indexRVED, s-1); % % indexRVED = mod(indexRVED,KRV) + 1; % % end % % end % % refRVED = 1; % % for s=halfSliceRVED:SRV-1 % % for k=1:KRV % % RVdist21EndoED(k) = (SEG_shift_resampled.RVEndoXED(refRVED, s) - SEG_shift_resampled.RVEndoXED(k, s+1))^2 + (SEG_shift_resampled.RVEndoYED(refRVED, s) - SEG_shift_resampled.RVEndoYED(k, s+1))^2; % % end % % [YRVED , indRVED] = min(RVdist21EndoED); % % indexRVED = indRVED; % % refRVED = indRVED; % % for l=1:KRV % % SEG_shift_clean.RVEndoXED(l, s+1) = SEG_shift_resampled.RVEndoXED(indexRVED, s+1); % % SEG_shift_clean.RVEndoYED(l, s+1) = SEG_shift_resampled.RVEndoYED(indexRVED, s+1); % % indexRVED = mod(indexRVED,KRV) + 1; % % end % % end % % %RV % if RVyes ==1 % refRV = 1; % for n = 1 % % if n>1 % % for j = 1:K % % TestIndPrevFrameRV(j) = (SEG_shift.RVEndoX(j, n, s) - SEG_shift.RVEndoX(refRV, n-1, s))^2 + (SEG_shift.RVEndoY(j, n, s) - SEG_shift.RVEndoY(refRV, n-1, s))^2; % % end % % [YTestRV , indTestRV] = min(TestIndPrevFrameRV); % % refRV = indTestRV; % % end % for s=SRV:-1:2 % for k=1:KRV % RVdist21Endo(k) = (SEG_shift.RVEndoX(refRV, n, s) - SEG_shift.RVEndoX(k, n, s-1))^2 + (SEG_shift.RVEndoY(refRV, n, s) - SEG_shift.RVEndoY(k, n, s-1))^2; % end % [YRV , indRV] = min(RVdist21Endo); % indexRV = indRV; % refRV = indRV; % for l=1:KRV % SEG_shift_clean.RVEndoXnew(l, n, s-1) = SEG_shift.RVEndoX(indexRV, n, s-1); % SEG_shift_clean.RVEndoYnew(l, n, s-1) = SEG_shift.RVEndoY(indexRV, n, s-1); % indexRV = mod(indexRV,KRV) + 1; % end % end % end % end % % %RV ES % % refRVES = 1; % % for s=SRVES:-1:2 % % for k=1:KRVES % % RVdist21EndoES(k) = (SEG_shift_resampled.RVEndoXES(refRVES, s) - SEG_shift_resampled.RVEndoXES(k, s-1))^2 + (SEG_shift_resampled.RVEndoYES(refRVES, s) - SEG_shift_resampled.RVEndoYES(k, s-1))^2; % % end % % [YRVES , indRVES] = min(RVdist21EndoES); % % indexRVES = indRVES; % % refRVES = indRVES; % % for l=1:KRVES % % SEG_shift_clean.RVEndoXES(l, s-1) = SEG_shift_resampled.RVEndoXES(indexRVES, s-1); % % SEG_shift_clean.RVEndoYES(l, s-1) = SEG_shift_resampled.RVEndoYES(indexRVES, s-1); % % indexRVES = mod(indexRVES,KRVES) + 1; % % end % % end % % % n = SEG_shift_clean.EDT; % % for s = 1:SRV % % for k = 1:KRV % % i = (s-1)*KRV+k; % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG_shift_clean.RVEndoXED(k,s);']); % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG_shift_clean.RVEndoYED(k,s);']); % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZ(k,s);']); % % end % % end % % n = SEG_shift_clean.EST; % % for s = 1:SRV % % for k = 1:KRV % % i = (s-1)*KRV+k; % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,1) = SEG_shift_clean.RVEndoXES(k,s);']); % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,2) = SEG_shift_clean.RVEndoYES(k,s);']); % % eval(['SEG_shift_clean.RVEndoPoints.Frame' int2str(n) '(i,3) = RVEndoZES(k,s);']); % % end % % end %end clear n s k j i N S K NEpi SEpi KEpi SRV KRV SRVES KRVES YRV YEpi YEndo... YTestEpi YTestEndo YTestRV end
github
vildenst/3D-heart-models-master
fillWedge.m
.m
3D-heart-models-master/Matlab_Process/Bullseye/fillWedge.m
1,991
utf_8
151b6cdd2780385e92dc40c7409c490d
% PATCHCHIDLREN = FILLWEDGE(vec,rho1,rho2,theta1,theta2) creates a % wedge "patch" using xdata/ydata from a polar plot. The color of the patch % is determined scaled by the value of the vector. To be used with % createBullseye. In order to not have the vector automatically scaled, the % max of the vector should not be larger than 1. % % -vec: 1XN vector corresponding to the color of the patch % -rho1/2: Inner/outer radius of the wedge, respectively % -theta1/theta2: Start/end angle of wedge, in degrees % % The maximum wedge size is 359.99 degrees. % % ========================================================================= % Adrian Lam Oshinski Lab % August 4 2014 % ========================================================================= function patchChildren = fillWedge(vec,theta1,theta2,rho1,rho2) if length(vec) > 1 dtheta = (theta2 - theta1)/(length(vec)); else dtheta = (theta2 - theta1); end scale = 1; for i = 1:length(vec) if dtheta == 360 if rho1 == 0 t = 0:0.01:2*pi; x = sin(t) * rho2; y = cos(t) * rho2; else t = 0:0.01:2*pi; x = [ sin(t) * rho1 sin(t) * rho2 0 ]; y = [ cos(t) * rho1 cos(t) * rho2 0 ]; end else theta1 + dtheta*(i-1); [theta,rho] = getWedgeBorder(theta1 + dtheta*(i-1), ... theta1 + dtheta*i,rho1,rho2); [x,y] = pol2cart(theta,rho); end p = patch(x,y,[vec(i)]/scale); set( p,'EdgeAlpha',0); end tmp = findall(gca,'Type','patch'); patchChildren = tmp(1:length(vec)); end
github
vildenst/3D-heart-models-master
createBullseye.m
.m
3D-heart-models-master/Matlab_Process/Bullseye/createBullseye.m
2,354
utf_8
28986c77cb08e385bce379f26f906fa6
function bullseyeChild = createBullseye(data) % CREATEBULLSEYE creates a bullseye, with the main function of creating % an AHA 17 segment bullseye. Each row in "data" should have the % following structure: % % [rho1, rho2, nSegs, thetaStart] % % where % -rho1 is the inner radius % -rho2 is the outer radius % -nSegs is the number of segments desired per ring % -thetaStart is the starting angle of a segment (in degrees) % % Example: createBullseye([0 0.5 1 0; 0.5 1 4 45; ... % 1 1.5 6 0; 1.5 2 6 0]); % This creates the AHA 17-segment bullseye. % % ========================================================================= % Adrian Lam Oshinski Lab % August 4 2014 % ========================================================================= sz = size(data); ax = gca; hold(ax,'on'); count = 0; for i = 1:sz(1) % min number of segments must be at least 1 if data(i,3) == 0 data(i,3) = 1; end for j = 1:data(i,3) wedgeSize = 360/data(i,3); createWedge(j*wedgeSize + data(i,4), ... (j+1)*wedgeSize + data(i,4), ... data(i,1),data(i,2)); count = count+1; end end set(ax,'YTick',[],'XTick',[], ... 'XLim',[-max(data(:,2))-1 max(data(:,2))+1], ... 'YLim',[-max(data(:,2))-1 max(data(:,2))+1] ) ; tmp = findall(gca,'Type','line'); bullseyeChild = tmp(1:count); set(bullseyeChild,'Color','y'); end function [wedgeHandle,XData,YData] = createWedge(theta1,theta2,rho1,rho2) % CREATEWEDGE creates an unfilled wedge on the polar graph where: % -theta1 is the starting angle of the wedge % -theta2 is the final angle of the wedge % -rho1 is the inner angle of the wedge % -rho2 is the outer angle of the wedge % % Example: createWedge(45,135,3,3.5); % [theta,rho] = getWedgeBorder(theta1,theta2,rho1,rho2); wedgeHandle = polar(gca,theta,rho); XData = get(wedgeHandle,'XData'); YData = get(wedgeHandle,'YData'); end
github
EthanZhu90/MultilayerBSMC_ICCV17-master
bsmc_loadDataset.m
.m
MultilayerBSMC_ICCV17-master/Code/BSMC/bsmc_loadDataset.m
1,635
utf_8
606df2888d974332a6fe830fc76e72c3
function [img_template, start_frame, last_frame, options, datapath] = bsmc_loadDataset(dataset) % global mTracksAll; % global mLabelAll; basedir = strrep(fileparts(mfilename('fullpath')),'\','/'); options.lookahead = 5; options.smoothSize = 5; res = 3; datapath = [ basedir, '/../../Data/moseg_dataset/', dataset]; img_template = [datapath, '/', dataset, '_%02d.ppm']; %[start_frame, last_frame] = getFrameNums(datapath, 'jpg', [dataset, '_%02d.jpg']); [start_frame, last_frame] = getFrameNums(datapath, 'ppm', [dataset,'_%02d.ppm']); options.addNew = 1; options.sigma_traj = 10; options.description = 'Bg+Fg modelling, Window size = 7, window gaussian propability based on motion, post GC'; options.method = 'kde'; options.submethod = 'bg+fg'; options.kde_n = 10; options.kde_thresh = 5e-7; % For people 1 sequence it seems we need to increase this threshold from 1e-9 to say 2e-9 or 1e-8 otherwise we loose most of the legs options.kde_start_eval = 5; options.win_size = 7; options.colorspace = 'rgs'; options.postGC = 1; options.borderInitNeighbor = 0; options.label_prior = 0; options.motion_window = 1; % Example lookahed = 3 maximum smooth size 4 % or minimum lookahead is smooth size - 1 assert(options.smoothSize <= (options.lookahead+1)); end function [start_frame, last_frame] = getFrameNums(datapath, extension, fileTemplate) % Find the number of frame automaticaly files = dir([datapath '/*.' extension]); last_frame = 0; start_frame = 1000000; for i=1:length(files) frameNo = sscanf(files(i).name, fileTemplate); last_frame = max(last_frame, frameNo); start_frame = min(start_frame, frameNo); end end
github
EthanZhu90/MultilayerBSMC_ICCV17-master
bsmc_computeSegKDE.m
.m
MultilayerBSMC_ICCV17-master/Code/BSMC/bsmc_computeSegKDE.m
20,682
utf_8
77f76f706e03ffe72fcddadc5b904ce0
function [state] = bsmc_computeSegKDE(state, options) debug_info = struct; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Initialize with Maximum Liklihood segmentation using graph cut. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% layer_num = length(state.layers); label_mask = bsmc_computeGCInitSeg_multilabels(state, options, options.lambda_gc); %%% this counts is only for segmentation. final count is update later, %%% not this one. app_addCurr_count = cell(1, layer_num); for i = 1: layer_num app_addCurr_count{i} = state.layers(i).app_model.counts + double(label_mask == state.layers(i).label); end [nrow, ncol] = size(label_mask); debug_info.InitSegIm = label_mask; app_counts = cell(1,layer_num); app_invalid_LsPixel = cell(1, layer_num); %% for part that 0 < app count < options.kde_start_eval 0 -6 app_invalid_NoPixel = cell(1, layer_num); for i = 1:layer_num app_counts{i} = min(state.layers(i).app_model.counts, options.kde_n); %10 app_invalid_NoPixel{i} = app_addCurr_count{i} == 0 ; %5 app_invalid_LsPixel{i} = (app_addCurr_count{i} > 0) & (app_addCurr_count{i} < options.kde_start_eval+1); end debug_info.app_invalid_NoPixel = app_invalid_NoPixel; debug_info.app_invalid_LsPixel = app_invalid_LsPixel; % given the predicted label prior and appearance models, a MAP % estimate of the labels is inferred. for i = 1:layer_num state.layers(i).prob_model.post = bsmc_evalKDE_padded(state.layers(i).app_model.x, state.layers(i).app_model.counts,... state.obs, state.layers(i).motion_model.var, options); state.layers(i).prob_model.post(app_invalid_NoPixel{i}) = options.kde_thresh; %%% reset prob: step 1 end %%%%%%%% add equal prob mask %%%%% reset prob: step 2 zeroMask = zeros(nrow, ncol); for i = 1:layer_num zeroMask = zeroMask | app_invalid_LsPixel{i}; end for i = 1:layer_num state.layers(i).prob_model.post(zeroMask) = 1; end debug_info.app_invalid_LsPixel_Com = zeroMask; %%%%% reset prob: step 3: protect the new layers idx = find([state.layers.nframe] < (options.kde_start_eval+1)); if(~isempty(idx)) newlayer_mask = zeros(nrow,ncol); for i = idx newlayer_mask = newlayer_mask | (label_mask == state.layers(i).label); end debug_info.newlayer_mask = newlayer_mask; oneMask = ones(nrow, ncol); for i = 1:layer_num state.layers(i).prob_model.post((label_mask == state.layers(i).label) & newlayer_mask) =... (options.kde_thresh + options.kde_shift).*oneMask((label_mask == state.layers(i).label) & newlayer_mask); state.layers(i).prob_model.post((label_mask ~= state.layers(i).label) & newlayer_mask) =... (options.kde_thresh - options.kde_shift).*oneMask((label_mask ~= state.layers(i).label) & newlayer_mask); end end for i = 1:layer_num if i == 1 post_norm_scale = state.layers(1).prob_model.post; else post_norm_scale = post_norm_scale + state.layers(i).prob_model.post; end end if (options.label_prior == 0) for i = 1:layer_num state.layers(i).prob_model.post = state.layers(i).prob_model.post ./ post_norm_scale; end else bgprior = (1-state.model.fgprior); fgprior = state.model.fgprior; bgpost = (bgprior .* bgprob) ./ (bgprior .* bgprob + fgprior .* fgprob); % For places where we have only one appearance model, likelihood % can be very large which gives us one or zeros % This prevents the code from recovering at a later iteration. % Scale the values to an acceptable range, say between 0.05 and % 0.95. Basically here we decide how much temporal smoothing do we % want, beside of course the place where we predict the labels. bgpost2 = bgprob ./ ( bgprob + fgprob ); bgpost2 = 0.05 + 0.5 .* bgpost2; fgpost2 = 1 - bgpost2; bgpost3 = (bgprior .* bgpost2) ./ (bgprior .* bgpost2 + fgprior .* fgpost2); a = xor(fginvalid,bginvalid); bgpost(a == 1) = bgpost3(a==1); end [m,n,~] = size(state.frame); post_matrix = zeros(m,n,layer_num); for i = 1:layer_num post_matrix(:,:,i) = state.layers(i).prob_model.post; end [~, mask] = max(post_matrix,[],3); % find the max along dim 3 % replace mask with cluster label lmask = zeros(size(mask)); for i = 1:layer_num lmask(mask==i) = state.layers(i).label; end state.beforeGC = lmask; if (options.postGC == 1) state = computePostGraphCutSegmentation_multilabels(state, lmask, options); %%% label as the data cost end %figure(2) %imshow(mask{1}); if (options.postGC == 2) state = computePostGraphCutSegmentationProb_multilabels(state, options); %%% prob as the data cost end %figure(3) %imshow(mask{1}); state.debug_info = debug_info; end function [state] = computePostGraphCutSegmentationProb_multilabels(state, options) %by ethan dframe = double(state.frame); [m n ~] = size(dframe); layer_num = length(state.layers); %idx = find([state.layers.label] == bgClust); % it's bg. initial_labels =randi([1, layer_num],1,m*n); % for CLASS %initial_labels = reshape(mask, [1,m*n]); % for CLASS initial_labels = initial_labels -1; % became 0,1,2 %%%%%%%% prepare the data cost (UNARY) layer_num = length(state.layers); datacost = []; for i = 1:layer_num post = 1 - state.layers(i).prob_model.post; post = reshape(post, 1, m*n); datacost = [datacost; post]; end %%% no need to normal; % norm_scale = sum(datacost,1); % norm_scale = repmat(norm_scale, layer_num, 1); % datacost= datacost./norm_scale; %%% normalization %%%%%%%% prepare label cost (LABELCOST) labelcost = ones(layer_num); for i = 1:layer_num labelcost(i, i) = 0; end %%%%%%%% prepare edge weigh cost (PAIRWISE) hDiff = [dframe(:,1:n-1,:) - dframe(:,2:n,:), zeros(m,1,3)]; vDiff = [dframe(1:m-1,:,:) - dframe(2:m,:,:); zeros(1,n,3)]; seDiff = [dframe(1:m-1,1:n-1,:) - dframe(2:m,2:n,:) zeros(m-1,1,3); zeros(1,n,3)]; neDiff = [zeros(1,n,3); dframe(2:m,1:n-1,:) - dframe(1:m-1,2:n,:) zeros(m-1,1,3)]; halfInvSig = (1/(options.sigma_app)) * eye(3); hZ = halfInvSig * reshape(permute(hDiff, [3 1 2]), 3, m*n); vZ = halfInvSig * reshape(permute(vDiff, [3 1 2]), 3, m*n); seZ = halfInvSig * reshape(permute(seDiff, [3 1 2]), 3, m*n); neZ = halfInvSig * reshape(permute(neDiff, [3 1 2]), 3, m*n); hCue = reshape(exp(-0.5 * sum(hZ .* hZ)), m, n); vCue = reshape(exp(-0.5 * sum(vZ .* vZ)), m, n); seCue = reshape(exp(-0.5 * sum(seZ .* seZ)), m,n); neCue = reshape(exp(-0.5 * sum(neZ .* neZ)), m,n); rows_store = []; cols_store = []; v_store = []; % prepare pairwise for hCue data hCue = hCue(:, 1:n-1);% m * n-1 i = 1:m; i = repmat(i, n-1, 1); i = reshape(i, [1, (n-1)*m]); j = (1:n-1)'; j = repmat(j, 1, m); j = reshape(j, [1, (n-1)*m]); rows = sub2ind([m,n], i, j); cols = sub2ind([m,n], i, j+1); v = reshape(hCue', [1, m*(n-1)]); rows_store = [rows_store, rows]; cols_store = [cols_store, cols]; v_store = [v_store, v]; rows_store = [rows_store, cols]; cols_store = [cols_store, rows]; v_store = [v_store, v]; % prepare pairwise for vCue data vCue = vCue(1:m-1, :); % m-1 * n i = 1:m-1; i = repmat(i, n, 1); i = reshape(i, [1, n*(m-1)]); j = (1:n)'; j= repmat(j, 1, m-1); j = reshape(j, [1, n*(m-1)]); rows = sub2ind([m,n], i, j); cols = sub2ind([m,n], i+1, j); v = reshape(vCue', [1, n*(m-1)]); rows_store = [rows_store, rows]; cols_store = [cols_store, cols]; v_store = [v_store, v]; rows_store = [rows_store, cols]; cols_store = [cols_store, rows]; v_store = [v_store, v]; % prepare pairwise for seCue data seCue = seCue(1:m-1, 1:n-1); % m-1 * n-1 i = 1:m-1; i = repmat(i, n-1, 1); i = reshape(i, [1, (n-1)*(m-1)]); j = (1:n-1)'; j= repmat(j, 1, m-1); j = reshape(j, [1, (n-1)*(m-1)]); rows = sub2ind([m,n], i, j); cols = sub2ind([m,n], i+1, j+1); v = reshape(seCue', [1, (n-1)*(m-1)]); rows_store = [rows_store, rows]; cols_store = [cols_store, cols]; v_store = [v_store, v]; rows_store = [rows_store, cols]; cols_store = [cols_store, rows]; v_store = [v_store, v]; % prepare pairwise for seCue data neCue = neCue(2:m, 1:n-1); % m-1 * n-1 i = 2:m; i = repmat(i, n-1, 1); i = reshape(i, [1, (n-1)*(m-1)]); j = (1:n-1)'; j= repmat(j, 1, m-1); j = reshape(j, [1, (n-1)*(m-1)]); rows = sub2ind([m,n], i, j); cols = sub2ind([m,n], i-1, j+1); v = reshape(neCue', [1, (n-1)*(m-1)]); rows_store = [rows_store, rows]; cols_store = [cols_store, cols]; v_store = [v_store, v]; rows_store = [rows_store, cols]; cols_store = [cols_store, rows]; v_store = [v_store, v]; sMatrix = sparse(rows_store, cols_store, v_store, m*n, m*n); % N X N sparse matrix %EXPANSION = 0; % 0 == swap(2 lablels), 1 == expansion if(layer_num > 2) EXPANSION = 1; % 0 == swap(2 lablels), 1 == expansion else EXPANSION = 0; end dinitial_labels = double(initial_labels); sdatacost = single(datacost); slabelcost = single(labelcost); % use graph cut with multiple labels [labels energy energy_after] = GCMex(dinitial_labels, options.datacost_lambda *sdatacost, ... options.pairwise_lambda * sMatrix, options.labelcost_lambda * slabelcost, EXPANSION); mask = reshape(labels, [m , n]); mask = mask + 1; label_mask = zeros(size(mask)); for i = 1: layer_num %mask_term = zeros(size(mask)); %mask_term(mask==i) = 1; %state.layers(i).mask = mask_term; label_mask(mask==i) = state.layers(i).label; end state.lmask = label_mask; end function [state] = computePostGraphCutSegmentation_multilabels(state, lmask, options) %by ethan dframe = double(state.frame); [m n ~] = size(dframe); layer_num = length(state.layers); %idx = find([state.layers.label] == bgClust); % it's bg. initial_labels =randi([1, layer_num],1,m*n); % for CLASS %initial_labels = reshape(mask, [1,m*n]); % for CLASS initial_labels = initial_labels -1; % became 0,1,2 %%%%%%%% prepare the data cost (UNARY) bmask = zeros(size(lmask)); layer_num = length(state.layers); for i = 1:layer_num bmask(lmask==state.layers(i).label) = i; end bmask = reshape(bmask, [1,m*n]); datacost = []; % (C X N) (1,0,1) for i = 1: layer_num datacost_term = 0.5 * ones(1, m*n); datacost_term(bmask == i) = 0.0001; datacost = [datacost; datacost_term]; end norm_scale = sum(datacost,1); norm_scale = repmat(norm_scale, layer_num, 1); datacost= datacost./norm_scale; %%% normalization %%%%%%%% prepare label cost (LABELCOST) labelcost = ones(layer_num); for i = 1:layer_num labelcost(i, i) = 0; end %%%%%%%% prepare edge weigh cost (PAIRWISE) hDiff = [dframe(:,1:n-1,:) - dframe(:,2:n,:), zeros(m,1,3)]; vDiff = [dframe(1:m-1,:,:) - dframe(2:m,:,:); zeros(1,n,3)]; seDiff = [dframe(1:m-1,1:n-1,:) - dframe(2:m,2:n,:) zeros(m-1,1,3); zeros(1,n,3)]; neDiff = [zeros(1,n,3); dframe(2:m,1:n-1,:) - dframe(1:m-1,2:n,:) zeros(m-1,1,3)]; halfInvSig = (1/(options.sigma_app)) * eye(3); hZ = halfInvSig * reshape(permute(hDiff, [3 1 2]), 3, m*n); vZ = halfInvSig * reshape(permute(vDiff, [3 1 2]), 3, m*n); seZ = halfInvSig * reshape(permute(seDiff, [3 1 2]), 3, m*n); neZ = halfInvSig * reshape(permute(neDiff, [3 1 2]), 3, m*n); hCue = reshape(exp(-0.5 * sum(hZ .* hZ)), m, n); vCue = reshape(exp(-0.5 * sum(vZ .* vZ)), m, n); seCue = reshape(exp(-0.5 * sum(seZ .* seZ)), m,n); neCue = reshape(exp(-0.5 * sum(neZ .* neZ)), m,n); rows_store = []; cols_store = []; v_store = []; % prepare pairwise for hCue data hCue = hCue(:, 1:n-1);% m * n-1 i = 1:m; i = repmat(i, n-1, 1); i = reshape(i, [1, (n-1)*m]); j = (1:n-1)'; j = repmat(j, 1, m); j = reshape(j, [1, (n-1)*m]); rows = sub2ind([m,n], i, j); cols = sub2ind([m,n], i, j+1); v = reshape(hCue', [1, m*(n-1)]); rows_store = [rows_store, rows]; cols_store = [cols_store, cols]; v_store = [v_store, v]; rows_store = [rows_store, cols]; cols_store = [cols_store, rows]; v_store = [v_store, v]; % prepare pairwise for vCue data vCue = vCue(1:m-1, :); % m-1 * n i = 1:m-1; i = repmat(i, n, 1); i = reshape(i, [1, n*(m-1)]); j = (1:n)'; j= repmat(j, 1, m-1); j = reshape(j, [1, n*(m-1)]); rows = sub2ind([m,n], i, j); cols = sub2ind([m,n], i+1, j); v = reshape(vCue', [1, n*(m-1)]); rows_store = [rows_store, rows]; cols_store = [cols_store, cols]; v_store = [v_store, v]; rows_store = [rows_store, cols]; cols_store = [cols_store, rows]; v_store = [v_store, v]; % prepare pairwise for seCue data seCue = seCue(1:m-1, 1:n-1); % m-1 * n-1 i = 1:m-1; i = repmat(i, n-1, 1); i = reshape(i, [1, (n-1)*(m-1)]); j = (1:n-1)'; j= repmat(j, 1, m-1); j = reshape(j, [1, (n-1)*(m-1)]); rows = sub2ind([m,n], i, j); cols = sub2ind([m,n], i+1, j+1); v = reshape(seCue', [1, (n-1)*(m-1)]); rows_store = [rows_store, rows]; cols_store = [cols_store, cols]; v_store = [v_store, v]; rows_store = [rows_store, cols]; cols_store = [cols_store, rows]; v_store = [v_store, v]; % prepare pairwise for seCue data neCue = neCue(2:m, 1:n-1); % m-1 * n-1 i = 2:m; i = repmat(i, n-1, 1); i = reshape(i, [1, (n-1)*(m-1)]); j = (1:n-1)'; j= repmat(j, 1, m-1); j = reshape(j, [1, (n-1)*(m-1)]); rows = sub2ind([m,n], i, j); cols = sub2ind([m,n], i-1, j+1); v = reshape(neCue', [1, (n-1)*(m-1)]); rows_store = [rows_store, rows]; cols_store = [cols_store, cols]; v_store = [v_store, v]; rows_store = [rows_store, cols]; cols_store = [cols_store, rows]; v_store = [v_store, v]; sMatrix = sparse(rows_store, cols_store, v_store, m*n, m*n); % N X N sparse matrix %EXPANSION = 0; % 0 == swap(2 lablels), 1 == expansion if(layer_num > 2) EXPANSION = 1; % 0 == swap(2 lablels), 1 == expansion else EXPANSION = 0; end dinitial_labels = double(initial_labels); sdatacost = single(datacost); slabelcost = single(labelcost); % use graph cut with multiple labels [labels energy energy_after] = GCMex(dinitial_labels, options.datacost_lambda *sdatacost, ... options.pairwise_lambda * sMatrix, options.labelcost_lambda * slabelcost, EXPANSION); mask = reshape(labels, [m , n]); mask = mask + 1; label_mask = zeros(size(mask)); for i = 1: layer_num %mask_term = zeros(size(mask)); %mask_term(mask==i) = 1; %state.layers(i).mask = mask_term; label_mask(mask==i) = state.layers(i).label; end state.lmask = label_mask; end function mask = computePostGraphCutSegmentationProb(state, bgpost, options) dframe = double(state.frame); [m n ~] = size(dframe); hDiff = [dframe(:,1:n-1,:) - dframe(:,2:n,:) zeros(m,1,3)]; vDiff = [dframe(1:m-1,:,:) - dframe(2:m,:,:); zeros(1,n,3)]; seDiff = [dframe(1:m-1,1:n-1,:) - dframe(2:m,2:n,:) zeros(m-1,1,3); zeros(1,n,3)]; neDiff = [zeros(1,n,3); dframe(2:m,1:n-1,:) - dframe(1:m-1,2:n,:) zeros(m-1,1,3)]; halfInvSig = (1/(options.sigma_app)) * eye(3); hZ = halfInvSig * reshape(permute(hDiff, [3 1 2]), 3, m*n); vZ = halfInvSig * reshape(permute(vDiff, [3 1 2]), 3, m*n); neZ = halfInvSig * reshape(permute(neDiff, [3 1 2]), 3, m*n); seZ = halfInvSig * reshape(permute(seDiff, [3 1 2]), 3, m*n); hCue = reshape(exp(-0.5 * sum(hZ .* hZ)), m, n); vCue = reshape(exp(-0.5 * sum(vZ .* vZ)), m, n); neCue = reshape(exp(-0.5 * sum(neZ .* neZ)), m,n); seCue = reshape(exp(-0.5 * sum(seZ .* seZ)), m,n); dataCost(:,:,1) = 1-bgpost; dataCost(:,:,2) = bgpost; mask = bsmc_gridCut(2 * dataCost, 8 * hCue, 8 *vCue, 8 *seCue, 8 *neCue); end function mask = computePostGraphCutSegmentation(state, mask, options) dframe = double(state.frame); [m n ~] = size(dframe); hDiff = [dframe(:,1:n-1,:) - dframe(:,2:n,:) zeros(m,1,3)]; vDiff = [dframe(1:m-1,:,:) - dframe(2:m,:,:); zeros(1,n,3)]; seDiff = [dframe(1:m-1,1:n-1,:) - dframe(2:m,2:n,:) zeros(m-1,1,3); zeros(1,n,3)]; neDiff = [zeros(1,n,3); dframe(2:m,1:n-1,:) - dframe(1:m-1,2:n,:) zeros(m-1,1,3)]; halfInvSig = (1/(options.sigma_app)) * eye(3); hZ = halfInvSig * reshape(permute(hDiff, [3 1 2]), 3, m*n); vZ = halfInvSig * reshape(permute(vDiff, [3 1 2]), 3, m*n); neZ = halfInvSig * reshape(permute(neDiff, [3 1 2]), 3, m*n); seZ = halfInvSig * reshape(permute(seDiff, [3 1 2]), 3, m*n); hCue = reshape(exp(-0.5 * sum(hZ .* hZ)), m, n); vCue = reshape(exp(-0.5 * sum(vZ .* vZ)), m, n); neCue = reshape(exp(-0.5 * sum(neZ .* neZ)), m,n); seCue = reshape(exp(-0.5 * sum(seZ .* seZ)), m,n); sparse_fgll_noapp = 0.5 * ones(size(state.frame,1), size(state.frame,2)); sparse_bgll_noapp = 0.5 * ones(size(state.frame,1), size(state.frame,2)); sparse_fgll_noapp(mask) = options.lrgNum; sparse_bgll_noapp(~mask) = options.lrgNum; norm_factor = sparse_fgll_noapp + sparse_bgll_noapp; sparse_fgll_noapp = sparse_fgll_noapp ./ norm_factor; sparse_bgll_noapp = sparse_bgll_noapp ./ norm_factor; dataCost(:,:,1) = sparse_fgll_noapp; dataCost(:,:,2) = sparse_bgll_noapp; mask = bsmc_gridCut(2 * dataCost, 8 * hCue, 8 *vCue, 8 *seCue, 8 *neCue); end function mask = computeGraphCutSegmentation(state,options) dframe = double(state.frame); [m n ~] = size(dframe); hDiff = [dframe(:,1:n-1,:) - dframe(:,2:n,:) zeros(m,1,3)]; vDiff = [dframe(1:m-1,:,:) - dframe(2:m,:,:); zeros(1,n,3)]; seDiff = [dframe(1:m-1,1:n-1,:) - dframe(2:m,2:n,:) zeros(m-1,1,3); zeros(1,n,3)]; neDiff = [zeros(1,n,3); dframe(2:m,1:n-1,:) - dframe(1:m-1,2:n,:) zeros(m-1,1,3)]; halfInvSig = (1/(options.sigma_app)) * eye(3); hZ = halfInvSig * reshape(permute(hDiff, [3 1 2]), 3, m*n); vZ = halfInvSig * reshape(permute(vDiff, [3 1 2]), 3, m*n); neZ = halfInvSig * reshape(permute(neDiff, [3 1 2]), 3, m*n); seZ = halfInvSig * reshape(permute(seDiff, [3 1 2]), 3, m*n); hCue = reshape(exp(-0.5 * sum(hZ .* hZ)), m, n); vCue = reshape(exp(-0.5 * sum(vZ .* vZ)), m, n); neCue = reshape(exp(-0.5 * sum(neZ .* neZ)), m,n); seCue = reshape(exp(-0.5 * sum(seZ .* seZ)), m,n); % [~, ia,ib] = intersect(state.memTrajIds, state.trajIds); % sparse_fgpoints = round(state.points(1:2, ib(state.clust.lbls(ia) == state.clust.fgClust))); % sparse_bgpoints = round(state.points(1:2, ib(state.clust.lbls(ia) ~= state.clust.fgClust))); sparse_fgpoints = state.sparse_fgpoints; sparse_bgpoints = state.sparse_bgpoints; sparse_fgll_noapp = 0.5 * ones(size(state.frame,1), size(state.frame,2)); sparse_bgll_noapp = 0.5 * ones(size(state.frame,1), size(state.frame,2)); sparse_fgll_noapp(sub2ind(size(sparse_fgll_noapp), sparse_fgpoints(2,:), sparse_fgpoints(1,:))) = options.lrgNum; sparse_bgll_noapp(sub2ind(size(sparse_bgll_noapp), sparse_bgpoints(2,:), sparse_bgpoints(1,:))) = options.lrgNum; norm_factor = sparse_fgll_noapp + sparse_bgll_noapp; seg.sparse_fgll_noapp = sparse_fgll_noapp ./ norm_factor; seg.sparse_bgll_noapp = sparse_bgll_noapp ./ norm_factor; dataCost(:,:,1) = seg.sparse_fgll_noapp; dataCost(:,:,2) = seg.sparse_bgll_noapp; mask = bsmc_gridCut(4 * dataCost, 8 * hCue, 8 *vCue, 8 *seCue, 8 *neCue); end
github
EthanZhu90/MultilayerBSMC_ICCV17-master
bsmc_predictModelKDE.m
.m
MultilayerBSMC_ICCV17-master/Code/BSMC/bsmc_predictModelKDE.m
6,735
utf_8
7d66ba64d2f1803f04be114e616f1f52
function [state] = bsmc_predictModelKDE(prevState, state, options) % addpath('/home/elqursh/Projects/Research/Libraries/Belief Propagation/gabp-src/'); if (~isfield(prevState,'layers')) % Initialize appearance model %fprintf('\nInitializing appearance models\n'); layer_num = length(state.layers); for i = 1: layer_num app_x = zeros(size(state.obs,1), size(state.obs,2), options.kde_n * size(state.obs,3)); app_counts = zeros(size(state.obs,1), size(state.obs,2)); %app_labels = 0.5 .* ones(size(state.obs,1), size(state.obs,2)); %% what's this? state.layers(i).app_model = struct('x',app_x, 'counts',app_counts); prob_prior = (1/layer_num) * ones(size(state.obs,1), size(state.obs,2)); %% need to change state.layers(i).prob_model = struct('prior', prob_prior, 'post', -1 ); % post is for later end return; end % Predict change to appearance model from previous frame to current % frame. %idx = find([traj_store.label] == bgClust); % if it's fg. layer_num = length(state.layers); for i = 1: layer_num A = computeA(state.layers(i).motion_model, options); % as far,for me, A is just a shift matrix. mlabel = state.layers(i).label; idx = find([prevState.layers.label] == mlabel); % find the corresponding app model %%% if you can't find the app of this new cluster, we create a new element in app struct. if(isempty(idx)) app_x = zeros(size(state.obs,1), size(state.obs,2), options.kde_n * size(state.obs,3)); app_counts = zeros(size(state.obs,1), size(state.obs,2)); %app_labels = 0.5 .* ones(size(state.obs,1), size(state.obs,2)); %% what's this? prev_app = struct('x',app_x, 'counts',app_counts); state.layers(i).app_model = predictState(A, prev_app, options); else state.layers(i).app_model = predictState(A, prevState.layers(idx).app_model, options); end end %%% generate the prob_models %%% it seems like prob_prior is not used later if (options.label_prior ==1) error('do not set label_prior to 1'); fgprior = predictFGSig(A2, 1-prevState.model.bgpost, state.motion_models{2}.var, options); else for i = 1: layer_num mlabel = state.layers(i).label; idx = find([prevState.layers.label] == mlabel); % find the corresponding app model if(isempty(idx)) % new cluster prob_prior = (1/layer_num) * ones(size(state.obs,1), size(state.obs,2)); state.layers(i).prob_model = struct('prior', prob_prior, 'post',-1 ); % post is for later else prob_prior = predictFG(A, prevState.layers(idx).prob_model.post); % eq(10) fg prob shift to current frame. state.layers(i).prob_model = struct('prior', prob_prior, 'post',-1 ); % post is for later end end end end function fgprediction = predictFG(A, prev_fgpost) [m,n] = size(prev_fgpost); % Apply the mean motion (encapsulated in A) to the prev_fgpost, such % that we now get 0 mean distributions. fgprediction = reshape(A * reshape(prev_fgpost, m*n,1),m,n); end function proball = predictFGSig(A, prev_fgpost, sig2, options) [m n] = size(prev_fgpost); fgprediction = reshape(A * reshape(prev_fgpost, m*n,1),m,n); proball = bsmc_adapGridKDE(fgprediction, sig2, options.win_size2); end function app = predictState(A, prev_bgapp, options) [m n c] = size(prev_bgapp.x); app_x = zeros(m,n,c); for i=1:c app_x(:,:,i) = reshape(A * reshape(prev_bgapp.x(:,:,i),m*n,1),m,n); end app_counts = reshape(A * reshape(prev_bgapp.counts,m*n,1),m,n); app = struct('x',app_x, 'counts',app_counts); end function A = computeA(motionModel, options) % Here we assume motion model is accurate. [m n ~] = size(motionModel.mean); [x,y] = meshgrid((1:n),(1:m)); if (~isfield(options,'motion_subpixel') || options.motion_subpixel == 0) shifts_x = round(motionModel.mean(:,:,1)) + x; shifts_y = round(motionModel.mean(:,:,2)) + y; outofbounds = shifts_x < 1 | shifts_x > n | shifts_y < 1 | shifts_y > m; shifts_x = max(min(shifts_x, n),1); shifts_y = max(min(shifts_y, m),1); vals = ones(m,n); if (options.borderInitNeighbor == 0) vals(outofbounds) = 0; end idx = sub2ind([m n], shifts_y(:), shifts_x(:)); is = (1:m*n); A = sparse(is, idx, vals(:),m*n,m*n); else % Each pixel comes from 4 other pixels xx = motionModel.mean(:,:,1); xx = xx(:); yy = motionModel.mean(:,:,2); yy = yy(:); xx_floor = floor(xx); xx_ceil = ceil(xx); yy_floor = floor(yy); yy_ceil = ceil(yy); vec_ff = [ xx - xx_floor yy - yy_floor ]'; vec_fc = [ xx - xx_floor yy_ceil - yy ]'; vec_cf = [ xx_ceil - xx yy - yy_floor ]'; vec_cc = [ xx_ceil - xx yy_ceil - yy ]'; dist_ff = sqrt(sum(vec_ff.^2)); dist_fc = sqrt(sum(vec_fc.^2)); dist_cf = sqrt(sum(vec_cf.^2)); dist_cc = sqrt(sum(vec_cc.^2)); sum_dist = dist_ff + dist_fc + dist_cf + dist_cc; weight_ff = dist_ff ./ sum_dist; weight_fc = dist_fc ./ sum_dist; weight_cf = dist_cf ./ sum_dist; weight_cc = dist_cc ./ sum_dist; shifts_x_f = max(min(xx_floor + x(:), n),1); shifts_y_f = max(min(yy_floor + y(:), m),1); shifts_x_c = max(min(xx_ceil + x(:), n),1); shifts_y_c = max(min(yy_ceil + y(:), m),1); same_x = shifts_x_f == shifts_x_c; same_y = shifts_y_f == shifts_y_c; weight_ff(same_x) = weight_ff(same_x) + weight_cf(same_x); weight_cf(same_x) = 0; weight_fc(same_x) = weight_fc(same_x) + weight_cc(same_x); weight_cc(same_x) = 0; weight_ff(same_y) = weight_ff(same_y) + weight_fc(same_y); weight_fc(same_y) = 0; weight_cf(same_y) = weight_cf(same_y) + weight_cc(same_y); weight_cc(same_y) = 0; js_ff = sub2ind([m n], shifts_y_f, shifts_x_f); js_fc = sub2ind([m n], shifts_y_c, shifts_x_f); js_cf = sub2ind([m n], shifts_y_f, shifts_x_c); js_cc = sub2ind([m n], shifts_y_c, shifts_x_c); is = (1:m*n); A = sparse(repmat(is,1,4), ... [js_ff; js_fc; js_cf; js_cc]', ... [weight_ff weight_fc weight_cf weight_cc],m*n,m*n); assert(all((sum(A,2) -1) <= 20*eps)); end end
github
EthanZhu90/MultilayerBSMC_ICCV17-master
bsmc_inferM.m
.m
MultilayerBSMC_ICCV17-master/Code/BSMC/bsmc_inferM.m
3,154
utf_8
6e643c4c758b092955aedcc4b4db0354
function state = bsmc_inferM(state, options) % Given the motion vectors for the background objects, infer the optical % flow field. Use gaussian belief propagation GaBP. % Compute Vxx h = size(state.frame,1); w = size(state.frame,2); % n = w * h; Vxx = bsmc_computeVxx(w,h); Vxx = Vxx ./ (options.sig_edge^2); layer_num = length(state.layers); layers = state.layers; for i = 1: layer_num sparse_points_m = layers(i).traj_store.sparse_points_m; if(layers(i).label == state.bgClust) % if it's background. % Background is pretty rigidm no need to compute var [M_b, sig2_b] = computeFlow(Vxx, [h w], sparse_points_m, options, false); layers(i).motion_model = struct('mean', M_b, 'var',sig2_b); else if (isempty(sparse_points_m)) M_f = zeros(h,w,2); sig2_f = 3^2 * ones(h,w); else [M_f,sig2_f] = computeFlow(Vxx, [h w], sparse_points_m, options, false); % original true end layers(i).motion_model = struct('mean', M_f, 'var',sig2_f); end end state.layers = layers; end function [flow, sig2] = computeFlow(Vxx_in, sz, points, options, compute_sig2) %%% compute_sig2: true, compute var otherwise not is = sub2ind(sz, points(2,:), points(1,:)); n = prod(sz); m = size(points,2); h = sz(1); w = sz(2); % Update Vxx Vxx = Vxx_in; VxxDiff = sparse(is,is,repmat((1/(options.sig_motion^2)), length(is),1),n,n); %Vxx(sub2ind([n n], is,is)) = Vxx(sub2ind([n n], is, is)) + (1/(options.sig_motion^2)); Vxx = Vxx + VxxDiff; % Compute Vxy Vxy = sparse(n,m); Vxy(sub2ind([n m], is, 1:m)) = -(1/(options.sig_motion^2)); % Now add labeled information. % Find motion vectors y1 = (points(3,:) - points(1,:))'; y2 = (points(4,:) - points(2,:))'; flow1 = Vxx\(-Vxy * y1); flow2 = Vxx\(-Vxy * y2); flow(:,:,1) = reshape(full(flow1),h,w); flow(:,:,2) = reshape(full(flow2),h,w); if (~compute_sig2) sig2 = ones(h,w); else % Down scale input 8 times h = sz(1); w = sz(2); if (mod(h,8) == 0 && mod(w,8) == 0) r = 8; else if (mod(h,5) == 0 && mod(h,5) == 0) r = 5; else disp('Cannot find a suitable down-scale for the image'); sig2 = 1*ones(h,w); return; end end sig_edge = options.sig_edge * r; points = ceil(points/r); w = w/r; h = h/r; sz = [h w]; % Compute sig2 Vxx = bsmc_computeVxx(w,h); Vxx = Vxx ./ (sig_edge^2); is = sub2ind(sz, points(2,:), points(1,:)); n = prod(sz); VxxDiff = sparse(is,is,repmat((1/(options.sig_motion^2)), length(is),1),n,n); Vxx = Vxx + VxxDiff; invVxx = inv(Vxx); sig2_downsampled = reshape(full(diag(invVxx)),h,w); [x,y ] = meshgrid(1:r*w,1:r*h); x = ceil(x/r); y = ceil(y/r); sig2 = sig2_downsampled(sub2ind(size(sig2_downsampled), y(:),x(:))); sig2 = reshape(sig2, r*h,r*w); end end
github
EthanZhu90/MultilayerBSMC_ICCV17-master
munkres.m
.m
MultilayerBSMC_ICCV17-master/Code/BSMC/munkres.m
7,171
utf_8
b44ad4f1a20fc5d03db019c44a65bac3
function [assignment,cost] = munkres(costMat) % MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem. % % [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices, % ASSIGN assigned to each row and the minimum COST based on the assignment % problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth % job to the ith worker. % % Partial assignment: This code can identify a partial assignment is a full % assignment is not feasible. For a partial assignment, there are some % zero elements in the returning assignment vector, which indicate % un-assigned tasks. The cost returned only contains the cost of partially % assigned tasks. % This is vectorized implementation of the algorithm. It is the fastest % among all Matlab implementations of the algorithm. % Examples % Example 1: a 5 x 5 example %{ [assignment,cost] = munkres(magic(5)); disp(assignment); % 3 2 1 5 4 disp(cost); %15 %} % Example 2: 400 x 400 random data %{ n=400; A=rand(n); tic [a,b]=munkres(A); toc % about 2 seconds %} % Example 3: rectangular assignment with inf costs %{ A=rand(10,7); A(A>0.7)=Inf; [a,b]=munkres(A); %} % Example 4: an example of partial assignment %{ A = [1 3 Inf; Inf Inf 5; Inf Inf 0.5]; [a,b]=munkres(A) %} % a = [1 0 3] % b = 1.5 % Reference: % "Munkres' Assignment Algorithm, Modified for Rectangular Matrices", % http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html % version 2.3 by Yi Cao at Cranfield University on 11th September 2011 assignment = zeros(1,size(costMat,1)); cost = 0; validMat = costMat == costMat & costMat < Inf; bigM = 10^(ceil(log10(sum(costMat(validMat))))+1); costMat(~validMat) = bigM; % costMat(costMat~=costMat)=Inf; % validMat = costMat<Inf; validCol = any(validMat,1); validRow = any(validMat,2); nRows = sum(validRow); nCols = sum(validCol); n = max(nRows,nCols); if ~n return end maxv=10*max(costMat(validMat)); dMat = zeros(n) + maxv; dMat(1:nRows,1:nCols) = costMat(validRow,validCol); %************************************************* % Munkres' Assignment Algorithm starts here %************************************************* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % STEP 1: Subtract the row minimum from each row. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% minR = min(dMat,[],2); minC = min(bsxfun(@minus, dMat, minR)); %************************************************************************** % STEP 2: Find a zero of dMat. If there are no starred zeros in its % column or row start the zero. Repeat for each zero %************************************************************************** zP = dMat == bsxfun(@plus, minC, minR); starZ = zeros(n,1); while any(zP(:)) [r,c]=find(zP,1); starZ(r)=c; zP(r,:)=false; zP(:,c)=false; end while 1 %************************************************************************** % STEP 3: Cover each column with a starred zero. If all the columns are % covered then the matching is maximum %************************************************************************** if all(starZ>0) break end coverColumn = false(1,n); coverColumn(starZ(starZ>0))=true; coverRow = false(n,1); primeZ = zeros(n,1); [rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn))); while 1 %************************************************************************** % STEP 4: Find a noncovered zero and prime it. If there is no starred % zero in the row containing this primed zero, Go to Step 5. % Otherwise, cover this row and uncover the column containing % the starred zero. Continue in this manner until there are no % uncovered zeros left. Save the smallest uncovered value and % Go to Step 6. %************************************************************************** cR = find(~coverRow); cC = find(~coverColumn); rIdx = cR(rIdx); cIdx = cC(cIdx); Step = 6; while ~isempty(cIdx) uZr = rIdx(1); uZc = cIdx(1); primeZ(uZr) = uZc; stz = starZ(uZr); if ~stz Step = 5; break; end coverRow(uZr) = true; coverColumn(stz) = false; z = rIdx==uZr; rIdx(z) = []; cIdx(z) = []; cR = find(~coverRow); z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz); rIdx = [rIdx(:);cR(z)]; cIdx = [cIdx(:);stz(ones(sum(z),1))]; end if Step == 6 % ************************************************************************* % STEP 6: Add the minimum uncovered value to every element of each covered % row, and subtract it from every element of each uncovered column. % Return to Step 4 without altering any stars, primes, or covered lines. %************************************************************************** [minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn)); minC(~coverColumn) = minC(~coverColumn) + minval; minR(coverRow) = minR(coverRow) - minval; else break end end %************************************************************************** % STEP 5: % Construct a series of alternating primed and starred zeros as % follows: % Let Z0 represent the uncovered primed zero found in Step 4. % Let Z1 denote the starred zero in the column of Z0 (if any). % Let Z2 denote the primed zero in the row of Z1 (there will always % be one). Continue until the series terminates at a primed zero % that has no starred zero in its column. Unstar each starred % zero of the series, star each primed zero of the series, erase % all primes and uncover every line in the matrix. Return to Step 3. %************************************************************************** rowZ1 = find(starZ==uZc); starZ(uZr)=uZc; while rowZ1>0 starZ(rowZ1)=0; uZc = primeZ(rowZ1); uZr = rowZ1; rowZ1 = find(starZ==uZc); starZ(uZr)=uZc; end end % Cost of assignment rowIdx = find(validRow); colIdx = find(validCol); starZ = starZ(1:nRows); vIdx = starZ <= nCols; assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx)); pass = assignment(assignment>0); pass(~diag(validMat(assignment>0,pass))) = 0; assignment(assignment>0) = pass; cost = trace(costMat(assignment>0,assignment(assignment>0))); function [minval,rIdx,cIdx]=outerplus(M,x,y) ny=size(M,2); minval=inf; for c=1:ny M(:,c)=M(:,c)-(x+y(c)); minval = min(minval,min(M(:,c))); end [rIdx,cIdx]=find(M==minval);
github
bobbielf2/BIE2D-master
fig_lapconvK1.m
.m
BIE2D-master/doublyperiodic/fig_lapconvK1.m
11,601
utf_8
c2453cbaaf467699775bd8ef1b668792
function fig_lapconvK1 % Laplace Neu periodic BVP, convergence and soln plots. Single inclusion (K=1). % All dense matrices, native quadr for solve, close eval for plot. % Barnett, cleaned up from perineu2dnei1.m 5/11/16. % Small codes broken out 6/12/16 (no longer self-contained); BIE2D 6/29/16 % X,y,r notation & non-random r, 8/17/16. 5x5 known src 8/23/16. warning('off','MATLAB:nearlySingularMatrix') % backward-stable ill-cond is ok! warning('off','MATLAB:rankDeficientMatrix') lso.RECT = true; % linsolve opts, forces QR even when square (LU much worse), % ...and much faster than the following backward-stable SVD solve: %[UE,S,V] = svd(E,'econ'); Sr = max(diag(S),1e-14); co = V*((UE'*rhs)./Sr); format long g jumps = [1 0]; %[0 1]; % potential jumps across R-L and T-B (not for known sol) U.e1 = 1; U.e2 = 1i; % unit cell lattice vectors and src direct sum list... U.nei = 1; [tx ty] = meshgrid(-U.nei:U.nei); U.trlist = tx(:)+1i*ty(:); % 3x3 m = 22; [U L R B T] = doublywalls(U,m); proxyrep = @LapSLP; % sets proxy pt type via a kernel function call Rp = 1.4; M = 70; % proxy params p.x = Rp * exp(1i*(0:M-1)'/M*2*pi); p = setupquad(p); % proxy pts a = 0.7; b = 0.15; % worm params, spills horizontally out of any unit cell uexdiff = 0.11101745840635; flux1ex = 0.5568613934999; % 1e-12 err, a=.7,b=.15 % known soln dipole location: must be deep inside Omega (careful) src.x = 0.42+.23i; src.w = 1; src.nx = 1+0i; src.nei = 5; % creates 5x5 grid % -------------------------- single soln and plot N = 140; s = wormcurve(a,b,N); rhs = [0*s.x; jumps(1)+0*L.x; 0*L.x; jumps(2)+0*B.x; 0*B.x]; % driving tic E = ELSmatrix(s,p,proxyrep,U); % fill co = linsolve(E,rhs,lso); % direct bkw stable solve toc fprintf('resid norm = %.3g\n',norm(E*co - rhs)) sig = co(1:N); psi = co(N+1:end); fprintf('density norm = %.3g, proxy norm = %.3g\n',norm(sig), norm(psi)) fprintf('density integral = %.3g\n',s.w'*sig) z = (.1+.4i)*[-1;1]; % pot difference btw 2 pts (invariant to const shift)... u = evalsol(s,p,proxyrep,U,z,co); fprintf('u diff btw two pts = %.16g \t(est abs err: %.3g)\n',u(2)-u(1), abs(u(2)-u(1)-uexdiff)) tic; J = evalfluxes(s,p,proxyrep,U,co); toc fprintf('fluxes (%.16g,%.16g) (est abs err: %.3g)\n',J(1),J(2),J(1)-flux1ex) if 0 % soln potential figure utyp = mean(u); nx = 300; gx = ((1:nx)/nx*2-1)*Rp; % eval grid gy = gx; [xx yy] = meshgrid(gx,gy); zz = (xx(:)+1i*yy(:)); clear xx yy; u = evalsol(s,p,proxyrep,U,zz,co); for i=-2:2, for j=-2:2, u(s.inside(zz+U.e1*i+U.e2*j)) = nan; end, end % tidy u(abs(zz)>Rp) = nan; % exclude stuff outside proxy u = reshape(u,[nx nx]) - utyp; % subtract typical value figure; contourf(gx,gy,u,[-1.8:.1:1.8]); colormap(jet(256)); hold on; showsegment(s); n=2; for i=-n:n, for j=-n:n, plot([s.x;s.x(1)]+j+1i*i,'-'); end,end showsegment({L R T B}); axis equal off; axis([-Rp real(src.x+U.e1) -Rp Rp]); plot(z,'k.'); plot(p.x,'r.'); plot(src.x+U.trlist,'k*'); text(-.45,0,'L');text(0.55,0,'R'); text(0,-.42,'D');text(0,0.58,'U'); text(0,0,'$\Omega$','interpreter','latex'); text(-1.2,1.3,'(a)'); %,'fontsize',14); %set(gcf,'paperposition',[0 0 4 4]); print -depsc2 figs/lapsolK1.eps end if 1, Ns = 30:10:230; % ------------------------ N-convergence us = nan*Ns; res = us; rest = us; ust = us; es = us; Js = nan(2,numel(Ns)); Jst = Js; uek = knownsol(U,z,src); % known dipole grid soln, fixed, ignores jumps %v = [0*L.w';1+0*L.w';0*B.w';1+0*B.w']; % obsolete r = ones(M,1)/M; % scaled Sifuentes 1s-vector for i=1:numel(Ns) s = wormcurve(a,b,Ns(i)); g = [jumps(1)+0*L.x; 0*L.x; jumps(2)+0*B.x; 0*B.x]; rhs = [0*s.x; g]; %driving [E,A,Bm,C,Q] = ELSmatrix(s,p,proxyrep,U); co = linsolve(E,rhs,lso); res(i) = norm(E*co - rhs); u = evalsol(s,p,proxyrep,U,z,co); us(i) = u(2)-u(1); Js(:,i) = evalfluxes(s,p,proxyrep,U,co); H = ones(Ns(i),1); v = C*H; % Gary's non-const v, overwrites above Qtilde = Q + v*r'; % Schur stuff... (soln u given suffix "t") %if i==1, norm(Q), norm(v*d'), svd(Q), svd(Qtilde), end % sim size norms? X = linsolve(Qtilde,C,lso); y = linsolve(Qtilde,g,lso); %Qtdag = pinv(Qtilde); X = Qtdag*C; y = Qtdag*g; % bad, loses 7 digits %Bm = Bm + (A*H)*d'; % Gary version of my B corr; makes nullity(Aper)=1 again taut = gmres(@(x) A*x - Bm*(X*x), -Bm*y, [], 1e-14, Ns(i)); %taut = linsolve(A - Bm*X,-Bm*y,lso); % direct soln %cond(A - Bm*X) % 8.3 xit = y - X*taut; % note no taut correction for Gary since d'*xit = 0... cot = [taut;xit]; % build full soln vector %norm(r'*xit) % check what we know from theory, should be zero rest(i) = norm(E*cot - rhs); % residual back in ELS u = evalsol(s,p,proxyrep,U,z,cot); ust(i) = u(2)-u(1); Jst(:,i) = evalfluxes(s,p,proxyrep,U,cot); % Schur flux rhsk = knownrhs(src,s,U); % set up RHS for known 3x3 unit source soln... cok = linsolve(E,rhsk,lso); % coeffs for approx to known soln %norm(E*cok - rhsk) % resid for known soln - plot? uk = evalsol(s,p,proxyrep,U,z,cok); % eval this approx es(i) = uk(2)-uk(1)-(uek(2)-uek(1)); % err vs known diff btw test pts end % [U S V] = svd(E); V(:,end) % show that Nul E = [0;stuff], ie tau unique fprintf('norm X=Qt\\C is %.3g\n',norm(X)) disp('pot diff N-convergence for ELS, Schur, their diff:') [us',ust',us'-ust'] disp('flux J1 N-convergence for ELS, Schur, their diff:') [Js(1,:)',Jst(1,:)',Js(1,:)'-Jst(1,:)'] disp('flux J2 N-convergence for ELS, Schur, their diff:') [Js(2,:)',Jst(2,:)',Js(2,:)'-Jst(2,:)'] figure; %semilogy(Ns,res,'ro-'); % why is resid always around 1e-14? semilogy(Ns,abs(us-us(i)),'+-'); hold on; plot(Ns,abs(Js(1,:)-Js(1,end)),'go-'); plot(Ns,abs(ust-ust(i)),'+--'); plot(Ns,abs(Jst(1,:)-Jst(1,end)),'go--'); %plot(Ns,rest,'rd-'); plot(Ns,abs(es),'ks-'); %legend('u convergence','J_1 convergence','u err vs known'); legend('u conv ELS','J_1 conv ELS','u conv Schur','J_1 conv Schur','u err vs known'); xlabel('N'); text(40,1e-4,'(c)'); text(140,1e-8, sprintf('$M=%d$, $m=%d$',M,m),'interpreter','latex'); axis([Ns(1) Ns(end-1) 1e-15 1e-3]); %set(gcf,'paperposition',[0 0 3.5 3.5]); print -depsc2 figs/lapconvK1.eps end if 1, Ms = 10:5:120; % -------------------- M convergence (not incl Schur) N = 100; s = wormcurve(a,b,N); % fixed rhs = [0*s.x; jumps(1)+0*L.x; 0*L.x; jumps(2)+0*B.x; 0*B.x]; % driving Js = nan(2,numel(Ms)); nrms = nan*Ms; nsings = 6; sings = nan(numel(Ms),nsings); % save some sing vals for i=1:numel(Ms) p.x = Rp * exp(1i*(1:Ms(i))'/Ms(i)*2*pi); p = setupquad(p); % reset proxy pts E = ELSmatrix(s,p,proxyrep,U); S = svd(E); sings(i,1) = max(S); sings(i,2:nsings) = S(end-nsings+2:end); % 1st & last few co = linsolve(E,rhs,lso); nrms(i) = norm(co); Js(:,i) = evalfluxes(s,p,proxyrep,U,co); end disp('flux J1 M-convergence for ELS:') Js(1,:)' figure; semilogy(Ms,abs(Js(1,:)-Js(1,end)),'b+-'); hold on; h = load('/home/alex/physics/shravan/dpls/Fig22eData.mat'); % K=1e2 M-conv plot(h.M,abs(h.J-h.J(end)),'bs-'); semilogy(Ms,nrms,'b.-'); semilogy(Ms,sings(:,2:end),'-','color',.5*[1 1 1]); legend('J_1 conv, Ex.1', 'J_1 conv, Ex.2','soln norm, Ex.1','sing vals, Ex.1','location','east'); text(15,max(nrms)/10,'(e)'); %text(60,max(nrms)/10,sprintf('$N=%d, m=%d$',N,m),'interpreter','latex'); xlabel('M'); axis([Ms(1) Ms(end-1) 1e-17 max(nrms)]); %set(gcf,'paperposition',[0 0 3.5 3.5]); print -depsc2 figs/lapMconv.eps end if 0 % --------- old Schur tests warm-up (see above for their convergence) N = 140; s = wormcurve(a,b,N); % reset curve M = 40; p.x = Rp * exp(1i*(1:M)'/M*2*pi); p = setupquad(p); % reset proxy pts rhs = [0*s.x; jumps(1)+0*L.x; 0*L.x; jumps(2)+0*B.x; 0*B.x]; % driving [E,~,~,C,Q] = ELSmatrix(s,p,proxyrep,U); w = [0*L.w';L.w';0*B.w';B.w']; % consistency vector in Nul Q^T fprintf('norm w^T Q = %.3g\n',norm(w'*Q)) fprintf('norm Q\\C = %.3g\n',norm(Q\C)) %svd(Q\C) % just one huge sing val, then gap to a decaying sequence. %[U S V] = svd(Q); S = diag(S); r = numel(S); figure; plot(U(:,r),'+-'); end %keyboard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function u = evalsol(s,p,proxyrep,U,z,co) % z = list of targets as C values. p = proxy struct, s = source curve struct % co = full coeff vec, U = unit cell struct. Does potential value only. N = numel(s.x); sig = co(1:N); psi = co(N+1:end); % split up solution coeffs (psi=proxy) u = proxyrep(struct('x',z), p, psi); % init u w/ proxies eval for i=1:numel(U.trlist) % sum potentials faster than srcsum matrices u = u + srcsum(@LapSLP, U.trlist(i),[], struct('x',z), s, sig); % pot of SLP end function J = evalfluxes(s,p,proxyrep,U,co) % inputs as in evalsol. Uses Gary-inspired bdry of 3x3 block far-field method if U.nei~=1, warning('U.neu must equal 1'); end w = U.L.w; if norm(w-U.B.w)>1e-14, error('L and B must have same weights'); end m = numel(w); N = numel(s.x); sig = co(1:N); psi = co(N+1:end); t.x = [U.L.x;U.B.x]; t.nx = [U.L.nx;U.B.nx]; % 2-wall target [~,Tn] = proxyrep(t, p); u = Tn * psi; % proxy contrib to un only J = sum(reshape(u,[m 2])'.*([1;1]*w),2); % .... do its quadr on L,B for i=-1:1 % set up big loop of 12 walls, just their nodes x{i+2} = U.L.x - U.e1 +i*U.e2; x{i+5} = x{i+2} + 3*U.e1; x{i+8} = U.B.x +i*U.e1 -U.e2; x{i+11} = x{i+8} + 3*U.e2; end t.x = vertcat(x{:}); t.nx = [repmat(U.L.nx,[6 1]); repmat(U.B.nx,[6 1])]; [~,un] = LapSLP(t, s, sig); % central density only, many target walls amts = [0 0 0 3 3 3 -1 -2 -3 1 2 3; -1 -2 -3 1 2 3 0 0 0 3 3 3]; % wall wgts J = J + sum(repmat(un',[2 1]).*kron(amts,w),2); % weight each wall function [E A B C Q] = ELSmatrix(s,p,proxyrep,U) % builds matrix blocks for extended linear system. [~,A] = srcsum(@LapSLP, U.trlist,[], s,s); % directly summed self-int matrix N = numel(s.x); A = A - eye(N)/2; % Neumann exterior jump relation [~,B] = proxyrep(s,p); % Neu data from proxies C = Cblock(s,U,@LapSLP); [QL QLn] = proxyrep(U.L,p); [QR QRn] = proxyrep(U.R,p); [QB QBn] = proxyrep(U.B,p); [QT QTn] = proxyrep(U.T,p); Q = [QR-QL; QRn-QLn; QT-QB; QTn-QBn]; E = [A B; C Q]; function C = Cblock(s,U,densrep) % fill C from source curve s to U walls % densrep is handle to LapSLPmat/LapDLPmat depending on density type on curve s nei = U.nei; N = numel(s.x); m = numel(U.L.x); [CL CLn] = srcsum(densrep,nei*U.e1 + (-nei:nei)*U.e2,[], U.L,s); [CR CRn] = srcsum(densrep,-nei*U.e1 + (-nei:nei)*U.e2,[], U.R,s); [CB CBn] = srcsum(densrep,(-nei:nei)*U.e1 + nei*U.e2,[], U.B,s); [CT CTn] = srcsum(densrep,(-nei:nei)*U.e1 - nei*U.e2,[], U.T,s); C = [CR-CL; CRn-CLn; CT-CB; CTn-CBn]; function u = knownsol(U,z,src) % z = targets. U = unit cell struct, src = 1-pt struct, with src.nei for grid. % Potential only. Note use of dipole (monopole ok, but dipole closer to appl) [tx ty] = meshgrid(-src.nei:src.nei); trk = tx(:)+1i*ty(:); % src grid u = srcsum(@LapDLP, trk, [], struct('x',z), src); % pot due to DLP function rhs = knownrhs(src,s,U) % src is a 1-pt struct with x, w, nx; it will be summed over (2*src.nei+1)^2 % grid, w/ unit mag. s is usual target curve (needs normals). % The rhs will always be consistent, with f and g nonconstant. Matches knownsol. [tx ty] = meshgrid(-src.nei:src.nei); trk = tx(:)+1i*ty(:); % src grid [~,f] = srcsum(@LapDLP,trk,[],s,src); % direct Neu data sum to curve U.nei = src.nei; % sets up C correct for src grid g = Cblock(src,U,@LapDLP); % only works if u_ex = (2*U.neu+1)^2 src grid. rhs = [f;g];
github
bobbielf2/BIE2D-master
discarray_effcond.m
.m
BIE2D-master/doublyperiodic/discarray_effcond.m
6,827
utf_8
0cd727ae0e5af132cf84c4aaab8f83c8
function discarray_effcond % Effective conductivity (kappa) of infinite disc array. % Laplace BVP, single inclusion (K=1), native quad for matrix fill, ELS. % Adapted from fig_discarray_drag. Uses helsingeffcond.m % Barnett 9/27/17. Fixed close and reparam 9/28/17 warning('off','MATLAB:nearlySingularMatrix') % backward-stable ill-cond is ok! warning('off','MATLAB:rankDeficientMatrix') lso.RECT = true; % linsolve opts, forces QR even when square, more stable jumps = [1 0]; % pressure driving (jumps) across R-L and T-B schur = 1; % 0 for rect ELS direct solve; 1 for Schur iterative solve verbhel = 0; % print helsing ref soln info U.e1 = 1; U.e2 = 1i; % unit cell; nei=1 for 3x3 scheme U.nei = 1; [tx ty] = meshgrid(-U.nei:U.nei); U.trlist = tx(:)+1i*ty(:); m = 22; [U L R B T] = doublywalls(U,m); proxyrep = @LapSLP; % sets proxy pt type via a kernel function call Rp = 1.4; M = 80; % proxy params p.x = Rp * exp(1i*(0:M-1)'/M*2*pi); p = setupquad(p); % proxy pts %cs = 2; sigs = 10; Ns = 120; close=0; % geom and conductivity params %cs = 10; sigs = 10; Ns = 240; close=1; % geom and conductivity params %cs = 5; sigs = 10; Ns = 900; close=0; % geom and conductivity params %cs = 10; sigs = 10; Ns = 800; reparam=1; close=0; % geom, conductivity params cs = 100; sigs = 100; Ns = 200; reparam=1; close=1; % geom, conductivity params %cs = 1000; sigs = 1000; Ns = 240; reparam=1; close=1; % geom, conductivity params %cs = 10; sigs = 10; Ns = 200; close=1; % geom and conductivity params, fails % reparam: 0: plain trap rule; 1 reparam bunching near touching pts % close: if 0, plain Nystrom for Aelse; if 1, close-eval (slow) chkconv = 0; % if true, check each ans vs bumped-up N if chkconv, cs=kron(cs,[1 1]); sigs=kron(sigs,[1 1]); Ns = kron(Ns,[1 1]) + kron(1+0*Ns,[0 400]); end ts = 0*cs; effconds = 0*cs; % what we compute for i=1:numel(cs) % -------------------- loop over filling fractions N = Ns(i); r0 = 0.5*sqrt(1-1/cs(i)^2); % disc radius h=2*pi*r0/N; delta=(1-2*r0)/h; % quadr spacing h; h-scaled closeness measure lam = (sigs(i)-1)/(sigs(i)+1); % lambda contrast param s = wobblycurve(r0,0,1,N); s.a = 0; % interior pt needed for close only if reparam be = .7*log(cs(i))/log(2); s = reparam_bunched(s,be); s.cur = (1/r0)*ones(N,1); end, %figure; showsegment(s); % check bunching g = [jumps(1)+0*L.x; 0*L.x; jumps(2)+0*B.x; 0*B.x]; rhs = [0*s.x; g]; %driving tic [E,A,Bm,C,Q] = ELSmatrix(s,p,proxyrep,U,lam,close); % fill (w/ close option) if ~schur co = linsolve(E,rhs,lso); % ..... direct bkw stable solve of ELS iter=[0 0]; resvec = 0; % dummies tau = co(1:N); psi = co(N+1:end); else % ..... schur, square well-cond solve R = ones(M,1)/M; H = ones(N,1); % 1s vectors Qtilde = Q + (C*H)*R'; % Gary version of Schur X = linsolve(Qtilde,C,lso); y = linsolve(Qtilde,g,lso); [tau,flag,relres,iter,resvec] = gmres(@(x) A*x - Bm*(X*x), -Bm*y, [], 1e-15, N); % note iter has 2 elements: 2nd is what want xi = y - X*tau; co = [tau;xi]; % build full soln vector end ts(i) = toc; %fprintf('resid norm = %.3g\n',norm(E*co - rhs)) %fprintf('density norm = %.3g, proxy norm = %.3g\n',norm(tau), norm(psi)) J = evalfluxes(s,p,proxyrep,U,co); %fprintf('fluxes (%.16g,%.16g)\n',J(1),J(2)) effconds(i) = J(1); effcondse(i) = helsingeffcond(cs(i),sigs(i),[],verbhel); % reference soln fprintf('c=%g r=%.3g\tN=%d (%.2gh)\t%.3gs\t%d its %.3g\tkap=%.14e\n',cs(i),r0,N,delta,ts(i),iter(2),resvec(end),effconds(i)) fprintf('\t\t\t\trel err from helsing ref = %.3g\n',abs((effconds(i)-effcondse(i))/effcondse(i))) if chkconv & mod(i,2)==0, fprintf('\t\t\t\test rel err = %.3g\n',abs((effconds(i)-effconds(i-1))/effconds(i))), end end % --------------------- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function u = evalsol(s,p,proxyrep,U,z,co) % z = list of targets as C values. p = proxy struct, s = source curve struct % co = full coeff vec, U = unit cell struct. Does potential value only. N = numel(s.x); tau = co(1:N); psi = co(N+1:end); % split up solution coeffs (psi=proxy) u = proxyrep(struct('x',z), p, psi); % init u w/ proxies eval for i=1:numel(U.trlist) % sum potentials faster than srcsum matrices u = u + srcsum(@LapSLP, U.trlist(i),[], struct('x',z), s, tau); % pot of SLP end function J = evalfluxes(s,p,proxyrep,U,co) % inputs as in evalsol. Uses Gary-inspired bdry of 3x3 block far-field method if U.nei~=1, warning('U.neu must equal 1'); end w = U.L.w; if norm(w-U.B.w)>1e-14, error('L and B must have same weights'); end m = numel(w); N = numel(s.x); tau = co(1:N); psi = co(N+1:end); t.x = [U.L.x;U.B.x]; t.nx = [U.L.nx;U.B.nx]; % 2-wall target [~,Tn] = proxyrep(t, p); u = Tn * psi; % proxy contrib to un only J = sum(reshape(u,[m 2])'.*([1;1]*w),2); % .... do its quadr on L,B for i=-1:1 % set up big loop of 12 walls, just their nodes x{i+2} = U.L.x - U.e1 +i*U.e2; x{i+5} = x{i+2} + 3*U.e1; x{i+8} = U.B.x +i*U.e1 -U.e2; x{i+11} = x{i+8} + 3*U.e2; end t.x = vertcat(x{:}); t.nx = [repmat(U.L.nx,[6 1]); repmat(U.B.nx,[6 1])]; [~,un] = LapSLP(t, s, tau); % central density only, many target walls amts = [0 0 0 3 3 3 -1 -2 -3 1 2 3; -1 -2 -3 1 2 3 0 0 0 3 3 3]; % wall wgts J = J + sum(repmat(un',[2 1]).*kron(amts,w),2); % weight each wall function [E A B C Q] = ELSmatrix(s,p,proxyrep,U,lam,close) % builds matrix blocks for extended linear system, SLP rep on curve, w/ close % as option, and lambda conductivity param. N = numel(s.x) if ~close % plain Nystrom for nei interactions... [~,A] = srcsum(@LapSLP, U.trlist,[], s,s); % directly summed self-int matrix else [~,A] = LapSLP(s,s); notself = U.trlist(U.trlist~=0); [~,Ans] = srcsum2(@LapSLP_closeglobal, notself,[],s,s, [],'e'); % dens=[], 'e' exterior A = A + Ans; end A = A + eye(N)/(2*lam); % lambda-modified Neumann exterior jump relation [~,B] = proxyrep(s,p); % Neu data from proxies C = Cblock(s,U,@LapSLP); [QL QLn] = proxyrep(U.L,p); [QR QRn] = proxyrep(U.R,p); [QB QBn] = proxyrep(U.B,p); [QT QTn] = proxyrep(U.T,p); Q = [QR-QL; QRn-QLn; QT-QB; QTn-QBn]; E = [A B; C Q]; function C = Cblock(s,U,densrep) % fill C from source curve s to U walls % densrep is handle to LapSLPmat/LapDLPmat depending on density type on curve s nei = U.nei; N = numel(s.x); m = numel(U.L.x); [CL CLn] = srcsum(densrep,nei*U.e1 + (-nei:nei)*U.e2,[], U.L,s); [CR CRn] = srcsum(densrep,-nei*U.e1 + (-nei:nei)*U.e2,[], U.R,s); [CB CBn] = srcsum(densrep,(-nei:nei)*U.e1 + nei*U.e2,[], U.B,s); [CT CTn] = srcsum(densrep,(-nei:nei)*U.e1 - nei*U.e2,[], U.T,s); C = [CR-CL; CRn-CLn; CT-CB; CTn-CBn];
github
bobbielf2/BIE2D-master
tbl_discarray_effcond.m
.m
BIE2D-master/doublyperiodic/tbl_discarray_effcond.m
6,764
utf_8
b925bed5cfcbc409931d694fb40dae0c
function tbl_discarray_effcond % Make table of effective conductivity (kappa) of infinite disc array, to match % some of Table 2 of J. Helsing, Proc Roy Lond Soc A, 1994. % Laplace BVP, single inclusion (K=1), native quad for matrix fill, ELS. % Adapted from fig_discarray_drag. Uses helsingeffcond.m % Barnett 9/27/17. Fixed close and reparam 9/28/17 warning('off','MATLAB:nearlySingularMatrix') % backward-stable ill-cond is ok! warning('off','MATLAB:rankDeficientMatrix') lso.RECT = true; % linsolve opts, forces QR even when square, more stable jumps = [1 0]; % pressure driving (jumps) across R-L and T-B schur = 1; % 0 for rect ELS direct solve; 1 for Schur iterative solve verbhel = 0; % 1: print helsing ref soln info, 0: don't. U.e1 = 1; U.e2 = 1i; % unit cell; nei=1 for 3x3 scheme U.nei = 1; [tx ty] = meshgrid(-U.nei:U.nei); U.trlist = tx(:)+1i*ty(:); m = 22; [U L R B T] = doublywalls(U,m); proxyrep = @LapSLP; % sets proxy pt type via a kernel function call Rp = 1.4; M = 80; % proxy params p.x = Rp * exp(1i*(0:M-1)'/M*2*pi); p = setupquad(p); % proxy pts cs = [100 100 1000 1000]; % geom and conductivity params sigs = [100 1000 100 1000]; % Hel17 ref val for last: 243.00597813292 Ns = [200 200 200 300]; %cs = 1e3; sigs=1e3; Ns=300; reparam = 1; % 0: plain trap rule; 1 reparam bunching near touching pts close = 1; % 0: plain Nystrom for A. 1: close-eval (slow) chkconv = 1; % if true, check each ans vs bumped-up N if chkconv, cs=kron(cs,[1 1]); sigs=kron(sigs,[1 1]); Ns = kron(Ns,[1 1]) + kron(1+0*Ns,[0 50]); end ts = 0*cs; effconds = 0*cs; % what we compute for i=1:numel(cs) % -------------------- loop over filling fractions N = Ns(i); r0 = 0.5*sqrt(1-1/cs(i)^2); mindist = 1-2*r0; % disc radius lam = (sigs(i)-1)/(sigs(i)+1); % lambda contrast param s = wobblycurve(r0,0,1,N); s.a = 0; % interior pt needed for close only if reparam be = -0.5*log(mindist); s = reparam_bunched(s,be); s.cur = (1/r0)*ones(N,1); end h = min(abs(diff(s.x))); delta=mindist/h; % min quadr spacing; h-scaled closeness measure g = [jumps(1)+0*L.x; 0*L.x; jumps(2)+0*B.x; 0*B.x]; rhs = [0*s.x; g]; %driving tic [E,A,Bm,C,Q] = ELSmatrix(s,p,proxyrep,U,lam,close); % fill (w/ close option) if ~schur co = linsolve(E,rhs,lso); % ..... direct bkw stable solve of ELS tau = co(1:N); psi = co(N+1:end); iter(2)=nan; resvec = nan; % dummies else % ..... schur, square well-cond solve R = ones(M,1)/M; H = ones(N,1); % 1s vectors Qtilde = Q + (C*H)*R'; % Gary version of Schur X = linsolve(Qtilde,C,lso); y = linsolve(Qtilde,g,lso); %W = diag(sqrt(abs(s.xp))); % expt left precond [tau,flag,relres,iter,resvec] = gmres(@(x) A*x - Bm*(X*x), -Bm*y, [], 1e-14, N); % note iter has 2 elements: 2nd is what want %cond(A-Bm*X) % is bad for c,sig large xi = y - X*tau; co = [tau;xi]; % build full soln vector end ts(i) = toc; %fprintf('resid norm = %.3g\n',norm(E*co - rhs)) %fprintf('density norm = %.3g, proxy norm = %.3g\n',norm(tau), norm(psi)) J = evalfluxes(s,p,proxyrep,U,co); %fprintf('fluxes (%.16g,%.16g)\n',J(1),J(2)) effconds(i) = J(1); effcondse(i) = helsingeffcond(cs(i),sigs(i),[],verbhel); % reference soln fprintf('c=%g r=%.3g\tN=%d (%.2gh)\t%.3gs\t%d its %.3g\tkap=%.14e\n',cs(i),r0,N,delta,ts(i),iter(2),resvec(end),effconds(i)) fprintf('\t\t\t\trel err from helsing ref (%.15g) = %.3g\n',effcondse(i),abs((effconds(i)-effcondse(i))/effcondse(i))) if chkconv & mod(i,2)==0, fprintf('\t\t\t\test rel err = %.3g\n',abs((effconds(i)-effconds(i-1))/effconds(i))), end end % --------------------- %figure; showsegment(s); ss=s; ss.x=ss.x+1; showsegment(ss); % view quadr %keyboard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function u = evalsol(s,p,proxyrep,U,z,co) % z = list of targets as C values. p = proxy struct, s = source curve struct % co = full coeff vec, U = unit cell struct. Does potential value only. N = numel(s.x); tau = co(1:N); psi = co(N+1:end); % split up solution coeffs (psi=proxy) u = proxyrep(struct('x',z), p, psi); % init u w/ proxies eval for i=1:numel(U.trlist) % sum potentials faster than srcsum matrices u = u + srcsum(@LapSLP, U.trlist(i),[], struct('x',z), s, tau); % pot of SLP end function J = evalfluxes(s,p,proxyrep,U,co) % inputs as in evalsol. Uses Gary-inspired bdry of 3x3 block far-field method if U.nei~=1, warning('U.neu must equal 1'); end w = U.L.w; if norm(w-U.B.w)>1e-14, error('L and B must have same weights'); end m = numel(w); N = numel(s.x); tau = co(1:N); psi = co(N+1:end); t.x = [U.L.x;U.B.x]; t.nx = [U.L.nx;U.B.nx]; % 2-wall target [~,Tn] = proxyrep(t, p); u = Tn * psi; % proxy contrib to un only J = sum(reshape(u,[m 2])'.*([1;1]*w),2); % .... do its quadr on L,B for i=-1:1 % set up big loop of 12 walls, just their nodes x{i+2} = U.L.x - U.e1 +i*U.e2; x{i+5} = x{i+2} + 3*U.e1; x{i+8} = U.B.x +i*U.e1 -U.e2; x{i+11} = x{i+8} + 3*U.e2; end t.x = vertcat(x{:}); t.nx = [repmat(U.L.nx,[6 1]); repmat(U.B.nx,[6 1])]; [~,un] = LapSLP(t, s, tau); % central density only, many target walls amts = [0 0 0 3 3 3 -1 -2 -3 1 2 3; -1 -2 -3 1 2 3 0 0 0 3 3 3]; % wall wgts J = J + sum(repmat(un',[2 1]).*kron(amts,w),2); % weight each wall function [E A B C Q] = ELSmatrix(s,p,proxyrep,U,lam,close) % builds matrix blocks for extended linear system, SLP rep on curve, w/ close % as option, and lambda conductivity param. N = numel(s.x) if ~close % plain Nystrom for nei interactions... [~,A] = srcsum(@LapSLP, U.trlist,[], s,s); % directly summed self-int matrix else [~,A] = LapSLP(s,s); notself = U.trlist(U.trlist~=0); [~,Ans] = srcsum2(@LapSLP_closeglobal, notself,[],s,s, [],'e'); % dens=[], 'e' exterior A = A + Ans; end A = A + eye(N)/(2*lam); % lambda-modified Neumann exterior jump relation [~,B] = proxyrep(s,p); % Neu data from proxies C = Cblock(s,U,@LapSLP); [QL QLn] = proxyrep(U.L,p); [QR QRn] = proxyrep(U.R,p); [QB QBn] = proxyrep(U.B,p); [QT QTn] = proxyrep(U.T,p); Q = [QR-QL; QRn-QLn; QT-QB; QTn-QBn]; E = [A B; C Q]; function C = Cblock(s,U,densrep) % fill C from source curve s to U walls % densrep is handle to LapSLPmat/LapDLPmat depending on density type on curve s nei = U.nei; N = numel(s.x); m = numel(U.L.x); [CL CLn] = srcsum(densrep,nei*U.e1 + (-nei:nei)*U.e2,[], U.L,s); [CR CRn] = srcsum(densrep,-nei*U.e1 + (-nei:nei)*U.e2,[], U.R,s); [CB CBn] = srcsum(densrep,(-nei:nei)*U.e1 + nei*U.e2,[], U.B,s); [CT CTn] = srcsum(densrep,(-nei:nei)*U.e1 - nei*U.e2,[], U.T,s); C = [CR-CL; CRn-CLn; CT-CB; CTn-CBn];
github
bobbielf2/BIE2D-master
fig_lapQconv.m
.m
BIE2D-master/doublyperiodic/fig_lapQconv.m
4,226
utf_8
53cb37327b9b69b670d62166e6490497
function fig_lapQconv % make figs for doubly periodic empty BVP convergence, Laplace case. % All matrix-filling, native quadr. % Barnett 5/9/16, adapted from perineu2dnei1.m. bie2d 6/29/16 warning('off','MATLAB:nearlySingularMatrix') % backward-stable ill-cond is ok! warning('off','MATLAB:rankDeficientMatrix') lso.RECT = true; % linsolve opts, forces QR even when square (LU much worse) rho=1.5; z0 = rho * exp(0.7i); % singularity in v exact soln ve = @(z) log(abs(z-z0)); % exact soln and its partials... vex = @(z) real(z-z0)./abs(z-z0).^2; vey = @(z) imag(z-z0)./abs(z-z0).^2; disp('test partials of known exact v:'); testpartials(ve,vex,vey) U.e1 = 1; U.e2 = 1i; % unit cell lattice vectors Rp = 1.4; % proxy radius M = 100; p.x = Rp * exp(1i*(0:M-1)'/M*2*pi); p = setupquad(p); % proxy pts proxyrep = @LapSLP; % sets proxy pt type via a kernel function call nt = 100; t.x = rand(nt,1)-0.5 + 1i*(rand(nt,1)-0.5); % rand test pts in UC %[xx yy] = meshgrid(linspace(-.5,.5,10)); t.x = xx(:)+1i*yy(:); % tp grid in UC Atest = proxyrep(t,p); % evaluation matrix, only changes when M does % m-conv plot (# wall pts) ms = 2:2:24; verrs = nan*ms; for i=1:numel(ms) [U L R B T] = doublywalls(U,ms(i)); Q = Qmat(p,L,R,B,T,proxyrep); g = discrep(L,R,B,T,ve,vex,vey); xi = linsolve(Q,g,lso); %norm(xi) verr = Atest*xi - ve(t.x); % err at all test pts verr = verr-verr(1); % fix the offset using the first test pt verrs(i) = max(abs(verr)); end %figure; showsegment({p L R T B}); hold on; plot(z0,'*'); figure; semilogy(ms,verrs,'+-'); xlabel('m'); ylabel('max abs error in v'); axis([min(ms) max(ms) 1e-16 1]); text(4,1e-1,'(a)','fontsize',12); text(15,1e-1,sprintf('$M=%d$',M),'interpreter','latex','fontsize',12); set(gcf,'paperposition',[0 0 3 3]); %print -depsc2 figs/lapQmconv.eps m = 22; [U L R B T] = doublywalls(U,m); g = discrep(L,R,B,T,ve,vex,vey); % fix w = [0*L.w L.w 0*B.w B.w]'; % supposed left null-vector (note v will not be) nsings = 6; % how many singular values to keep and show Ms = 10:5:120; verrs = nan*Ms'; sings = nan(numel(Ms),nsings); nrms = verrs; nwtqs = verrs; for i=1:numel(Ms), M = Ms(i); % # proxy pts conv p.x = Rp * exp(1i*(1:M)'/M*2*pi); p = setupquad(p); % proxy pts Atest = proxyrep(t,p); % evaluation matrix Q = Qmat(p,L,R,B,T,proxyrep); nwtqs(i) = norm(w'*Q); % check left null vector S = svd(Q); % nkeep = min(numel(S),nsings); sings(i,1:nkeep) = S(end-nkeep+1:end); sings(i,1) = max(S); sings(i,2:nsings) = S(end-nsings+2:end); % 1st & last few xi = linsolve(Q,g,lso); nrms(i) = norm(xi); verr = Atest*xi - ve(t.x); % err at all test pts verr = verr-verr(1); % fix the offset using the first test pt verrs(i) = max(abs(verr)); %if M==40, [U S V] = svd(Q); V(:,end), Atest*V(:,end), end % sing vec is approx constant, and generates consts to high acc end figure; semilogy(Ms,[verrs],'+-'); hold on; semilogy(Ms,sings(:,2:end),'-','color',.5*[1 1 1]); semilogy(Ms,nrms,'go-'); % semilogy(Ms,nwtqs,'rs-'); % boring, always zero rB = sqrt(0.5); semilogy(Ms,0.05*(rho/rB).^(-Ms/2),'r--'); % conv rate! xlabel('M'); %ylabel('max abs error in v'); axis([min(Ms) max(Ms) 1e-17 max(nrms)]); text(15,max(nrms)/10,'(b)','fontsize',12); text(90,max(nrms)/10,sprintf('$m=%d$',m),'interpreter','latex','fontsize',12); set(gcf,'paperposition',[0 0 3 3]); set(gca,'ytickmode','manual', 'ytick',[1e-15 1e-10 1e-5 1 1e5]); %print -depsc2 figs/lapQMconv.eps %%%%%%%%%%%%%%%%% function testpartials(v,vx,vy) % finite differencing test of analytic partials eps = 1e-5; z = 1-0.5i; vx(z) - (v(z+eps)-v(z-eps))/(2*eps) % should be around 1e-10 vy(z) - (v(z+1i*eps)-v(z-1i*eps))/(2*eps) % " function Q = Qmat(p,L,R,B,T,proxyrep) % matrix Q given proxy and colloc pts [QL QLn] = proxyrep(L,p); [QR QRn] = proxyrep(R,p); [QB QBn] = proxyrep(B,p); [QT QTn] = proxyrep(T,p); Q = [QR-QL; QRn-QLn; QT-QB; QTn-QBn]; function g = discrep(L,R,B,T,v,vx,vy) % discrepancy of known solution % v, vx, vy are funcs from C to R. Output is 4m col vec g1 = v(R.x)-v(L.x); g2 = vx(R.x)-vx(L.x); % assumes vert g3 = v(T.x)-v(B.x); g4 = vy(T.x)-vy(B.x); % assumes horiz g = [g1;g2;g3;g4];
github
bobbielf2/BIE2D-master
fig_stoconvK1.m
.m
BIE2D-master/doublyperiodic/fig_stoconvK1.m
14,350
utf_8
a14b0223bf06c064ce2f6832f4f9e102
function fig_stoconvK1 % make Stokes no-slip periodic convergence and soln plots. % Single inclusion (K=1), native quad for matrix fill, close eval for soln. % Adapted from fig_lapconvK1.m % Barnett 6/7/16. 6/30/16 brought into BIE2D. % X,y,R,H notation, Gary's V=CH, Alex's nullspace fix, nonrandom. 8/17/16 warning('off','MATLAB:nearlySingularMatrix') % backward-stable ill-cond is ok! warning('off','MATLAB:rankDeficientMatrix') lso.RECT = true; % linsolve opts, forces QR even when square mu = 0.7; % overall viscosity const for Stokes PDE sd = [1 1]; % layer potential representation prefactors for SLP & DLP resp. jumps = [1 0]; %[0 1]; % pressure jumps across R-L and T-B (not for known soln) U.e1 = 1; U.e2 = 1i; % unit cell; nei=1 for 3x3 scheme U.nei = 1; [tx ty] = meshgrid(-U.nei:U.nei); U.trlist = tx(:)+1i*ty(:); m = 22; [U L R B T] = doublywalls(U,m); proxyrep = @StoSLP; % sets proxy pt type via a kernel function call Rp = 1.4; M = 70; % proxy params - 80 is 1-2 digits worse than 70 or 120 - why? p.x = Rp * exp(1i*(0:M-1)'/M*2*pi); p = setupquad(p); % proxy pts a = 0.7; b = 0.15; % worm params, spills horizontally out of any unit cell uex = [0.016778793238;0.005152952237]; flux1ex = 0.008234042360; % a=.7,b=.15 % known soln stokeslet location & force: must be deep inside Omega (careful) src.x = 0.42+.23i; src.w = 1; src.nx = 1+0i; fsrc = [0.8;0.6]; src.nei = 5; % -------------------------- single soln and plot N = 150; s = wormcurve(a,b,N); s.a = mean(s.x); % a needed for p ext close %s.x = s.x + 0.1i; % check translational invariance of flux % obstacle no-slip & pressure-drop driving... rhs = [zeros(2*N,1); zeros(2*m,1);jumps(1)+0*L.x;zeros(4*m,1);jumps(2)+0*B.x]; tic E = ELSmatrix(s,p,proxyrep,mu,sd,U); % fill co = linsolve(E,rhs,lso); % direct bkw stable solve toc %S = svd(E); disp('last few sing vals of E:'), S(end-5:end) % dim Nul E = 1 fprintf('resid norm = %.3g\n',norm(E*co - rhs)) sig = co(1:2*N); psi = co(N+1:end); fprintf('density norm = %.3g, proxy norm = %.3g\n',norm(sig), norm(psi)) fprintf('body force + jumps = (%.3g,%.3g) should vanish\n',s.w'*sig(1:N)+abs(U.e1)*jumps(1),s.w'*sig(N+1:end)+abs(U.e2)*jumps(2)) z = .1+.4i; % test pt [u p0] = evalsol(s,p,proxyrep,mu,sd,U,z,co); % native quad (far) test fprintf('u at pt = (%.16g,%.16g) \t(est abs err: %.3g)\n',u(1),u(2),norm(u-uex)) tic; J = evalfluxes(s,p,proxyrep,mu,sd,U,co); toc fprintf('fluxes (%.16g,%.16g) (est abs err: %.3g)\n',J(1),J(2),abs(J(1)-flux1ex)) if 0 % soln flow figure nx = 201; gx = 0.5*((0:nx-1)/(nx-1)*2-1); ng = nx^2; % fine pres eval grid gy = gx; [zz ii] = extgrid(gx,gy,s,U); pg = nan(ng,1); % pressure on fine grid tic; [~,pg(ii)] = evalsol(s,p,proxyrep,mu,sd,U,zz(ii),co,1); toc pg = reshape(pg,[nx nx]) - p0; % shift to pres=0 at test pt figure; contourf(gx,gy,pg,[-.6:.1:.6]); colormap(jet(256)); hold on; nx = 26; gx = 0.5*((0:nx-1)/(nx-1)*2-1); ng = nx^2; % coarse vel eval grid gy = gx; [zz ii] = extgrid(gx,gy,s,U); ug = nan(2*ng,1); tic; ug([ii;ii]) = evalsol(s,p,proxyrep,mu,sd,U,zz(ii),co,1); toc u1 = reshape(ug(1:ng),[nx nx]); u2 = reshape(ug(ng+1:end),[nx nx]); % u cmpts % the following sends only the non-nan parts of grid since otherwise get dots: quiver(real(zz(ii)),imag(zz(ii)),u1(ii),u2(ii),2.0,'k-'); % show vec field n=1; for i=-n:n, for j=-n:n, plot([s.x;s.x(1)]+j+1i*i,'-'); end,end % curves plot([L.x;R.x;T.x;B.x],'b.'); % wall nodes axis xy equal off; plot(z,'k.'); axis([0 1 0 1]-0.5); %for i=-1:1, for j=-1:1, plot(src.x+U.e1*i+U.e2*j,'k*'); end, end % known text(0,0,'$\Omega$','interpreter','latex','fontsize',14); text(-.58,.45,'(a)'); %,'fontsize',14); drawnow; %set(gcf,'paperposition',[0 0 4 4]); print -depsc2 figs/stosolK1.eps end if 1, Ns = 30:10:230; % ------------------------ N-convergence us = nan(2,numel(Ns)); ust = us; Js = us; Jst = Js; es = nan(1,numel(Ns)); res = es; rest = es; uek = knownsol(U,z,src,fsrc,mu); % known stokeslet 3x3 grid soln, fixed %v = zeros(8*m,3); % obsolete Sifuentes vector %v(2*m+1:3*m,1) = -1; v(7*m+1:8*m,2) = -1; % x,y force balance (g_3,g_4) %v(1:m,3) = 1; v(5*m+1:6*m,3) = 1; % mass cons (g_1 + g_2) %R = randn(2*M,3)/M; % randomized version R = [[ones(M,1);zeros(M,1)],[zeros(M,1);ones(M,1)],[real(p.x);imag(p.x)]]/M; for i=1:numel(Ns), N = Ns(i); s = wormcurve(a,b,Ns(i)); g = [zeros(2*m,1);jumps(1)+0*L.x;zeros(4*m,1);jumps(2)+0*B.x]; % pres driving rhs = [zeros(2*N,1); g]; % driving [E,A,Bm,C,Q] = ELSmatrix(s,p,proxyrep,mu,sd,U); co = linsolve(E,rhs,lso); res(i) = norm(E*co - rhs); us(:,i) = evalsol(s,p,proxyrep,mu,sd,U,z,co); % both cmpts of vel Js(:,i) = evalfluxes(s,p,proxyrep,mu,sd,U,co); % three non-consistent vectors of inclusion density (Gary)... H = [ones(1,N) zeros(1,N);zeros(1,N) ones(1,N);real(s.nx)' imag(s.nx)']'; %H = randn(2*N,3); % randomized version Qtilde = Q + (C*H)*R'; % Gary version of Schur %if i==1, norm(Q), norm(C*H*R'), svd(Q), svd(Qtilde), end % sim size norms? X = linsolve(Qtilde,C,lso); y = linsolve(Qtilde,g,lso); %Bm = Bm + (A*H)*R'; % Gary version of my B corr, preserves nullity 1 Bm = Bm + (A*H(:,1:2))*R(:,1:2)'; % Alex taut = gmres(@(x) A*x - Bm*(X*x), -Bm*y, [], 1e-14, Ns(i)); %cond(A - Bm*X) % 82.7 xit = y - X*taut; taut = taut + H*(R'*xit); % Gary correction cot = [taut;xit]; % build full soln vector pair rest(i) = norm(E*cot - rhs); % residual back in ELS ust(:,i) = evalsol(s,p,proxyrep,mu,sd,U,z,cot); Jst(:,i) = evalfluxes(s,p,proxyrep,mu,sd,U,cot); % Schur flux rhsk = knownrhs(src,fsrc,mu,s,U); % RHS for known 3x3 stokeslet soln... cok = linsolve(E,rhsk,lso); % coeffs for approx to known soln %norm(E*cok - rhsk) % resid for known soln - plot? uk = evalsol(s,p,proxyrep,mu,sd,U,z,cok); % eval this approx es(i) = norm(uk-uek); % err in known case vs exact end fprintf('norm X=Qt\\C is %.3g\n',norm(X)) %[U S V] = svd(E); V(:,end) % show that Nul E = [0;stuff], ie tau unique disp('u1 N-convergence for ELS, Schur, their diff:') [us(1,:)',ust(1,:)',us(1,:)'-ust(1,:)'] % 1st cmpt: u is ELS, ut is Schur disp('J1 N-convergence for ELS, Schur, their diff:') [Js(1,:)',Jst(1,:)',Js(1,:)'-Jst(1,:)'] %[Js(2,:)',Jst(2,:)',Js(2,:)'-Jst(2,:)'] figure; %semilogy(Ns,res,'ro-'); % why is resid always around 1e-14? uerr = sqrt(sum((us-repmat(us(:,end),[1 numel(Ns)])).^2,1)); % 2-norm u errs semilogy(Ns,uerr,'+-'); hold on; plot(Ns,abs(Js(1,:)-Js(1,end)),'go-'); uerrt = sqrt(sum((ust-repmat(ust(:,end),[1 numel(Ns)])).^2,1)); % 2-norm ut errs plot(Ns,uerrt,'+--'); plot(Ns,abs(Jst(1,:)-Jst(1,end)),'go--'); %plot(Ns,res,'r*-'); plot(Ns,rest,'rd-'); plot(Ns,es,'ks-'); legend('u conv ELS','J_1 conv ELS','u conv Schur','J_1 conv Schur','u err vs known'); %legend('u conv ELS','J_1 conv ELS','u conv Schur','J_1 conv Schur','resid ELS','resid Schur','u err vs known'); xlabel('N'); text(70,1e-4,'(c)'); text(140,1e-8, sprintf('$M=%d$, $m=%d$',M,m),'interpreter','latex'); axis([Ns(1) Ns(end-1) 1e-15 1e-3]); %set(gcf,'paperposition',[0 0 3.5 3.5]); print -depsc2 figs/stoconvK1.eps end if 0, Ms = 10:5:120; % -------------------- M convergence (not incl Schur) N = 100; s = wormcurve(a,b,N); % fixed g = [zeros(2*m,1);jumps(1)+0*L.x;zeros(4*m,1);jumps(2)+0*B.x]; % pres driving rhs = [zeros(2*N,1); g]; % driving Js = nan(2,numel(Ms)); nrms = nan*Ms; nsings = 6; sings = nan(numel(Ms),nsings); % save some sing vals for i=1:numel(Ms) p.x = Rp * exp(1i*(1:Ms(i))'/Ms(i)*2*pi); p = setupquad(p); % reset proxy pts E = ELSmatrix(s,p,proxyrep,mu,sd,U); S = svd(E); sings(i,1) = max(S); sings(i,2:nsings) = S(end-nsings+2:end); % 1st & last few co = linsolve(E,rhs,lso); nrms(i) = norm(co); Js(:,i) = evalfluxes(s,p,proxyrep,mu,sd,U,co); end Js(1,:)' figure; semilogy(Ms,abs(Js(1,:)-Js(1,end)),'b+-'); hold on; semilogy(Ms,sings(:,2:end),'-','color',.5*[1 1 1]); semilogy(Ms,nrms,'b.-'); % *** TODO: bring in K=1e3 M-conv data and add to plot as squares text(15,max(nrms)/10,'(e)'); text(60,max(nrms)/10,sprintf('$N=%d, m=%d$',N,m),'interpreter','latex'); xlabel('M'); axis([Ms(1) Ms(end-1) 1e-17 max(nrms)]); %set(gcf,'paperposition',[0 0 3 3]); print -depsc2 figs/stoMconv.eps end if 0 % ------------ Schur tests warm-up (see above for convergence) N = 140; s = wormshape(a,b,N); % reset curve M = 40; p.x = Rp * exp(1i*(1:M)'/M*2*pi); p = quadr(p); % reset proxy pts rhs = [0*s.x; jumps(1)+0*L.x; 0*L.x; jumps(2)+0*B.x; 0*B.x]; % driving [E,~,~,C,Q] = ELSmatrix(s,p,proxyrep,U); w = [0*L.w';L.w';0*B.w';B.w']; % consistency vector in Nul Q^T fprintf('norm w^T Q = %.3g\n',norm(w'*Q)) fprintf('norm Q\\C = %.3g\n',norm(Q\C)) %svd(Q\C) % just one huge sing val, then gap to a decaying sequence. %[U S V] = svd(Q); S = diag(S); r = numel(S); figure; plot(U(:,r),'+-'); end %keyboard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [u p] = evalsol(s,pr,proxyrep,mu,sd,U,z,co,close) % eval soln rep u,p % z = list of targets as C values. pr = proxy struct, s = source curve struct % co = full coeff vec, U = unit cell struct, mu = viscosity % sd = prefactors for source rep, close enables special close quadr. % Note: not for self-eval since srcsum2 used, 6/30/16 if nargin<9, close=0; end % default is plain native quadr z = struct('x',z); % make targets z a segment struct N = numel(s.x); sig = co(1:2*N); psi = co(2*N+1:end); % split into sig (density) & psi (proxy) if close, S = @(t,s,mu,dens) StoSLP_closeglobal(t,s,mu,dens,'e'); % exterior D = @(t,s,mu,dens) StoDLP_closeglobal(t,s,mu,dens,'e'); else, S = @StoSLP; D = @StoDLP; end % NB now native & close have same 4 args if nargout==1 % don't want pressure output u = proxyrep(z,pr,mu,psi); % init sol w/ proxies (always far) u = u + sd(1)*srcsum2(S,U.trlist,[],z,s,mu,sig) + sd(2)*srcsum2(D,U.trlist,[],z,s,mu,sig); else [u p] = proxyrep(z,pr,mu,psi); % init sol w/ proxies (always far) [uS pS] = srcsum2(S,U.trlist,[],z,s,mu,sig); [uD pD] = srcsum2(D,U.trlist,[],z,s,mu,sig); u = u + sd(1)*uS + sd(2)*uD; p = p + sd(1)*pS + sd(2)*pD; end function J = evalfluxes(s,p,proxyrep,mu,sd,U,co) % inputs as in evalsol. Uses Gary-inspired bdry of 3x3 block far-field method if U.nei~=1, warning('U.neu must equal 1'); end w = U.L.w; if norm(w-U.B.w)>1e-14, error('L and B must have same weights'); end m = numel(w); N = numel(s.x); sig = co(1:2*N); psi = co(2*N+1:end); t.x = [U.L.x;U.B.x]; t.nx = [U.L.nx;U.B.nx]; % 2-wall target v = proxyrep(t, p, mu, psi); % flow vel on L+B u = v(1:2*m).*real(t.nx) + v(2*m+1:end).*imag(t.nx); % proxy contrib to u = v.n J = sum(reshape(u,[m 2])'.*([1;1]*w),2); % .... do its quadr on L,B for i=-1:1 % set up big loop of 12 walls, just their nodes x{i+2} = U.L.x - U.e1 +i*U.e2; x{i+5} = x{i+2} + 3*U.e1; x{i+8} = U.B.x +i*U.e1 -U.e2; x{i+11} = x{i+8} + 3*U.e2; end t.x = vertcat(x{:}); t.nx = [repmat(U.L.nx,[6 1]); repmat(U.B.nx,[6 1])]; v = sd(1)*StoSLP(t,s,mu,sig) + sd(2)*StoDLP(t,s,mu,sig); % ctr copy only u = v(1:12*m).*real(t.nx) + v(12*m+1:end).*imag(t.nx); % v.n, as col vec amts = [0 0 0 3 3 3 -1 -2 -3 1 2 3; -1 -2 -3 1 2 3 0 0 0 3 3 3]; % wall wgts J = J + sum(repmat(u',[2 1]).*kron(amts,w),2); % weight each wall function [E A B C Q] = ELSmatrix(s,p,proxyrep,mu,sd,U) % builds matrix blocks for Stokes extended linear system, S+D rep w/ Kress self N = numel(s.x); A = sd(1)*srcsum(@StoSLP,U.trlist,[],s,s,mu) + sd(2)*(eye(2*N)/2 + srcsum(@StoDLP,U.trlist,[],s,s,mu)); % notes: DLP gives exterior JR term; srcsum self is ok B = proxyrep(s,p,mu); % map from proxy density to vel on curve C = Cblock(s,U,mu,sd); [QL,~,QLt] = proxyrep(U.L,p,mu); [QR,~,QRt] = proxyrep(U.R,p,mu); % vel, tract [QB,~,QBt] = proxyrep(U.B,p,mu); [QT,~,QTt] = proxyrep(U.T,p,mu); Q = [QR-QL; QRt-QLt; QT-QB; QTt-QBt]; E = [A B; C Q]; function C = Cblock(s,U,mu,sd) % fill C from source curve s to U walls % sd controls prefactors on SLP & DLP for Stokes rep on the obstacle curve n = U.nei; e1 = U.e1; e2 = U.e2; S = @StoSLP; D = @StoDLP; % abbrevs trlist = n*e1 + (-n:n)*e2; [CLS,~,TLS] = srcsum(S,trlist,[],U.L,s,mu); [CLD,~,TLD] = srcsum(D,trlist,[],U.L,s,mu); trlist = -n*e1 + (-n:n)*e2; [CRS,~,TRS] = srcsum(S,trlist,[],U.R,s,mu); [CRD,~,TRD] = srcsum(D,trlist,[],U.R,s,mu); trlist = (-n:n)*e1 + n*e2; [CBS,~,TBS] = srcsum(S,trlist,[],U.B,s,mu); [CBD,~,TBD] = srcsum(D,trlist,[],U.B,s,mu); trlist = (-n:n)*e1 - n*e2; [CTS,~,TTS] = srcsum(S,trlist,[],U.T,s,mu); [CTD,~,TTD] = srcsum(D,trlist,[],U.T,s,mu); C = sd(1)*[CRS-CLS; TRS-TLS; CTS-CBS; TTS-TBS] +... sd(2)*[CRD-CLD; TRD-TLD; CTD-CBD; TTD-TBD]; function u = knownsol(U,z,src,fsrc,mu) % z = targets. U = unit cell struct, src = 1-pt struct, fsrc = source force vec. % src.nei sets the src grid. output vel only [tx ty] = meshgrid(-src.nei:src.nei); trk = tx(:)+1i*ty(:); % grid u = srcsum(@StoSLP, trk, [], struct('x',z), src, mu, fsrc); % dens=fsrc function rhs = knownrhs(src,fsrc,mu,s,U) % src is a 1-pt struct with x, w, nx; it will be summed over sec.nei grid, % unit mag. s is usual target curve (needs normals). fsrc = source force vec. % The rhs will always be consistent, with f and g nonconstant. Matches knownsol. [tx ty] = meshgrid(-src.nei:src.nei); trk = tx(:)+1i*ty(:); % src grid f = srcsum(@StoSLP,trk,[],s,src,mu, fsrc); % direct vel data sum to curve U.nei = src.nei; % sets up C correct for src grid g = Cblock(src,U,mu,[1 0]) * fsrc; % sd sets SLP only rhs = [f;g]; function [zz ii] = extgrid(gx,gy,s,U) % grid points and indices outside Omegas % given gx,gy 1d x,y grids, s=curve segment, U = unit cell struct, return % zz = col list of grid pts as C-#s, and ii = logical index array if outside % Omega and all images [xx yy] = meshgrid(gx,gy); zz = (xx(:)+1i*yy(:)); clear xx yy; ii = true(size(zz)); % indices outside Omega or its copies for i=-1:1, for j=-1:1, si = s.inside(zz+U.e1*i+U.e2*j); ii(si)=false; end, end
github
bobbielf2/BIE2D-master
tbl_discarray_drag.m
.m
BIE2D-master/doublyperiodic/tbl_discarray_drag.m
7,934
utf_8
d8f267701cfcdf9fb46e2a2508f94771
function tbl_discarray_drag % Generate table of dimensionless drag of regular array of discs, to match % Table 1 of Greengard-Kropinski, J. Engs. Math. 48: 157–170, 2004. % Single inclusion (K=1), native quad for matrix fill, ELS. % Adapted from fig_stoconvK1.m % Barnett 8/2/16, graded parameterization 10/7/17 warning('off','MATLAB:nearlySingularMatrix') % backward-stable ill-cond is ok! warning('off','MATLAB:rankDeficientMatrix') lso.RECT = true; % linsolve opts, forces QR even when square, more stable mu = 0.8; % overall viscosity const for Stokes PDE, can be anything positive sd = [1 1]; % layer potential representation prefactors for SLP & DLP resp. jumps = [1 0]; % pressure jumps across R-L and T-B schur = 1; % 0 for rect ELS direct solve; 1 for Schur iterative solve % Note: schur loses the last around 1 digit when close. U.e1 = 1; U.e2 = 1i; % unit cell; nei=1 for 3x3 scheme U.nei = 1; [tx ty] = meshgrid(-U.nei:U.nei); U.trlist = tx(:)+1i*ty(:); m = 22; [U L R B T] = doublywalls(U,m); proxyrep = @StoSLP; % sets proxy pt type via a kernel function call Rp = 1.4; M = 80; % proxy params p.x = Rp * exp(1i*(0:M-1)'/M*2*pi); p = setupquad(p); % proxy pts convstudy = 0; if convstudy % set up a convergence study at a single c param... cs = 0.77; % close: if 0, plain Nystrom for Aelse; if 1, close-eval (slow 10s @ N=200!) : close = 0; Ns = 400:40:1000; % gets 5e-9 rel err, by N=650 (~6h). %close = 1; Ns = 50:20:200; % gets slightly worse than 1e-8 rel err, by N=90 reparam = 1; % 0: plain trap rule; 1 reparam bunching near touching pts cs = cs*ones(size(Ns)); chkconv=0; % set up for the conv study else % generate the table (with error estimation for each) close=0; reparam=1; % vol fracs, from G-K 04 paper, plus one more... cs = [0.05 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.75 0.76 0.77 0.78]; Ns = [60 60 60 100 150 150 300 400 500 600 700 1300]; %cs=0.78; Ns=1300; close = 0; % for fun %cs=0.78; Ns=200; close = 1; % for fun, tiny N, but loses a digit chkconv = 1; % 1: check each ans vs bumped-up N's (~3x time) if chkconv, cs=kron(cs,[1 1 1 1]); Ns = kron(Ns,[1 1 1 1]) + kron(1+0*Ns,[0 100 200 300]); end % use three higher N values to estimate error end ts = 0*cs; Dcalcs = 0*cs; % what we compute % "ones vectors" for schur: R = [[ones(M,1);zeros(M,1)],[zeros(M,1);ones(M,1)],[real(p.x);imag(p.x)]]/M; for i=1:numel(cs) % -------------------- loop over filling fractions N = Ns(i); r0 = sqrt(cs(i)/pi); mindist = 1-2*r0; s = wobblycurve(r0,0,1,N); s.a=0; if reparam be = -0.5*log(mindist); s = reparam_bunched(s,be); s.cur = (1/r0)*ones(N,1); end h = min(abs(diff(s.x))); delta=mindist/h; % min quadr spacing; h-scaled closeness measure % obstacle no-slip & pressure-drop driving... g = [zeros(2*m,1);jumps(1)+0*L.x;zeros(4*m,1);jumps(2)+0*B.x]; % pres driving rhs = [zeros(2*N,1); g]; tic [E,A,Bm,C,Q] = ELSmatrix(s,p,proxyrep,mu,sd,U,close); % fill (w/ close option) if ~schur co = linsolve(E,rhs,lso); % ..... direct bkw stable solve of ELS sig = co(1:2*N); psi = co(N+1:end); iter(2)=nan; resvec=nan; % dummies else % ..... schur, square well-cond solve H = [ones(1,N) zeros(1,N);zeros(1,N) ones(1,N);real(s.nx)' imag(s.nx)']'; Qtilde = Q + (C*H)*R'; % Gary version of Schur X = linsolve(Qtilde,C,lso); y = linsolve(Qtilde,g,lso); Bm = Bm + (A*H(:,1:2))*R(:,1:2)'; % Alex %tauhat = linsolve(A-Bm*X,-Bm*y,lso); iter(2)=nan; resvec=nan; % dummies [tauhat,flag,relres,iter,resvec] = gmres(@(x) A*x - Bm*(X*x), -Bm*y, [], 1e-14, Ns(i)); % note iter has 2 elements, 2nd is what want %if i==21, S = svd(A - Bm*X), keyboard, end % cond only 2e3 %fprintf('cond of gmres lin sys = %.3g\n',cond(A-Bm*X)) xi = y - X*tauhat; tau = tauhat + H*(R'*xi); % Gary correction co = [tau;xi]; % build full soln vector end ts(i) = toc; %fprintf('resid norm = %.3g\n',norm(E*co - rhs)) %fprintf('density norm = %.3g, proxy norm = %.3g\n',norm(sig), norm(psi)) J = evalfluxes(s,p,proxyrep,mu,sd,U,co); %fprintf('fluxes (%.16g,%.16g)\n',J(1),J(2)) Dcalcs(i) = 1/(J(1)*mu); % dimless drag; note force = 1 fprintf('c=%g r=%.3g\tN=%d (%.2gh)\t%.3gs\t%d its %.3g\tD=%.14e\n',cs(i),r0,N,delta,ts(i),iter(2),resvec(end),Dcalcs(i)) if chkconv & mod(i,4)==0, fprintf('\t\t est rel err = %.3g\n',max(abs(Dcalcs(i)-Dcalcs(i-3:i-1)))/Dcalcs(i)), end end % --------------------- Dcalcs if convstudy, figure; semilogy(Ns,abs(Dcalcs-Dcalcs(end))/abs(Dcalcs(end)),'+-'); xlabel('N'); ylabel('rel err'); title('tbl discarray drag: conv study'); end %figure; showsegment(s); ss=s; ss.x=ss.x+1; showsegment(ss); % view quadr %keyboard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function J = evalfluxes(s,p,proxyrep,mu,sd,U,co) % inputs as in evalsol. Uses Gary-inspired bdry of 3x3 block far-field method if U.nei~=1, warning('U.neu must equal 1'); end w = U.L.w; if norm(w-U.B.w)>1e-14, error('L and B must have same weights'); end m = numel(w); N = numel(s.x); sig = co(1:2*N); psi = co(2*N+1:end); t.x = [U.L.x;U.B.x]; t.nx = [U.L.nx;U.B.nx]; % 2-wall target v = proxyrep(t, p, mu, psi); % flow vel on L+B u = v(1:2*m).*real(t.nx) + v(2*m+1:end).*imag(t.nx); % proxy contrib to u = v.n J = sum(reshape(u,[m 2])'.*([1;1]*w),2); % .... do its quadr on L,B for i=-1:1 % set up big loop of 12 walls, just their nodes x{i+2} = U.L.x - U.e1 +i*U.e2; x{i+5} = x{i+2} + 3*U.e1; x{i+8} = U.B.x +i*U.e1 -U.e2; x{i+11} = x{i+8} + 3*U.e2; end t.x = vertcat(x{:}); t.nx = [repmat(U.L.nx,[6 1]); repmat(U.B.nx,[6 1])]; v = sd(1)*StoSLP(t,s,mu,sig) + sd(2)*StoDLP(t,s,mu,sig); % ctr copy only u = v(1:12*m).*real(t.nx) + v(12*m+1:end).*imag(t.nx); % v.n, as col vec amts = [0 0 0 3 3 3 -1 -2 -3 1 2 3; -1 -2 -3 1 2 3 0 0 0 3 3 3]; % wall wgts J = J + sum(repmat(u',[2 1]).*kron(amts,w),2); % weight each wall function [E A B C Q] = ELSmatrix(s,p,proxyrep,mu,sd,U,close) % builds matrix blocks for Stokes extended linear system, S+D rep w/ Kress self % & with close option for A block 3x3 neighbors. Barnett 8/2/16 N = numel(s.x); if ~close % plain Nystrom for nei interactions... A = sd(1)*srcsum(@StoSLP,U.trlist,[],s,s,mu) + sd(2)*(eye(2*N)/2 + srcsum(@StoDLP,U.trlist,[],s,s,mu)); % notes: DLP gives ext JR term; srcsum self is ok else % Nystrom self & close-eval for nei interactions... A = sd(1)*StoSLP(s,s,mu) + sd(2)*(eye(2*N)/2 + StoDLP(s,s,mu)); % self w/ JR notself = U.trlist(U.trlist~=0); A = A + sd(1)*srcsum2(@StoSLP_closeglobal,notself,[],s,s,mu,[],'e') + sd(2)*srcsum2(@StoDLP_closeglobal,notself,[],s,s,mu,[],'e'); % dens=[], 'e' exterior end B = proxyrep(s,p,mu); % map from proxy density to vel on curve C = Cblock(s,U,mu,sd); [QL,~,QLt] = proxyrep(U.L,p,mu); [QR,~,QRt] = proxyrep(U.R,p,mu); % vel, tract [QB,~,QBt] = proxyrep(U.B,p,mu); [QT,~,QTt] = proxyrep(U.T,p,mu); Q = [QR-QL; QRt-QLt; QT-QB; QTt-QBt]; E = [A B; C Q]; function C = Cblock(s,U,mu,sd) % fill C from source curve s to U walls % sd controls prefactors on SLP & DLP for Stokes rep on the obstacle curve n = U.nei; e1 = U.e1; e2 = U.e2; S = @StoSLP; D = @StoDLP; % abbrevs trlist = n*e1 + (-n:n)*e2; [CLS,~,TLS] = srcsum(S,trlist,[],U.L,s,mu); [CLD,~,TLD] = srcsum(D,trlist,[],U.L,s,mu); trlist = -n*e1 + (-n:n)*e2; [CRS,~,TRS] = srcsum(S,trlist,[],U.R,s,mu); [CRD,~,TRD] = srcsum(D,trlist,[],U.R,s,mu); trlist = (-n:n)*e1 + n*e2; [CBS,~,TBS] = srcsum(S,trlist,[],U.B,s,mu); [CBD,~,TBD] = srcsum(D,trlist,[],U.B,s,mu); trlist = (-n:n)*e1 - n*e2; [CTS,~,TTS] = srcsum(S,trlist,[],U.T,s,mu); [CTD,~,TTD] = srcsum(D,trlist,[],U.T,s,mu); C = sd(1)*[CRS-CLS; TRS-TLS; CTS-CBS; TTS-TBS] +... sd(2)*[CRD-CLD; TRD-TLD; CTD-CBD; TTD-TBD];
github
bobbielf2/BIE2D-master
fig_stoQconv.m
.m
BIE2D-master/doublyperiodic/fig_stoQconv.m
3,497
utf_8
838064073588a49d7f6071d4c69954d6
function fig_stoQconv % Makes figs for doubly-periodic empty BVP convergence, Stokes. % Barnett 5/28/16. Adapted from fig_lapQconv.m. BIE2D 6/29/16 warning('off','MATLAB:nearlySingularMatrix') % backward-stable ill-cond is ok! warning('off','MATLAB:rankDeficientMatrix') lso.RECT = true; % linsolve opts, forces QR even when square (LU much worse) mu = 0.7; % overall viscosity const for Stokes PDE rho = 1.5; z0 = rho*exp(0.7i); f0 = [0.3;-0.6]; % known Stokeslet loc & force U.e1 = 1; U.e2 = 1i; % unit cell lattice vectors Rp = 1.4; % proxy radius M = 100; p.x = Rp * exp(1i*(0:M-1)'/M*2*pi); p = setupquad(p); % proxy pts proxyrep = @StoSLP; % set proxy type via a kernel function nt = 100; t.x = rand(nt,1)-0.5 + 1i*(rand(nt,1)-0.5); % rand test pts in UC %[xx yy] = meshgrid(linspace(-.5,.5,10)); t.x = xx(:)+1i*yy(:); % tp grid in UC Atest = proxyrep(t,p,mu); % evaluation matrix, only changes when M does m = 22; [U L R B T] = doublywalls(U,m); g = discrep(L,R,B,T,@(t) vTknown(t,z0,f0,mu)); w = [0*L.w 0*L.w L.w 0*L.w 0*B.w 0*B.w 0*B.w B.w]'; % 8m-cpt left null-vector? nsings = 6; % how many singular values to keep and show Ms = 10:5:120; verrs = nan*Ms'; sings = nan(numel(Ms),nsings); nrms = verrs; nwtqs = verrs; for i=1:numel(Ms), M = Ms(i); % ------ convergence in M (# proxy pts) p.x = Rp * exp(1i*(0:M-1)'/M*2*pi); p = setupquad(p); % proxy pts Atest = proxyrep(t,p,mu); % vel evaluation matrix Q = Qmat(p,L,R,B,T,proxyrep,mu); nwtqs(i) = norm(w'*Q); % check presumptive left null vector S = svd(Q); sings(i,1) = max(S); sings(i,2:nsings) = S(end-nsings+2:end); % 1st & last few xi = linsolve(Q,g,lso); nrms(i) = norm(xi); verr = Atest*xi - vTknown(t,z0,f0,mu); % vel err at all test pts verr(1:nt) = verr(1:nt)-verr(1); % fix offset in x cpt from 1st test pt verr(nt+1:end) = verr(nt+1:end)-verr(1+nt); % ..and y cpt verrs(i) = max(abs(verr)); %if M==40, [U S V] = svd(Q); V(:,end), Atest*V(:,end), end % sing vec is approx constant, and generates consts to high acc end % ------- figure; semilogy(Ms,[verrs],'+-'); hold on; semilogy(Ms,sings(:,2:end),'-','color',.5*[1 1 1]); semilogy(Ms,nrms,'go-'); % semilogy(Ms,nwtqs,'rs-'); % boring, always zero rB = sqrt(0.5); semilogy(Ms,0.05*(rho/rB).^(-Ms/2),'r--'); % conv rate! xlabel('M'); axis([min(Ms) max(Ms) 1e-17 max(nrms)]); text(15,max(nrms)/10,'(c)','fontsize',12); text(90,max(nrms)/10,sprintf('$m=%d$',m),'interpreter','latex','fontsize',12); set(gcf,'paperposition',[0 0 3 3]); set(gca,'ytickmode','manual', 'ytick',[1e-15 1e-10 1e-5 1 1e5]); %print -depsc2 figs/stoQMconv.eps %%%%%%%%%%%%%%%%% function Q = Qmat(p,L,R,B,T,proxyrep,mu) % matrix Q given proxy and colloc pts [QL,~,QLn] = proxyrep(L,p,mu); [QR,~,QRn] = proxyrep(R,p,mu); % vel & trac, no p [QB,~,QBn] = proxyrep(B,p,mu); [QT,~,QTn] = proxyrep(T,p,mu); Q = [QR-QL; QRn-QLn; QT-QB; QTn-QBn]; function [ve Te] = vTknown(t,z0,f0,mu) % known vel, trac on t, targ seg if nargout==1, ve = StoSLP(t,struct('x',z0,'w',1),mu,f0); else, [ve,~,Te] = StoSLP(t,struct('x',z0,'w',1),mu,f0); end function g = discrep(L,R,B,T,vTfun) % discrepancy of given solution % vTfun should have interface [velvec, tractionvec] = vTfun(targetsegment) % Other inputs: LRBT are walls. Outputs: g is 8m col vec [vR,tR] = vTfun(R); [vL,tL] = vTfun(L); [vT,tT] = vTfun(T); [vB,tB] = vTfun(B); g = [vR-vL; tR-tL; vT-vB; tT-tB];
github
bobbielf2/BIE2D-master
perispecint.m
.m
BIE2D-master/utils/perispecint.m
1,392
utf_8
87d49dc8e157443f20a2f45659b2f554
function g = perispecint(f) % PERISPECINT - use FFT to take periodic spectral antiderivative of vector % % g = perispecint(f) returns g an antiderivative of the spectral interpolant % of f, which is assumed to be the values of a smooth 2pi-periodic function % at the N gridpoints 2.pi.j/N, for j=1,..,N (or any translation of such % points). Can be row or col vec, and output is same shape. % If sum(f)=0 then g is smoothly periodic; otherwise, there is a sawtooth % jump in g. The offset of g is arbitrary. % % Without arguments, does a self-test. % % Also see: PERISPECDIFF % Barnett 9/28/17 if nargin==0, test_perispecint; return; end N = numel(f); fbar = mean(f); f = f-fbar; if mod(N,2)==0 % even g = ifft(fft(f(:)).*[0 1./(1i*(1:N/2-1)) 0 1./(1i*(-N/2+1:-1))].'); else g = ifft(fft(f(:)).*[0 1./(1i*(1:(N-1)/2)) 1./(1i*((1-N)/2:-1))].'); end g = g + (1:N)'*(fbar*2*pi/N); % add a sawtooth (could add arbitrary offset too) g = reshape(g,size(f)); %%%%%% function test_perispecint N = 50; tj = 2*pi/N*(1:N)'; f = sin(3*tj); fp = 3*cos(3*tj); % trial periodic function & its deriv % since offset arbitrary, must measure and subtract... F = perispecint(fp); off = F(1)-f(1); norm(F-off-f) % zero-mean case for fp f = sin(3*tj)+tj; fp = 3*cos(3*tj)+1; % trial periodic function & its deriv F = perispecint(fp); off = F(1)-f(1); norm(F-off-f) % nonzero-mean case for fp
github
bobbielf2/BIE2D-master
showsegment.m
.m
BIE2D-master/utils/showsegment.m
1,213
utf_8
3672151c11b3e1fd043630c3b5e1bb20
function h = showsegment(s, trlist) % SHOWSEGMENT plot segment(s) & possibly translated copies % % h = showsegment(s) where s is segment struct with s.x nodes, optionally s.nx % normal vectors, adds to the current axes a plot of the segment. % If s is a cell array of segment structs, it plots all of them. % % h = showsegment(s, trlist) also plots translated copies given by list of % complex numbers in trlist. % % No arguments does a self-test. % Based on variants of showseg. Barnett 6/12/16 if nargin<1, test_showsegment; return; end if nargin<2, trlist = 0; end if iscell(s), for i=1:numel(s), showsegment(s{i},trlist); end, return, end hold on for i=1:numel(trlist) plot(s.x+trlist(i), 'b.-'); if isfield(s,'nx') l=0.05; plot([s.x, s.x+l*s.nx].'+trlist(i), 'k-'); end end axis equal xy %%%%%%% function test_showsegment N = 100; s.x = exp(2i*pi*(1:N)/N); figure; showsegment(s); % plain, no normals s = setupquad(s); % adds normals [xx yy] = meshgrid([-3 0 3]); trlist = xx(:)+1i*yy(:); figure; showsegment(s,trlist); % check translation copies s2 = s; s2.x = s.x*0.5; % smaller circles figure; showsegment({s s2},trlist); % check cell array
github
bobbielf2/BIE2D-master
gauss.m
.m
BIE2D-master/utils/gauss.m
287
utf_8
cc60b6c98d11c710bbcbce2f5a42802b
% GAUSS nodes x (Legendre points) and weights w % for Gauss quadrature on [-1,1], for N small (<100). Trefethen book. function [x,w] = gauss(N) beta = .5./sqrt(1-(2*(1:N-1)).^(-2)); T = diag(beta,1) + diag(beta,-1); [V,D] = eig(T); x = diag(D); [x,i] = sort(x); w = 2*V(1,i).^2;
github
bobbielf2/BIE2D-master
perispecinterp.m
.m
BIE2D-master/utils/perispecinterp.m
1,118
utf_8
3612c6bd058b5d08dd68ee217dfb9a24
function g = perispecinterp(f,N) % PERISPECINTERP resample periodically sampled function on finer uniform grid. % % g = perispecinterp(f,N) % inputs: f - (row or column) vector length n (must be even) of samples % N - desired output number of samples, must be >= n and even % outputs: g - vector length N of interpolant, (row or col as f was) % % Note on phasing: the output and input grid first entry align (ie, as if they % are both 0-indexed; note this matches setupquad) % Barnett 6/27/16 renaming fftinterp from 9/5/14 % todo: * downsample case N<n. * odd cases. if nargin==0, test_perispecinterp; return; end n = numel(f); if N==n, g = f; return; end if mod(N,2)~=0 || mod(n,2)~=0, warning('N and n must be even, sorry'); end F = fft(f(:).'); % row vector g = ifft([F(1:n/2) F(n/2+1)/2 zeros(1,N-n-1) F(n/2+1)/2 F(n/2+2:end)]); g = g*(N/n); % factor from the ifft if size(f,1)>size(f,2), g = g(:); end % make col vector %%%%%% function test_perispecinterp n = 50; N = 100; x = 2*pi*(0:n-1)/n; f = @(x) exp(sin(x)); g = perispecinterp(f(x),N); ge = f(2*pi*(0:N-1)/N); % g ./ ge norm(g - ge)
github
bobbielf2/BIE2D-master
reparam_bunched.m
.m
BIE2D-master/utils/reparam_bunched.m
1,412
utf_8
e7ff2d7e6e384306d05b7a1cafdbd40a
function s = reparam_bunched(s,be) % REPARAM_BUNCHED Reparameterize a segment slowing down at 0,pi/2,pi,3pi/2. % % s = reparam_bunched(s,be) takes a segment struct s and returns another, % where be is the beta parameter giving the angular range devoted to the % central. The bunching factor is of order exp(be), or bunching region % of order exp(-be). % % Note: s.cur may be inaccurate. The user should consider replacing with % analytic values % % Without arguments, does self-test % % Barnett 9/28/17 if nargin==0, test_reparam_bunched; return; end % set up reparam func on grid in [0,2pi) t = s.t; N = numel(t); %(1:N)/N * 2*pi; h = 2*pi/N; yp = cosh(be*sin(2*t)); I = sum(yp)*h; al = 2*pi/I; yp = yp*al; % make yp integrate to 2*pi y = perispecint(yp); y = y-y(1); % start at t=0 s.x = s.Z(y); % new nodes and their derivs, exactly s.xp = yp.*s.Zp(y); % (here could replace s.xpp analytically) scopy = s; s = rmfield(s,{'Z','Zp','Zpp'}); % kill otherwise get used s = setupquad(s); % regenerate all from from s.x and s.xp %s.t = y; % in case user needs... %s.Z = scopy.Z; %s.Zp = scopy.Zp; %s.Zpp = scopy.Zpp; %%%%%%%% function test_reparam_bunched N=200; figure; % animate... for be=1:0.5:8 s = wobblycurve(0.5,0,1,N); s = reparam_bunched(s,be); clf; showsegment(s); title(sprintf('\\beta = %.3f\n',be)); drawnow end %s.cur % round-off deviates from 2 by up to 1e-7
github
bobbielf2/BIE2D-master
setupquad.m
.m
BIE2D-master/utils/setupquad.m
4,215
utf_8
0774317ae402c3f279b63eec2b2179dd
function s = setupquad(s, N) % SETUPQUAD Set up periodic trapezoid quadrature & geom for smooth closed curve % % s = setupquad(s,N) where s is a struct containing a parametrization of the % curve in the form of function s.Z from [0,2pi) to the complex plane, uses % this to build the set of nodes, weights, speeds, curvatures, etc, using the % N-node PTR on [0,2pi). % % s = setupquad(s) where s contains at least the field s.x (column vector of % N node locations) generates all other fields by spectral differentiation. % % If s.Zp is present it is used as the function Z'; likewise s.Zpp is used for % Z''. The point of using these is that slightly more accurate normals and % curvatures may result compared to differentiation. On the other hand, Zp and % Zpp are not checked for plausibility, and are often complicated to code. % % Note: curves go counter-clockwise. Node j is at Z(2pi.(j-1)/N), ie 0-indexed. % FFT is used so is O(N log N), or O(N) if Z, Zp and Zpp available. % % Run without arguments, a self-test is done. % % Inputs: % s : struct containing either the field s.Z, a mapping from [0,2pi) to % the complex plane, which must be able to accept vectorized inputs, % or the field s.x containing column vector of the nodes. % N : number of nodes (not needed if s.x is present; however, if s.Z is also % present, N overrides the number of nodes in s.x). % Outputs: % s : same struct with added column vector fields (nodes, weights, velocities, % curvatures, etc) needed for quadrature and Nystrom methods. Namely, % s.x nodes in complex plane, Z(s_j) % s.xp velocities Z'(s_j) % s.xp accelerations Z''(s_j) % s.t parameter values s_j for trapezoid rule, 2pi.(j-1)/N, j=1,...,N % s.nx outward unit normals % s.tang forward unit tangential vectors % s.sp speeds |Z'(s_j)| % s.w "speed weights" (2pi/N)*s.sp % s.cw velocity weights (ie complex speed) % s.cur curvatures kappa(s_j) (inverse bending radius) % % Example usage: % % s.Z = @(s) (1+0.3*cos(5*s).*exp(1i*s); % starfish param % s = setupquad(s,100); % figure; plot(s.x,'k.'); hold on; plot([s.x, s.x+0.2*s.nx].', 'b-'); axis equal % % Now check that normals from spectral differentiation are accurate: % % s.Zp = @(s) -1.5*sin(5*s).*exp(1i*s) + 1i*s.Z(s); % Z' formula % t = setupquad(s,100); norm(t.nx-s.nx) % should be small % % Also see: PERISPECDIFF. % (c) Alex Barnett 10/8/14, name changed to avoid conflict w/ mpspack 6/12/16. % 0-indexed to match interp, 6/29/16 if nargin==0, test_setupquad; return; end if nargin>1 % use N from args s.t = (0:N-1)'*(2*pi/N); if isfield(s,'Z'), s.x = s.Z(s.t); end % use formula if N~=length(s.x), error('N differs from length of s.x; that sucks!'); end elseif isfield(s,'x') s.x = s.x(:); % ensure col vec N = length(s.x); s.t = (0:N-1)'*(2*pi/N); % we don't know the actual params, but choose this else error('Need to provide at least s.Z and N, or s.x. Neither found!'); end if isfield(s,'Zp'), s.xp = s.Zp(s.t); else, s.xp = perispecdiff(s.x); end if isfield(s,'Zpp'), s.xpp = s.Zpp(s.t); else, s.xpp = perispecdiff(s.xp); end % Now local stuff that derives from x, xp, xpp at each node... s.sp = abs(s.xp); s.tang = s.xp./s.sp; s.nx = -1i*s.tang; s.cur = -real(conj(s.xpp).*s.nx)./s.sp.^2; % recall real(conj(a)*b) = "a dot b" s.w = (2*pi/N)*s.sp; s.cw = (2*pi/N)*s.xp; % complex weights (incl complex speed) %%%%%%%%%%%%%%%%%%%%%%%%% function test_setupquad % not very extensive! Barnett 10/8/14 Z = @(s) (1+0.3*cos(5*s)).*exp(1i*s); % starfish param s.Z = Z; n = 100; s = setupquad(s,n); s = []; s.x = Z((0:n-1)/n*2*pi); s = setupquad(s); % testing s.x input only figure; plot(s.x,'k.'); hold on; plot([s.x, s.x+0.2*s.nx].', 'b-'); axis equal % Now check that normals from spectral differentiation are accurate: Zp = @(s) -1.5*sin(5*s).*exp(1i*s) + 1i*Z(s); % Z' formula s.Zp = Zp; t = setupquad(s); norm(t.nx-s.nx) % should be small s = []; s.x = 3; s.Z = Z; s = setupquad(s,100); % N should override s.x %s = []; s.x = Z((1:50)'/50*2*pi); s=setupquad(s,100); should fail
github
bobbielf2/BIE2D-master
wobblycurve.m
.m
BIE2D-master/utils/wobblycurve.m
1,160
utf_8
0dba00c5a6771d86bd120c42bdf738bc
function s = wobblycurve(r0,a,w,N) % WOBBLYCURVE Set up a wobbly smooth closed curve ("starfish") % % s = wobblycurve(r0,a,w) where r0 is the mean radius (eg 1), a is amplitude of % wobble (eg 0.3) and w is the frequency (eg 5), returns a segment struct of % the form as in setupquad, but with s.inside being a handle to Boolean test % whether a point is inside the curve. Parametrization uniform in theta. % % Without arguments, does self-test of analytic 1st and 2nd derivatives % Barnett repackaged 6/12/16, generic angle offset 6/29/16, r0 8/2/16 if nargin==0, test_wobblycurve; return; end th = 0.2; % generic rotation. todo: make an opt % since analytic derivs not too messy, use them... R = @(t) r0 + a*cos(w*(t-th)); Rp = @(t) -w*a*sin(w*(t-th)); Rpp = @(t) -w*w*a*cos(w*(t-th)); s.Z = @(t) R(t).*exp(1i*t); s.Zp = @(t) (Rp(t) + 1i*R(t)).*exp(1i*t); s.Zpp = @(t) (Rpp(t) + 2i*Rp(t) - R(t)).*exp(1i*t); s = setupquad(s,N); s.inside = @(z) abs(z)<R(angle(z)); %%%%%%% function test_wobblycurve s = wobblycurve(0.9,0.3,5,150); max(abs(s.xp - perispecdiff(s.x))) % make sure analytic close to numerical max(abs(s.xpp - perispecdiff(s.xp)))
github
bobbielf2/BIE2D-master
perispecdiff.m
.m
BIE2D-master/utils/perispecdiff.m
853
utf_8
083247f836d7df429d48963ea3567cdb
function g = perispecdiff(f) % PERISPECDIFF - use FFT to take periodic spectral differentiation of vector % % g = perispecdiff(f) returns g the derivative of the spectral interpolant % of f, which is assumed to be the values of a smooth 2pi-periodic function % at the N gridpoints 2.pi.j/N, for j=1,..,N (or any translation of such % points). Can be row or col vec, and output is same shape. % % Without arguments, does a self-test. % Barnett 2/18/14 if nargin==0, test_perispecdiff; return; end N = numel(f); if mod(N,2)==0 % even g = ifft(fft(f(:)).*[0 1i*(1:N/2-1) 0 1i*(-N/2+1:-1)].'); else g = ifft(fft(f(:)).*[0 1i*(1:(N-1)/2) 1i*((1-N)/2:-1)].'); end g = reshape(g,size(f)); %%%%%% function test_perispecdiff N = 50; tj = 2*pi/N*(1:N)'; f = sin(3*tj); fp = 3*cos(3*tj); % trial periodic function & its deriv norm(fp-perispecdiff(f))
github
bobbielf2/BIE2D-master
StoDLP_closeglobal.m
.m
BIE2D-master/kernels/StoDLP_closeglobal.m
5,987
utf_8
f3e6f06539c4ac195862d0e1d38f6a75
function [u p] = StoDLP_closeglobal(t, s, mu, sigma, side) % STODLP_CLOSEGLOBAL - close-eval velocity Stokes DLP w/ global quadr curve % % u = StoDLP_closeglobal(t,s,mu,dens,side) returns velocities at targets t.x % due to double-layer potential with real-valued density dens sampled on the % nodes s.x of a smooth global quadrature rule on the curve s, either inside % or outside the curve. % The DLP velocity is broken down into 5 Laplace DLP-like (2 are Cauchy) % potential calls, each of which are evaluated with the globally-compensated % scheme. See [lsc2d] for details. % The pressure uses the gradient of a single Laplace DLP call. % % [u p] = StoDLP_closeglobal(t,s,mu,dens,side) also returns pressure at targets % % Inputs: % t = target struct with t.x = M-by-1 list of targets in complex plane % s = curve struct containing N-by-1 vector s.x of source nodes (as complex % numbers), and all other fields in s which are generated by quadr(), and % s.a one interior point far from bdry (mean(s.x) used if not provided). % mu = viscosity in Stokes equations (real positive number); has no effect on % DLP but is part of the standard interface. % dens = double-layer density values (2N-by-1) at nodes, with real values % (1-cpts followed by 2-cpts). % If dens is empty, output u is the full 2M-by-2N evaluation matrix. % side = 'i','e' to indicate targets are all interior or exterior to curve. % % Outputs: % u = velocity values at targets (2M-by-1): all 1- then all 2-cmpts. % Or, if 2M-by-2N velocity evaluation matrix (if dens=[]) % p = pressure values at targets (M-by-1), or M-by-2N evaluation matrix. % % Called without arguments, a self-test (far eval & mat vs StoDLP) is done. % % Also see: STODLP, SETUPQUAD, STOINTDIRBVP % Bowei Wu, Sept 2014; Barnett 10/8/14 tweaks, repackage 6/13/16. % viscosity input (doesn't affect result) 6/27/16. pressure 6/29/16. % todo: * speed up matrix filling exploiting incoming 0s, do mult of Nf*Nf % efficiently-filled LapDLP_closeglobal, against the Nf*N dense interp mat, % will be O(MN^2) but fast. if nargin==0, test_StoDLP_closeglobal; return; end N=size(s.x,1); M=size(t.x,1); % # srcs, # targs mat = isempty(sigma); if mat, sigma=eye(2*N); end % case of dense matrix sigma = sigma(1:N,:)+1i*sigma(N+1:end,:); % put into complex notation Nc = size(sigma,2); % # density vecs (cols) % find I_1: % Bowei's version with "illegal" complex tau, with interp to fine nodes beta = 2.2; % >=1: how many times more dense to make fine nodes, for I_1 Nf = ceil(beta*numel(s.x)/2)*2; % nearest even # fine nodes sf.x = perispecinterp(s.x,Nf); sf = setupquad(sf); % build fine nodes sigf=zeros(Nf,Nc); for k=1:Nc sigf(:,k) = perispecinterp(sigma(:,k),Nf); % fine Stokes density end % feed complex tau to Laplace close eval - careful: tauf = bsxfun(@times, sigf, real(sf.nx)./sf.nx); % undo n_y rotation I1x1 = LapDLP_closeglobal(t, sf, tauf, side); tauf = bsxfun(@times, sigf, imag(sf.nx)./sf.nx); % undo n_y rotation I1x2 = LapDLP_closeglobal(t, sf, tauf, side); % Note: for mat fill the above would be faster done by mat-mat prod I1 = I1x1+1i*I1x2; % find I_2 tau = real(bsxfun(@times,s.x,conj(sigma))); [~, I2x1, I2x2] = LapDLP_closeglobal(t, s, tau, side); I2 = I2x1+1i*I2x2; % find I_3 and I_4 if ~mat [~, I3x1, I3x2] = LapDLP_closeglobal(t, s, real(sigma), side); I3 = bsxfun(@times, real(t.x), I3x1+1i*I3x2); [~, I4x1, I4x2] = LapDLP_closeglobal(t, s, imag(sigma), side); I4 = bsxfun(@times, imag(t.x), I4x1+1i*I4x2); else % *** specific to the matrix case, not arb Nc... [~, L1, L2] = LapDLP_closeglobal(t, s, eye(N), side); % only need 1 call I4x1=[zeros(M,N),L1]; % could be tidied up, but not a bottleneck... I4x2=[zeros(M,N),L2]; I3x1=[L1,zeros(M,N)]; I3x2=[L2,zeros(M,N)]; I3 = bsxfun(@times,real(t.x),I3x1+1i*I3x2); I4 = bsxfun(@times,imag(t.x),I4x1+1i*I4x2); end u = I1+I2-I3-I4; u=[real(u);imag(u)]; % back to real notation, always stack [u1;u2] % test which is causing slow convergence at nearby pt (side='e', vary N): % jj= find(abs(x - (0.7-0.9i))<1e-12); I1(jj), I2(jj), I3(jj)+I4(jj) % ans: it's I1, of course. (Alex, 2013) if nargout>1 % ----------- want pressure, do its extension (not in [lsc2c]) if ~mat p = -2*mu*(I3x1 + I4x2); % already computed for u, turns out easy else p = -2*mu*[L1,L2]; % " end end %%%%%%%%%%%%%%%%%%%% function test_StoDLP_closeglobal % adapted from Lap tests fprintf('check Stokes DLP close-eval quadr match native rule in far field...\n') verb = 0; % to visualize s = wobblycurve(1,0.3,5,280); s.a = mean(s.x); if verb,figure;showsegment(s);end mu = 0.9; % viscosity (real, pos) tau = [0.7+sin(3*s.t); -0.4+cos(2*s.t)]; % pick smooth density w/ nonzero mean nt = 100; t.nx = exp(2i*pi*rand(nt,1)); % target normals %profile clear; profile on; for side = 'ie' if side=='e', t.x = 1.5+1i+rand(nt,1)+1i*rand(nt,1); % distant targs else, t.x = 0.6*(rand(nt,1)+1i*rand(nt,1)-(0.5+0.5i)); end % targs far inside if verb, plot(t.x,'.'); end fprintf('\nside = %s:\n',side) [u p] = StoSLP(t,s,mu,tau); % eval given density cases... tic, [uc pc] = StoSLP_closeglobal(t,s,mu,tau,side); fprintf('Sto DLP density eval (%.3g sec), max abs err in u cmpts, p:\n',toc) disp([max(abs(u-uc)), max(abs(p-pc))]) tic, [Ac Pc] = StoSLP_closeglobal(t,s,mu,[],side); % fill 20x slower than apply fprintf('matrix fill (%.3g sec) & apply, max abs err in u cmpts, p:\n',toc) disp([max(abs(u-Ac*tau)), max(abs(p-Pc*tau))]) [A P] = StoSLP(t,s,mu); % compare matrix els... fprintf('matrix fill, max abs matrix element diffs for u, p (more stringent, not needed):\n') disp([max(abs(A(:)-Ac(:))), max(abs(P(:)-Pc(:)))]) end %profile off; profile viewer
github
bobbielf2/BIE2D-master
StoSLP.m
.m
BIE2D-master/kernels/StoSLP.m
4,799
utf_8
25b27eac66dc0b0b2ba3174216d67926
function [u,p,T] = StoSLP(t,s,mu,dens) % STOSLP Evaluate 2D Stokes single-layer velocity, pressure, and traction. % % [A,P,T] = StoSLP(t,s,mu) returns dense matrices taking single-layer % density values on the nodes of a source curve to velocity, pressure, and % traction on the nodes of a target curve. Native quadrature is used, apart % from if target=source when A and T are the Nystrom matrices filled using % spectrally-accurate quadratures (log-singular for A; smooth diagonal limit % for T, ie transpose of DLP). % % [u,p,T] = StoSLP(t,s,mu,dens) evaluates the single-layer density dens, % returning flow velocity u, pressure p, and target-normal traction T. % % The normalization is as in Sec 2.3 of [HW], and [Mar15]; notably there is a % prefactor 1/(4.pi.mu) for velocity. % % References: % [HW] "Boundary Integral Equations", G. C. Hsiao and W. L. Wendland % (Springer, 2008). % % [Mar15] "A fast algorithm for simulating multiphase flows through periodic % geometries of arbitrary shape," G. Marple, A. H. Barnett, % A. Gillman, and S. Veerapaneni, in press, SIAM J. Sci. Comput. % https://arXiv.org/abs/1510.05616 % % Inputs: (see setupquad for source & target struct definitions) % s = source segment struct with s.x nodes, s.w weights on [0,2pi), % s.sp speed function |Z'| at the nodes, and s.tang tangent angles. % t = target segment struct with t.x nodes, and t.nx normals if traction needed % mu = viscosity % % Outputs: (matrix case) % A = 2M-by-2N matrix taking density (force vector) to velocity on the % target curve. As always for Stokes, ordering is nodes fast, % components (1,2) slow, so that A has 4 large blocks A_11, A_12, etc. % P = M-by-2N matrix taking density to pressure (scalar) on target nodes. % T = 2M-by-2N matrix taking density to normal traction on target nodes. % Outputs: (density case) all are col vecs (as if N=1). % % Notes: 1) Uses whatever self-interaction quadrature Laplace SLP uses % % To test use STOINTDIRBVP % % See also: SETUPQUAD, LAPSLP. % Barnett 6/12/16; T diag limit as in Bowei code SLPmatrixp 6/13/16. 6/27/16 % todo: doc formulae. if numel(mu)~=1, error('mu must be a scalar'); end if nargout==1 u = StoSLPmat(t,s,mu); if nargin>3 && ~isempty(dens) u = u * dens; end elseif nargout==2 [u p] = StoSLPmat(t,s,mu); if nargin>3 && ~isempty(dens) u = u * dens; p = p * dens; end else [u p T] = StoSLPmat(t,s,mu); if nargin>3 && ~isempty(dens) u = u * dens; p = p * dens; T = T * dens; end end %%%%%% function [A,P,T] = StoSLPmat(t,s,mu) % Returns native quadrature matrices, or self-evaluation matrices. self = sameseg(t,s); N = numel(s.x); M = numel(t.x); r = bsxfun(@minus, t.x, s.x.'); % C-# displacements mat irr = 1./(conj(r).*r); % 1/r^2, used in all cases below d1 = real(r); d2 = imag(r); % worth storing I think c = 1/(4*pi*mu); % factor from Hsiao-Wendland book, Ladyzhenskaya if self S = LapSLP(s,s); % note includes speed weights A = kron((1/2/mu)*eye(2),S); % prefactor & diagonal log-part blocks t1 = real(s.tang); t2 = imag(s.tang); % now add r tensor r part, 4 blocks A11 = d1.^2.*irr; A11(diagind(A11)) = t1.^2; % diagonal limits A12 = d1.*d2.*irr; A12(diagind(A12)) = t1.*t2; A22 = d2.^2.*irr; A22(diagind(A22)) = t2.^2; A = A + bsxfun(@times, [A11 A12; A12 A22], c*[s.w(:)' s.w(:)']); % pref & wei else % distinct src and targ logir = -log(abs(r)); % log(1/r) diag block A12 = d1.*d2.*irr; % off diag vel block A = c*[logir + d1.^2.*irr, A12; % u_x A12, logir + d2.^2.*irr]; % u_y A = bsxfun(@times, A, [s.w(:)' s.w(:)']); % quadr wei end if nargout>1 % pressure (no self-eval) P = [d1.*irr, d2.*irr]; P = bsxfun(@times, P, (1/2/pi)*[s.w(:)' s.w(:)']); % quadr wei end if nargout>2 % traction (negative of DLP vel matrix w/ nx,ny swapped) rdotn = bsxfun(@times, d1, real(t.nx)) + bsxfun(@times, d2, imag(t.nx)); rdotnir4 = rdotn.*(irr.*irr); clear rdotn A12 = (-1/pi)*d1.*d2.*rdotnir4; T = [(-1/pi)*d1.^2.*rdotnir4, A12; % own derivation A12, (-1/pi)*d2.^2.*rdotnir4]; if self c = -s.cur/2/pi; % diagonal limit of Laplace DLP tx = 1i*s.nx; t1=real(tx); t2=imag(tx); % tangent vectors on the curve T(sub2ind(size(T),1:N,1:N)) = c.*t1.^2; % overwrite diags of 4 blocks T(sub2ind(size(T),1+N:2*N,1:N)) = c.*t1.*t2; T(sub2ind(size(T),1:N,1+N:2*N)) = c.*t1.*t2; T(sub2ind(size(T),1+N:2*N,1+N:2*N)) = c.*t2.^2; end T = bsxfun(@times, T, [s.w(:)' s.w(:)']); % quadr wei end
github
bobbielf2/BIE2D-master
StoSLP_closeglobal.m
.m
BIE2D-master/kernels/StoSLP_closeglobal.m
5,682
utf_8
94e1275fce7eed65d38ab3422727bae9
function [u p] = StoSLP_closeglobal(t, s, mu, sigma, side) % STOSLP_CLOSEGLOBAL - close-eval velocity Stokes SLP w/ global quadr curve % % u = StoSLP_closeglobal(t,s,mu,dens,side) returns velocities at targets t.x % due to single-layer potential with real-valued density dens sampled on the % nodes s.x of a smooth global quadrature rule on the curve s, either inside % or outside the curve. % The SLP for velocity is broken down into 3 Laplace SLP potential calls, % each of which are evaluated with the globally-compensated scheme. % See [lsc2d] for details (except we include viscosity prefactor). % The pressure uses a single Laplace DLP call, using the complex density % tau = sigma_1 + i.sigma_2. % % [u p] = StoSLP_closeglobal(t,s,mu,dens,side) also returns pressure at targets % % Inputs: % t = target struct with t.x = M-by-1 list of targets in complex plane % s = curve struct containing N-by-1 vector s.x of source nodes (as complex % numbers), and all other fields in s which are generated by quadr(), and % for the 'e' case, s.a one interior point far from bdry. % mu = viscosity in Stokes equations (real positive number). % dens = single-layer density values (2N-by-1) at nodes, with real values % (1-cpts followed by 2-cpts). % If dens is empty, output u is the full 2M-by-2N evaluation matrix. % side = 'i','e' to indicate targets are all interior or exterior to curve. % % Outputs: % u = velocity values at targets (2M-by-1): all 1- then all 2-cmpts. % Or, if 2M-by-2N velocity evaluation matrix (if dens=[]) % p = pressure values at targets (M-by-1), or M-by-2N evaluation matrix. % % Called without arguments, a self-test (far eval & mat vs StoSLP) is done. % % Also see: STOSLP, SETUPQUAD, STOINTDIRBVP % Bowei Wu, Sept 2014; Barnett 10/8/14 tweaks, repackage 6/13/16, 6/27/16 % viscosity scaling & debug 6/28/16. % todo: * speed up matrix filling exploiting incoming 0s & dgemm on Lap mats if nargin==0, test_StoSLP_closeglobal; return; end N=size(s.x,1); M=size(t.x,1); % # srcs, # targs mat = isempty(sigma); if mat, sigma=eye(2*N); end % case of dense matrix fill, slow sigma = sigma(1:N,:)+1i*sigma(N+1:end,:); % work in complex notation Nc = size(sigma,2); % # density vecs (cols), either 1 or 2N % find I_1 if ~mat % eval from single density col vec [I1x1, I3x1, I3x2] = LapSLP_closeglobal(t, s, real(sigma), side); [I1x2, I4x1, I4x2] = LapSLP_closeglobal(t, s, imag(sigma), side); else % *** specific to the matrix fill case, not arb Nc [I1x1, I3x1, I3x2] = LapSLP_closeglobal(t, s, eye(N), side); I1x2=[zeros(M,N),I1x1]; I4x1=[zeros(M,N),I3x1]; I4x2=[zeros(M,N),I3x2]; I1x1=[I1x1,zeros(M,N)]; I3x1=[I3x1,zeros(M,N)]; I3x2=[I3x2,zeros(M,N)]; end I1 = (I1x1+1i*I1x2)/2; % find I_2 tau = real(bsxfun(@times, s.x, conj(sigma))); % careful, does y dot sigma [~, I2x1, I2x2] = LapSLP_closeglobal(t, s, tau, side); I2 = (I2x1+1i*I2x2)/2; % find I_3 I3 = bsxfun(@times, real(t.x)/2, I3x1+1i*I3x2); % find I_4 I4 = bsxfun(@times, imag(t.x)/2, I4x1+1i*I4x2); % Stokes SLP (with viscosity prefactor) u = (1/mu)*(I1+I2-I3-I4); u=[real(u);imag(u)]; % back to real notation, always stack [u1;u2] if nargout>1 % -------- want pressure, do its extension by rotating n_y to sigma % & since this rotation makes more osc funcs, must resample to fine grid % as in the DLP u. (This pressure extension not in [lsc2d].) beta = 1.5; % >=1: how many times more dense to make fine nodes. Seems enough Nf = ceil(beta*numel(s.x)/2)*2; % nearest even # fine nodes sf.x = perispecinterp(s.x,Nf); sf = setupquad(sf); % build fine nodes %sf = setupquad(s,Nf); % uncomment to elim err due to geom interp if have s.Z sigf = zeros(Nf,Nc); for k=1:Nc sigf(:,k) = perispecinterp(sigma(:,k),Nf); % fine Stokes density end tauf = bsxfun(@times, sigf, 1./sf.nx); % 2 complex cmpts p = LapDLP_closeglobal(t, sf, tauf, side); % slow, resampled cols of eye % (todo: replace by BLAS3 mat-mat prod, faster) p = real(p); end %%%%%%%%%%%%%%%%%%%% function test_StoSLP_closeglobal % adapted from Lap tests fprintf('check Stokes SLP close-eval quadr match native rule in far field...\n') verb = 0; % to visualize s = wobblycurve(1,0.3,5,280); s.a = mean(s.x)+0.4+0.2i; % can't be near bdry if verb, figure; showsegment(s); plot(s.a,'+'); end mu = 0.9; % viscosity (real, pos) tau = [0.7+sin(3*s.t); -0.4+cos(2*s.t)]; % pick smooth density w/ nonzero mean nt = 100; t.nx = exp(2i*pi*rand(nt,1)); % target normals %profile clear; profile on; for side = 'ie' if side=='e', t.x = 1.5+1i+rand(nt,1)+1i*rand(nt,1); % distant targs else, t.x = 0.6*(rand(nt,1)+1i*rand(nt,1)-(0.5+0.5i)); end % targs far inside if verb, plot(t.x,'.'); end fprintf('\nside = %s:\n',side) [u p] = StoSLP(t,s,mu,tau); % eval given density cases... tic, [uc pc] = StoSLP_closeglobal(t,s,mu,tau,side); fprintf('Sto SLP density eval (%.3g sec), max abs err in u cmpts, p:\n',toc) disp([max(abs(u-uc)), max(abs(p-pc))]) tic, [Ac Pc] = StoSLP_closeglobal(t,s,mu,[],side); % fill 20x slower than apply fprintf('matrix fill (%.3g sec) & apply, max abs err in u cmpts, p:\n',toc) disp([max(abs(u-Ac*tau)), max(abs(p-Pc*tau))]) [A P] = StoSLP(t,s,mu); % compare matrix els... fprintf('matrix fill, max abs matrix element diffs for u, p (more stringent, not needed):\n') disp([max(abs(A(:)-Ac(:))), max(abs(P(:)-Pc(:)))]) end %profile off; profile viewer
github
bobbielf2/BIE2D-master
LapSLP_closeglobal.m
.m
BIE2D-master/kernels/LapSLP_closeglobal.m
8,255
utf_8
e2057039f30f6ba95db0e0a61eeea742
function [u ux uy info] = LapSLP_closeglobal(t, s, tau, side) % LAPSLP_CLOSEGLOBAL - Laplace SLP potential & deriv w/ global close-eval quad % % u = LapSLP_closeglobal(t,s,dens,side) returns potentials at targets t.x % due to single-layer potential with real-valued density dens sampled on the % nodes s.x of a smooth global quadrature rule on the curve s, either inside % outside the curve. The new global scheme of [lsc2d] based on barycentric % Cauchy close-evaluation (see reference in Cau_closeglobal.m) is used. % % Our definition of the SLP on curve Gamma is % % u(x) = (1/2pi) int_Gamma log(1/|r|) tau(y) ds_y, where r:=x-y, x,y in R2 % % Inputs: % t = target struct containing % t.x = M-by-1 list of targets, as points in complex plane % (optionally also t.nx target normals as unit complex numbers) % s = curve struct containing N-by-1 vector s.x of source nodes (as complex % numbers), and other fields as generated by setupquad. % Also needed (for side='e'): s.a, a point interior to the curve. % dens = single-layer density values at nodes. Note, must be real-valued to % evaluate Laplace layer potentials (note Stokes feeds it complex dens). % If dens has multiple columns, the evaluation is done for each. % If dens is empty, outputs are matrices mapping density to values, etc. % side = 'i','e' to indicate targets are interior or exterior to the curve. % % Outputs: % u = column vector of M potential values where M = numel(t.x), or if % dens has n columns, the n column vector outputs are stacked (M-by-n). % [u un] = LapSLPeval_closeglobal(t,s,dens,side) also returns target-normal % derivatives (M-by-n) using t.nx % [u ux uy] = LapSLPeval_closeglobal(t,s,dens,side) instead returns x- and y- % partials of u at the targets (ignores t.nx) % [u ux uy info] = LapSLPeval_closeglobal(t,s,dens,side) also gives diagnostic: % info.vb = vector of v boundary values (M-by-n) % info.imv = imag part of v at targets (M-by-n) % % References: % % [lsc2d] Spectrally-accurate quadratures for evaluation of layer potentials % close to the boundary for the 2D Stokes and Laplace equations, % A. H. Barnett, B. Wu, and S. Veerapaneni, SIAM J. Sci. Comput., % 37(4), B519-B542 (2015) https://arxiv.org/abs/1410.2187 % % See also: LAPSLP, SETUPQUAD, CAU_CLOSEGLOBAL, LAPINTDIRBVP % % complexity O(N^2) for evaluation of v^+ or v^-, plus O(NM) for globally % compensated quadrature to targets % Barnett 2013; multiple-column generalization by Gary Marple, 2014. % Repackaged Barnett 6/12/16, 6/27/16 col vec outputs, 6/28/16 vp 'e' corrected % todo: * efficient special case of matrix filling, join Steps 1 & 2 with dgemm. if nargin==0 %testCSLPselfmatrix; test_LapSLP_closeglobal; return; end N = numel(s.x); M = numel(t.x); % # source, target nodes if isempty(tau), tau = eye(N); end % case of filling matrices n = size(tau,2); % # density columns % Step 1: eval v^+ or v^- = cmplx SLP(tau): vb = CSLPselfmatrix(s,side) * tau; if side=='e' sawlog = s.t/1i + log(s.a - s.x); % sawtooth with jump cancelled by log for i=1:numel(sawlog)-1, p = imag(sawlog(i+1)-sawlog(i)); % remove phase jumps sawlog(i+1) = sawlog(i+1) - 2i*pi*round(p/(2*pi)); end totchgp = sum((s.w*ones(1,n)).*tau,1)/(2*pi); % total charge due to SLP, over 2pi (suffix p is for n-cmpt row vec) vb = vb + sawlog*totchgp; % is now r cw = 1i*s.nx.*s.w; % complex speed weights for native quadr... vinf = sum(bsxfun(@times, vb, cw./(s.x-s.a)),1) / (2i*pi); % interior Cauchy gets v_infty vb = vb - ones(size(vb,1),1)*vinf; % kill off v_infty so that v is in exterior Hardy space end info.vb = vb; % save for diagnostics (if totchg=0 it's useful) % Step 2: compensated close-evaluation of v & v', followed by take Re: if nargout>1 % want derivatives [v vp] = Cau_closeglobal(t.x,s,vb,side); % does Sec. 3 of [lsc2d] ux = real(vp); uy = -imag(vp); % col vecs, leave as partials... if nargout==2 % or dot w/ targ nor... ux = bsxfun(@times,ux,real(t.nx)) + bsxfun(@times,uy,imag(t.nx)); end else v = Cau_closeglobal(t.x,s,vb,side); % does Sec. 3 of [lsc2d] end u = real(v); if side=='e' % add real part of log and of v_infty back in... u = u - log(abs(s.a - t.x))*totchgp + ones(M,1)*real(vinf); % Re v_infty = 0 anyway if nargout==2 % don't forget to correct the derivs too! ux = ux + real(t.nx./(s.a - t.x))*totchgp; elseif nargout==3 ux = ux + real(1./(s.a - t.x))*totchgp; uy = uy - imag(1./(s.a - t.x))*totchgp; end end %%%%%% function S = CSLPselfmatrix(s,side) % complex SLP Kress-split Nystrom matrix % s = src seg, even # nodes. side = 'i'/'e' int/ext case. Barnett 10/18/13. % only correct for zero-mean densities. N = numel(s.x); d = s.x*ones(1,N) - ones(N,1)*s.x.'; % C-# displacements mat, t-s x = exp(1i*s.t); % unit circle nodes relative to which angles measured. S = -log(d) + log(x*ones(1,N) - ones(N,1)*x.'); % NB circ angles S(diagind(S)) = log(1i*x./s.xp); % complex diagonal limit % O(N^2) hack to remove 2pi phase jumps in S (assumes enough nodes for smooth): for i=1:numel(S)-1, p = imag(S(i+1)-S(i)); % phase jump between pixels S(i+1) = S(i+1) - 2i*pi*round(p/(2*pi)); end % (NB access matrix as 1d array!) %figure; imagesc(real(S)); figure; imagesc(imag(S)); stop % check S mat smooth m = 1:N/2-1; if side=='e', Rjn = ifft([0 1./m 1/N 0*m]); % imag sign dep on side else, Rjn = ifft([0 0*m 1/N 1./m(end:-1:1)]); end % cmplx Kress Rj(N/2)/4pi %m = 1:N/2-1; Rjn = ifft([0 0*m 1/N 1./m(end:-1:1)]); Rjn = [Rjn(1) Rjn(end:-1:2)]; % flips order S = S/N + circulant(Rjn); % incl 1/2pi SLP prefac. drops const part in imag S = bsxfun(@times, S, s.sp.'); % include speed (2pi/N weights already in) %%%%%%%%%%%%%%%%%%% function testCSLPselfmatrix % test spectral conv of complex SLP self-int Nystrom % Barnett 10/18/13, repackaged 6/27/16 s = wobblycurve(1,0.3,5,200); fprintf('CSLP self matrix test, check digits freeze:\n') for N=40:40:500 % convergence study of Re v, Im v... s = setupquad(s,N); sig = cos(3*s.t + 1); % zero-mean real SLP density func v = CSLPselfmatrix(s,'i') * sig; % holomorphic potential bdry value fprintf('N=%d:\tu(s=0) = %.15g Im[v(s=0)-v(s=pi)] = %.15g\n',N,real(v(end)),imag(v(end)-v(end/2))); % note overall const for Im not high-order convergence end % NB needs N=320 for 13 digits in Re, but 480 for Im part (why slower?) %figure; plot(s.t, [real(v) imag(v)], '+-'); title('Re and Im of v=S\sigma'); %%%%%%%%%%%%%%%%%%%% function test_LapSLP_closeglobal fprintf('check Laplace SLP close-eval quadr match native rule in far field...\n') verb = 1; % to visualize s = wobblycurve(1,0.3,5,200); s.a = mean(s.x)+0.4+0.2i; % can't be near bdry if verb, figure; showsegment(s); plot(s.a,'+'); end tau = -0.7+exp(sin(3*s.t)); % pick smooth density w/ nonzero mean nt = 100; t.nx = exp(2i*pi*rand(nt,1)); % target normals for side = 'ie' if side=='e', t.x = 1.5+1i+rand(nt,1)+1i*rand(nt,1); % distant targs else, t.x = 0.6*(rand(nt,1)+1i*rand(nt,1)-(0.5+0.5i)); end % targs far inside if verb, plot(t.x,'.'); end fprintf('\nside = %s:\n',side) [u un] = LapSLP(t,s,tau); % eval given density cases... [uc unc] = LapSLP_closeglobal(t,s,tau,side); tic, [uc uxc uyc] = LapSLP_closeglobal(t,s,tau,side); fprintf('Lap SLP density eval (%.3g sec), max abs err in u, un, and [ux,uy]...\n',toc) disp([max(abs(u-uc)), max(abs(un-unc)), max(abs(un - (uxc.*real(t.nx)+uyc.*imag(t.nx))))]) [uc unc] = LapSLP_closeglobal(t,s,[],side); tic, [uc uxc uyc] = LapSLP_closeglobal(t,s,[],side); fprintf('matrix fill (%.3g sec) & apply, max abs err in u, un, and [ux,uy]...:\n',toc) disp([max(abs(u-uc*tau)), max(abs(un-unc*tau)), max(abs(un - ((uxc*tau).*real(t.nx)+(uyc*tau).*imag(t.nx))))]) [u un] = LapSLP(t,s); % compare matrix els.... fprintf('matrix fill, max abs matrix element diffs in u, un, and [ux,uy]...\n') disp([max(abs(u(:)-uc(:))), max(abs(un(:)-unc(:))), max(max(abs(un - (bsxfun(@times,uxc,real(t.nx))+bsxfun(@times,uyc,imag(t.nx))))))]) end
github
bobbielf2/BIE2D-master
LapDLP.m
.m
BIE2D-master/kernels/LapDLP.m
2,338
utf_8
af3c40315b00f14da317ca4ed61de17a
function [u un] = LapDLP(t,s,dens) % LAPDLP Evaluate Laplace double-layer potential from curve to targets % % This evaluates the 2D Laplace double-layer potential for the density tau, % % u(x) = (1/2pi) int_gamma (n_y.(x-y))/r^2 tau(y) ds_y, % where r:=x-y, x,y in R2, % % using the native quadrature rule on the source segment, where point % values of tau are given. % % [u un] = LapDLP(t,s,dens) evaluates potential and its target-normal % derviative. % % [A An] = LapDLP(t,s) or LapDLP(t,s,[]) returns matrix which maps a % density vector to the vector of potentials (A) and target-normal derivatives % (An). % % Tested by: LAPINTDIRBVP % Crude native quadr and O(NM) RAM for now. Obviously C/Fortran would not % form matrices for the density eval case, rather direct sum w/o/ wasting RAM. % todo: make O(N+M) & incorporate Gary's scf % Barnett 6/12/16. Interface change 6/27/16. if nargout==1 u = LapDLPmat(t,s); % local matrix filler if nargin>2 && ~isempty(dens) u = u * dens; end else [u un] = LapDLPmat(t,s); if nargin>2 && ~isempty(dens) u = u * dens; un = un * dens; end end %%%%%% function [A An] = LapDLPmat(t,s) % [A An] = LapDLPmat(t,s) % plain double-layer kernel matrix & targ n-deriv % t = target seg (x,nx cols), s = src seg. % No jump included on self-interaction (ie principal-value integral). % Self-evaluation for the hypersingular An currently gives inf. % Barnett 6/12/16 from stuff since 2008. speed repmat->bsxfun 6/28/16 N = numel(s.x); d = bsxfun(@minus,t.x,s.x.'); % C-# displacements mat % mult by identical rows given by source normals... A = real(bsxfun(@rdivide,(1/2/pi)*s.nx.',d)); % complex form of dipole if sameseg(t,s) % self? A(diagind(A)) = -s.cur*(1/4/pi); end % diagonal term for Laplace A = bsxfun(@times, A, s.w(:)'); if nargout>1 % deriv of double-layer. Not correct for self-interaction. csry = bsxfun(@times, conj(s.nx.'), d); % (cos phi + i sin phi).r % identical cols given by target normals... csrx = bsxfun(@times, conj(t.nx), d); % (cos th + i sin th).r r = abs(d); % dist matrix R^{MxN} An = -real(csry.*csrx)./((r.^2).^2); % divide is faster than bxsfun here An = bsxfun(@times, An, (1/2/pi)*s.w(:)'); % prefac & quadr wei end
github
bobbielf2/BIE2D-master
LapSLP.m
.m
BIE2D-master/kernels/LapSLP.m
2,194
utf_8
a059bb7d72b5cea17a636e72f1f03b63
function [u un] = LapSLP(t,s,dens) % LAPSLP Evaluate Laplace single-layer potential from curve to targets % % This evaluates the 2D Laplace single-layer potential for the density tau, % % u(x) = (1/2pi) int_gamma log(1/r) tau(y) ds_y, where r:=x-y, x,y in R2, % % using the native quadrature rule on the source segment gamma, where point % values of tau are given. % % [u un] = LapSLP(t,s,dens) evaluates potential and its target-normal % derviative. % % [A An] = LapSLP(t,s) or LapSLP(t,s,[]) returns matrix which maps a % density vector to the vector of potentials (A) and target-normal derivatives % (An). % % Tested by: LAPINTDIRBVP % % Crude native quadr and O(NM) RAM for now % todo: make O(N+M) & incorporate Gary's scf % Barnett 6/27/16 if nargout==1 u = LapSLPmat(t,s); if nargin>2 && ~isempty(dens) u = u * dens; end else [u un] = LapSLPmat(t,s); if nargin>2 && ~isempty(dens) u = u * dens; un = un * dens; end end %%%%%% function [A An] = LapSLPmat(t,s) % [A An] = LapSLPmat(t,s) % plain single-layer kernel matrix & targ n-deriv % t = target seg (x,nx cols), s = src seg. % Kress quadrature used for self-interaction (assumes global quad). % No jump included on self-interaction of derivative (ie PV integral). % Barnett 6/12/16 from stuff since 2008; bsxfun speedups 6/28/16 N = numel(s.x); d = bsxfun(@minus,t.x,s.x.'); % C-# displacements mat ss = sameseg(t,s); if ss A = -log(abs(d)) + circulant(0.5*log(4*sin(pi*(0:N-1)/N).^2)); % peri log A(diagind(A)) = -log(s.sp); % diagonal limit m = 1:N/2-1; Rjn = ifft([0 1./m 2/N 1./m(end:-1:1)])/2; % Kress Rj(N/2)/4pi A = A/N + circulant(Rjn); % includes SLP prefac 1/2pi. Kress peri log matrix L A = bsxfun(@times, A, s.sp.'); % do speed factors (2pi/N weights already) else A = bsxfun(@times, log(abs(d)), -(1/2/pi)*s.w(:)'); % prefactor & wei end if nargout==2 % apply D^T (flips sign and src deriv) An = real(bsxfun(@rdivide,(1/2/pi)*(-t.nx),d)); % complex form of dipole if ss An(diagind(An)) = -s.cur*(1/4/pi); % self? diagonal term for Laplace end An = bsxfun(@times, An, s.w(:)'); % quadr wei end
github
bobbielf2/BIE2D-master
LapDLP_closeglobal.m
.m
BIE2D-master/kernels/LapDLP_closeglobal.m
5,939
utf_8
6a45d8371c9f21057986fe1eef5807ba
function [u ux uy info] = LapDLP_closeglobal(t, s, tau, side) % LAPDLP_CLOSEGLOBAL - Laplace DLP potential & deriv w/ global close-eval quad % % u = LapDLP_closeglobal(t,s,dens,side) returns potentials at targets t.x % due to double-layer potential with real-valued density dens sampled on the % nodes s.x of a smooth global quadrature rule on the curve s, either inside % outside the curve. The global scheme of [hel08] based on barycentric Cauchy % close-evaluation (see references in Cau_closeglobal.m) is used. % % Our definition of the DLP on curve \Gamma is, associating R^2 with the complex % plane, with x = (x_1,x_2) a point in the complex plane, % % u(x) = Re (1/2\pi i) \int_\Gamma \tau(y) / (x-y) dy % % Inputs: % t = target struct containing % t.x = M-by-1 list of targets, as points in complex plane % (optionally also t.nx target normals as unit complex numbers) % s = curve struct containing N-by-1 vector s.x of source nodes (as complex % numbers), and other fields as generated by setupquad. % dens = double-layer density values at nodes. Note, must be real-valued to % evaluate Laplace layer potentials (note Stokes feeds it complex dens). % If dens has multiple columns, the evaluation is done for each. % If dens is empty, outputs are matrices mapping density to values, etc. % side = 'i','e' to indicate targets are interior or exterior to the curve. % % Outputs: % u = column vector of M potential values where M = numel(t.x), or if % dens has n columns, the n column vector outputs are stacked (M-by-n). % [u un] = LapDLPeval_closeglobal(t,s,dens,side) also returns target-normal % derivatives (M-by-n) using t.nx % [u ux uy] = LapDLPeval_closeglobal(t,s,dens,side) instead returns x- and y- % partials of u at the targets (ignores t.nx) % [u ux uy info] = LapDLPeval_closeglobal(t,s,dens,side) also gives diagnostic: % info.vb = vector of v boundary values (M-by-n) % info.imv = imag part of v at targets (M-by-n) % % References: % % [hel08] J. Helsing and R. Ojala, On the evaluation of layer potentials close % to their sources, J. Comput. Phys., 227 (2008), pp. 2899–292 % % [lsc2d] Spectrally-accurate quadratures for evaluation of layer potentials % close to the boundary for the 2D Stokes and Laplace equations, % A. H. Barnett, B. Wu, and S. Veerapaneni, SIAM J. Sci. Comput., % 37(4), B519-B542 (2015) https://arxiv.org/abs/1410.2187 % % See also: LAPDLP, SETUPQUAD, CAU_CLOSEGLOBAL, LAPINTDIRBVP % % complexity O(N^2) for evaluation of v^+ or v^-, plus O(NM) for globally % compensated quadrature to targets % Barnett 2013; multiple-column Gary Marple, 2014. % Repackaged Barnett 6/12/16, 6/27/16 col vec outputs. 6/29/16 bsxfun faster if nargin==0, test_LapDLP_closeglobal; return; end N = numel(s.x); M = numel(t.x); % # source, target nodes if isempty(tau), tau = eye(N); end % case of filling matrices n = size(tau,2); % # density columns % Helsing step 1: eval bdry limits at nodes of v = complex DLP(tau)... % (note to future fortran/C versions: this also needs to be able to handle % complex input, real output, since the Stokes DLP feeds that in) vb = zeros(N,n); % alloc v^+ or v^- bdry data of holom func taup = zeros(N,n); % alloc tau' for k=1:n taup(:,k) = perispecdiff(tau(:,k)); % numerical deriv of each dens end for i=1:N, j = [1:i-1, i+1:N]; % skip pt i. Eqn (4.2) in [lsc2d] vb(i,:) = sum(bsxfun(@times,bsxfun(@minus,tau(j,:),tau(i,:)),s.cw(j)./(s.x(j)-s.x(i))),1) + taup(i,:)*s.w(i)/s.sp(i); % vectorized over cols (ahb) end vb = vb*(1/(-2i*pi)); % prefactor if side=='i', vb = vb - tau; end % JR's add for v^-, cancel for v^+ (Eqn 4.3) info.vb = vb; % diagnostics % Helsing step 2: compensated close-evaluation of v & v', followed by take Re: if nargout>1 % want derivatives [v vp] = Cau_closeglobal(t.x,s,vb,side); % does Sec. 3 of [lsc2d] ux = real(vp); uy = -imag(vp); % col vecs, leave as partials... if nargout==2 % or dot w/ targ nor... ux = bsxfun(@times,ux,real(t.nx)) + bsxfun(@times,uy,imag(t.nx)); end else v = Cau_closeglobal(t.x,s,vb,side); % does Sec. 3 of [lsc2d] end u = real(v); info.imv = imag(v); %%%%%%%%%%%%%%%%%%% function test_LapDLP_closeglobal fprintf('check Laplace DLP close-eval quadr match native rule in far field...\n') verb = 0; % to visualize s = wobblycurve(1,0.3,5,200); s.a = mean(s.x); if verb,figure;showsegment(s);end tau = -0.7+exp(sin(3*s.t)); % pick smooth density w/ nonzero mean nt = 100; t.nx = exp(2i*pi*rand(nt,1)); % target normals for side = 'ie' if side=='e', t.x = 1.5+1i+rand(nt,1)+1i*rand(nt,1); % distant targs else, t.x = 0.6*(rand(nt,1)+1i*rand(nt,1)-(0.5+0.5i)); end % targs far inside if verb, plot(t.x,'.'); end fprintf('\nside = %s:\n',side) [u un] = LapSLP(t,s,tau); % eval given density cases... [uc unc] = LapSLP_closeglobal(t,s,tau,side); tic, [uc uxc uyc] = LapSLP_closeglobal(t,s,tau,side); fprintf('Lap DLP density eval (%.3g sec), max abs err in u, un, and [ux,uy]...\n',toc) disp([max(abs(u-uc)), max(abs(un-unc)), max(abs(un - (uxc.*real(t.nx)+uyc.*imag(t.nx))))]) [uc unc] = LapSLP_closeglobal(t,s,[],side); tic, [uc uxc uyc] = LapSLP_closeglobal(t,s,[],side); fprintf('matrix fill (%.3g sec) & apply, max abs err in u, un, and [ux,uy]...:\n',toc) disp([max(abs(u-uc*tau)), max(abs(un-unc*tau)), max(abs(un - ((uxc*tau).*real(t.nx)+(uyc*tau).*imag(t.nx))))]) [u un] = LapSLP(t,s); % compare matrix els.... fprintf('matrix fill, max abs matrix element diffs in u, un, and [ux,uy]...\n') disp([max(abs(u(:)-uc(:))), max(abs(un(:)-unc(:))), max(max(abs(un - (bsxfun(@times,uxc,real(t.nx))+bsxfun(@times,uyc,imag(t.nx))))))]) end
github
bobbielf2/BIE2D-master
srcsum2.m
.m
BIE2D-master/kernels/srcsum2.m
3,784
utf_8
813262bbeb3de8223b1dd07456429793
function [A B C] = srcsum2(kernel, trlist, phlist, t, s, varargin) % SRCSUM2 Sum a kernel eval or matrix over source translations via single call % % This is a variant of srcsum that sums over targets in a single kernel call, % instead of summing over sources with multiple calls. This is useful for % periodized close evaluation. NOTE: it cannot be used for self-interactions! % % [A B ...] = srcsum2(kernel, trlist, phlist, t, s) % [A B ...] = srcsum2(kernel, trlist, phlist, t, s, param) % % Inputs: % kernel : function of form A = kernel(t,s,...) or [A B] = kernel(t,s,...) % trlist : list of complex numbers giving source translations % phlist : list of complex numbers giving source phase factors (1 if empty) % t : target segment struct % s : source segment struct % Outputs: % A (& optionally B, C): outputs as from kernel but summed over the source % % Example usage: % s = wobblycurve(.3,5,100); t = wobblycurve(.3,5,50); t.x = t.x/2; % t neq s % tau = sin(4*s.t); % pick a density % u = srcsum2(@LapDLP,[-2 0 2], [], s,s, tau); % do it % ss = s; v = LapDLP(s,ss,tau); % check matches direct sum % ss.x = s.x-2; v = v + LapDLP(s,ss,tau); % ss.x = s.x+2; v = v + LapDLP(s,ss,tau); % norm(u-v) % % Also see: SRCSUM % Barnett 6/30/16 when realized close eval prefers more targs but single src. % 9/28/17 fixed tt.nx omission. if nargin==0, test_srcsum2; return; end if isempty(phlist), phlist = 0*trlist+1.0; end M = numel(t.x); n = numel(trlist); tt.x = []; % will store all targets with copies for i=1:n, tt.x = [tt.x; t.x - trlist(i)]; end % all transl trgs, by invariance if isfield(t,'nx'), tt.nx = repmat(t.nx,[n 1]); end % all trg normals % (we assumed x and nx are only fields relevant for targets) if nargout==1 At = kernel(tt,s,varargin{:}); A = sumblk(At,M,phlist); elseif nargout==2 [At Bt] = kernel(tt,s,varargin{:}); A = sumblk(At,M,phlist); B = sumblk(Bt,M,phlist); elseif nargout==3 [At Bt Ct] = kernel(tt,s,varargin{:}); A = sumblk(At,M,phlist); B = sumblk(Bt,M,phlist); C = sumblk(Ct,M,phlist); else error('srcsum2 cannot handle >3 output args'); end function A = sumblk(At,M,phlist) % crush At along target image sum n = numel(phlist); % d will be how many vector components per targ pt (presumably 1 or 2)... d = size(At,1)/M/n; if d~=1 && d~=2, error('sumblk cant handle # rows At'); end A = zeros(M*d,size(At,2)); if d==1, ii = 1:M; else, ii = [1:M,n*M+(1:M)]; end % only handles d=1,2 for i=1:n, A = A + phlist(i)*At(ii+(i-1)*M,:); end %%%%%%%%%%%%%%%% function test_srcsum2 % tests non-self interactions only % density case... s = wobblycurve(1,.3,5,100); t = wobblycurve(1,.3,5,50); t.x = t.x/2; % t neq s tau = sin(4*s.t); % pick a density u = srcsum2(@LapDLP,[0 2], [1 3], t,s, tau); % do it (include "phase") ss = s; v = LapDLP(t,ss,tau); % check matches direct sum ss.x = s.x+2; v = v + 3*LapDLP(t,ss,tau); % note phase norm(u-v) % matrix case... u = srcsum2(@LapDLP,[0 2], [1 3], t,s); % do it (include phase) ss = s; v = LapDLP(t,ss); % check matches direct sum ss.x = s.x+2; v = v + 3*LapDLP(t,ss); % note phase norm(u-v) % 2-cmpt output matrix case... mu = 0.6; u = srcsum2(@StoDLP,[0 2], [1 3], t,s,mu); % do it (include phase) ss = s; v = StoDLP(t,ss,mu); % check matches direct sum ss.x = s.x+2; v = v + 3*StoDLP(t,ss,mu); % note phase norm(u-v) % 2-cmpt multi-output matrix case... [u p] = srcsum2(@StoDLP,[0 2], [1 3],t,s,mu); % do it (include phase) ss = s; [v q] = StoDLP(t,ss,mu); % check matches direct sum ss.x = s.x+2; [v2 q2] = StoDLP(t,ss,mu); v = v + 3*v2; q = q + 3*q2; norm(u-v)
github
bobbielf2/BIE2D-master
Cau_closeglobal.m
.m
BIE2D-master/kernels/Cau_closeglobal.m
21,333
utf_8
4dd051a07dc6fea05de5cbef9eb8e089
function [vc vcp] = Cau_closeglobal(x,s,vb,side,o) % CAU_CLOSEGLOBAL. Globally compensated barycentric int/ext Cauchy integral % % This is a spectrally-accurate close-evaluation scheme for Cauchy integrals. % It returns approximate values (and possibly first derivatives) of a function % either holomorphic inside of, or holomorphic and decaying outside of, a % closed curve, given a set of its values on nodes of a smooth global % quadrature rule for the curve (such as the periodic trapezoid rule). % This is done by approximating the Cauchy integral % % v(x) = +- (1/(2i.pi)) integral_Gamma v(y) / (x-y) dy, % % where Gamma is the curve, the sign is + (for x interior) or - (exterior), % using special barycentric-type formulae which are accurate arbitrarily close % to the curve. % % By default, for the value these formulae are (23) for interior and (27) for % exterior, from [hel08], before taking the real part. The interior case % is originally due to [ioak]. For the derivative, the Schneider-Werner formula % (Prop 11 in [sw86]; see [berrut]) is used to get v' at the nodes, then since % v' is also holomorphic, it is evaluated using the same scheme as v. This % "interpolate the derivative" suggestion of Trefethen (personal communication, % 2014) contrasts [lsc2d] which "differentes the interpolant". The former gives % around 15 digits for values v, 14 digits for interior derivatives v', but % only 13 digits for exterior v'. (The other [lsc2d] scheme gives 14 digits % in the last case; see options below). The paper [lsc2d] has key background, % and is helpful to understand [hel08] and [sw86]. This code replaces code % referred to in [lsc2d]. % % The routine can (when vb is empty) instead return the full M-by-N dense % matrices mapping v at the nodes to values (and derivatives) at targets. % % Basic use: v = Cau_closeglobal(x,s,vb,side) % [v vp] = Cau_closeglobal(x,s,vb,side) % % Inputs: % x = row or col vec of M target points in complex plane % s = closed curve struct containing a set of vectors with N items each: % s.x = smooth quadrature nodes on curve, points in complex plane % s.w = smooth weights for arc-length integrals (scalar "speed weights") % s.nx = unit normals at nodes (unit magnitude complex numbers) % vb = col vec (or stack of such) of N boundary values of holomorphic function % v. If empty, causes outputs to be the dense matrix/matrices. % side = 'i' or 'e' specifies if all targets interior or exterior to curve. % % Outputs: % v = col vec (or stack of such) approximating the homolorphic function v % at the M targets % vp = col vec (or stack of such) approximating the complex first derivative % v' at the M targets % % Without input arguments, a self-test is done outputting errors at various % distances from the curve for a fixed N. (Needs setupquad.m) % % Notes: % 1) For accuracy, the smooth quadrature must be accurate for the boundary data % vb, and it must come from a holomorphic function (be in the right Hardy % space). % 2) For the exterior case, v must vanish at infinity. % 3) The algorithm is O(NM) in time. In order to vectorize in both sources and % targets, it is also O(NM) in memory - using loops this could of course be % reduced to O(N+M). If RAM is a limitation, targets should be blocked into % reasonable numbers and a separate call done for each). % % If vb is empty, the outputs v and vp are instead the dense evaluation % matrices, and the time cost is O(N^2M) --- this should be rewritten. % % Advanced use: [vc vcp] = Cau_closeglobal(x,s,vb,side,opts) allows control of % options such as % opts.delta : switches to a different [lsc2d] scheme for v', which is % non-barycentric for distances beyond delta, but O(N) slower % for distances closer than delta. This achieves around 1 extra % digit for v' in the exterior case. I recommend delta=1e-2. % For this scheme, s must have the following extra field: % s.a = a point in the "deep" interior of curve (far from % the boundary) % delta=0 never uses the barycentric form for v', loses digits % in v' as target approaches source. % % References: % % [sw86] C. Schneider and W. Werner, Some new aspects of rational % interpolation, Math. Comp., 47 (1986), pp. 285–299 % % [ioak] N. I. Ioakimidis, K. E. Papadakis, and E. A. Perdios, Numerical % evaluation of analytic functions by Cauchy’s theorem, BIT Numer. % Math., 31 (1991), pp. 276–285 % % [berrut] J.-P. Berrut and L. N. Trefethen, Barycentric Lagrange % interpolation, SIAM Review, 46 (2004), pp. 501-517 % % [hel08] J. Helsing and R. Ojala, On the evaluation of layer potentials close % to their sources, J. Comput. Phys., 227 (2008), pp. 2899–292 % % [lsc2d] Spectrally-accurate quadratures for evaluation of layer potentials % close to the boundary for the 2D Stokes and Laplace equations, % A. H. Barnett, B. Wu, and S. Veerapaneni, SIAM J. Sci. Comput., % 37(4), B519-B542 (2015) https://arxiv.org/abs/1410.2187 % % See also: test/FIG_CAU_CLOSEGLOBAL, SETUPQUAD. % % Todo: * allow mixed interior/exterior targets, and/or auto-detect this. % * O(N) faster matrix filling version! % * Think about if interface should be t.x. % Note in/output format changed to col vecs, 6/27/16 % (c) Alex Barnett, June 2016, based on code from 10/22/13. Blocked 8/2/16 if nargin<1, test_Cau_closeglobal; return; end if nargin<5, o = []; end N = numel(s.x); %'size vb = ', size(vb) if isempty(vb) % do matrix filling version (N data col vecs) if nargout==1, vc = Cau_closeglobal(x,s,eye(N),side,o); % THIS IS MN^2 SLOW! else, [vc vcp] = Cau_closeglobal(x,s,eye(N),side,o); end return end if isfield(o,'delta') if ~isfield(s,'a'), error('s.a interior pt needed to use lsc2d version'); end if nargout==1, vc = cauchycompeval_lsc2d(x,s,vb,side,o); else, [vc vcp] = cauchycompeval_lsc2d(x,s,vb,side,o); end return end M = numel(x); Nc = size(vb,2); % # targets, input col vecs cw = s.cw; % complex speed weights, col vec if Nc==1 % ---------------------------- original single-vector version ----- % Do bary interp for value outputs. note sum along 1-axis faster than 2-axis comp = repmat(cw, [1 M]) ./ (repmat(s.x,[1 M]) - repmat(x(:).',[N 1])); I0 = sum(repmat(vb,[1 M]).*comp); J0 = sum(comp); % Ioakimidis notation if side=='e', J0 = J0-2i*pi; end % Helsing exterior form vc = (I0./J0).'; % bary form (col vec) [jj ii] = ind2sub(size(comp),find(~isfinite(comp))); % node-targ coincidences for l=1:numel(jj), vc(ii(l)) = vb(jj(l)); end % replace each hit w/ corresp vb if nargout>1 % 1st deriv also wanted... Trefethen idea first get v' @ nodes vbp = 0*vb; % prealloc v' @ nodes if side=='i' for j=1:N notj = [1:j-1, j+1:N]; % std Schneider-Werner form for deriv @ node... vbp(j) = -sum(cw(notj).*(vb(j)-vb(notj))./(s.x(j)-s.x(notj)))/cw(j); end else for j=1:N notj = [1:j-1, j+1:N]; % ext version of S-W form derived 6/12/16... vbp(j) = (-sum(cw(notj).*(vb(j)-vb(notj))./(s.x(j)-s.x(notj)))-2i*pi*vb(j))/cw(j); %abs(vbp(j) / (2i*pi*vb(j)/cw(j))) % shows 2.5 digits of cancel, bad! end end % now again do bary interp of v' using its value vbp at nodes... I0 = sum(repmat(vbp,[1 M]).*comp); J0 = sum(comp); if side=='e', J0 = J0-2i*pi; end % Helsing exterior form vcp = (I0./J0).'; % bary form (col vec) for l=1:numel(jj), vcp(ii(l)) = vbp(jj(l)); end % replace each hit w/ vbp end else % ------------------------------ multi-vector version --------------- % Note: this is non-optimal as method for matrix filling, due to incoming 0s. % Do bary interp for value outputs: % Precompute weights in O(NM)... note sum along 1-axis faster than 2-axis... comp = repmat(cw, [1 M]) ./ (repmat(s.x,[1 M]) - repmat(x(:).',[N 1])); % mult input vec version (transp of Wu/Marple): comp size N*M, I0 size M*Nc I0 = blockedinterp(vb,comp); % local func, directly below J0 = sum(comp).'; % size N*1, Ioakimidis notation if side=='e', J0 = J0-2i*pi; end % Helsing exterior form vc = I0./(J0*ones(1,Nc)); % bary form (multi-vec), size M*Nc [jj ii] = ind2sub(size(comp),find(~isfinite(comp))); % node-targ coincidences for l=1:numel(jj), vc(ii(l),:) = vb(jj(l),:); end % replace each hit w/ corresp vb if nargout>1 % 1st deriv also wanted... Trefethen idea first get v' @ nodes vbp = 0*vb; % prealloc v' @ nodes (size N*Nc) if side=='i' for j=1:N notj = [1:j-1, j+1:N]; % std Schneider-Werner form for deriv @ node... % Note repmat or ones (Wu/Marple) changed to bsxfun, faster: vbp(j,:) = -sum(bsxfun(@times, bsxfun(@times,cw(notj),bsxfun(@minus,vb(j,:),vb(notj,:))), 1./(s.x(j)-s.x(notj))),1)/cw(j); % fast but unreadable end else for j=1:N notj = [1:j-1, j+1:N]; % ext version of S-W form derived 6/12/16... % Note repmat or ones (Wu/Marple) changed to bsxfun, faster: vbp(j,:) = (-sum(bsxfun(@times, bsxfun(@times,cw(notj),bsxfun(@minus,vb(j,:),vb(notj,:))), 1./(s.x(j)-s.x(notj))),1) -2i*pi*vb(j,:) )/cw(j); % fast but unreadable end end % now again do bary interp of v' using its value vbp at nodes... I0 = blockedinterp(vbp,comp); J0 = sum(comp).'; if side=='e', J0 = J0-2i*pi; end % Helsing exterior form vcp = I0./(J0*ones(1,Nc)); % bary form for l=1:numel(jj), vcp(ii(l),:) = vbp(jj(l),:); end % replace hits w/ vbp end end %%%%% function I0 = blockedinterp(vb,comp) % .................................... % perform barycentric interpolation using precomputed comp wei mat, used in % multi-density vec version above, in a RAM-efficient way (the naive approach % is O(M.N.Nc); here we limit RAM by blocking. Output: I0 (size M*Nc). % Barnett 8/2/16 [N M] = size(comp); [N Nc] = size(vb); I0 = nan(M,Nc); blk = 1e7; % user param: how many doubles you want to handle in RAM Ncstep = min(Nc,ceil(blk/(M*N))); % how many col vecs from vb in each chunk for i=1:Ncstep:Nc % do blocking, still vectorized efficient ii = i+(0:Ncstep-1); ii = ii(ii<=Nc); Nci = numel(ii); % don't overrun array vbi = vb(:,ii); % just the block of density vectors I0(:,ii) = permute(sum(repmat(permute(vbi,[1 3 2]),[1 M 1]).*repmat(comp,[1 1 Nci]),1),[2 3 1]); end % ................................... %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [vc, vcp] = cauchycompeval_lsc2d(x,s,vb,side,o) % Variant of the above, used in the [lsc2d] paper. % % The only new input needed is s.a, an interior point far from the boundary. % % The algorithm is that of Ioakimidis et al BIT 1991 for interior, and, % for the exterior, a modified version using 1/(z-a) in place of the function 1. % For the derivative, the formula is mathematically the derivative of the % barycentric formula of Schneider-Werner 1986 described in Berrut et al 2005, % but using the complex quadrature weights instead of the barycentric weights. % However, since this derivative is not itself a true barycentric form, a hack % is needed to compute the difference v_j-v(x) in a form where roundoff error % cancels correctly. The exterior case is slightly more intricate. When % a target coincides with a node j, the true value v_j (or Schneider-Werner % formula for v'(x_j)) is used. % % Alex Barnett 10/22/13 based on cauchycompevalint, pole code in lapDevalclose.m % 10/23/13 node-targ coincidences fixed, exterior true barycentric discovered. % todo: check v' ext at the node (S-W form), seems to be wrong. if nargin<5, o = []; end if size(vb,2)>1 % matrix versions if nargout==1, vc = cauchycompmat_lsc2d(x,s,vb,side,o); else, [vc vcp] = cauchycompmat_lsc2d(x,s,vb,side,o); end return end if ~isfield(o,'delta'), o.delta = 1e-2; end % currently won't ever be run. % delta = dist param where $O(N^2.M) deriv bary form switched on. % Roughly deriv errors are then limited to emach/mindist % The only reason to decrease mindist is if lots of v close % nodes on the curve with lots of close target points. cw = s.cw; % complex speed weights N = numel(s.x); M = numel(x); if nargout==1 % no deriv wanted... (note sum along 1-axis faster than 2-axis) comp = repmat(cw(:), [1 M]) ./ (repmat(s.x(:),[1 M]) - repmat(x(:).',[N 1])); if side=='e', pcomp = comp .* repmat(1./(s.x(:)-s.a), [1 M]); else pcomp = comp; end % pcomp are weights and bary poles appearing in J0 I0 = sum(repmat(vb(:),[1 M]).*comp); J0 = sum(pcomp); % Ioakimidis notation vc = I0./J0; % bary form if side=='e', vc = vc./(x(:).'-s.a); end % correct w/ pole [jj ii] = ind2sub(size(comp),find(~isfinite(comp))); % node-targ coincidences for l=1:numel(jj), vc(ii(l)) = vb(jj(l)); end % replace each hit w/ corresp vb else % 1st deriv wanted... invd = 1./(repmat(s.x(:),[1 M]) - repmat(x(:).',[N 1])); % 1/displacement mat comp = repmat(cw(:), [1 M]) .* invd; if side=='e', pcomp = comp .* repmat(1./(s.x(:)-s.a), [1 M]); else pcomp = comp; end % pcomp are weights and bary poles appearing in J0 I0 = sum(repmat(vb(:),[1 M]).*comp); J0 = sum(pcomp); if side=='e', prefac = 1./(x(:).'- s.a); else prefac = 1; end vc = prefac .* I0./J0; % bary form (poss overall pole) dv = repmat(vb(:),[1 M]) - repmat(vc(:).',[N 1]); % v value diff mat [jj ii] = ind2sub(size(invd),find(abs(invd) > 1/o.delta)); % bad pairs indices if side=='e' % exterior: for l=1:numel(jj), j=jj(l); i=ii(l); % loop over node-targ pairs too close p = sum(comp(:,i).*(vb(j)./(s.x(:)-s.a)-vb(:)./(s.x(j)-s.a))) / sum(pcomp(:,i)); % p is v_j - (x-a)/(yj-a)*v(x) for x=i'th target dv(j,i) = prefac(i) * ((s.x(j)-s.a)*p + (x(i)-s.x(j))*vb(j)); end % pole-corrected for dv, gives bary stability for close node-targ pairs else % interior: for l=1:numel(jj), j=jj(l); i=ii(l); % loop over node-targ pairs too close dv(j,i) = sum(comp(:,i).*(vb(j)-vb(:))) / sum(pcomp(:,i)); end % bary for dv, gives bary stability for close node-targ pairs end vcp = prefac .* sum(dv.*comp.*invd) ./ J0; % bary form for deriv [jj ii] = ind2sub(size(comp),find(~isfinite(comp))); % node-targ coincidences for l=1:numel(jj), j=jj(l); i=ii(l); % loop over hitting node-targ pairs vc(i) = vb(j); % replace each hit w/ corresp vb notj = [1:j-1, j+1:N]; % Schneider-Werner form for deriv @ node: vcp(i) = -sum(cw(notj).*(vb(j)-vb(notj))./(s.x(j)-s.x(notj)))/cw(j); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [vc vcp] = cauchycompmat_lsc2d(x,s,vb,side,o) % Multiple vb-vector version of cauchycompeval_lsc2d, written by Gary Marple % and Bowei Wu, 2014-2015. This can be called with eye(N) to fill the evaluation % matrix (note that each column is not a holomorphic function, but by linearity % when summed they give the right answer). When sent a single column vector % for vb, this duplicates the action of cauchycompeval_lsc2d. % Undocumented; notes by Barnett 6/12/16 % todo: check v' ext at the node (S-W form), seems to be wrong. if nargin<5, o = []; end if ~isfield(o,'delta'), o.delta = 1e-2; end % dist param where $O(N^2.M) deriv bary form switched on. % Roughly deriv errors are then limited to emach/mindist % The only reason to decrease mindist is if lots of v close % nodes on the curve with lots of close target points. cw = s.cw; % complex speed weights N = numel(s.x); M = numel(x); n=size(vb,2); % # vb vectors if nargout==1 % no deriv wanted... (note sum along 1-axis faster than 2-axis) comp = repmat(cw(:), [1 M]) ./ (repmat(s.x(:),[1 M]) - repmat(x(:).',[N 1])); if side=='e', pcomp = comp .* repmat(1./(s.x(:)-s.a), [1 M]); else pcomp = comp; end % pcomp are weights and bary poles appearing in J0 %I0 = sum(repmat(vb(:),[1 M]).*comp); I0 = permute(sum(repmat(permute(vb,[1 3 2]),[1 M 1]).*repmat(comp,[1 1 n]),1),[3 2 1]); J0 = sum(pcomp); % Ioakimidis notation vc = I0./(ones(n,1)*J0); % bary form if side=='e', vc = vc./(ones(n,1)*(x(:).'-s.a)); end % correct w/ pole [jj ii] = ind2sub(size(comp),find(~isfinite(comp))); % node-targ coincidences for l=1:numel(jj), vc(:,ii(l)) = vb(jj(l),:).'; end % replace each hit w/ corresp vb else % 1st deriv wanted... invd = 1./(repmat(s.x(:),[1 M]) - repmat(x(:).',[N 1])); % 1/displacement mat comp = repmat(cw(:), [1 M]) .* invd; if side=='e', pcomp = comp .* repmat(1./(s.x(:)-s.a), [1 M]); else pcomp = comp; end % pcomp are weights and bary poles appearing in J0 %I0 = sum(repmat(vb(:),[1 M]).*comp); I0 = permute(sum(repmat(permute(vb,[1 3 2]),[1 M 1]).*repmat(comp,[1 1 n]),1),[3 2 1]); J0 = sum(pcomp); if side=='e', prefac = 1./(x(:).'- s.a); else prefac = ones(1,M); end vc = (ones(n,1)*prefac) .* I0./(ones(n,1)*J0); % bary form (poss overall pole) %dv = repmat(vb(:),[1 M]) - repmat(vc(:).',[N 1]); % v value diff mat dv = repmat(permute(vb,[1 3 2]),[1 M 1]) - repmat(permute(vc,[3 2 1]),[N 1 1]); % v value diff mat [jj ii] = ind2sub(size(invd),find(abs(invd) > 1/o.delta)); % bad pairs indices if side=='e' % exterior: for l=1:numel(jj), j=jj(l); i=ii(l); % loop over node-targ pairs too close p = sum((comp(:,i)*ones(1,n)).*((ones(N,1)*vb(j,:))./(s.x(:)*ones(1,n)-s.a)-vb/(s.x(j)-s.a)),1) / sum(pcomp(:,i)); % p is v_j - (x-a)/(yj-a)*v(x) for x=i'th target dv(j,i,:) = prefac(i) * ((s.x(j)-s.a)*p + (x(i)-s.x(j))*vb(j,:)); end % pole-corrected for dv, gives bary stability for close node-targ pairs else % interior: for l=1:numel(jj), j=jj(l); i=ii(l); % loop over node-targ pairs too close dv(j,i,:) = sum((comp(:,i)*ones(1,n)).*(ones(size(vb,1),1)*vb(j,:)-vb),1) / sum(pcomp(:,i)); end % bary for dv, gives bary stability for close node-targ pairs end % This is faster, but gives rounding errors when compared to the original % cauchycompeval. vcp = (ones(n,1)*(prefac./ J0)).* permute(sum(dv.*repmat(comp.*invd,[1 1 n]),1),[3 2 1]) ; % bary form for deriv % This vectorized form is slower, but does not give rounding errors. %vcp = (ones(n,1)*prefac).* permute(sum(dv.*repmat(comp,[1 1 n]).*repmat(invd,[1 1 n]),1),[3 2 1])./(ones(n,1)*J0) ; % bary form for deriv [jj ii] = ind2sub(size(comp),find(~isfinite(comp))); % node-targ coincidences for l=1:numel(jj), j=jj(l); i=ii(l); % loop over hitting node-targ pairs vc(:,i) = vb(j,:).'; % replace each hit w/ corresp vb notj = [1:j-1, j+1:N]; % Schneider-Werner form for deriv @ node: vcp(i,:) = -sum((cw(notj)*ones(1,n)).*((ones(N-1,1)*vb(j,:))-vb(notj,:))./((s.x(j)-s.x(notj))*ones(1,n)),1)/cw(j); end end %%%%%%%%%%%%%%%%%%%%%%%%% function test_Cau_closeglobal % test self-reproducing of Cauchy integrals N = 200, s = wobblycurve(1,0.3,5,N); % smooth wobbly radial shape params tic; %profile clear; profile on; format short g for side = 'ie' % test Cauchy formula for holomorphic funcs in and out... a = 1.1+1i; if side=='e', a = .1+.5i; end % pole, dist 0.5 from G, .33 for ext v = @(z) 1./(z-a); vp = @(z) -1./(z-a).^2; % used in paper z0 = s.x(floor(N/4)); ds = logspace(0,-18,10).'*(.1-1i); % displacements (col vec) if side=='e', ds = -ds; end % flip to outside z = z0 + ds; z(end) = z0; % ray of pts heading to a node, w/ last hit exactly vz = v(z); vpz = vp(z); M = numel(z); %d = repmat(s.x(:),[1 M])-repmat(z(:).',[N 1]); % displ mat for... %vc = sum(repmat(v(s.x).*s.cw,[1 M])./d,1)/(2i*pi); % naive Cauchy (so bad!) [vc vcp] = Cau_closeglobal(z,s,v(s.x),side); % current version %s.a=0; [vc vcp] = Cau_closeglobal(z,s,v(s.x),side,struct('delta',.01)); % oldbary alg, 0.5-1 digit better for v' ext, except at the node itself, where wrong. err = abs(vc - vz); errp = abs(vcp - vpz); disp(['side ' side ': dist v err v'' err']) [abs(imag(ds)) err errp] % test multi-col-vec inputs & mat filling: [vcm vcpm] = Cau_closeglobal(z,s,[v(s.x),0.5*v(s.x)],side); % basic Nc=2 case fprintf(' multi-col test: %.3g %.3g\n',max(abs(vcm(:,1)-vc)), max(abs(vcpm(:,1)-vcp))) [A Ap] = Cau_closeglobal(z,s,[],side); % matrix fill case fprintf(' mat fill test: %.3g %.3g\n',max(abs(A*v(s.x)-vc)), max(abs(Ap*v(s.x)-vcp))) [A Ap] = Cau_closeglobal(s.x,s,[],side); % test N*N self matrix version fprintf(' self-eval value ||A-I|| (should be 0): %.3g\n', norm(A-eye(N))) fprintf(' self-eval deriv mat apply err (tests S-W form): %.3g\n',max(abs(Ap*v(s.x)-vp(s.x)))) end toc, %profile off; profile viewer %figure; plot(s.x,'k.-'); hold on; plot(z,'+-'); axis equal
github
bobbielf2/BIE2D-master
srcsum.m
.m
BIE2D-master/kernels/srcsum.m
3,271
utf_8
02e5ed4b7254f5901fc6b48d2c328a98
function [A B C] = srcsum(kernel, trlist, phlist, t, s, varargin) % SRCSUM Sum any kernel evaluation or matrix over a set of source translations % % Note, unlike srcsum2 this handles self-interactions correctly % % [A B ...] = srcsum(kernel, trlist, phlist, t, s) % [A B ...] = srcsum(kernel, trlist, phlist, t, s, param) % % Inputs: % kernel : function of form A = kernel(t,s,...) or [A B] = kernel(t,s,...) % trlist : list of complex numbers giving source translations % phlist : list of complex numbers giving source phase factors (1 if empty) % t : target segment struct % s : source segment struct % Outputs: % A (& optionally B, C): outputs as from kernel but summed over the source % % Example usage: % s = wobblycurve(.3,5,100); % tau = sin(4*s.t); % pick a density % u = srcsum(@LapDLP,[-2 0 2], [], s,s, tau); % do it (incl a self-int) % ss = s; v = LapDLP(s,ss,tau); % check matches direct sum % ss.x = s.x-2; v = v + LapDLP(s,ss,tau); % ss.x = s.x+2; v = v + LapDLP(s,ss,tau); % norm(u-v) % % Also see: SRCSUM2 % Barnett 6/12/16, 6/29/16 phlist, self-demo. 6/30/16 "a" field for ext close. if nargin==0, test_srcsum; return; end afield = isfield(s,'a'); if isempty(phlist), phlist = 0*trlist+1.0; end xo = s.x; s.x = xo + trlist(1); if afield, ao = s.a; s.a = ao + trlist(1); end if nargout==1 A = kernel(t,s,varargin{:}); % since we don't know the size can't prealloc for i=2:numel(trlist) s.x = xo + trlist(i); if afield, s.a = ao + trlist(i); end A = A + phlist(i)*kernel(t,s,varargin{:}); end elseif nargout==2 [A B] = kernel(t,s,varargin{:}); for i=2:numel(trlist) s.x = xo + trlist(i); if afield, s.a = ao + trlist(i); end [Ai Bi] = kernel(t,s,varargin{:}); A = A + phlist(i)*Ai; B = B + phlist(i)*Bi; end elseif nargout==3 [A B C] = kernel(t,s,varargin{:}); for i=2:numel(trlist) s.x = xo + trlist(i); if afield, s.a = ao + trlist(i); end [Ai Bi Ci] = kernel(t,s,varargin{:}); A = A + phlist(i)*Ai; B = B + phlist(i)*Bi; C = C + phlist(i)*Ci; end else, error('srcsum cannot handle >3 output args'); end %%%%%%%%%%%%%%%% function test_srcsum % includes self-interactions % density case... s = wobblycurve(1,.3,5,100); tau = sin(4*s.t); % pick a density u = srcsum(@LapDLP,[0 2], [1 3], s,s, tau); % do it (include "phase") ss = s; v = LapDLP(s,ss,tau); % check matches direct sum ss.x = s.x+2; v = v + 3*LapDLP(s,ss,tau); % note phase norm(u-v) % matrix case... u = srcsum(@LapDLP,[0 2], [1 3], s,s); % do it (include phase) ss = s; v = LapDLP(s,ss); % check matches direct sum ss.x = s.x+2; v = v + 3*LapDLP(s,ss); % note phase norm(u-v) % 2-cmpt output matrix case... mu = 0.6; u = srcsum(@StoDLP,[0 2], [1 3], s,s,mu); % do it (include phase) ss = s; v = StoDLP(s,ss,mu); % check matches direct sum ss.x = s.x+2; v = v + 3*StoDLP(s,ss,mu); % note phase norm(u-v) % 2-cmpt multi-output matrix case... [u p] = srcsum(@StoDLP,[0 2], [1 3], s,s,mu); % do it (include phase) ss = s; [v q] = StoDLP(s,ss,mu); % check matches direct sum ss.x = s.x+2; [v2 q2] = StoDLP(s,ss,mu); v = v + 3*v2; q = q + 3*q2; norm(u-v)
github
bobbielf2/BIE2D-master
StoDLP.m
.m
BIE2D-master/kernels/StoDLP.m
4,661
utf_8
d031357a91adbb7c5de42d4cad0c7c0e
function [u,p,T] = StoDLP(t,s,mu,dens) % STODLP Evaluate 2D Stokes single-layer velocity, pressure, and traction. % % [A,P,T] = StoDLP(t,s,mu) returns dense matrices taking double-layer % density values on the nodes of a source curve to velocity, pressure, and % traction on the nodes of a target curve. Native quadrature is used, apart % from when target=source when A is the self-interaction Nystrom matrix using % the smooth diagonal-limit formula for DLP. % % [u,p,T] = StoDLP(t,s,mu,dens) evaluates the double-layer density dens, % returning flow velocity u, pressure p, and target-normal traction T. % % The normalization is as in Sec 2.3 of [HW], and [Mar15]. % % References: % [HW] "Boundary Integral Equations", G. C. Hsiao and W. L. Wendland % (Springer, 2008). % % [Mar15] "A fast algorithm for simulating multiphase flows through periodic % geometries of arbitrary shape," G. Marple, A. H. Barnett, % A. Gillman, and S. Veerapaneni, in press, SIAM J. Sci. Comput. % https://arXiv.org/abs/1510.05616 % % Inputs: (see setupquad for source & target struct definitions) % s = source segment struct with s.x nodes, s.w weights on [0,2pi), % s.sp speed function |Z'| at the nodes, and s.tang tangent angles. % t = target segment struct with t.x nodes, and t.nx normals if traction needed % mu = viscosity % % Outputs: (matrix case) % A = 2M-by-2N matrix taking density (force vector) to velocity on the % target curve. As always for Stokes, ordering is nodes fast, % components (1,2) slow, so that A has 4 large blocks A_11, A_12, etc. % P = M-by-2N matrix taking density to pressure (scalar) on target nodes. % T = 2M-by-2N matrix taking density to normal traction on target nodes. % % Notes: 1) no self-evaluation for P or T. % % To test use STOINTDIRBVP % % See also: SETUPQUAD % Barnett 6/13/16, 6/27/16 if numel(mu)~=1, error('mu must be a scalar'); end if nargout==1 u = StoDLPmat(t,s,mu); if nargin>3 && ~isempty(dens) u = u * dens; end elseif nargout==2 [u p] = StoDLPmat(t,s,mu); if nargin>3 && ~isempty(dens) u = u * dens; p = p * dens; end else [u p T] = StoDLPmat(t,s,mu); if nargin>3 && ~isempty(dens) u = u * dens; p = p * dens; T = T * dens; end end %%%%%% function [A,P,T] = StoDLPmat(t,s,mu) % Returns native quadrature matrices, or self-evaluation matrices. % some repmat->bsxfun 6/28/16 N = numel(s.x); M = numel(t.x); r = bsxfun(@minus,t.x,s.x.'); % C-# displacements mat irr = 1./(conj(r).*r); % 1/r^2, used in all cases below d1 = real(r); d2 = imag(r); %rdotny = d1.*repmat(real(s.nx)', [M 1]) + d2.*repmat(imag(s.nx)', [M 1]); rdotny = bsxfun(@times, d1, real(s.nx)') + bsxfun(@times, d2, imag(s.nx)'); rdotnir4 = rdotny.*(irr.*irr); if nargout==1, clear rdotny; end A12 = (1/pi)*d1.*d2.*rdotnir4; % off diag vel block A = [(1/pi)*d1.^2.*rdotnir4, A12; % Ladyzhenskaya A12, (1/pi)*d2.^2.*rdotnir4]; if sameseg(t,s) % self-int DLP velocity diagonal correction c = -s.cur/2/pi; % diagonal limit of Laplace DLP tx = 1i*s.nx; t1=real(tx); t2=imag(tx); % tangent vectors on the curve A(sub2ind(size(A),1:N,1:N)) = c.*t1.^2; % overwrite diags of 4 blocks A(sub2ind(size(A),1+N:2*N,1:N)) = c.*t1.*t2; A(sub2ind(size(A),1:N,1+N:2*N)) = c.*t1.*t2; A(sub2ind(size(A),1+N:2*N,1+N:2*N)) = c.*t2.^2; end A = bsxfun(@times, A, [s.w(:)' s.w(:)']); % quadr wei if nargout>1 % pressure of DLP (no self-int) % P = [(mu/pi)*(-repmat(real(s.nx)', [M 1]).*irr + 2*rdotnir4.*d1), ... % (mu/pi)*(-repmat(imag(s.nx)', [M 1]).*irr + 2*rdotnir4.*d2) ]; P = [bsxfun(@times, real(-s.nx)',irr) + 2*rdotnir4.*d1, ... bsxfun(@times, imag(-s.nx)',irr) + 2*rdotnir4.*d2 ]; P = bsxfun(@times, P, (mu/pi)*[s.w(:)' s.w(:)']); % quadr wei end if nargout>2 % traction, my derivation of formula (no self-int) nx1 = repmat(real(t.nx), [1 N]); nx2 = repmat(imag(t.nx), [1 N]); rdotnx = d1.*nx1 + d2.*nx2; ny1 = repmat(real(s.nx)', [M 1]); ny2 = repmat(imag(s.nx)', [M 1]); dx = rdotnx.*irr; dy = rdotny.*irr; dxdy = dx.*dy; R12 = d1.*d2.*irr; R = [d1.^2.*irr, R12; R12, d2.^2.*irr]; nydotnx = nx1.*ny1 + nx2.*ny2; T = R.*kron(ones(2), nydotnx.*irr - 8*dxdy) + kron(eye(2), dxdy); T = T + [nx1.*ny1.*irr, nx1.*ny2.*irr; nx2.*ny1.*irr, nx2.*ny2.*irr] + ... kron(ones(2),dx.*irr) .* [ny1.*d1, ny1.*d2; ny2.*d1, ny2.*d2] + ... kron(ones(2),dy.*irr) .* [d1.*nx1, d1.*nx2; d2.*nx1, d2.*nx2]; T = bsxfun(@times, T, (mu/pi)*[s.w(:)' s.w(:)']); % prefac & quadr wei end
github
bobbielf2/BIE2D-master
perivelpipe_gmres.m
.m
BIE2D-master/singlyperiodic/perivelpipe_gmres.m
13,644
utf_8
a0298df440e4fe5136d64642b3649cc2
function perivelpipe_gmres % Longitudinal periodize 2D velocity-BC Stokes "pipe" geom w/ press drop (pgro) % using circle of SLP proxy sources. Barnett, for Veerapaneni & Gillman 3/11/14 % Playing w/ GMRES and Schur options 3/17/15 clear; v=1; expt='t'; % verbosity=0,1,2. expt='t' test, 'd' driven no-slip demo makefigs = 0; % whether to write to EPS files for writeup uc.d = 2*pi; % unitcell, d=period in space N = 80; % pts per top and bottom wall (enough for 1e-15 in this case) U.Z = @(t) t + 1i*(1.5+sin(t)); U.Zp = @(t) 1 + 1i*cos(t); U.Zpp = @(t) -1i*sin(t); U = quadr(U,N); % t=0 is left end, t=2pi right end D.Z = @(t) t + 1i*(-1.5+cos(2*t)); D.Zp = @(t) 1 - 2i*sin(2*t); D.Zpp = @(t) - 4i*cos(2*t); D = quadr(D,N); % same direction (left to right) U.nx = -U.nx; U.cur = -U.cur; % correct for sense of U, opp from periodicdirpipe % normals on pipe walls point outwards inside = @(z) imag(z-D.Z(real(z)))>0 & imag(z-U.Z(real(z)))<0; % ok U,D graphs mu = 0.7; % viscosity if expt=='t' % Exact soln: either periodic or plus fixed pressure drop / period: %ue = @(x) [1+0*x; -2+0*x]; pe = @(x) 0*x; % the exact soln: uniform rigid flow, constant pressure everywhere (no drop) h=.2; ue = @(x) h*[imag(x).^2;0*x]; pe = @(x) h*2*mu*real(x); % horiz Poisseuil flow (pres drop) rhs = [ue(U.x); ue(D.x)]; % Driving: U,D bdry vels, each stacked as [u_1;u_2] pgro = pe(uc.d)-pe(0); % known pressure growth across one period (a number) elseif expt=='d' rhs = zeros(4*N,1); % no-slip BCs, ie homog vel data on U,D pgro = -1; % given pressure driving, for flow +x (a number) end uc.nei = 1; % how many nei copies either side (use eg 1e3 to test A w/o AP) n = 30; % pts per side [x w] = gauss(n); x = (1+x)/2; w = w'/2; % quadr on [0,1] H = U.Z(0)-D.Z(0); L.x = D.Z(0) + H*x; L.nx = 0*L.x+1; L.w = H*w; % left side R = L; R.x = L.x+uc.d; % right side M = 50; % # proxy pts in periodizing basis (2 force comps per pt, so 2M dofs) b.x = pi + 1.1*2*pi*exp(2i*pi*(1:M)'/M); % the proxy pts %b.nx = exp(2i*pi*(1:M)'/M); % only needed if DLP proxy basis b.w = 1+0*b.x; % unit quadr weights (dummy) nx = 60; gx = 2*pi*((1:nx)-0.5)/nx; ny = nx; gy = gx - pi; % plotting grid [xx yy] = meshgrid(gx,gy); t.x = xx(:)+1i*yy(:); Mt = numel(t.x); di = reshape(inside(t.x),size(xx)); % boolean if inside domain if expt=='t', ueg = ue(t.x); % evaluate exact soln on grid ue1 = reshape(ueg(1:Mt),size(xx)); ue2 = reshape(ueg(Mt+(1:Mt)),size(xx)); peg = reshape(pe(t.x),size(xx)); if v, figure; imagesc(gx,gy, peg); colormap(jet(256)); colorbar; hold on; quiver(gx,gy, ue1,ue2, 10); end else, figure; end if v, showseg(U,uc); hold on; showseg(D,uc); showseg(L); showseg(R); vline([0 uc.d]); axis xy equal tight; text(-.5,0,'L');text(2*pi+.5,0,'R');text(4,-1,'D');text(pi,0.5,'U'); plot(b.x, 'r.'); title('geom'); if expt=='t',title('geom and (u,p) known soln'); end if makefigs, axis([-4 10 -7 7]); print -depsc2 geom.eps, end end % fill system matrices A B C Q (subblock ordering always U then D), same A = -eye(4*N)/2; % A's jump relation part. A maps density to vel vec, on U,D for i=-uc.nei:uc.nei, a = i*uc.d; A = A + [DLPmatrix(U,U,mu,a) DLPmatrix(U,D,mu,a); DLPmatrix(D,U,mu,a) DLPmatrix(D,D,mu,a)]; end %figure; imagesc(A); colorbar; title('A'); % single layer (monopoles) on proxy points: B = [SLPmatrix(U,b,mu); SLPmatrix(D,b,mu)]; % maps 2M peri dofs to vels on U,D a=uc.nei*uc.d; [RU RUn] = DLPmatrix(R,U,mu,-a); [LU LUn] = DLPmatrix(L,U,mu,a); [RD RDn] = DLPmatrix(R,D,mu,-a); [LD LDn] = DLPmatrix(L,D,mu,a); C = [RU-LU, RD-LD; RUn-LUn, RDn-LDn]; % maps cancelled densities to discrepancy [Rb Rbn] = SLPmatrix(R,b,mu); [Lb Lbn] = SLPmatrix(L,b,mu); Q = [Rb-Lb; Rbn-Lbn]; % maps periodizing dofs to discrepancy % Schur... QdagC = Q\C; % backwards stable least-sq solve fprintf('norm QdagC = %.3g\n',norm(QdagC)) % should be O(1) AP = A - B*QdagC; % system mat maps periodized density on U,D to vels on U,D if v>1, figure; imagesc(AP); colorbar; title('A_P'); end %figure; plot(eig(AP),'+'); axis equal; Tgro = -pgro * [real(R.nx);imag(R.nx)]; % traction driving growth (vector func) Qdagg = Q\[zeros(2*n,1); Tgro]; % no vel growth; here []=g is rhs for peri rows rhsgro = -B*Qdagg; % change in rhs due to peri (along-pipe) driving rhs = rhs + rhsgro; if 1 % GMRES %matvec = @(x) AP*x; % is fine % matvec = @(x) A*x - B*(Q\(C*x)); % fast form, indeed stagnates, why? matvec = @(x) A*x - B*(QdagC*x); % fast form, Gary's choice, works % matvec = @(x) A*x - (B*QdagC)*x; % same, dense form, works of course %[UQ S V] = svd(Q,0); QbC = V*(diag(min(1e14,1./diag(S)))*(UQ'*C)); % alt %matvec = @(x) A*x - B*(QbC*x); % resid %x = randn(4*N,1); norm(matvec(x) - AP*x) % QdagC and QbC not the same! why % matvec = @(x) A*x - B*(V*Sdag*UU')*(C*x))); %matvec = @(x) A*x - B*(V*(Sdag*UU'*(C*x))); % matvec = @(x) A*x - B*((V*Sdag)*(UU'*(C*x))); tau = gmres(matvec,rhs,size(AP,1),1e-14,size(AP,1)); %[tau,iters] = gmres_helsing(@(x) matvec(x)-x,rhs,size(AP,1),size(AP,1),1e-12); iters % doesn't help fprintf('resid norm = %.3g\n',norm(AP*tau - rhs)) %fprintf('matvec resid norm = %.3g\n',norm(matvec(tau) - rhs)) else % dense solve, note nullity(AP)=1 corresp to unknown pres const, but consistent: tau = AP\rhs; % tau is DLP "vector density" (ie bdry force dipole) end c = -QdagC*tau + Qdagg; % get periodizing dofs (incl peri driving part) if v, figure; plot([tau;c],'+-'); legend('[\tau;c]'); title('soln density and periodizing dofs'); end if expt=='t', z = []; z.x = 2+1i; % pointwise test u soln (target object z) u = SLPmatrix(z,b,mu) * c; % eval @ test pt: first do MFS (proxy) contrib for i=-uc.nei:uc.nei, a = i*uc.d; % add in 3 copies of LPs on U,D... u = u + [DLPmatrix(z,U,mu,a) DLPmatrix(z,D,mu,a)] * tau; end fprintf('u error at pt = %.3g, ||tau||=%.3g\n', norm(u-ue(z.x)),norm(tau)) end ug = SLPmatrix(t,b,mu) * c; % eval on grid: MFS (proxy) contrib pg = SLPpresmatrix(t,b,mu) * c; % (vel and pres parts separate matrices) for i=-uc.nei:uc.nei, a = i*uc.d; % add in 3 copies of LPs on U,D... ug = ug + [DLPmatrix(t,U,mu,a) DLPmatrix(t,D,mu,a)] * tau; % uses RAM pg = pg + [DLPpresmatrix(t,U,mu,a) DLPpresmatrix(t,D,mu,a)] * tau; end u1 = reshape(ug(1:Mt),size(xx)); u2 = reshape(ug(Mt+(1:Mt)),size(xx)); p = reshape(pg,size(xx)); if expt=='t' % show errors vs known soln... i=ceil(ny/2); j=ceil(nx/4); % index interior pt to get pres const p = p - p(i,j) + peg(i,j); % shift const in pres to match known eg2 = sum([u1(:)-ue1(:),u2(:)-ue2(:)].^2,2); % squared ptwise vector L2 errs if v, figure; subplot(1,2,1); imagesc(gx,gy,log10(reshape(eg2,size(xx)))/2); axis xy equal tight; caxis([-16 0]); colorbar; hold on; plot(U.x,'k.-'); plot(D.x,'k.-'); title('peri vel Stokes BVP: log_{10} u err') subplot(1,2,2); imagesc(gx,gy,log10(abs(p-reshape(peg,size(xx))))); axis xy equal tight; caxis([-16 0]); colorbar; hold on; plot(U.x,'k.-'); plot(D.x,'k.-'); title('log_{10} p err (up to const)'); end else % just show (velocity,pressure) soln... if v, figure; p0 = p(35,1); % pressure const contourf(gx,gy,p.*di, p0+pgro*(0:0.05:1)); hold on; u0 = 0.1; u1c = min(max(u1,-u0),u0); u2c = min(max(u2,-u0),u0); % clip vel colorbar; axis xy equal; quiver(gx,gy, u1c.*di,u2c.*di, 3); plot(U.x,'k.-'); plot(D.x,'k.-'); axis([0 uc.d -pi pi]); title('peri no-slip p-driven Stokes BVP: (u,p)'), end end %keyboard % don't forget to use dbquit to finish otherwise trapped in debug mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = quadr(s, N) % set up periodic trapezoid quadrature on a segment % Note sign change in normal vs periodicdirpipe.m. % Barnett 4/21/13 from testlapSDevalclose.m t = (1:N)'/N*2*pi; s.x = s.Z(t); s.sp = abs(s.Zp(t)); s.nx = -1i*s.Zp(t)./s.sp; s.cur = -real(conj(s.Zpp(t)).*s.nx)./s.sp.^2; s.w = 2*pi/N*s.sp; % speed weights s.t = t; s.cw = 1i*s.nx.*s.w; % complex weights (incl complex speed) function h = showseg(s, uc) % plot a segment & possibly its nei copies if nargin<2, uc.nei = 0; uc.d = 0; end % dummy uc if uc.nei>0, uc.nei = 1; end % don't plot a ridiculous # of copies for i=-uc.nei:uc.nei plot(s.x+uc.d*i, 'b.-'); axis equal xy; l=0.3; hold on; plot([s.x+uc.d*i, s.x+l*s.nx+uc.d*i].', 'k-'); end % Following kernel matrix fillers are taken from (debugged in) testkernels.m: function [A T] = SLPmatrix(t,s,mu,a) % single-layer 2D Stokes kernel vel matrix % Returns 2N-by-2N matrix from src force vector to 2 flow component % t = target seg (x cols), s = src seg, a = optional translation of src seg % No option for self-int, gives Inf on diag. 3/2/14 % 2nd output is traction matrix, needs t.nx normal (C-#); no self-int either. if nargin<4, a = 0; end N = numel(s.x); M = numel(t.x); r = repmat(t.x, [1 N]) - repmat(s.x.' + a, [M 1]); % C-# displacements mat irr = 1./(conj(r).*r); % 1/r^2 d1 = real(r); d2 = imag(r); Ilogr = -log(abs(r)); % log(1/r) diag block c = 1/(4*pi*mu); % factor from Hsiao-Wendland book, Ladyzhenskaya A12 = c*d1.*d2.*irr; % off diag vel block A = [c*(Ilogr + d1.^2.*irr), A12; % u_x A12, c*(Ilogr + d2.^2.*irr)]; % u_y A = A .* repmat([s.w(:)' s.w(:)'], [2*M 1]); % quadr wei if nargout>1 % traction (negative of DLP vel matrix w/ nx,ny swapped) rdotn = d1.*repmat(real(t.nx), [1 N]) + d2.*repmat(imag(t.nx), [1 N]); rdotnir4 = rdotn.*(irr.*irr); clear rdotn A12 = -(1/pi)*d1.*d2.*rdotnir4; T = [-(1/pi)*d1.^2.*rdotnir4, A12; % own derivation A12, -(1/pi)*d2.^2.*rdotnir4]; T = T .* repmat([s.w(:)' s.w(:)'], [2*M 1]); % quadr wei end function A = SLPpresmatrix(t,s,mu,a) % single-layer 2D Stokes kernel press mat % Returns N-by-2N matrix from src force vector to pressure value, no self-int. % t = target seg (x cols), s = src seg, a = optional transl of src seg. 2/1/14 if nargin<4, a = 0; end N = numel(s.x); M = numel(t.x); r = repmat(t.x, [1 N]) - repmat(s.x.' + a, [M 1]); % C-# displacements mat irr = 1./(conj(r).*r); % 1/r^2 d1 = real(r); d2 = imag(r); A = [d1.*irr/(2*pi), d2.*irr/(2*pi)]; % pressure A = A .* repmat([s.w(:)' s.w(:)'], [M 1]); % quadr wei function [A T] = DLPmatrix(t,s,mu,a) % double-layer 2D Stokes vel kernel matrix % Returns 2N-by-2N matrix from src force vector to 2 flow components % If detects self-int, does correct diagonal limit, no jump condition (PV int). % t = target seg (x cols), s = src seg, a = optional transl of src seg. % 2nd output is optional traction matrix, without self-eval. 2/1/14, 3/2/14 if nargin<4, a = 0; end N = numel(s.x); M = numel(t.x); r = repmat(t.x, [1 N]) - repmat(s.x.' + a, [M 1]); % C-# displacements mat irr = 1./(conj(r).*r); % 1/R^2 d1 = real(r); d2 = imag(r); rdotny = d1.*repmat(real(s.nx)', [M 1]) + d2.*repmat(imag(s.nx)', [M 1]); rdotnir4 = rdotny.*(irr.*irr); if nargout<=1, clear rdotny; end A12 = (1/pi)*d1.*d2.*rdotnir4; % off diag vel block A = [(1/pi)*d1.^2.*rdotnir4, A12; % Ladyzhenzkaya A12, (1/pi)*d2.^2.*rdotnir4]; if numel(s.x)==numel(t.x) & max(abs(s.x+a-t.x))<1e-14 c = -s.cur/2/pi; % diagonal limit of Laplace DLP tx = 1i*s.nx; t1=real(tx); t2=imag(tx); % tangent vectors on src curve A(sub2ind(size(A),1:N,1:N)) = c.*t1.^2; % overwrite diags of 4 blocks: A(sub2ind(size(A),1+N:2*N,1:N)) = c.*t1.*t2; A(sub2ind(size(A),1:N,1+N:2*N)) = c.*t1.*t2; A(sub2ind(size(A),1+N:2*N,1+N:2*N)) = c.*t2.^2; end A = A .* repmat([s.w(:)' s.w(:)'], [2*M 1]); % quadr wei if nargout>1 % traction, my formula nx1 = repmat(real(t.nx), [1 N]); nx2 = repmat(imag(t.nx), [1 N]); rdotnx = d1.*nx1 + d2.*nx2; ny1 = repmat(real(s.nx)', [M 1]); ny2 = repmat(imag(s.nx)', [M 1]); dx = rdotnx.*irr; dy = rdotny.*irr; dxdy = dx.*dy; R12 = d1.*d2.*irr; R = [d1.^2.*irr, R12; R12, d2.^2.*irr]; nydotnx = nx1.*ny1 + nx2.*ny2; T = R.*kron(ones(2), nydotnx.*irr - 8*dxdy) + kron(eye(2), dxdy); T = T + [nx1.*ny1.*irr, nx1.*ny2.*irr; nx2.*ny1.*irr, nx2.*ny2.*irr] + ... kron(ones(2),dx.*irr) .* [ny1.*d1, ny1.*d2; ny2.*d1, ny2.*d2] + ... kron(ones(2),dy.*irr) .* [d1.*nx1, d1.*nx2; d2.*nx1, d2.*nx2]; T = (mu/pi) * T; % prefac T = T .* repmat([s.w(:)' s.w(:)'], [2*M 1]); % quadr wei end function A = DLPpresmatrix(t,s,mu,a) % double-layer 2D Stokes kernel press mat % Returns N-by-2N matrix from src force vector to pressure values, no self-int % t = target seg (x cols), s = src seg, a = optional transl of src seg. 2/1/14 if nargin<4, a = 0; end N = numel(s.x); M = numel(t.x); r = repmat(t.x, [1 N]) - repmat(s.x.' + a, [M 1]); % C-# displacements mat irr = 1./(conj(r).*r); % 1/R^2 d1 = real(r); d2 = imag(r); rdotn = d1.*repmat(real(s.nx)', [M 1]) + d2.*repmat(imag(s.nx)', [M 1]); rdotnir4 = rdotn.*(irr.*irr); clear rdotn A = [(mu/pi)*(-repmat(real(s.nx)', [M 1]).*irr + 2*rdotnir4.*d1), ... (mu/pi)*(-repmat(imag(s.nx)', [M 1]).*irr + 2*rdotnir4.*d2) ]; A = A .* repmat([s.w(:)' s.w(:)'], [M 1]); % quadr wei function i = diagind(A,s) %return indices of (shifted) diagonal of square matrix if nargin<2, s=0; end % if present, s shifts diagonal cyclicly N = size(A,1); i = sub2ind(size(A), 1:N, mod(s+(0:N-1),N)+1);
github
bobbielf2/BIE2D-master
perivelpipe.m
.m
BIE2D-master/singlyperiodic/perivelpipe.m
12,601
utf_8
685092c15e0d7d2584349abcd2fafbfd
function perivelpipe % Longitudinal periodize 2D velocity-BC Stokes "pipe" geom w/ press drop (pgro) % using circle of SLP proxy sources. Barnett, for Veerapaneni & Gillman 3/11/14 clear; v=2; expt='t'; % verbosity=0,1,2. expt='t' test, 'd' driven no-slip demo makefigs = 0; % whether to write to EPS files for writeup uc.d = 2*pi; % unitcell, d=period in space N = 100; %80; % pts per top and bottom wall (enough for 1e-15 in this case) U.Z = @(t) t + 1i*(1.5+sin(t)); U.Zp = @(t) 1 + 1i*cos(t); U.Zpp = @(t) -1i*sin(t); U = quadr(U,N); % t=0 is left end, t=2pi right end D.Z = @(t) t + 1i*(-1.5+cos(2*t)); D.Zp = @(t) 1 - 2i*sin(2*t); D.Zpp = @(t) - 4i*cos(2*t); D = quadr(D,N); % same direction (left to right) U.nx = -U.nx; U.cur = -U.cur; % correct for sense of U, opp from periodicdirpipe % normals on pipe walls point outwards inside = @(z) imag(z-D.Z(real(z)))>0 & imag(z-U.Z(real(z)))<0; % ok U,D graphs mu = 0.7; % viscosity if expt=='t' % Exact soln: either periodic or plus fixed pressure drop / period: %ue = @(x) [1+0*x; -2+0*x]; pe = @(x) 0*x; % the exact soln: uniform rigid flow, constant pressure everywhere (no drop) h=.2; ue = @(x) h*[imag(x).^2;0*x]; pe = @(x) h*2*mu*real(x); % horiz Poisseuil flow (pres drop) rhs = [ue(U.x); ue(D.x)]; % Driving: U,D bdry vels, each stacked as [u_1;u_2] pgro = pe(uc.d)-pe(0); % known pressure growth across one period (a number) elseif expt=='d' rhs = zeros(4*N,1); % no-slip BCs, ie homog vel data on U,D pgro = -1; % given pressure driving, for flow +x (a number) end uc.nei = 1; % how many nei copies either side (use eg 1e3 to test A w/o AP) n = 30; % pts per side [x w] = gauss(n); x = (1+x)/2; w = w'/2; % quadr on [0,1] H = U.Z(0)-D.Z(0); L.x = D.Z(0) + H*x; L.nx = 0*L.x+1; L.w = H*w; % left side R = L; R.x = L.x+uc.d; % right side M = 50; % # proxy pts in periodizing basis (2 force comps per pt, so 2M dofs) b.x = pi + 1.1*2*pi*exp(2i*pi*(1:M)'/M); % the proxy pts %b.nx = exp(2i*pi*(1:M)'/M); % only needed if DLP proxy basis b.w = 1+0*b.x; % unit quadr weights (dummy) nx = 60; gx = 2*pi*((1:nx)-0.5)/nx; ny = nx; gy = gx - pi; % plotting grid [xx yy] = meshgrid(gx,gy); t.x = xx(:)+1i*yy(:); Mt = numel(t.x); di = reshape(inside(t.x),size(xx)); % boolean if inside domain if expt=='t', ueg = ue(t.x); % evaluate exact soln on grid ue1 = reshape(ueg(1:Mt),size(xx)); ue2 = reshape(ueg(Mt+(1:Mt)),size(xx)); peg = reshape(pe(t.x),size(xx)); if v, figure; imagesc(gx,gy, peg); colormap(jet(256)); colorbar; hold on; quiver(gx,gy, ue1,ue2, 10); end else, figure; end if v, showseg(U,uc); hold on; showseg(D,uc); showseg(L); showseg(R); vline([0 uc.d]); axis xy equal tight; text(-.5,0,'L');text(2*pi+.5,0,'R');text(4,-1,'D');text(pi,0.5,'U'); plot(b.x, 'r.'); title('geom'); if expt=='t',title('geom and (u,p) known soln'); end if makefigs, axis([-4 10 -7 7]); print -depsc2 geom.eps, end end % fill system matrices A B C Q (subblock ordering always U then D), same A = -eye(4*N)/2; % A's jump relation part. A maps density to vel vec, on U,D for i=-uc.nei:uc.nei, a = i*uc.d; A = A + [DLPmatrix(U,U,mu,a) DLPmatrix(U,D,mu,a); DLPmatrix(D,U,mu,a) DLPmatrix(D,D,mu,a)]; end %figure; imagesc(A); colorbar; title('A'); % single layer (monopoles) on proxy points: B = [SLPmatrix(U,b,mu); SLPmatrix(D,b,mu)]; % maps 2M peri dofs to vels on U,D a=uc.nei*uc.d; [RU RUn] = DLPmatrix(R,U,mu,-a); [LU LUn] = DLPmatrix(L,U,mu,a); [RD RDn] = DLPmatrix(R,D,mu,-a); [LD LDn] = DLPmatrix(L,D,mu,a); C = [RU-LU, RD-LD; RUn-LUn, RDn-LDn]; % maps cancelled densities to discrepancy [Rb Rbn] = SLPmatrix(R,b,mu); [Lb Lbn] = SLPmatrix(L,b,mu); Q = [Rb-Lb; Rbn-Lbn]; % maps periodizing dofs to discrepancy QdagC = Q\C; % backwards stable least-sq solve AP = A - B*QdagC; % system mat maps periodized density on U,D to vels on U,D if v>1, figure; imagesc(AP); colorbar; title('A_P'); end Tgro = -pgro * [real(R.nx);imag(R.nx)]; % traction driving growth (vector func) Qdagg = Q\[zeros(2*n,1); Tgro]; % no vel growth; here []=g is rhs for peri rows rhsgro = -B*Qdagg; % change in rhs due to peri (along-pipe) driving rhs = rhs + rhsgro; % dense solve, note nullity(AP)=1 corresp to unknown pres const, but consistent: tau = AP\rhs; % tau is DLP "vector density" (ie bdry force dipole) c = -QdagC*tau + Qdagg; % get periodizing dofs (incl peri driving part) if v, figure; plot([tau;c],'+-'); legend('[\tau;c]'); title('soln density and periodizing dofs'); end if expt=='t', z = []; z.x = 2+1i; % pointwise test u soln (target object z) u = SLPmatrix(z,b,mu) * c; % eval @ test pt: first do MFS (proxy) contrib for i=-uc.nei:uc.nei, a = i*uc.d; % add in 3 copies of LPs on U,D... u = u + [DLPmatrix(z,U,mu,a) DLPmatrix(z,D,mu,a)] * tau; end fprintf('u error at pt = %.3g, ||tau||=%.3g\n', norm(u-ue(z.x)),norm(tau)) end ug = SLPmatrix(t,b,mu) * c; % eval on grid: MFS (proxy) contrib pg = SLPpresmatrix(t,b,mu) * c; % (vel and pres parts separate matrices) for i=-uc.nei:uc.nei, a = i*uc.d; % add in 3 copies of LPs on U,D... ug = ug + [DLPmatrix(t,U,mu,a) DLPmatrix(t,D,mu,a)] * tau; % uses RAM pg = pg + [DLPpresmatrix(t,U,mu,a) DLPpresmatrix(t,D,mu,a)] * tau; end u1 = reshape(ug(1:Mt),size(xx)); u2 = reshape(ug(Mt+(1:Mt)),size(xx)); p = reshape(pg,size(xx)); if expt=='t' % show errors vs known soln... i=ceil(ny/2); j=ceil(nx/4); % index interior pt to get pres const p = p - p(i,j) + peg(i,j); % shift const in pres to match known eg2 = sum([u1(:)-ue1(:),u2(:)-ue2(:)].^2,2); % squared ptwise vector L2 errs if v, figure; subplot(1,2,1); imagesc(gx,gy,log10(reshape(eg2,size(xx)))/2); axis xy equal tight; caxis([-16 0]); colorbar; hold on; plot(U.x,'k.-'); plot(D.x,'k.-'); title('peri vel Stokes BVP: log_{10} u err') subplot(1,2,2); imagesc(gx,gy,log10(abs(p-reshape(peg,size(xx))))); axis xy equal tight; caxis([-16 0]); colorbar; hold on; plot(U.x,'k.-'); plot(D.x,'k.-'); title('log_{10} p err (up to const)'); end else % just show (velocity,pressure) soln... if v, figure; p0 = p(35,1); % pressure const contourf(gx,gy,p.*di, p0+pgro*(0:0.05:1)); hold on; u0 = 0.1; u1c = min(max(u1,-u0),u0); u2c = min(max(u2,-u0),u0); % clip vel colorbar; axis xy equal; quiver(gx,gy, u1c.*di,u2c.*di, 3); plot(U.x,'k.-'); plot(D.x,'k.-'); axis([0 uc.d -pi pi]); title('peri no-slip p-driven Stokes BVP: (u,p)'), end end %keyboard % don't forget to use dbquit to finish otherwise trapped in debug mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = quadr(s, N) % set up periodic trapezoid quadrature on a segment % Note sign change in normal vs periodicdirpipe.m. % Barnett 4/21/13 from testlapSDevalclose.m t = (1:N)'/N*2*pi; s.x = s.Z(t); s.sp = abs(s.Zp(t)); s.nx = -1i*s.Zp(t)./s.sp; s.cur = -real(conj(s.Zpp(t)).*s.nx)./s.sp.^2; s.w = 2*pi/N*s.sp; % speed weights s.t = t; s.cw = 1i*s.nx.*s.w; % complex weights (incl complex speed) function h = showseg(s, uc) % plot a segment & possibly its nei copies if nargin<2, uc.nei = 0; uc.d = 0; end % dummy uc if uc.nei>0, uc.nei = 1; end % don't plot a ridiculous # of copies for i=-uc.nei:uc.nei plot(s.x+uc.d*i, 'b.-'); axis equal xy; l=0.3; hold on; plot([s.x+uc.d*i, s.x+l*s.nx+uc.d*i].', 'k-'); end % Following kernel matrix fillers are taken from (debugged in) testkernels.m: function [A T] = SLPmatrix(t,s,mu,a) % single-layer 2D Stokes kernel vel matrix % Returns 2N-by-2N matrix from src force vector to 2 flow component % t = target seg (x cols), s = src seg, a = optional translation of src seg % No option for self-int, gives Inf on diag. 3/2/14 % 2nd output is traction matrix, needs t.nx normal (C-#); no self-int either. if nargin<4, a = 0; end N = numel(s.x); M = numel(t.x); r = repmat(t.x, [1 N]) - repmat(s.x.' + a, [M 1]); % C-# displacements mat irr = 1./(conj(r).*r); % 1/r^2 d1 = real(r); d2 = imag(r); Ilogr = -log(abs(r)); % log(1/r) diag block c = 1/(4*pi*mu); % factor from Hsiao-Wendland book, Ladyzhenskaya A12 = c*d1.*d2.*irr; % off diag vel block A = [c*(Ilogr + d1.^2.*irr), A12; % u_x A12, c*(Ilogr + d2.^2.*irr)]; % u_y A = A .* repmat([s.w(:)' s.w(:)'], [2*M 1]); % quadr wei if nargout>1 % traction (negative of DLP vel matrix w/ nx,ny swapped) rdotn = d1.*repmat(real(t.nx), [1 N]) + d2.*repmat(imag(t.nx), [1 N]); rdotnir4 = rdotn.*(irr.*irr); clear rdotn A12 = -(1/pi)*d1.*d2.*rdotnir4; T = [-(1/pi)*d1.^2.*rdotnir4, A12; % own derivation A12, -(1/pi)*d2.^2.*rdotnir4]; T = T .* repmat([s.w(:)' s.w(:)'], [2*M 1]); % quadr wei end function A = SLPpresmatrix(t,s,mu,a) % single-layer 2D Stokes kernel press mat % Returns N-by-2N matrix from src force vector to pressure value, no self-int. % t = target seg (x cols), s = src seg, a = optional transl of src seg. 2/1/14 if nargin<4, a = 0; end N = numel(s.x); M = numel(t.x); r = repmat(t.x, [1 N]) - repmat(s.x.' + a, [M 1]); % C-# displacements mat irr = 1./(conj(r).*r); % 1/r^2 d1 = real(r); d2 = imag(r); A = [d1.*irr/(2*pi), d2.*irr/(2*pi)]; % pressure A = A .* repmat([s.w(:)' s.w(:)'], [M 1]); % quadr wei function [A T] = DLPmatrix(t,s,mu,a) % double-layer 2D Stokes vel kernel matrix % Returns 2N-by-2N matrix from src force vector to 2 flow components % If detects self-int, does correct diagonal limit, no jump condition (PV int). % t = target seg (x cols), s = src seg, a = optional transl of src seg. % 2nd output is optional traction matrix, without self-eval. 2/1/14, 3/2/14 if nargin<4, a = 0; end N = numel(s.x); M = numel(t.x); r = repmat(t.x, [1 N]) - repmat(s.x.' + a, [M 1]); % C-# displacements mat irr = 1./(conj(r).*r); % 1/R^2 d1 = real(r); d2 = imag(r); rdotny = d1.*repmat(real(s.nx)', [M 1]) + d2.*repmat(imag(s.nx)', [M 1]); rdotnir4 = rdotny.*(irr.*irr); if nargout<=1, clear rdotny; end A12 = (1/pi)*d1.*d2.*rdotnir4; % off diag vel block A = [(1/pi)*d1.^2.*rdotnir4, A12; % Ladyzhenzkaya A12, (1/pi)*d2.^2.*rdotnir4]; if numel(s.x)==numel(t.x) & max(abs(s.x+a-t.x))<1e-14 c = -s.cur/2/pi; % diagonal limit of Laplace DLP tx = 1i*s.nx; t1=real(tx); t2=imag(tx); % tangent vectors on src curve A(sub2ind(size(A),1:N,1:N)) = c.*t1.^2; % overwrite diags of 4 blocks: A(sub2ind(size(A),1+N:2*N,1:N)) = c.*t1.*t2; A(sub2ind(size(A),1:N,1+N:2*N)) = c.*t1.*t2; A(sub2ind(size(A),1+N:2*N,1+N:2*N)) = c.*t2.^2; end A = A .* repmat([s.w(:)' s.w(:)'], [2*M 1]); % quadr wei if nargout>1 % traction, my formula nx1 = repmat(real(t.nx), [1 N]); nx2 = repmat(imag(t.nx), [1 N]); rdotnx = d1.*nx1 + d2.*nx2; ny1 = repmat(real(s.nx)', [M 1]); ny2 = repmat(imag(s.nx)', [M 1]); dx = rdotnx.*irr; dy = rdotny.*irr; dxdy = dx.*dy; R12 = d1.*d2.*irr; R = [d1.^2.*irr, R12; R12, d2.^2.*irr]; nydotnx = nx1.*ny1 + nx2.*ny2; T = R.*kron(ones(2), nydotnx.*irr - 8*dxdy) + kron(eye(2), dxdy); T = T + [nx1.*ny1.*irr, nx1.*ny2.*irr; nx2.*ny1.*irr, nx2.*ny2.*irr] + ... kron(ones(2),dx.*irr) .* [ny1.*d1, ny1.*d2; ny2.*d1, ny2.*d2] + ... kron(ones(2),dy.*irr) .* [d1.*nx1, d1.*nx2; d2.*nx1, d2.*nx2]; T = (mu/pi) * T; % prefac T = T .* repmat([s.w(:)' s.w(:)'], [2*M 1]); % quadr wei end function A = DLPpresmatrix(t,s,mu,a) % double-layer 2D Stokes kernel press mat % Returns N-by-2N matrix from src force vector to pressure values, no self-int % t = target seg (x cols), s = src seg, a = optional transl of src seg. 2/1/14 if nargin<4, a = 0; end N = numel(s.x); M = numel(t.x); r = repmat(t.x, [1 N]) - repmat(s.x.' + a, [M 1]); % C-# displacements mat irr = 1./(conj(r).*r); % 1/R^2 d1 = real(r); d2 = imag(r); rdotn = d1.*repmat(real(s.nx)', [M 1]) + d2.*repmat(imag(s.nx)', [M 1]); rdotnir4 = rdotn.*(irr.*irr); clear rdotn A = [(mu/pi)*(-repmat(real(s.nx)', [M 1]).*irr + 2*rdotnir4.*d1), ... (mu/pi)*(-repmat(imag(s.nx)', [M 1]).*irr + 2*rdotnir4.*d2) ]; A = A .* repmat([s.w(:)' s.w(:)'], [M 1]); % quadr wei function i = diagind(A,s) %return indices of (shifted) diagonal of square matrix if nargin<2, s=0; end % if present, s shifts diagonal cyclicly N = size(A,1); i = sub2ind(size(A), 1:N, mod(s+(0:N-1),N)+1);
github
bobbielf2/BIE2D-master
testStokernels.m
.m
BIE2D-master/test/testStokernels.m
5,133
utf_8
bcde9edae25a2ce341ecc155327ee854
function testStokernels % TESTSTOKERNELS plot and test properties of Stokes kernels. % % Plot and test 2D Stokes kernels, both velocity and pressure bits, % check satisfies Stokes PDE, traction is correct, and % net outflow and force on wall integrated over enclosing circle, % Barnett 6/27/16 cleaned up from testkernels of 1/29/14-2/11/16. s.x = 1 + 1.5i; % src pt, C-# s.nx = exp(1i*pi/5); % surface normal (for DLP only), C-# s.w = 1; % src pt quadr wei (dummy for now) th = pi/6; force = [cos(th);sin(th)]; % src force vector @ angle th fprintf('src normal (%g,%g), force (%g,%g)\n',... real(s.nx),imag(s.nx),force(1),force(2)) fprintf('src normal dot force = %g\n',force(1)*real(s.nx)+force(2)*imag(s.nx)) mu = 0.3; % viscosity, some random positive value disp('test (u,p) pairs satisfy Stokes and their traction correct, using finite diff approx at one pt (expect around 9 digits)...') t.x = 3+2i; t.nx = exp(1i*pi/3); % target pt and normal for traction eval fprintf('SLP:'); testPDE(@StoSLP,t,s,force,mu) fprintf('DLP:'); testPDE(@StoDLP,t,s,force,mu) if 1 % vector flow and pressure color plot... n = 50; gx = 2*pi*((1:n)-0.5)/n; gy = gx; % target plotting grid [xx yy] = meshgrid(gx,gy); clear t; t.x = xx(:)+1i*yy(:); clear xx yy Mt = numel(t.x); % SLP........ swirling due to pushing a force at src pt, mass is conserved [u p] = StoSLP(t,s,mu,force); u1=reshape(u(1:n*n),[n n]); u2=reshape(u(n*n+1:end),[n n]); p=reshape(p,[n n]); figure; imagesc(gx,gy, p); caxis([-1 1]); hold on; axis xy equal tight; plot(s.x, 'r*'); sc = 50; quiver(gx,gy, u1,u2, sc./norm([u1(:);u2(:)])); title('Stokes SLP') % DLP......... note flow is purely radial, but with angular size variation figure; %for n = exp(1i*2*pi*(1:100)/100), %v = [real(n);imag(n)]; % anim loop [u p] = StoDLP(t,s,mu,force); u1=reshape(u(1:n*n),[n n]); u2=reshape(u(n*n+1:end),[n n]); p=reshape(p,[n n]); imagesc(gx,gy, p); caxis([-1 1]); hold on; axis xy equal tight; plot(s.x, 'r*'); sc = 200; quiver(gx,gy, u1,u2, sc./norm([u1(:);u2(:)])); title('Stokes DLP') %hold off; drawnow; end % end anim end % Integrate over an enclosing circle... N=100; R=0.7; t.x = s.x + R*exp(2i*pi*(1:N)'/N); t.nx = exp(2i*pi*(1:N)'/N); t.w = ones(1,N)*2*pi*R/N; % targ quadr wei [u,~,T] = StoSLP(t,s,mu,force); Mt = numel(t.x); u1 = u(1:Mt); u2 = u(Mt+(1:Mt)); % vel f1 = -T(1:Mt); f2 = -T(Mt+(1:Mt)); % force (-traction dot target nx) outfl = t.w*(u1.*real(t.nx) + u2.*imag(t.nx)); fprintf('SLP: net outflow %g, \t net force (%g,%g)\n',outfl,t.w*f1,t.w*f2) [u,~,T] = StoDLP(t,s,mu,force); Mt = numel(t.x); u1 = u(1:Mt); u2 = u(Mt+(1:Mt)); % vel f1 = -T(1:Mt); f2 = -T(Mt+(1:Mt)); % force (-traction dot target nx) outfl = t.w*(u1.*real(t.nx) + u2.*imag(t.nx)); fprintf('DLP: net outflow %g, \t net force (%g,%g)\n',outfl,t.w*f1,t.w*f2) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end main %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function up = velpres(kernel, xtarg, s, mu, dens) % wrapper to stack vel and pres of a given kernel, at target xtarg. Ie [u1;u2;p] [u p] = kernel(struct('x',xtarg),s,mu,dens); % works for Sto{S,D}LP up = [u;p]; function testPDE(kernel,t,s,v,mu) % uses src s w/ force v and targ t to test SLP or DLP satisfies mu-Stokes PDE, % and traction correct. eps = 1e-4; % finite difference stencil size rhs = applyStokesPDEs(@(x) velpres(kernel,x,s,mu,v),t.x,mu,eps); fprintf('\tforce equation err = %g, incompressibility err = %g\n',... norm(rhs(1:2)),abs(rhs(3))) % finite-diff approx to traction @ x,nx... T = traction(@(x) velpres(kernel,x,s,mu,v),t.x,t.nx,mu,eps); % send in targ [~,~,Te] = kernel(t,s,mu,v); % supposedly exact traction eval fprintf('\ttraction err = %g\n',norm(T - Te)) function rhs = applyStokesPDEs(f,x,mu,eps) % check if func f (returning 3 components: u_1, u_2, and p, given C-# loc x) % obeys mu-Stokes PDE. Outputs the RHS (3 components: f_1, f_2, and rho) up = nan(3,5); % three rows are u1,u2,p at each of 5 stencil pts up(:,1) = f(x); up(:,2) = f(x-eps); up(:,3) = f(x+eps); up(:,4) = f(x-1i*eps); up(:,5) = f(x+1i*eps); % do 5-pt stencil evals gradp = [up(3,3)-up(3,2); up(3,5)-up(3,4)]/(2*eps); stencil = [-4 1 1 1 1]'/eps^2; lapu = up(1:2,:)*stencil; divu = (up(1,3)-up(1,2) + up(2,5)-up(2,4))/(2*eps); rhs(1:2) = -mu*lapu + gradp; % Stokes PDE pair rhs(3) = divu; function T = traction(f,x,nx,mu,eps) % approx traction vec T of Stokes pair (u_vec, p) given by func f (returning 3 % components: u_x, u_y, and p, given C-# loc x). Barnett 3/2/14 if numel(nx)==1, n=[real(nx); imag(nx)]; % get target normal as 2-by-1 elseif numel(nx)==2, n = nx(:); else error('nx must be one C# or 2-component vector'); end up = nan(3,5); % three rows are u1,u2,p at each of 5 stencil pts up(:,1) = f(x); up(:,2) = f(x-eps); up(:,3) = f(x+eps); up(:,4) = f(x-1i*eps); up(:,5) = f(x+1i*eps); % do evals p = up(3,1); % pressure stress = [up(1:2,3)-up(1:2,2), up(1:2,5)-up(1:2,4)]/(2*eps); % 2-by-2 d_j u_i stress = stress + stress'; % d_i u_j + d_j u_i T = -p*n + mu*stress*n; % std formula
github
SenticNet/one-class-svm-master
mog_threshold.m
.m
one-class-svm-master/dd_tools/mog_threshold.m
1,645
utf_8
52fd54f310b2cbf05db73c6e39b92de8
%MOG_THRESHOLD Set threshold of a MoG % % W = MOG_THRESHOLD(W,X,FRACREJ) % % INPUT % W One-class MoG mapping % X One-class dataset % FRACREJ Error on the target class % % OUTPUT % W Updated MoG mapping % % DESCRIPTION % Set the threshold of the Mixture of Gaussians mapping W. The threshold % is set such that a pre-specified fraction FRACREJ of the target data X % is rejected. % % I still have problems to be sure when the obtained decision boundary % is closed around the target class... % % SEE ALSO % mog_init, mog_update, mog_P, mogEMupdate, mogEMextend % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function w = mog_threshold(w,x,fracrej) % setup the basic parameters: dat = w.data; x = +target_class(x); n = size(x,1); % target class distribution: Pt = sum(mog_P(x,dat.covtype,dat.mt,dat.ict,dat.pt),2); f = Pt; % outlier class distribution if isfield(dat,'mo') Po = mog_P(x,dat.covtype,dat.mo,dat.ico,dat.po) + 10*eps; s = warning('off'); f = f./sum(Po,2); warning(s); end % see if we only have to adapt the first threshold: q = dd_threshold(f,fracrej); if isfield(dat,'mo') & (q<1) & (1==0) % then we have a problem, i.e. the decision boundary is not closed % around the target class and we have to adapt beta warning('dd_tools:OpenBoundary','No closed boundary around the target class.'); % % base cluster: Pb = Po(:,1); % % extra specialization outlier clusters Pf = sum(Po(:,2:end),2); % [f Pt Pb Pf] end % store the results again: dat.threshold = q; w.data = dat; return
github
SenticNet/one-class-svm-master
svdd.m
.m
one-class-svm-master/dd_tools/svdd.m
4,393
utf_8
7d15dceb9662d7101722079a0313fd3a
%SVDD Support Vector Data Description % % W = SVDD(A,FRACREJ,SIGMA) % W = A*SVDD([],FRACREJ,SIGMA) % W = A*SVDD(FRACREJ,SIGMA) % % INPUT % A One-class dataset % FRACREJ Error on the target class (default = 0.1) % SIGMA Width parameter in the RBF kernel (default = 5) % % OUTPUT % W Support vector data description % % DESCRIPTION % Optimizes a support vector data description for the dataset A by % quadratic programming. The data description uses the Gaussian kernel % by default. FRACREJ gives the fraction of the target set which will % be rejected, when supplied FRACERR gives (an upper bound) for the % fraction of data which is completely outside the description. % % Note: this version of the SVDD is not compatible with older dd_tools % versions. This is to make the use of consistent_occ.m possible. % % Further note: this classifier is one of the few which can actually % deal with example outlier objects! % % REFERENCE %@article{Tax1999c, % author = {Tax, D.M.J. and Duin, R.P.W}, % title = {Support vector domain description}, % journal = {Pattern Recognition Letters}, % year = {1999},volume = {20}, % number = {11-13},pages = {1191-1199} %} % % SEE ALSO % incsvdd, svdd_optrbf, dd_roc. % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands %function W = svdd(a,fracrej,sigma) function W = svdd(varargin) argin = shiftargin(varargin,'scalar'); argin = setdefaults(argin,[],0.1,5); if mapping_task(argin,'definition') W = define_mapping(argin,'untrained','SVDD'); elseif mapping_task(argin,'training') [a,fracrej,sigma] = deal(argin{:}); if isempty(sigma) error('This versions needs a sigma.'); end % introduce outlier label for outlier class if it is available. if isocset(a) signlab = getoclab(a); if all(signlab<0), error('SVDD needs target objects!'); end else %error('SVDD needs a one-class dataset.'); % Noo, be nice, everything is target: signlab = ones(size(a,1),1); %a = target_class(+a); end % check the rejection rates if (length(fracrej)>2) % if no bound on the outlier error is given, we if length(fracrej)~=length(signlab) error('The length of C is not fitting.'); end C = fracrej; else if (length(fracrej)<2) % if no bound on the outlier error is given, we % do not care fracrej(2) = 1; end if (fracrej(1)>1) warning('dd_tools:AllReject',... 'Fracrej > 1? I cannot reject more than all my target data!'); end % Setup the appropriate C's if (fracrej(1)<0) %DXD: tricky trick.... C(1) = -fracrej(1); C(2) = -fracrej(2); else nrtar = length(find(signlab==1)); nrout = length(find(signlab==-1)); % we could get divide by zero, but that is ok. %warning off MATLAB:divideByZero; C(1) = 1/(nrtar*fracrej(1)); C(2) = 1/(nrout*fracrej(2)); %warning on MATLAB:divideByZero; end end % Find the alpha's % Standard optimization procedure: [alf,R2,Dx,J] = svdd_optrbf(sigma,+a,signlab,C); SVx = +a(J,:); alf = alf(J); % Compute the offset (not important, but now gives the possibility to % interpret the output as the distance to the center of the sphere) offs = 1 + sum(sum((alf*alf').*exp(-sqeucldistm(SVx,SVx)/(sigma*sigma)),2)); % store the results W.s = sigma; W.a = alf; W.threshold = offs+R2; W.sv = SVx; W.offs = offs; W = prmapping(mfilename,'trained',W,char('target','outlier'),size(a,2),2); W = setname(W,'SVDD'); elseif mapping_task(argin,'trained execution') %testing [a,fracrej] = deal(argin{1:2}); W = getdata(fracrej); m = size(a,1); % check if alpha's are OK if isempty(W.a) warning('dd_tools:OptimFailed','The SVDD is empty or not well defined'); out = zeros(m,1); else % and here we go: K = exp(-sqeucldistm(+a,W.sv)/(W.s*W.s)); out = W.offs - 2*sum( repmat(W.a',m,1).* K, 2); end newout = [out repmat(W.threshold,m,1)]; % Store the distance as output: W = setdat(a,-newout,fracrej); W = setfeatdom(W,{[-inf 0; -inf 0] [-inf 0; -inf 0]}); else error('Illegal call to SVDD.'); end return
github
SenticNet/one-class-svm-master
gendatoc.m
.m
one-class-svm-master/dd_tools/gendatoc.m
1,832
utf_8
2af0f2804f3cc1065009f1ed7e03a85d
%GENDATOC Generate a one-class dataset % % X = GENDATOC(Xt,Xo) % % INPUT % Xt Data matrix % Xo Data matrix % % OUTPUT % X One-class dataset % % DESCRIPTION % Generate the one-class dataset X from the two datasets Xt and Xo. Dataset % Xt will be labelled 'target', and Xo will be labelled 'outlier'. It is % possible to have Xt or Xo an empty dataset [], but not both at the same % time, of course. % Thus, X = GENDATOC([],X) will make X a dataset with only outlier objects. % % Note that X = GENDATOC(X) does the same as X = TARGET_CLASS(X) when X is % a data matrix. % % SEE ALSO % relabel, find_target, target_class % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function x = gendatoc(x_t,x_o) if nargin < 2, x_o = []; end [n_t,d1] = size(x_t); [n_o,d2] = size(x_o); % Because x_t or x_o can be empty, things become slightly complicated. % Furthermore, take care for the feature labels... if isempty(x_t) % we should get featlab from x_o if isempty(x_o) error('I need data to make a OC dataset'); end if isdataset(x_o) featlab = getfeatlab(x_o); else featlab = (1:d2)'; end else % get the featlab from x_t, and check the dims. if (~isempty(x_o)) && (d1 ~= d2) error('Dimensionality of x_t and x_o do not match.'); end if isdataset(x_t) featlab = getfeatlab(x_t); else featlab = (1:d1)'; end end % Create the labels and finally the dataset itself lab = [ones(n_t,1); repmat(2,n_o,1)]; lablist = ['target ';'outlier']; x = prdataset([+x_t;+x_o],lablist(lab,:),'featlab',featlab); x = setprior(x,getprior(x,0)); % is this good enough? %DXD A thing still to consider is: what name should be given to the %dataset? return
github
SenticNet/one-class-svm-master
dd_f1.m
.m
one-class-svm-master/dd_tools/dd_f1.m
1,328
utf_8
a6ab3a364d8d2f70825d318cfd6ba1d6
%DD_F1 compute the F1 score % % E = DD_F1(X,W) % E = DD_F1(X*W) % E = X*W*DD_F1 % % INPUT % X One-class dataset % W One-class classifier % % OUTPUT % E F1 performance % % DESCRIPTION % Compute the F1 score of a dataset, defined as: % 2*precision*recall % F1 = ------------------ % precision + recall % % SEE ALSO % dd_error, dd_roc % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function e = dd_f1(x,w) % Do it the same as testc: % When no input arguments are given, we just return an empty mapping: if nargin==0 e = prmapping(mfilename,'fixed'); e = setname(e,'F1'); return elseif nargin == 1 % Now we are doing the actual work, our input is a mapped dataset: % get the precision and recall: [dummy,f] = dd_error(x); % do some checks: if ~isfinite(f(1)) warning('dd_tools:NonfiniteOutputs',... 'The precision is not finite (all data is classified as outlier)'); e = nan; return; end if ~isfinite(f(2)) warning('dd_tools:NonfiniteOutputs',... 'The recall is not finite (no target data present?)'); e = nan; return end % and compute F1: e = (2*f(1)*f(2))/(f(1)+f(2)); else ismapping(w); istrained(w); e = feval(mfilename,x*w); end return
github
SenticNet/one-class-svm-master
inckernel.m
.m
one-class-svm-master/dd_tools/inckernel.m
1,254
utf_8
8a1f1cc91511a0d84ee9919363086593
%INCKERNEL Kernel definition for incsvdd/incsvc % % K = INCKERNEL(PAR,I,J); % % INPUT % PAR structure defining kernel type and parameters % I,J index (i,j) in kernel % % OUTPUT % K kernel value K(i,j) % % DESCRIPTION % Computation of the kernel function for the incremental SVDD. It is % assumed that there is a global variable X_incremental, containing the % objects. This is to avoid unnecessary overhead for very large % datasets. Therefore we will also not use the 'standard' ways to comute % the kernel (i.e. proxm). % % For the definition of the kernel types, see dd_kernel. % % The index vectors I and J indicate between which objects in % X_incremental the kernel should be computed. % % SEE ALSO % dd_kernel, incsvdd, dd_proxm, Wstartup, Wadd % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function K = inckernel(par,I,J); global X_incremental; if isempty(X_incremental) error('No data matrix X_incremental defined'); end if isdataset(X_incremental); error('Please make X_incremental a normal matlab array'); end A = X_incremental(I,:); B = X_incremental(J,:); K = dd_kernel(A,B,par.type,par.s); return
github
SenticNet/one-class-svm-master
unrandomize.m
.m
one-class-svm-master/dd_tools/unrandomize.m
1,011
utf_8
135113edf3db5e4d8cfb2c60a065157d
%UNRANDOMIZE 'Unrandomize' a dataset % % B = UNRANDOMIZE(A); % % INPUT % A Dataset % % OUTPUT % B Dataset % % DESCRIPTION % Reorder the objects in dataset A such that objects of the two classes % appear uniformly in the whole dataset. This is needed for the % incremental SVC to avoid that first the SVC gets all objects of class % +1, and after that all objects of class -1. The optimization becomes % very tough and numerically instable by that. % % SEE ALSO % incsvdd % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function a= unrandomize(a); [n,k,c]=getsize(a); if c~=2 error('Unrandomize requires just 2 classes.'); end nlab = getnlab(a); I1 = find(nlab==1); I2 = find(nlab==2); if length(I1)<length(I2) cmin = length(I1); else cmin = length(I2); tmpI = I1; I1 = I2; I2 = tmpI; end J=[]; J(1:2:2*cmin) = I1; J(2:2:2*cmin) = I2(1:cmin); J = [J,I2((cmin+1):end)']; a = a(J,:); return
github
SenticNet/one-class-svm-master
rankboostc.m
.m
one-class-svm-master/dd_tools/rankboostc.m
4,578
utf_8
aec9a75320d6a824b1e620eeb2ea839f
%RANKBOOSTC Binary rankboost % % W = RANKBOOSTC(A,FRACREJ,T) % W = A*RANKBOOSTC([],FRACREJ,T) % W = A*RANKBOOSTC(FRACREJ,T) % % INPUT % A One-class dataset % FRACREJ Error on the target class (default = 0.1) % T Number of weak classifiers (default = 10) % % OUTPUT % W Rankboost % % DESCRIPTION % Train a simple binary version of rankboost containing T weak % classifiers. The base (weak) classifiers only threshold a single % feature. % % SEE ALSO % dd_auc, auclpm % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands %function W = rankboostc(a,fracrej,T) function W = rankboostc(varargin) argin = shiftargin(varargin,'scalar'); argin = setdefaults(argin,[],0.1,10); if mapping_task(argin,'definition') [a,fracrej,T] = deal(argin{:}); W = define_mapping(argin,'untrained','Rankboost (T=%d)',T); elseif mapping_task(argin,'training') [a,fracrej,T] = deal(argin{:}); is_ocset(a) %some other magic parameter: reduce the maximum weight to: maxW = 1e6; [m,k] = size(a); y = 2*getnlab(a)-3; Ipos = find(y==+1); % target Ineg = find(y==-1); % outlier Npos = length(Ipos); Nneg = length(Ineg); %the weights per pair can be decomposed by an outer product on %vectors nu: nu(Ipos,1) = 1/Npos; nu(Ineg,1) = 1/Nneg; % some warning, we will get confused by zero-variance directions: % then we might suddenly get a good score, just by the fact that the % original objects were well ordered in the dataset Izerovariance = find(var(a)<=eps); if ~isempty(Izerovariance) warning(dd_tools:zeroVarianceFeatures,... 'Some features have zero variance; they will be ignored.'); end %now train T weak rankers: for i=1:T % recompute the weights per pair D = repmat(nu(Ipos),1,Nneg).*repmat(nu(Ineg)',Npos,1); % train the weak ranker w(i) = weakrank(a,D,Izerovariance); % find its weight if abs(w(i).r)<1 w(i).alf = 0.5*log(1+w(i).r) - 0.5*log(1-w(i).r+10*eps); if w(i).alf > maxW, w(i).alf=maxW; end if w(i).alf <-maxW, w(i).alf=-maxW; end else if w(i).r==1 % perfect solution, good order: w(i).alf = +maxW; else %w(i).r==-1, perfecto solution, negative order: w(i).alf = -maxW; end end % find the classifier output h = (+a(:,w(i).featnr)>w(i).threshold); % update the weights n1 = nu(Ipos).*exp(-w(i).alf*h(Ipos)); nu(Ipos) = n1/sum(n1); n2 = nu(Ineg).*exp(+w(i).alf*h(Ineg)); nu(Ineg) = n2/sum(n2); % If it is perfectly separable, in principle we should stop, It % think. But I am lazy and I just restart it: if w(i).r==1 %disp('reset'); nu(Ipos) = 1/Npos; nu(Ineg) = 1/Nneg; end end % now evaluate the training set for the threshold: out = zeros(Npos,1); for i=1:length(w) out = out + w(i).alf*(+a(Ipos,w(i).featnr)>w(i).threshold); end thr = dd_threshold(out,fracrej); % store the results W.w = w; W.threshold = thr; W = prmapping(mfilename,'trained',W,str2mat('target','outlier'),k,2); W = setname(W,'Rankboost (T=%d)',T); elseif mapping_task(argin,'trained execution') %testing [a,fracrej,T] = deal(argin{:}); % Unpack the mapping and dataset: W = getdata(fracrej); [m,k] = size(a); % the boosting is a sum over simple feature-threshold classifiers: out = zeros(m,1); for i=1:length(W.w) out = out + W.w(i).alf*(+a(:,W.w(i).featnr)>W.w(i).threshold); end % store the outcome, and pack it nicely: out = [out repmat(W.threshold,m,1)]; W = setdat(a,out,fracrej); W = setfeatdom(W,{[0 inf; 0 inf] [0 inf;0 inf]}); else error('Illegal call to rankboostc.'); end return function w = weakrank(a,D,Izerovariance) % W = WEAKRANK(A,D) % % Weak ranker, it only thresholds a single feature from dataset A. % Matrix D contains the weights for each point-pair. if nargin<3 Izerovariance = []; end [nra,n] = size(a); y = getoclab(a); Ipos = find(y==+1); % target Ineg = find(y==-1); % outlier % the weights pi: p(Ipos) = -sum(D,2); p(Ineg) = sum(D,1)'; % possible thresholds:first sort the data [sa,I] = sort(+a,1); % then re-sort also the pi: pI = p(I); % find the r, r = cumsum(pI); % suppress the features with zero variance: if ~isempty(Izerovariance) r(:,Izerovariance) = 0; end % find the best feature and threshold [mxr,J] = max(abs(r)); % j is the feature number [Rmax,j] = max(mxr); % J is the threshold number J = J(j); % find the fitting threshold if J>=nra thr = sa(nra,j); else thr = (sa(J,j)+sa(J+1,j))/2; end % store it w.featnr = j; w.threshold = thr; w.r = r(J,j); w.alf = 0; return
github
SenticNet/one-class-svm-master
incsvdd.m
.m
one-class-svm-master/dd_tools/incsvdd.m
3,343
utf_8
cfa3e2c2bd9db67acfae61bb61eed739
%INCSVDD Incremental Support Vector Data Description % % W = INCSVDD(A,FRACREJ,KTPYE,KPAR) % W = A*INCSVDD([],FRACREJ,KTPYE,KPAR) % W = A*INCSVDD(FRACREJ,KTPYE,KPAR) % % INPUT % A One-class dataset % FRACREJ Error on target class (default = 0.1) % KTYPE Kernel type (default = 'p') % KPAR Kernel parameter (default = 1) % % OUTPUT % W Incremental SVDD % % DESCRIPTION % Train an incremental support vector data description on dataset A. % The C-parameter is set such that FRACREJ of the target points is % rejected, using the formula: % C = 1/(N*FRACREJ) % The kernel (and its parameters) are defined by kernel type KTYPE and % parameter(s) KPAR. For possible definitions of the kernel, see DD_KERNEL. % % REFERENCE %@article{Tax1999c, % author = {Tax, D.M.J. and Duin, R.P.W}, % title = {Support vector domain description}, % journal = {Pattern Recognition Letters}, % year = {1999}, % volume = {20}, % number = {11-13}, % pages = {1191-1199}, %} % SEE ALSO % dd_kernel, inc_add, inc_setup, inc_store % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands %function W = incsvdd(a,fracrej,ktype,kpar) function W = incsvdd(varargin) argin = shiftargin(varargin,'scalar'); argin = setdefaults(argin,[],0.1,'p',1); if mapping_task(argin,'definition') [a,fracrej,ktype,kpar]=deal(argin{:}); W = define_mapping(argin,'untrained','IncSVDD (%s)',... getname(dd_proxm([],ktype,kpar))); elseif mapping_task(argin,'training') [a,fracrej,ktype,kpar]=deal(argin{:}); % be resistent against flipping of the third and forth input % parameter (which may be used in consistent_occ.m if isa(ktype,'double') if (nargin<4)||~isa(kpar,'char'), kpar = 'r'; end tmp = kpar; kpar = ktype; ktype = tmp; end % remove double objects... (should I give a warning??) [B,I] = unique(+a,'rows'); if length(I)~=size(a,1), a = a(I,:); warning('dd_tools:incsvdd:RemoveDoubleObjects',... 'Some double objects in dataset are removed.'); end dim = size(a,2); %define C: [It,Io] = find_target(a); if length(fracrej)==1 % only error on the target class if fracrej<0 % trick to define C directly C = -fracrej; else C = 1/(length(It)*fracrej); end C = [C C]; else % use two different Cs for target and outlier class if fracrej(1)<0, C(1) = fracrej(1); else C(1) = 1/(length(It)*fracrej(1)); end if fracrej(2)<0, C(2) = fracrej(2); else C(2) = 1/(length(Io)*fracrej(2)); end end % do the adding: W = inc_setup('svdd',ktype,kpar,C,+a,getoclab(a)); % store: w = inc_store(W); W = setname(w,'IncSVDD (%s)',getname(dd_proxm([],ktype,kpar))); elseif mapping_task(argin,'trained execution') [a,fracrej] = deal(argin{1:2}); % Now evaluate new objects: W = getdata(fracrej); % unpack [n,dim] = size(a); out = repmat(W.offs,n,1); for i=1:n wa = dd_kernel(+a(i,:),W.sv,W.ktype,W.kpar); out(i) = out(i) - 2*wa*W.alf + ... dd_kernel(+a(i,:),+a(i,:),W.ktype,W.kpar); end if (W.threshold<0) W.threshold = -W.threshold; % ...DXD hmmm end newout = [out repmat(W.threshold,n,1)]; % store: W = setdat(a,-newout,fracrej); W = setfeatdom(W,{[-inf 0;-inf 0] [-inf 0;-inf 0]}); else error('Illegal call to incsvdd.'); end
github
SenticNet/one-class-svm-master
isocset.m
.m
one-class-svm-master/dd_tools/isocset.m
544
utf_8
f9bb86dbf1ced69b0754506c8769c1b2
%ISOCSET True for one-class datasets % % N = ISOCSET(A) % % INPUT % A Dataset % % OUTPUT % N 0/1 if A isn't/is a one-class dataset % % DESCRIPTION % Exactly the same as IS_OCSET, so that you can use it with or without % underscore in the name. % % SEE ALSO % is_ocset % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function out = isocset(a) if nargout>0 out = is_ocset(a); else is_ocset(a); end
github
SenticNet/one-class-svm-master
dlpdda.m
.m
one-class-svm-master/dd_tools/dlpdda.m
4,805
utf_8
872c864b7b8f3ea5cad4550e3904156e
%DLPDDA Distance Linear Programming Data Description attracted by the Average distance % % W = DLPDDA(D,NU) % W = D*DLPDDA([],NU) % W = D*DLPDDA(NU) % % INPUT % D Dissimilarity dataset % NU Error fraction on target class (default = 0.1) % % OUTPUT % W Distance LPDD % % DESCRIPTION % This one-class classifier works directly on the distance (dissimilarity) % matrix D(X,R). Every entry of D is a dissimilarity between an object from % X and an object from R. X consists either of target examples or of both % target and outlier examples. The same holds for R, however, for logical % reasons, it might be better if R contains the targets only. % The distance matrix D does not need to be square. The distance itself % does not need to be metric. % % The DLPDDA is constructed as a hyperplane in the so-called dissimilarity % space D(X,R), such that it is attracted towards the average dissimilarity % output of the hyperplane. The data are still suppressed from above by % this hyperplane. This one-class classifier is inspired by the Campbell % and Bennett paper below. The setup of DLPDDA is similar to DLPDD, explained % in our reference paper. % % The NU parameter gives the fraction of error on the target set. % If NU = 0 and D is a square target distance matrix, then DLPDD and DLPDDA % tend to give the same results. % % Although it is more or less assumed that the data is in the positive quadrant, % you can put other data in as well and see how it may or may not work. % % EXAMPLE: % X = OC_SET(GENDATB([40 20]),'1'); % I = FIND_TARGET(X); % D = SQRT(DISTM(X,X(I,:))); % R <-- X(I,:), D is now 60 x 40 % W = DLPDDA(D,0.05); % % REFERENCES %@inproceedings{Campbell2000, % author = {Campbell, C. and Bennett, K.P.}, % title = {A Linear Programming Approach to Novelty Detection}, % year = {2000}, % pages = {395-401}, % booktitle = {Advances in Neural Information Processing Systems} % publisher = {MIT Press: Cambridge, MA} %} % @inproceedings{Pekalska2002, % author = {Pekalska, E. and Tax, D.M.J. and Duin, R.P.W.}, % title = {One-class {LP} classifier for dissimilarity representations}, % booktitle = {Advances in Neural Information Processing Systems}, % year = {2003}, % pages = {761-768}, % editor = {S.~Becker and S.~Thrun and K.~Obermayer}, % volume = {15}, % publisher = {MIT Press: Cambridge, MA} %} % SEE ALSO: % LPDD, DD_EX5, DLPDD % Copyright: E. Pekalska, D. Tax, [email protected] % Faculty of Applied Physics, Delft University of Technology % P.O. Box 5046, 2600 GA Delft, The Netherlands %function W = dlpdda(x,nu,usematlab) function W = dlpdda(varargin) argin = shiftargin(varargin,'scalar'); argin = setdefaults(argin,[],0.1,0); if mapping_task(argin,'definition') W = define_mapping(argin,'untrained','DLPDDA'); elseif mapping_task(argin,'training') [x,nu,usematlab] = deal(argin{:}); % work directly on the distance matrix [n,d] = size(x); % maybe we have example outliers... if isocset(x) labx = getoclab(x); else labx = ones(n,1); end x = +x; % no dataset please. % set up the LP problem: if nu > 0 & nu <= 1, C = 1./(n*nu); f = [1 -1 -sum(x,1)/d repmat(C,1,n)]'; A = [-labx labx repmat(labx,1,d).*x -eye(n)]; b = zeros(n,1); Aeq = [0 0 ones(1,d) zeros(1,n)]; beq = 1; N = n + d + 2; lb = zeros(N,1); ub = repmat(inf,N,1); elseif nu == 0, f = [1 -1 -sum(x,1)/d]'; A = [-labx labx repmat(labx,1,d).*x]; b = zeros(n,1); Aeq = [0 0 ones(1,d)]; beq = 1; N = d + 2; lb = zeros(N,1); ub = repmat(inf,N,1); else error ('Wrong nu.'); end % optimize:: if (exist('lp_solve')>0) & (usematlab==0) if ~exist('cplex_init') % we can have the lp optimizer: e = [0; -ones(d,1)]; [v,alf] = lp_solve(-f,sparse([Aeq;A]),[beq;b],e,lb,ub); else % the cplex optimizer: lpenv=cplex_init; disp = 0; [alf,y_upd_,how_upd_,p_lp]=... lp_solve(lpenv, f, sparse([Aeq;A]), [beq;b], lb, ub, 1, disp); end else % or the good old Matlab optimizer: opts = optimset('linprog'); opts.Display = 'off'; alf = linprog(f,A,b,Aeq,beq,lb,ub,[],opts); end % store the results paramalf = alf(3:2+d); W.I = find(paramalf>1e-8); W.w = paramalf(W.I); W.threshold = alf(1)-alf(2)+1e-12; W = prmapping(mfilename,'trained',W,str2mat('target','outlier'),d,2); W = setname(W,'DLPDDA'); elseif mapping_task(argin,'trained execution') %testing [x,nu] = deal(argin{1:2}); % get the data: W = getdata(nu); m = size(x,1); % and here we go: D = +x(:,W.I); % annoying prtools: newout = [D*W.w repmat(W.threshold,m,1)]; % Store the distance as output: W = setdat(x,-newout,fracrej); W = setfeatdom(W,{[-inf 0;-inf 0] [-inf 0;-inf 0]}); else error('Illegal call to DLPDDA'); end return
github
SenticNet/one-class-svm-master
plotroc_update.m
.m
one-class-svm-master/dd_tools/plotroc_update.m
4,003
utf_8
d8ed5dd7ae04ed502abf5bc2ff4b8cea
% PLOTROC_UPDATE(W,A) % % Auxiliary function containing the callbacks for the plotroc.m. % % SEE ALSO % plotroc % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function plotroc_update(w,a) if isocc(w) if ~isocset(a) error('setthres: I should have a OC-dataset to set the threshold'); end % Get the ROC data: H = gcf; % Prepare the figure for interaction: % Store the old settings and setup the new ones: UD = get(H,'userdata'); UD.units = get(H,'units'); set(H,'units','pixels') h_ax = get(H,'children'); UD.ax_units = get(h_ax,'units'); set(h_ax,'units','pixels') UD.sz = get(h_ax,'position'); UD.pointer = get(H,'pointer'); set(H,'pointer','crosshair') UD.olddown = get(H,'Windowbuttondownfcn'); set(H,'Windowbuttondownfcn','plotroc_update(''keydown'')'); UD.oldmove = get(H,'Windowbuttonmotionfcn'); set(H,'Windowbuttonmotionfcn','plotroc_update(''keymove'')'); UD.w = w; set(H,'userdata',UD); % and some speedups? set(H,'busyaction','cancel','DoubleBuffer','off'); else if ~ischar(w) error('I am expecting a string input'); end switch(w) case 'fix' % Restore to original situation: UD = get(gcbf,'userdata'); set(gcbf,'units',UD.units); set(gcbf,'pointer',UD.pointer); set(gcbf,'windowbuttondownfcn',UD.olddown); set(gcbf,'windowbuttonmotionfcn',UD.oldmove); h_ax = get(gcbf,'children'); set(h_ax,'units',UD.ax_units); case 'keydown' % When a mouse button is clicked, retrieve the operating point, % update the classifier and return the classifier. % Get the position of the temporary operating point: htmp = findobj('tag','currpoint'); currx = get(htmp,'xdata'); curry = get(htmp,'ydata'); % Set the position of the operating point: h = findobj('tag','OP'); set(h,'xdata',currx); set(h,'ydata',curry); % Find the position in the coordinate list: UD = get(gcbf,'userdata'); %Ix = find(currx==UD.coords(:,1)); %Iy = find(curry==UD.coords(:,2)); %J = intersect(Ix,Iy); % sometimes we didn't have a perfect match, use the closest % object: [minD,J] = min(sqeucldistm([currx curry],UD.coords)); if isempty(J) error('I cannot recover the operating point'); end if length(J)>1 error('Too many candidates'); end % update the stored classifier: W = UD.w; dat = W.data; %DXD this is a hack!! But I don't feel like checking again if this %classifier is distance based or density based %oldt = dat.threshold %newt = abs(UD.thresholds(J)) dat.threshold = abs(UD.thresholds(J)); ww = setdata(W,dat); UD.w = ww; set(gcbf,'userdata',UD); %update the title set(UD.h_title,'string','Set classifier to this operating point'); case 'keymove' % When moving the cursor, the temporary operating point should % move position: % find the possible coordinates for the OP: UD = get(gcbf,'userdata'); roc_x = UD.coords(:,1); roc_y = UD.coords(:,2); % Now find where the cursor is: %h = get(0,'PointerWindow'); pos = get(0,'PointerLocation'); loc = get(gcbf,'position'); pos_x = (pos(1)-loc(1)-UD.sz(1))/UD.sz(3); pos_y = (pos(2)-loc(2)-UD.sz(2))/UD.sz(4); % and find the closest object on the curve (in terms of the % x-feature): dff = abs(roc_x-pos_x); minD = min(dff); J = find(dff==minD); % if there are several points with minimum distance, take also the % y-coordinate into account): if length(J)>1 dff = abs(roc_y(J)-pos_y); [minD,Jy] = min(dff); J = J(Jy); end % Update the operating point: h = findobj('tag','currpoint'); set(h,'visible','off'); set(h,'xdata',roc_x(J)); set(h,'ydata',roc_y(J)); set(h,'visible','on'); % Update the title str = sprintf('(%5.3f, %5.3f)',roc_x(J),roc_y(J)); if pos_x>=0 && pos_x<=1 && pos_y>=0 && pos_y<=1 set(UD.h_title,'string',str); set(UD.h_title,'color',[1 0 0]); else set(UD.h_title,'string',''); end otherwise error('Unknown type in imroc'); end end return
github
SenticNet/one-class-svm-master
autoenc_dd.m
.m
one-class-svm-master/dd_tools/autoenc_dd.m
2,643
utf_8
c7e0eb588df89acaff5800fe9c6fa31a
%AUTOENC_DD Auto-Encoder data description. % % W = AUTOENC_DD(A,FRACREJ,N) % W = A*AUTOENC_DD([],FRACREJ,N) % W = A*AUTOENC_DD(FRACREJ,N) % % INPUT % A Dataset % FRACREJ Fraction of target objects rejected (default = 0.1) % N Number of hidden units (default = 5) % % OUTPUT % W AutoEncoder network % % DESCRIPTION % Train an Auto-Encoder network with N hidden units. The network should % recover the original data A at its output. The difference between the % network output and the original pattern (in MSE sense) is used as a % charaterization of the class. The threshold on this measure is optimized % such that FRACREJ of the training objects are rejected. % % REFERENCE %@phdthesis{Tax2001a, % author = {Tax, D.M.J.}, % title = {One-class classification}, % school = {Delft University of Technology}, % year = {2001}, % address = {http://www.ph.tn.tudelft.nl/\~{}davidt/thesis.pdf}, % month = {June}} % % SEE ALSO % datasets, mappings, dd_roc % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands %function W = autoenc_dd(a,fracrej,N) function W = autoenc_dd(varargin) argin = shiftargin(varargin,'scalar'); argin = setdefaults(argin,[],0.1,5); if mapping_task(argin,'definition') % empty mapping W = define_mapping(argin,'untrained','Auto-encoder'); elseif mapping_task(argin,'training') [a,fracrej,N] = deal(argin{:}); a = +target_class(a); % make sure a is an OC dataset [nrx,dim] = size(a); % set up the parameters for the network: % old neural network toolbox settings: % minmax = [min(a)' max(a)']; % net = newff(minmax,[N dim],{'tansig','purelin'},'trainlm'); net = newff(a',a',N,{'tansig','purelin'},'trainbfg'); net = init(net); net.trainParam.show = inf; net.trainParam.showWindow = false; net.trainParam.lr = 0.01; net.trainParam.goal = 1e-5; net = train(net,a',a'); % obtain the threshold: aout = sim(net,a'); d = sum((a-aout').^2,2); W.threshold = dd_threshold(d,1-fracrej); %and save all useful data: W.net = net; W.scale = mean(d); W = prmapping(mfilename,'trained',W,str2mat('target','outlier'),dim,2); W = setname(W,'Auto-encoder (N=%d)',N); elseif mapping_task(argin,'trained execution') %testing [a,fracrej] = deal(argin{1:2}); W = getdata(fracrej); % unpack m = size(a,1); %compute distance: out = sim(W.net,+a')'; out = [sum((a-out).^2,2) repmat(W.threshold,m,1)]; %store the distance as output: W = setdat(a,-out,fracrej); W = setfeatdom(W,{[-inf 0; -inf 0] [-inf 0; -inf 0]}); else error('Illegal call to autoenc_dd.'); end
github
SenticNet/one-class-svm-master
mog_update.m
.m
one-class-svm-master/dd_tools/mog_update.m
970
utf_8
d06184a26ce64866f68d4388065a7cfc
%MOG_UPDATE Train a MoG % % W = MOG_UPDATE(W,X,MAXITER) % % INPUT % W MoG mapping % X One-class dataset % MAXITER Number of EM iterations % % OUTPUT % W Updated MoG mapping % % DESCRIPTION % Fit a Mixture of Gaussians model W to data X, for MAXITER number of EM % steps. % % SEE ALSO % mog_dd, mog_init, mog_P, mog_extend, mogEMupdate % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function w = mog_update(w,x,maxiter) % unpack it: dat = w.data; [xt,xo] = target_class(x); % update the target class clusters: [dat.mt,dat.ict,dat.pt] = mogEMupdate(+xt,dat.covtype,... dat.mt,dat.ict,dat.pt,maxiter,0,dat.reg); % update the outlier class clusters: if isfield(dat,'mo') && ~isempty(xo) [dat.mo,dat.ico,dat.po] = mogEMupdate(+xo,dat.covtype,... dat.mo,dat.ico,dat.po,maxiter,1,dat.reg); end % pack it and return: w.data = dat; return
github
SenticNet/one-class-svm-master
roc2hit.m
.m
one-class-svm-master/dd_tools/roc2hit.m
1,142
utf_8
3dd784d876857cb48245e1a7a420c8f3
%ROC2HIT Conversion ROC to hit-rate/false-alarm curve % % P = ROC2HIT(R,N) % % INPUT % R ROC curve % N Number of target and outlier objects % % OUTPUT % P Hit-rate/false-alarm curve % % DESCRIPTION % Convert ROC curve R into a Hit-Rate/false-alarm graph P. % This is only possible when you supply the number of positive and % negative objects in N: % N(1): number of positive/target objects % N(2): number of negative/outier objects % % SEE ALSO % roc2prc, dd_roc, dd_prc, plotroc % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function rnew = roc2hit(r,n) if nargin<2 if isfield(r,'N') n = r.N; else error('N is not defined.'); end else if length(n)~=2 error('N should contain a number for each class.'); end end % compute the hit rate: hitrate = 1-r.err(:,1); % and the false alarm rate: FArate = r.N(2)*r.err(:,2)./(r.N(2)*r.err(:,2)+r.N(1)*hitrate); % store it in a new curve: rnew.type = 'hit'; rnew.op = []; rnew.err = [hitrate FArate]; rnew.thrcoords = []; rnew.thresholds = [];
github
SenticNet/one-class-svm-master
svddpath_opt.m
.m
one-class-svm-master/dd_tools/svddpath_opt.m
4,332
utf_8
42c11eaca25dae5460fadc4c5aaa0c9c
%SVDDPATH_OPT SVDD path of C % % [LAMBDA,ALF,B,O] = SVDDPATH_OPT(K,ENDLAMBDA) % % This is the optimization function for the weights in the SVDD by % varying the lambda (C) parameter. Lambda is changed from the maximum % (= the number of training objects) to the minimum, given by the user % in ENDLAMBDA. The solution for the last Lambda is returned. ALF % contains all the weights, B and O the indices of the objects that are % on the boundary (B) or outside (O) the SVDD. function [lambda,alf,B,O] = svddpath_opt(K,endLambda,ub) if nargin<3 ub = []; end if nargin<2 endLambda = 0; end % initialize tol = 1e-9; m = size(K,1); if isempty(ub) ub = ones(m,1); else ub(ub<=0) = tol; % stability later... ub = m*ub/sum(ub); %normalize end % all objects in O: alf = ub; lambda = sum(ub); O = (1:m)'; % the rest is empty: B = []; I = []; lastsituation = 0; % save for inspection reasons: ll = lambda; % GO! while (lambda>0) if isempty(B) % No support objects on the boundary, take the first one from O: nrO = length(O); f_cand = diag(K(O,O)) - 2*K(O,:)*alf/lambda... + sum(sum((alf*alf').*K))/(lambda*lambda); [fmin,obj] = min(f_cand); % move it in B: B = O(obj); O(obj) = []; %message(3,'EMPTY B, exceptional situation 3: move %d from O to B.\n', obj); end % Compute the 'sensitivities': k = B(1); Bmink = B(2:end); Y = K - repmat(K(k,:),m,1); y = diag(K) - K(k,k); Z = eye(m); %Z(Bmink,Bmink) = Y(Bmink,Bmink); % wrong! Z(B,B) = Y(B,B); Z(k,:) = ones(1,m); z = zeros(m,1); z(Bmink) = y(Bmink); z(k) = 2; W = zeros(m,m); W(Bmink,O) = -Y(Bmink,O); W(O,O) = eye(size(O,1)); % here the expensive part: iZ = inv(Z); p = iZ*z/2; q = iZ*W*ub; % consistency check: if max(abs(sum(alf)*p+q-alf))>tol disp('p and q do not reproduce the orig. solution!'); keyboard end % situation 1, B to I, alf becomes 0: lambda1 = -q(B)./p(B); lambda1(lambda1>lambda) = -inf; % okok, check if we are not inversing the last thing we did: if (lastsituation==4) obj=find(B==lastobj); lambda1(obj) = -inf; end [lambda1,obj1] = max(lambda1); % situation 2, B to O, alf becomes upper bounded: lambda2 = (ub(B)-q(B))./p(B); % we are a bit more strict here: we don't want to move an object from % B to O: lambda2(lambda2>=lambda) = -inf; % okok, check if we are not inversing the last thing we did: if (lastsituation==3) obj=find(B==lastobj); lambda2(obj) = -inf; end [lambda2,obj2] = max(lambda2); % situation 3, O to B, from bounded to unbounded SV: if ~isempty(O) lambda3 = (2*Y(O,:)*q)./(y(O) - 2*Y(O,:)*p); lambda3(lambda3>lambda) = -inf; % okok, check if we are not inversing the last thing we did: if (lastsituation==2) obj=find(O==lastobj); lambda3(obj) = -inf; end [lambda3,obj3] = max(lambda3); else lambda3 = -inf; end % situation 4, I to B, from rest to unbounded SV: if ~isempty(I) lambda4 = (2*Y(I,:)*q)./(y(I) - 2*Y(I,:)*p); lambda4(lambda4>lambda) = -inf; % okok, check if we are not inversing the last thing we did: if (lastsituation==1) obj=find(I==lastobj); lambda4(obj) = -inf; end [lambda4,obj4] = max(lambda4); else lambda4 = -inf; end % which is the most pressing object? %oldlambda = lambda; %oldI = I; oldB = B; oldO = O; oldalf = alf; [lambda,situation] = max([lambda1 lambda2 lambda3 lambda4]); %message(3,'situation %d\n',situation); % maybe we already obtained lambda=0? if lambda<=endLambda %disp('End!'); break; end ll = [ll;lambda]; % update the weights: alf = lambda*p + q; if any(alf<-tol) disp('Some alphas became <0.'); keyboard; end if any(alf>ub+tol) disp('Some alphas became > upper bound.'); keyboard; end % and move the object: switch situation case 1 lastsituation = 1; lastobj = B(obj1); I = [I; B(obj1)]; B(obj1) = []; case 2 lastsituation = 2; lastobj = B(obj2); O = [O; B(obj2)]; B(obj2) = []; case 3 lastsituation = 3; lastobj = O(obj3); B = [B; O(obj3)]; O(obj3) = []; case 4 lastsituation = 4; lastobj = I(obj4); B = [B; I(obj4)]; I(obj4) = []; end % what about 'cleaning' the weights, to avoid numerical % instabilities? %sum1=sum(alf); if ~isempty(O) alf(O) = ub(O); end if ~isempty(I) alf(I) = 0; end lambda = sum(alf); %message(4,'Cleaning weights, change=%e\n',abs(lambda-sum1)); end lambda = ll; return
github
SenticNet/one-class-svm-master
nparzen_dd.m
.m
one-class-svm-master/dd_tools/nparzen_dd.m
3,087
utf_8
8a29fdf04e296ad525f206c3e41a0b05
%NPARZEN_DD Naive Parzen data description. % % W = NPARZEN_DD(A,FRACREJ,H) % W = A*NPARZEN_DD([],FRACREJ,H) % W = A*NPARZEN_DD(FRACREJ,H) % % INPUT % A One-class dataset % FRACREJ Error on the target class (default = 0.1) % H Width parameter (default = []) % % OUTPUT % W Naive Parzen model % % DESCRIPTION % Fit a Parzen density on each individual feature in dataset A and % multiply the results for the final density estimate. This is similar % to the Naive Bayes approach used for classification. % The threshold is put such that FRACREJ of the target objects is % rejected. % % If the width parameter is known, it can be given as third parameter, % otherwise it is optimized using parzenml. % % SEE ALSO % parzen_dd, dd_roc % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands %function W = nparzen_dd(a,fracrej,h) function W = nparzen_dd(varargin) argin = shiftargin(varargin,'scalar'); argin = setdefaults(argin,[],0.1,[]); if mapping_task(argin,'definition') % Define mapping W = define_mapping(argin,'untrained','Naive Parzen'); elseif mapping_task(argin,'training') % Train a mapping. [a,fracrej,h] = deal(argin{:}); % Make sure a is an OC dataset: a = target_class(a); k = size(a,2); % Train it: if isempty(h) for i=1:k h(i) = parzenml(+a(:,i)); %DXD BAD patch!! % When the dataset contains identical objects, or when it % contains discrete features, the optimization of h using LOO % will fail. h -> NaN. If that is the case, I patch it and % replace h(i) by a small value % Actually, in the future I should implement that the features % are discrete (so, define it in the dataset) and use a % discrete probability density here. if ~isfinite(h(i)) h(i) = 1e-12; end end end % check if h is not the correct size: if length(h)~=k error('NParzen_dd expects k smoothing parameters'); end % Get the mappings: w = {}; for i=1:k w{i} = prmapping('parzen_map','trained',{a(:,i), h(i)}, 'target',1,1); end % Map the training data and obtain the threshold: d = zeros(size(a)); for i=1:k d(:,i) = +(a(:,i)*w{i}); end s = warning('off'); % these annoying 0 densities... p = sum(log(d),2); warning(s); thr = dd_threshold(p,fracrej); %and save all useful data: W.w = w; W.h = h; W.threshold = thr; W = prmapping(mfilename,'trained',W,str2mat('target','outlier'),k,2); W = setname(W,'NaiveParzen'); elseif mapping_task(argin,'trained execution') %testing [a,fracrej] = deal(argin{1:2}); W = getdata(fracrej); % unpack [m,k] = size(a); %compute: d = zeros(size(a)); for i=1:k d(:,i) = +(a(:,i)*W.w{i}); end s = warning('off'); % these annoying 0 densities... out = sum(log(d),2); warning(s); newout = [out, repmat(W.threshold,m,1)]; newout=exp(newout); % Store the density: W = setdat(a,newout,fracrej); W = setfeatdom(W,{[0 inf; 0 inf] [0 inf; 0 inf]}); else error('Illegal call to nparzen_dd.'); end return
github
SenticNet/one-class-svm-master
find_target.m
.m
one-class-svm-master/dd_tools/find_target.m
1,047
utf_8
1e480b414b57be9001a0b3d74f77d256
%FIND_TARGET extract the indices of the target and outlier objects % % [It,Io] = FIND_TARGET(A) % [It,Io] = FIND_TARGET(LAB) % % INPUT % A One-class dataset % LAB A label vector with 'target' and/or 'outlier' % % OUTPUT % It Indices of target objects % Io Indices of outlier objects % % DESCRIPTION % Return the indices of the objects from dataset A which are labeled % 'target' and 'outlier' in the index vectors It and Io respectively. A % warning is given when no target objects can be found. % % It also works when no dataset but a label matrix LAB is given. % % SEE ALSO % istarget, isocset, gendatoc, oc_set % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [I1,I2] = find_target(a) % first find the logical vector of target objects: I = istarget(a); % extract the indices: I1 = find(I); % if requested, also find the outliers: if (nargout>1) I2 = find(~I); end return
github
SenticNet/one-class-svm-master
simpleprc.m
.m
one-class-svm-master/dd_tools/simpleprc.m
2,772
utf_8
8c28a91db8df0af5a61a8d015a454821
%SIMPLEPRC Basic precision-recall characteristic curve % % F = SIMPLEPRC(PRED,TRUELAB) % % INPUT % PRED Prediction of a classifier % TRUELAB True labels % % OUTPUT % F Precision-recall graph % % DESCRIPTION % Compute the PR curve for the network output PRED, given the true % labels TRUELAB. TRUELAB should contain 0-1 values. When TRUELAB=0, % then we should have (PRED<some_threshold) , and when TRUELAB=1, we % should get (PRED>some_threshold). Output F contains [Prec Rec]. % % This version returns a vector of the same length as PRED and % TRUELAB. Maybe this will be shortened/subsampled in the future. % % Some speedups and improvements by G. Bombara <[email protected]> % % SEE ALSO % simpleroc, dd_prc, plotroc % Copyright: D.M.J. Tax, [email protected] % Faculty EWI, Delft University of Technology % P.O. Box 5031, 2600 GA Delft, The Netherlands function [f,thr] = simpleprc(netout,truelab) % Check the size of the netout vector if size(netout,2)~=1 netout = netout'; if size(netout,2)~=1 error('Please make netout a column vector.'); end end % Collect all sizes: n = size(netout,1); n_t = sum(truelab); % Sort the netout: [sout,I] = sort(-netout); % and therefore also reorder the true labels accordingly slab = truelab(I); % Make the index arrays for the target and outlier objects: slabt = slab; slabo = ~slab; % Check if there are identical outputs, and ... [uout,~,J] = unique(sout); % Change the slab such that the identical values are on top of each other if size(uout,1)<n %warning('dd_tools:NoUniqueROC',... % 'There are identical values in NETOUT, the ROC is not uniquely defined.'); n = size(uout,1); slabt2 = zeros(n,1); slabo2 = zeros(n,1); Sidx=1; J = [J; -1]; for j=1:n % count how many of each of the values occur, and store % the approprate number in slabt2 and slabo2: Ji=Sidx; i = Sidx+1; while J(i)==j; Ji(end+1) = i; i = i+1; end Sidx=i; slabt2(j) = sum(slabt(Ji)); slabo2(j) = sum(slabo(Ji)); end slabt = slabt2; slabo = slabo2; end %slabt 1110011101 0001001000000 %slabo 0001100010 1110110111111 % + <-----------+------------- %TP= 111 111 1 %FP= 11 1 %FN= 1 1 % % precision = TP/(TP+FP) % recall = TP/(TP+FN) cslabt = cumsum(slabt); cslabo = cumsum(slabo); prec = cslabt./(cslabt+cslabo); rec = cslabt/n_t; f = [prec rec]; % fix beginning of the curve uout = [uout(1)-10*eps(uout(1)); uout]; f = [NaN 0 ; f]; % reorder and flip sign of vectors to have a consistent output with simpleroc f = flipud(f); uout = flipud(-uout); % On request, also the thresholds are returned: if nargout>1 thr = uout; end end