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
epilepsyecosystem/1stplace_notsorandomanymore-master
csp.m
.m
1stplace_notsorandomanymore-master/Andriy/code/csp.m
1,635
utf_8
2c3cc9ecabee5250c8a4d953ac52f540
% Coded by James Ethridge and William Weaver function [result] = CSP(varargin) if (nargin ~= 2) disp('Must have 2 classes for CSP!') end Rsum=0; %finding the covariance of each class and composite covariance for i = 1:nargin %mean here? R{i} = ((varargin{i}*varargin{i}')/trace(varargin{i}*varargin{i}'));%instantiate me before the loop! %Ramoser equation (2) Rsum=Rsum+R{i}; end % Find Eigenvalues and Eigenvectors of RC % Sort eigenvalues in descending order [EVecsum,EValsum] = eig(Rsum); [EValsum,ind] = sort(diag(EValsum),'descend'); EVecsum = EVecsum(:,ind); % Find Whitening Transformation Matrix - Ramoser Equation (3) W = sqrt(inv(diag(EValsum))) * EVecsum'; for k = 1:nargin S{k} = W * R{k} * W'; % Whiten Data Using Whiting Transform - Ramoser Equation (4) end % Ramoser equation (5) %[U{1},Psi{1}] = eig(S{1}); %[U{2},Psi{2}] = eig(S{2}); %generalized eigenvectors/values [B,D] = eig(S{1},S{2}); % Simultanous diagonalization % Should be equivalent to [B,D]=eig(S{1}); %verify algorithim %disp('test1:Psi{1}+Psi{2}=I') %Psi{1}+Psi{2} %sort ascending by default %[Psi{1},ind] = sort(diag(Psi{1})); U{1} = U{1}(:,ind); %[Psi{2},ind] = sort(diag(Psi{2})); U{2} = U{2}(:,ind); [D,ind]=sort(diag(D)); B=B(:,ind); %Resulting Projection Matrix-these are the spatial filter coefficients result = B'*W; end
github
epilepsyecosystem/1stplace_notsorandomanymore-master
hjorth.m
.m
1stplace_notsorandomanymore-master/Andriy/code/hjorth.m
552
utf_8
a0bf784291539da122d8642eb5e6df86
% Function to calculate Hjorth parameters function [activity, mobility, complexity] = hjorth(y_step) activity = var(y_step,1); % Variance of each EEG epoch. 1st Hjorth parameter eeg_diff1 = diff(y_step,1,1); % 1st derivative of EEG mobility = std(eeg_diff1,1)./(std(y_step,1)+eps); % EEG Mobility. 2nd Hjorth parameter eeg_diff2 = diff(eeg_diff1,1,1); % 2nd derivative of EEG complexity = (std(eeg_diff2,1)./std(eeg_diff1,1)+eps)./mobility; % EEG Complexity. 3rd Hjorth parameter
github
epilepsyecosystem/1stplace_notsorandomanymore-master
ar.m
.m
1stplace_notsorandomanymore-master/Andriy/code/ar.m
8,371
utf_8
cf66d76a53acbec25e46d830a2f0385a
function [th,ref]=ar(data,n,varargin) %AR Computes AR-models of signals using various approaches. % Model = AR(Y,N) or TH = AR(Y,N,Approach) or TH = AR(Y,N,Approach,Win) % % Model: returned as an IDPOLY model with the estimated parameters of the % AR-model, see HELP IDPOLY. % % Y: The time series to be modelled, an IDDATA object. (See HELP IDDATA) % N: The order of the AR-model % Approach: The method used, one of the following ones: % 'fb' : The forward-backward approach (default) % 'ls' : The Least Squares method % 'yw' : The Yule-Walker method % 'burg': Burg's method % 'gl' : A geometric lattice method % For the two latter ones, reflection coefficients and loss functions % are returned in REFL by [Model,REFL] = AR(y,n,approach) % Win : Windows employed, one of the following ones: % 'now' : No windowing (default, except when approach='yw') % 'prw' : Prewindowing % 'pow' : Postwindowing % 'ppw' : pre- and post-windowing % % The Property/Value pairs 'MaxSize'/maxsize and 'Ts'/Ts can be added to % set the MaxSize property (see also IDPROPS ALG) and to override the sampling % interval of the data: Example: Model = AR(Y,N,Approach,'MaxSize',500). % The Property/Value pair 'CovarianceMatrix'/'None' will suppress the % calcualtion of the covariance matrix. % % See also IVAR, ARX, N4SID. % L. Ljung 10-7-87 % Copyright 1986-2006 The MathWorks, Inc. % $Revision: 1.15.4.5 $ $Date: 2006/12/27 20:52:50 $ if nargin <2 disp('Usage: TH = AR(Y,ORDER)') disp(' TH = AR(Y,ORDER,APPROACH,WINDOW)') disp(' APPROACH is one of ''fb'', ''ls'', ''yw'', ''burg'', ''gl''.') disp(' WINDOW is one of ''now'', ''prw'', ''pow'', ''ppw''.') return end ref = []; maxsize = 'auto'; T = 1; approach = 'fb'; win = 'now'; pt = 1; Tflag = 0; % Some initial tests on the input arguments indc = 1; list = {'Maxsize','Ts','fb','ls','yw','burg','gl','now',... 'prw','pow','ppw','CovarianceMatrix','None','Estimate'}; while indc<=length(varargin) arg = varargin{indc}; if ischar(arg) if arg(end)=='0' pt = 0; arg=arg(1:end-1); end try [prop,im] = pnmatchd(arg,list,7,0); catch rethrow(lasterror) end if im==1 maxsize = varargin{indc+1}; indc = indc+1; elseif im==2 T = varargin{indc+1}; indc=indc+1; Tflag = 1; elseif im<8 approach = prop; elseif im < 12 win = prop; elseif im == 13 pt = 0; end elseif indc == 3 maxsize = varargin{indc}; elseif indc==4 T = varargin{indc}; Tflag = 1; end indc=indc+1; end pt1 = pt; errn=0; if ~isa(n,'double') errn=1; elseif n~=fix(n) || n<=0 || ~isreal(n) errn=1; end if errn error('The order, n, must be a positive integer.') end if isa(data,'frd') || isa(data,'idfrd') || (isa(data,'iddata') ... && strcmp(pvget(data,'Domain'),'Frequency')) error('For frequency domain data, use ARX instead of AR.') end if ~isa(data,'iddata') [N,ny]=size(data); if min(N,ny)~=1 error('AR only handles single output time series.') end if N<ny data = data'; end data = iddata(data,[],T); end if Tflag, data = pvset(data,'Ts',T);end [yor,Ne,ny,nu,T,Name,Ncaps,errflag]=idprep(data,0,inputname(1)); y = yor; % Keep the original y for later computatation of e if ny>1 error('Only scalar time series can be handled. Use ARX for multivariate signals.') end if nu>0 error('This routine is for scalar time series only. Use ARX for the case with input.') end maxsdef=idmsize(max(Ncaps),n); if isempty(maxsize) || ischar(maxsize), maxsize=maxsdef; maxs = 1; else maxs = 0; end if strcmp(approach,'yw') win='ppw'; end if strcmp(win,'prw') || strcmp(win,'ppw') for kexp = 1:Ne y{kexp}=[zeros(n,1);y{kexp}]; end Ncaps = Ncaps+n; end if strcmp(win,'pow') || strcmp(win,'ppw') for kexp =1:Ne y{kexp} = [y{kexp};zeros(n,1)]; end Ncaps = Ncaps+n; end for zzz=1:n th{zzz} = idpoly; end %th1 = idpoly; if maxs Max = 'auto'; else Max = maxsize; end %th = pvset(th,'MaxSize',Max); % First the lattice based algorithms if any(strcmp(approach,{'burg','gl'})) ef=y;eb=y; rho = zeros(1,n+1); r = zeros(1,n); A = r; [ss,l] = sumcell(y,1,Ncaps); rho(1) = ss/l; for p=1:n nef = sumcell(ef,p+1,Ncaps); neb=sumcell(eb,p,Ncaps-1); if strcmp(approach,'gl') den=sqrt(nef*neb); else den=(nef+neb)/2; end ss=0; for kexp=1:Ne ss=ss+(-eb{kexp}(p:Ncaps(kexp)-1)'*ef{kexp}(p+1:Ncaps(kexp))); end r(p)=ss/den; A(p)=r(p); A(1:p-1)=A(1:p-1)+r(p)*conj(A(p-1:-1:1)); rho(p+1)=rho(p)*(1-r(p)*r(p)); efold=ef; for kexp = 1:Ne Ncap = Ncaps(kexp); ef{kexp}(2:Ncap)=ef{kexp}(2:Ncap)+r(p)*eb{kexp}(1:Ncap-1); eb{kexp}(2:Ncap)=eb{kexp}(1:Ncap-1)+conj(r(p))*efold{kexp}(2:Ncap); end end th = pvset(th,'a',[1 A]); ref=[0 r;rho]; else pt1 = 1; %override pt for the other appoaches end % Now compute the regression matrix if pt1 nmax=n; M=floor(maxsize/n); R1 = zeros(0,n+1); fb=strcmp(approach,'fb'); if strcmp(approach,'fb') R2 = zeros(0,n+1); yb = cell(1,Ne); for kexp = 1:Ne yb{kexp}=conj(y{kexp}(Ncaps(kexp):-1:1)); end end for kexp = 1:Ne Ncap = Ncaps(kexp); yy = y{kexp}; for k=nmax:M:Ncap-1 jj=(k+1:min(Ncap,k+M)); phi=zeros(length(jj),n); if fb, phib=zeros(length(jj),n); end for k1=1:n, phi(:,k1)=-yy(jj-k1); end if fb for k2=1:n, phib(:,k2)=-yb{kexp}(jj-k2); end end if fb, R2 = triu(qr([R2;[[phi;phib],[yy(jj);yb{kexp}(jj)]]])); [nRr,nRc] =size(R2); R2 = R2(1:min(nRr,nRc),:); end R1 = triu(qr([R1;[phi,yy(jj)]])); [nRr,nRc] =size(R1); R1 = R1(1:min(nRr,nRc),:); %end end end for zzz=1:n P{zzz} = pinv(R1(1:zzz,1:zzz)); end %P1 = pinv(R1(1:n-1,1:n-1)); if ~any(strcmp(approach,{'burg','gl'})) if ~fb for zzz=1:n A{zzz} = (P{zzz} * R1(1:zzz,zzz+1)).'; end for zzz=1:n-1 A{zzz} = -A{zzz}(end:-1:1); end %A1 = (P1 * R1(1:n-1,n-1+1)).'; %A1 = -A1(end:-1:1); else A = (pinv(R2(1:n,1:n)) * R2(1:n,n+1)).'; end for zzz=1:n th{zzz} = pvset(th{zzz},'a',[1 A{zzz}]); end %th1 = pvset(th1,'a',[1 A1]); end for zzz=1:n P{zzz} = P{zzz}*P{zzz}'; end else P = []; end if ~pt P = []; end for zzz=1:n e{zzz} = []; for kexp = 1:length(yor); tt{zzz}=filter([1 A{zzz}],1,yor{kexp}); tt{zzz}(1:zzz)=zeros(zzz,1); e{zzz} = [e{zzz};tt{zzz}]; end end for zzz=1:n lam{zzz} = e{zzz}'*e{zzz}/(length(e{zzz})-zzz); es{zzz} = pvget(th{zzz},'EstimationInfo'); es{zzz}.FPE = lam{zzz}*(1+2*zzz/sum(Ncaps)); es{zzz}.Status = 'Estimated Model (AR)'; es{zzz}.Method = ['AR (''',approach,'''/''',win,''')']; es{zzz}.DataLength = sum(Ncaps); es{zzz}.LossFcn = lam{zzz}; es{zzz}.DataTs = T; es{zzz}.DataName = Name; es{zzz}.DataInterSample = 'Not Applicable'; idm{zzz} = pvget(th{zzz},'idmodel'); idm{zzz} = pvset(idm{zzz},'Ts',T,'CovarianceMatrix',lam{zzz}*P{zzz},'NoiseVariance',lam{zzz},... 'EstimationInfo',es{zzz},'MaxSize',Max,... 'OutputName',pvget(data,'OutputName'),'OutputUnit',pvget(data,'OutputUnit')); th{zzz} = pvset(th{zzz},'idmodel',idm{zzz}); th{zzz} = timemark(th{zzz}); end %-------------------------------------------------------------------------- function [s,ln] = sumcell(y,p,N) ln = 0; s = 0; for kexp = 1:length(y) y1 = y{kexp}; s = s+y1(p:N(kexp))'*y1(p:N(kexp)); ln = ln + length(y1); end
github
epilepsyecosystem/1stplace_notsorandomanymore-master
ar_prediction_error.m
.m
1stplace_notsorandomanymore-master/Andriy/code/ar_prediction_error.m
1,304
utf_8
53bedeca00d334945ab9cbc48afad186
function fit_error=ar_prediction_error(model_data,test_data,ar_order) model_data = remove_infsnans(model_data); test_data = remove_infsnans(test_data); if(range(model_data)<1e-5) fit_error (1:ar_order) = 50; else if (range(test_data)<1e-5) fit_error(1:ar_order) = 100; else if size(model_data,2)>size(model_data,1) %These functions need column matrices model_data=model_data'; end if size(test_data,2)>size(test_data,1) test_data=test_data'; end m = ar(model_data,ar_order,'YW'); for zzz=1:size(m,2) fit_error(zzz) = compare_new(test_data,m{zzz}); end end end function data = remove_infsnans(data) NANs = find(isnan(data)); for i=1:length(NANs) if(NANs(i)==1) data(1) = data(2); else if(NANs(i)==length(data)) data(end) = data(end-1); else data(NANs(i)) = mean([data(NANs(i)-1);data(NANs(i)+1)]); end end end NANs = find(isinf(data)); for i=1:length(NANs) if(NANs(i)==1) data(1) = data(2); else if(NANs(i)==length(data)) data(end) = data(end-1); else data(NANs(i)) = mean([data(NANs(i)-1);data(NANs(i)+1)]); end end end
github
epilepsyecosystem/1stplace_notsorandomanymore-master
EEG_subbands.m
.m
1stplace_notsorandomanymore-master/Andriy/code/EEG_subbands.m
325
utf_8
33a6c3fb719a73bc1453d3d0e59a029b
% Function to calculate power in sub-bands from freq_range function [PSD_band] = EEG_subbands(PSD,freq,freq_range) i1 = find(freq==freq_range(1)); % f1 hertz index i2 = find(freq==freq_range(2)); % f2 Hz index PSD_band = trapz(PSD(i1+1:i2,:)); % Range of PSD %**********************************************
github
epilepsyecosystem/1stplace_notsorandomanymore-master
EEG_PSD_features.m
.m
1stplace_notsorandomanymore-master/Andriy/code/EEG_PSD_features.m
664
utf_8
89547b991537897c82241a13b45fc6f1
%Function to extract frequency and power features for EEG classifier method function [peak,peak_freq] = EEG_PSD_features(spectrum,freq,f1,f2) %*************** Find dominant peak in range F1-F2 ***************************** i1 = find(freq==f1); % f1 hertz index i2 = find(freq==f2); % f2 Hz index spec = spectrum(i1:i2,:); %of 2-20HZ %power [peak,w] = max(spec,[],1); %Find the peak and index of each peak for each psd for each epoch. Treats each column in spectrum as a vector and reurning max in each peak = peak+eps; % Add LSB to avoid errors peak_freq = freq(w+i1); %Find freqency of dominant peak
github
epilepsyecosystem/1stplace_notsorandomanymore-master
nonlinear_energy.m
.m
1stplace_notsorandomanymore-master/Andriy/code/nonlinear_energy.m
167
utf_8
d4ed89a03ce6bf04f97f0538581f426c
% Function to calculate nonlinear energy function [N,x] = nonlinear_energy(epoch) a = epoch.*epoch; x = a(2:end-1) - epoch(1:end-2).*epoch(3:end); N = mean(x);
github
epilepsyecosystem/1stplace_notsorandomanymore-master
spectral_entropy_g.m
.m
1stplace_notsorandomanymore-master/Andriy/code/spectral_entropy_g.m
350
utf_8
77b9b0be6e5d7693f626a3b75c1498e5
% EEG Spectral entropy per epoch function H = spectral_entropy_g(spectrum,w) flag=0; psd = spectrum; pdf = zeros(size(spectrum)); if(flag==1) for i = 1:1:w pdf(:,i) = psd(:,i)./(sum(psd(:,i))+eps); end elseif(flag==0) pdf = psd./(repmat(sum(psd,1),size(psd,1),1)+eps); end H = -(sum(pdf.*log2(pdf+eps)));
github
franciscozuccala/android-voip-master
echo_diagnostic.m
.m
android-voip-master/configuration/trunk/third_party/speex/libspeex/echo_diagnostic.m
2,076
utf_8
8d5e7563976fbd9bd2eda26711f7d8dc
% Attempts to diagnose AEC problems from recorded samples % % out = echo_diagnostic(rec_file, play_file, out_file, tail_length) % % Computes the full matrix inversion to cancel echo from the % recording 'rec_file' using the far end signal 'play_file' using % a filter length of 'tail_length'. The output is saved to 'out_file'. function out = echo_diagnostic(rec_file, play_file, out_file, tail_length) F=fopen(rec_file,'rb'); rec=fread(F,Inf,'short'); fclose (F); F=fopen(play_file,'rb'); play=fread(F,Inf,'short'); fclose (F); rec = [rec; zeros(1024,1)]; play = [play; zeros(1024,1)]; N = length(rec); corr = real(ifft(fft(rec).*conj(fft(play)))); acorr = real(ifft(fft(play).*conj(fft(play)))); [a,b] = max(corr); if b > N/2 b = b-N; end printf ("Far end to near end delay is %d samples\n", b); if (b > .3*tail_length) printf ('This is too much delay, try delaying the far-end signal a bit\n'); else if (b < 0) printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\n'); else printf ('Delay looks OK.\n'); end end end N2 = round(N/2); corr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2))))); corr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end))))); [a,b1] = max(corr1); if b1 > N2/2 b1 = b1-N2; end [a,b2] = max(corr2); if b2 > N2/2 b2 = b2-N2; end drift = (b1-b2)/N2; printf ('Drift estimate is %f%% (%d samples)\n', 100*drift, b1-b2); if abs(b1-b2) < 10 printf ('A drift of a few (+-10) samples is normal.\n'); else if abs(b1-b2) < 30 printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\n'); else printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\n'); end end end acorr(1) = .001+1.00001*acorr(1); AtA = toeplitz(acorr(1:tail_length)); bb = corr(1:tail_length); h = AtA\bb; out = (rec - filter(h, 1, play)); F=fopen(out_file,'w'); fwrite(F,out,'short'); fclose (F);
github
Wendroff/ModalTheory-master
select_script.m
.m
ModalTheory-master/Supplementary_Material_AMR-13-1059/Theofilis/select_script.m
22,698
utf_8
2a2588be03a779c4d9bb79aba2525962
function output = select_script(run) % This file contains Matlab codes for computing the eigenvalue % problem corresponding to the 2D Helmholtz, and the 2D and 1D LNS % equations. These are parts of the tutorial: % "Modal Stability Theory" by Matthew Juniper, Ardeshir Hanifi, % and Vassilios Theofilis, published in Applied Mechanics Reviews, % 66(2), 2014. % % (c) 2014 vt_productions % The main programs are % % Helmholtz2D.m : solve the 2D Helmholtz EVP % EVP2D : set up and solve the 2d BiGlobal EVP % LNSE1D : solve the EVP pertinent to the 1d LNSE % % To execute, replace the argument 'run' by the string obtained % from the corresponding function name, sans the suffix. switch run case 'Helmholtz2D' output = Helmholtz2D(); case 'EVP2D' output = EVP2D(); case 'LNSE1D' output = LNSE1D(); otherwise warning('AMR:nodemo', 'No such demo'); end end function output = Helmholtz2D() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Helmholtz2D: Solve the 2D Helmholtz EVP % % % % (c) 2014 vt_productions % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear; % Set number of discretization nodes in the x and y spatial directions Nx=48; Ny=48; % Set grids and collocation derivative matrices in the resolved spatial % directions Lx = 1; Ly = 1; [xgl,d1y,d2y] = set_chebyshev_derivative_matrices(Ny); [xgrid,d1x,d2x] = map_y( 0., Lx, xgl, d1y, d2y); [ygrid,d1y,d2y] = map_y( 0., Ly, xgl, d1y, d2y); % Form the EVP and impose boundary conditions [ A ] = form_Helmholtz_2D( Nx, Ny, d2x, d2y); [ A ] = impose_Helmholtz_BCs( Nx, Ny, A ); % Solve the EVP using the QZ algorithm (full spectrum computation) [V,lambda]=eig(A); % Extract the eigenvalues omegar=real(diag(lambda)); omegai=imag(diag(lambda)); % Plot the results [phi] = plot_Helmholtz2D(-diag(lambda)/pi^2,V,ygrid,xgrid,Lx,Ly); output = {}; end function output = EVP2D() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % EVP2D: Set up and solve the 2d BiGlobal EVP % % % % (c) 2014 vt_productions % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear; % Set number of discretization nodes in the x and y spatial directions Nx=4; Ny=128; % Set flow parameters Re = 10000; alpha = 1; % JHT test case: OMEGAR=0.23752649, OMEGAI=0.00373967 % Re=7500; % alpha=1; % CHQZ test case: OMEGAR=0.24989154, OMEGAI=0.00223497 Lx=2*pi/alpha; % Set grids and collocation derivative matrices in the resolved spatial % directions [xgrid]=set_x_grid(Nx); [d1x,d2x]=set_fourier_derivative_matrices(Nx); [xgrid,d1x,d2x] = map_x( 0., Lx, xgrid, d1x, d2x); [xgl,d1y,d2y] = set_chebyshev_derivative_matrices(Ny); % Form the EVP and impose boundary conditions [ A, B ] = form_EVP2d( Nx, Ny, Re, xgl, d1x, d2x, d1y, d2y); [ A, B ] = impose_BCs_EVP2d( Nx, Ny, d1y, A, B ); % Solve the EVP using the QZ algorithm (full spectrum computation) [V,lambda]=eig(A,B,'qz'); % Extract the eigenvalues omegar=real(diag(lambda)); omegai=imag(diag(lambda)); % Plot the results plot_EVP2d(1i*diag(lambda),V,xgl,xgrid,Re,alpha) output = {}; end function output = LNSE1D() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % LNSE1D: Solve the EVP pertinent to the 1d LNSE % % % % (c) 2014 vt_productions % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clear all; % Set number of discretization nodes in the y spatial direction Ny=128; % Set flow and parameters flow = 'SL'; % Set grid and collocation derivative matrices [xgl,d1y,d2y] = set_chebyshev_derivative_matrices(Ny); % If necessary, map the domain [ y, d1y, d2y ] = mapping ( flow, xgl, d1y, d2y ); % Define the base flow switch flow case 'PPF' [ U, Uy, Uyy ] = baseFlow_PPF( y ); % Th94 test case: OMEGAR=0.23752649, OMEGAI=0.00373967 Re = 10000; alpha = 1; beta = 0; % CHQZ test case: OMEGAR=0.24989154, OMEGAI=0.00223497 % Re=7500; % alpha=1; % beta=1; case 'SL' [ U, Uy, Uyy ] = baseFlow_SL( y ); % Michalke case Re=1e5; alpha=0.4446; beta=0; otherwise disp('Flow Case Not Implemented') pause end % Form the EVP [ A, B ] = form_LNSE1d(Re, alpha, Ny, U, Uy, d1y, d2y); % Impose BCs [ A, B ] = impose_BCs_LNSE1d( Ny, A, B ); % Solve the EVP using the QZ algorithm (full spectrum computation) [V,lambda]=eig(A,B,'qz'); % Extract the eigenvalues omegar=real(diag(lambda)); omegai=imag(diag(lambda)); % Plot the results plot_LNSE1d(flow,1i*lambda,V,y,Re,alpha,beta) output = {}; end function [xgl, d1y, d2y] = set_chebyshev_derivative_matrices(Ny) % SET_CHEBYSHEV_DERIVATIVE_MATRICES: Define matrices for % Chebyshev spectral collocation differentiation % INPUTS % Ny: number of Chebyshev Gauss-Lobatto collocation nodes % % OUTPUTS % xgl: Chebyshev Gauss-Lobatto points % d1y: 1st CGL collocation derivative matrix % d2y: 2nd CGL collocation derivative matrix % % (c) 2014 vt_productions for j=0:Ny jj=j+1; xgl(jj)=cos(j*pi/Ny); end for j=0:Ny jj=j+1; if(j==0 | j==Ny ) cj=2.; else cj=1.; end for k=0:Ny kk=k+1; if(k==0 | k==Ny ) ck=2.; else ck=1.; end if(j~=k) d1y(jj,kk)=(cj/ck)*(-1)^(j+k)/(xgl(jj)-xgl(kk)); end end end for j=1:Ny-1 jj=j+1; d1y(jj,jj)=-xgl(jj)/(2.*(1.-xgl(jj)^2)); end d1y(1,1)=(2.*Ny^2+1.)/6.; d1y(Ny+1,Ny+1)=-d1y(1,1); d2y = d1y*d1y; end function [ ygrid, d1y, d2y ] = map_y( yin, yout, ygrid, d1y, d2y ) % MAP_Y: Linearly map a non-periodic domain % % INPUTS % yin: start of mapped domain % yout: end of mapped domain % % INPUTS/OUTPUTS % ygrid, d1y, d2y: mapped domain (output) % % (c) 2014 vt_productions a = (yout - yin )/2.; b = (yin + yout )/2.; ygrid = a * ygrid + b; d1y = 1./a * d1y; d2y = d1y * d1y; end function [ A ] = form_Helmholtz_2D( Nx, Ny, d2x, d2y) % FORM_Helmholtz_2D: Form the 2D Laplacian % % INPUTS % Nx, Ny: number of Chebyshev collocation nodes % % d2x: Chebyshev Gauss Lobatto collocation derivative matrix % d2y: Chebyshev Gauss Lobatto collocation derivative matrix % % OUTPUTS % A: LHS of the discretized Laplacian operator in 2D % % (c) 2014 vt_productions Ix=eye(Nx+1); Iy=eye(Ny+1); A = kron(d2x,Iy)+kron(Ix,d2y); end function [ A ] = impose_Helmholtz_BCs( Nx, Ny, A ) % impose_Helmholtz_BCs: Impose homogeneous Dirichlet BCs % % INPUTS % Nx, Ny: number of Chebyshev collocation nodes % % INPUT/OUTPUT % A: LHS of the discretized Helmholtz operator in 2D % % (c) 2014 vt_productions % .. phi=0 at y = Ly.. for i=1:Nx+1 A(i*(Ny+1),:)=0; A(i*(Ny+1),i*(Ny+1))=1.; end % .. phi=0 at y = 0.. for i=1:Nx+1 A(i+(i-1)*Ny,:)=0; A(i+(i-1)*Ny,i+(i-1)*Ny)=1.; end % .. phi=0 at x = Lx.. for i=2:Ny A(i,:)=0; A(i,i)=1.; end % .. phi=0 at x = 0.. for i=2:Ny A(Nx*(Ny+1)+i,:)=0; A(Nx*(Ny+1)+i,Nx*(Ny+1)+i)=1.; end end function [phi]=plot_Helmholtz2D(eigval,eigvec,y,x,Lx,Ly) % plot_Helmholtz2D plots the eigenfunctions computed by Helmholtz2D Ny=length(y); Nx=length(x); NN=Nx*Ny; [X,Y]=meshgrid(x,y); x1=linspace(0,Lx,50); y1=linspace(0,Ly,50); [X1,Y1]=meshgrid(x1,y1); disp('Right click to pick the mode. Left click to stop'); button=1; while button==1 figure(1) plot(real(eigval),imag(eigval),'o'); axis([30,40,-1,1]); axis('square'); ylabel('-imag(\lambda)/\pi^2') xlabel('-real(\lambda)/\pi^2') % pick the eigenfunction [xp,yp,button] = ginput(1); a=xp+sqrt(-1)*yp; [c,locate]=min(abs(eigval-a)); % extract the eigenfunction phi=reshape(eigvec(1:NN,locate),Ny,Nx); % interpolate on a finer grid % phi=interp2([X X],[Y Y],[phi phi],X1,Y1,'spline'); phi=phi/max(max(phi)); vecp=[0 0.2 0.4 0.6 0.8 1]; figure(2) contour(X,Y,phi,vecp,'k-'); axis('square'); hold on; vecm=[-0.2 -0.4 -0.6 -0.8 -1]; contour(X,Y,phi,vecm,'k-.'); hold off; end end function [ xgrid ] = set_x_grid( Nx ) % SET_X_GRID: Define a periodic domain and discretize it % using Fourier spectral collocation % INPUTS % Nx: number of Fourier collocation nodes % OUTPUTS % xgrid: periodic domain % % (c) 2014 vt_productions for jj=1:Nx j=jj-1; xgrid(jj)=2*pi*j/Nx; end end function[d1x,d2x] = set_fourier_derivative_matrices(Nx) % SET_FOURIER_DERIVATIVE_MATRICES: Define matrices for % Fourier spectral collocation differentiation % INPUTS % Nx: number of Fourier collocation nodes % OUTPUTS % d1x: 1st Fourier collocation derivative matrix % d2x: 2nd Fourier collocation derivative matrix % % (c) 2014 vt_productions for jj = 1:Nx j=jj-1; for kk = 1:Nx k=kk-1; if(j==k) d1x(kk,jj)=0.; d2x(kk,jj)=-Nx^2/12-1./6; else d1x(kk,jj)=0.5*(-1)^(k+j)*cot((k-j)*pi/Nx); d2x(kk,jj)=-0.5*(-1)^(k+j)/sin((k-j)*pi/Nx)^2; end end end end function [ xgrid, d1x, d2x ] = map_x( xin, xout, xgrid, d1x, d2x ) % MAP_X: Linearly map a periodic domain % % INPUTS % xin: start of mapped domain % xout: end of mapped domain % % INPUTS/OUTPUTS % xgrid, d1x, d2x: mapped domain (output) % % (c) 2014 vt_productions L_x=(xout-xin); metric = 2.*pi/L_x; xgrid = (L_x/2./pi) * xgrid + xin; d1x = metric * d1x; d2x = d1x * d1x; end function [ A, B ] = form_EVP2d( Nx, Ny, Re, xgl, d1x, d2x, d1y, d2y) % FORM_EVP2D: Form the Linearized Navier-Stokes Equations in 2D % % INPUTS % Nx: number of Fourier collocation nodes % d1x, d2x: Fourier collocation derivative matrices % Ny: number of Chebyshev collocation nodes % xgl: Chebyshev Gauss Lobatto nodes % d1y, d2y: Chebyshev Gauss Lobatto collocation derivative matrices % U, Uy: Streamwise velocity of plane Poiseuille flow and 1st derivative % % OUTPUTS % A: LHS of the discretized LNSE operator in 2D % B: RHS of the discretized LNSE operator in 2D, % including an artificial compressibility parameter: % epsilon=1e-8 % % (c) 2014 vt_productions Ix=eye(Nx); Iy=eye(Ny+1); U=1.-xgl.^2; Uy=-2*xgl; epsilon = 1e-8; Lop=1/Re*(kron(d2x,Iy)+kron(Ix,d2y))-kron(Ix,diag(U))*kron(d1x,Iy); A11=Lop; A12=-kron(Ix,diag(Uy)); A13=-kron(d1x,Iy); A1=horzcat(A11,A12,A13); A21=zeros(Nx*(Ny+1)); A22=Lop; A23=-kron(Ix,d1y); A2=horzcat(A21,A22,A23); A31=kron(d1x,Iy); A32=kron(Ix,d1y); A33=zeros(Nx*(Ny+1)); A3=horzcat(A31,A32,A33); A=vertcat(A1,A2,A3); B11=eye(Nx*(Ny+1)); B12=zeros(Nx*(Ny+1)); B13=zeros(Nx*(Ny+1)); B1=horzcat(B11,B12,B13); B21=zeros(Nx*(Ny+1)); B22=eye(Nx*(Ny+1)); B23=zeros(Nx*(Ny+1)); B2=horzcat(B21,B22,B23); B31=zeros(Nx*(Ny+1)); B32=zeros(Nx*(Ny+1)); %B33=zeros(Nx*(Ny+1)); B33=epsilon*eye(Nx*(Ny+1)); B3=horzcat(B31,B32,B33); B=vertcat(B1,B2,B3); end function [ A, B ] = impose_BCs_EVP2d( Nx, Ny, d1y, A, B ) % % IMPOSE_BCS Impose Boundary Conditions on the discretized LNSE operator. % Impose BCs on perturbation velocity components only, none on pressure % % INPUTS/OUTPUTS % A: LHS of the discretized LNSE operator in 2D % B: RHS of the discretized LNSE operator in 2D % % (c) 2014 vt_productions OffSet = Nx * (Ny+1); % .. u=0 at y = +1.. for i=1:Nx A(i*(Ny+1)+0*OffSet,:)=0; B(i*(Ny+1)+0*OffSet,:)=0; A(i*(Ny+1)+0*OffSet,i*(Ny+1)+0*OffSet)=1.; end % .. u=0 at y = -1.. for i=1:Nx A(i+(i-1)*Ny+0*OffSet,:)=0; B(i+(i-1)*Ny+0*OffSet,:)=0; A(i+(i-1)*Ny+0*OffSet,i+(i-1)*Ny+0*OffSet)=1.; end % .. v=0 at y = +1.. for i=1:Nx A(i*(Ny+1)+1*OffSet,:)=0; B(i*(Ny+1)+1*OffSet,:)=0; A(i*(Ny+1)+1*OffSet,i*(Ny+1)+1*OffSet)=1.; end % .. v=0 at y = -1.. for i=1:Nx A(i+(i-1)*Ny+1*OffSet,:)=0; B(i+(i-1)*Ny+1*OffSet,:)=0; A(i+(i-1)*Ny+1*OffSet,i+(i-1)*Ny+1*OffSet)=1.; end end function plot_EVP2d(eigval,eigvec,y,x,Re,alpha) % plot_EVP2d plots the eigenfunctions computed by EVP2d Ny=length(y); Nx=length(x); NN=Nx*Ny; [X,Y]=meshgrid(x,y); lambda=2*pi/alpha; x1=linspace(0,x(end)+lambda,2*Nx*5); disp('extend of x-domain'),x(end) disp('# of points'),2*Nx*5 [X1,Y1]=meshgrid(x1,y); disp('Right click to pick the mode. Left click to stop'); button=1; while button==1 figure(1) plot(real(eigval),imag(eigval),'o',[-100 100],[0 0],'r-'); axis([0,1,-1,0.1]);axis('square'); title(strcat({'Re= '},{num2str(Re)},{' , alpha= '},{num2str(alpha)})); ylabel('imag(\omega)') xlabel('real(\omega)') % pick the eigenfunction [xp,yp,button] = ginput(1); a=xp+sqrt(-1)*yp; [c,locate]=min(abs(eigval-a)); % extract different components of eigenfunction u=reshape(eigvec(1:NN,locate),Ny,Nx); v=reshape(eigvec(NN+1:2*NN,locate),Ny,Nx); p=reshape(eigvec(2*NN+1:3*NN,locate),Ny,Nx); % interpolate on a finer grid u=interp2([X X+lambda],[Y Y],[u u],X1,Y1,'spline'); v=interp2([X X+lambda],[Y Y],[v v],X1,Y1,'spline'); p=interp2([X X+lambda],[Y Y],[p p],X1,Y1,'spline'); % scale with respective maxima u = u/max(max(abs(u))); v = v/max(max(abs(v))); p = p/max(max(abs(p))); %define contours to plot vecp = [+0.1 +0.2 +0.3 +0.4 +0.5 +0.6 +0.7 +0.8 +0.9 +1]; vecm = [-0.1 -0.2 -0.3 -0.4 -0.5 -0.6 -0.7 -0.8 -0.9 -1]; % u figure(2) [C,h] = contour(X1/lambda,Y1,real(u),vecp,'k-'); hold on; [C,h] = contour(X1/lambda,Y1,real(u),vecm,'k:'); [C,h] = contour(X1/lambda,Y1,real(u),[0 0],'k.'); hold off; axis('square'); % [C,h] = contourf(X1/lambda,Y1,real(u),10); % set(h,'LineStyle','none') % colormap('jet'); title('u'); ylabel('y'); xlabel('x/\lambda'); % % v figure(3) [C,h] = contour(X1/lambda,Y1,real(v),vecp,'k-'); hold on; [C,h] = contour(X1/lambda,Y1,real(v),vecm,'k:'); [C,h] = contour(X1/lambda,Y1,real(v),[0 0],'k.'); hold off; axis('square'); % [C,h] = contourf(X1/lambda,Y1,real(v),10); % set(h,'LineStyle','none') % colormap('jet'); title('v'); ylabel('y'); xlabel('x/\lambda'); % Pressure figure(4) [C,h] = contour(X1/lambda,Y1,real(p),vecp,'k-'); hold on; [C,h] = contour(X1/lambda,Y1,real(p),vecm,'k:'); [C,h] = contour(X1/lambda,Y1,real(p),[0 0],'k.'); hold off; axis('square'); % [C,h] = contourf(X1/lambda,Y1,real(p),10); % set(h,'LineStyle','none') % colormap('jet'); title('p'); ylabel('y'); xlabel('x/\lambda'); end end function [ y, d1, d2 ] = mapping ( flow_case, y, d1, d2 ) % mapping: Map the [-1,1] CGL domain onto [-y_inf,y_inf]. % Compute the metric of the transformation and modify % first and second derivative matrices accordingly. % Plane Poiseuille flow and tanh(y) profiles implemented % % INPUT % flow_case: PPF and free shear layer (SL) model % % INPUTS/OUTPUTS % y, d1, d2: CGL grid and collocation derivative matrices % % (c) 2014 vt_productions metric(:,2) = zeros(size(y)); switch flow_case case 'PPF' eta = y; metric(:,1) = ones(size(y)); metric(:,2) = zeros(size(y)); case 'SL' len = 10; s_inf = 15; s = (len/s_inf)^2; for i=1:length(y) eta(i) = -len*y(i)/sqrt(1.+s-y(i)^2); % eta(i) = len*sinh(-s*y(i))/sinh(s); end for i=1:length(y) metric(i,1) = -sqrt(1.+s)*len^2/(len^2+eta(i)^2)^(3./2); metric(i,2) = 3*len^2*sqrt(1.+s)*eta(i)/(len^2+eta(i)^2)^(5./2); % metric(i,1) = -(1./len/s)*sinh(s)/sqrt(1.+(sinh(s)*eta(i)/len)^2); % metric(i,2) = (1./len^3/s)*eta(i)*sinh(s)^3/sqrt(1.+(sinh(s)*eta(i)/len)^2)^3; end otherwise disp('Flow Case Not Implemented') pause end y = eta; for i=1:length(y) d1(i,:) = metric(i,1) * d1(i,:); d2(i,:) = metric(i,1)^2 * d2(i,:) + metric(i,2) * d1(i,:); end %d2 = d1*d1; end function [ U, Uy, Uyy ] = baseFlow_PPF( y ) % baseFlow_PPF: Define the parabolic velocity profile and its derivatives % % INPUTS % y: Chebyshev Gauss-Lobatto points % OUTPUTS % U, Uy, Uyy: Streamwise velocity, first and second derivatives % % (c) 2014 vt_productions U=1-y.^2; Uy=-2*y; Uyy=-2.; end function [ U, Uy, Uyy ] = baseFlow_SL( y ) % baseFlow_SL: Define the hyperbolic tangent velocity profile and its derivatives % % INPUTS % y: Chebyshev Gauss-Lobatto points % OUTPUTS % U, Uy, Uyy: Streamwise velocity, first and second derivatives % % (c) 2014 vt_productions U=tanh(y); for i=1:length(y) Uy(i)=1.-tanh(y(i))^2; Uyy(i)=-2.*tanh(y(i))*(1.-tanh(y(i))^2); end end function [ A, B ] = form_LNSE1d(Re, alpha, Ny, U, Uy, d1y, d2y) % FORM_LNSE1D: Form the Linearized Navier-Stokes Equations in 1D % INPUTS % Re, alpha: Reynolds number and streamwise wavenumber % Ny: number of Chebyshev collocation nodes % d1y, d2y: Chebyshev Gauss Lobatto collocation derivative matrices % U, Uy: Streamwise baseflow velocity and its 1st derivative % OUTPUTS % A: LHS of the discretized LNSE operator in 1D % B: RHS of the discretized LNSE operator in 1D, % including an artificial compressibility parameter: % epsilon=1e-8 % (c) 2014 vt_productions epsilon = 1e-8; Lop=1/Re*d2y-alpha^2/Re*eye(Ny+1,Ny+1)-1i*alpha*diag(U); A11=Lop; A12=-diag(Uy); A13=-1i*alpha*eye(Ny+1,Ny+1); A1=horzcat(A11,A12,A13); A21=zeros(Ny+1); A22=Lop; A23=-d1y; A2=horzcat(A21,A22,A23); A31=1i*alpha*eye(Ny+1,Ny+1); A32=d1y; A33=zeros(Ny+1); A3=horzcat(A31,A32,A33); A=vertcat(A1,A2,A3); B11=eye(Ny+1); B12=zeros(Ny+1); B13=zeros(Ny+1); B1=horzcat(B11,B12,B13); B21=zeros(Ny+1); B22=eye(Ny+1); B23=zeros(Ny+1); B2=horzcat(B21,B22,B23); B31=zeros(Ny+1); B32=zeros(Ny+1); %B33=epsilon*eye(Ny+1); B33=zeros(Ny+1); B3=horzcat(B31,B32,B33); B=vertcat(B1,B2,B3); end function [ A, B ] = impose_BCs_LNSE1d( Ny, A, B ) % IMPOSE_BCS Impose Boundary Conditions on the discretized LNSE operator. % Impose BCs on perturbation velocity components only, none on pressure % INPUTS/OUTPUTS % A: LHS of the discretized LNSE operator in 1D % B: RHS of the discretized LNSE operator in 1D % % (c) 2014 vt_productions OffSet = Ny+1; % .. u=0 at y = +1.. A(Ny+1,:)=0; B(Ny+1,:)=0; A(Ny+1,Ny+1)=1.; % .. u=0 at y = -1.. A(1,:)=0; B(1,:)=0; A(1,1)=1.; % .. v=0 at y = +1.. A(Ny+1+1*OffSet,:)=0; B(Ny+1+1*OffSet,:)=0; A(Ny+1+1*OffSet,Ny+1+1*OffSet)=1.; % .. v=0 at y = -1.. A(1+1*OffSet,:)=0; B(1+1*OffSet,:)=0; A(1+1*OffSet,1+1*OffSet)=1.; end function plot_LNSE1d(flow,eigval,eigvec,y,Re,alpha,beta) %eglist=find(abs(eigval)<10) %eigval=eigval(eglist);pause %eigvec=eigvec(:,eglist) N=length(y); % Choose eigenvalue to plot disp('Right click to pick the mode. Left click to stop'); button=1; while button==1 figure(1) plot(real(eigval),imag(eigval),'bo',[0 0.5],[0 0],'r-'); axis('square'); switch flow case 'PPF' ylim([-1,0.1]); case 'SL' ylim([-1,1]); end title(strcat({'Re= '},{num2str(Re)},{' , alpha= '},{num2str(alpha)},... {' , beta= '},{num2str(beta)})); ylabel('imag(\omega)') xlabel('real(\omega)') %ylim([-1,0.1]); % pick the eigenfunction [xp,yp,button] = ginput(1); a=xp+sqrt(-1)*yp; [c,locate]=min(abs(eigval-a)); % extract different components of eigenfunction u=eigvec(1:N,locate); v=eigvec(N+1:2*N,locate); p=eigvec(2*N+1:3*N,locate); u=u/max(max(abs(u))); v=v/max(max(abs(u))); p=p/max(max(abs(p))); figure(2) plot(abs(u),y,abs(v),y,abs(p),y); axis('square'); legend('abs(u)','abs(v)','abs(p)') title(strcat({'Re= '},{num2str(Re)},{' , alpha= '},{num2str(alpha)},... {', omega= '},{num2str(eigval(locate))})); ylabel('y') end dd = {y, abs(u), abs(v), abs(p)}; save eigfunc dd end function [ der1x, der2x ] = calculate_ddx( Nx, d1x, d2x, x ) %CALCULATE_DDX: Use Fourier spectral collocation to compute % 1st and 2nd derivatives of a periodic function % INPUTS % Nx: number of (mapped) Fourier collocation nodes % discretizing the periodic domain (not passed as an argument) % x: periodic function defined on the (mapped) domain % d1x: 1st Fourier collocation derivative matrix, % modified by the mapping transformation % d2x: 2nd Fourier collocation derivative matrix, % modified by the mapping transformation % OUTPUTS % der1x:1st derivative of the periodic function x % der2x:2nd derivative of the periodic function x % % (c) 2014 vt_productions for j =1:Nx der1x(j)=dot(d1x(j,:),x); der2x(j)=dot(d2x(j,:),x); end end function [ der1y, der2y ] = calculate_ddy( Ny, d1y, d2y, y ) %CALCULATE_DDY: Use Chebyshev spectral collocation to compute % 1st and 2nd derivatives of a non-periodic function % INPUTS % Ny: number of (mapped) Chebyshev collocation nodes % discretizing the non-periodic domain (not passed as an argument) % y: periodic function defined on the (mapped) domain % d1y: 1st Chebyshev collocation derivative matrix, % modified by the mapping transformation % d2y: 2nd Chebyshev collocation derivative matrix, % modified by the mapping transformation % OUTPUTS % der1y:1st derivative of the non-periodic function x % der2y:2nd derivative of the non-periodic function x for j =1:Ny+1 der1y(j)=dot(d1y(j,:),y); der2y(j)=dot(d2y(j,:),y); end end function [ ygrid ] = set_y_grid( Ny ) % SET_Y_GRID: Define the standard Chebyshev Gauss-Lobatto (CGL) % spectral collocation points % INPUTS % Ny: number of CGL collocation nodes % % OUTPUTS % ygrid: CGL domain % (c) 2014 vt_productions for jj=1:Ny+1 j=jj-1; ygrid(jj)=cos(j*pi/Ny); end end
github
Wendroff/ModalTheory-master
select_script.m
.m
ModalTheory-master/Supplementary_Material_AMR-13-1059/Juniper/select_script.m
29,508
utf_8
d243aa025bdaaad6fc2faeb9b35391b9
function output = select_script(run, param) % This file contains Matlab codes for local stability analysis % using analytical dispersion relations for plug flows. % These are parts of the tutorial: % "Modal Stability Theory" by Matthew Juniper, Ardeshir Hanifi, % and Vassilios Theofilis, published in Applied Mechanics Reviews, % 66(2), 2014. % These dispersion relations are adapted from two JFM papers: % The Effect of Confinement on the Stability of Two-dimensional Shear flows % M. Juniper % Journal of Fluid Mechanics, 565, 171-195 (2006) % The full impulse response of two-dimensional shear flows and implications for confinement % M. Juniper % Journal of Fluid Mechanics, 590, 163-185 (2007) % % (c) Matthew Juniper 2013 % The main programs are % % check_fun_eval_c : Evaluate c1 and c2, given k, and check it % against the dispersion relation % script_click.m : Find nearest saddle point % script_groupvel_001 : Perform a temporal stability analysis % and plot the phase and group velocities % of the permitted waves. % script_spatemp_001 : Perform a spatio-temporal stability analysis % script_spatemp_002 : Perform a spatio-temporal stability analysis % script_spatemp_003 : Perform a spatio-temporal stability analysis % script_spatial_001 : Perform a spatial stability anaylsis on a % single shear layer % script_spatial_002 : Perform a spatial stability anaylsis on a % single shear layer both directly and via % Gaster's transformation. % script_temporal_001 : Perform a temporal stability analysis % script_temporal_002 : Perform a temporal stability analysis for % all the dispersion relations % % To execute, replace the argument 'run' by the string obtained % from the corresponding function name, sans the suffix. % fun_eval_D_* holds the dispersion relations. % fun_eval_c_* solves the dispersion relations explicitly. % fun_eval_D.m and fun_eval_c.m are gatekeeper functions. % fun_eval_k.m uses an iterative method to find k(w). % fun_eval_w.m uses an explicit method to find w(k). % fun_eval_dwdk.m estimates the group velocity with a finite difference method. % fun_eval_dwdk0.m uses an interative method to find k(w) at which dw/dk = 0. % % Within fun_eval_c_*, the stencil changes Matlab's default ordering of the two solutions to c(k) in order to help visualization. switch run case 'check_fun_eval_c' output = check_fun_eval_c(); case 'script_click' output = script_click(param); case 'script_groupvel_001' output = script_groupvel_001(); case 'script_spatemp_001' output = script_spatemp_001(); case 'script_spatemp_002' output = script_spatemp_002(); case 'script_spatemp_003' output = script_spatemp_003(); case 'script_spatial_001' output = script_spatial_001(); case 'script_spatial_002' output = script_spatial_002(); case 'script_temporal_001' output = script_temporal_001(); case 'script_temporal_002' output = script_temporal_002(); otherwise warning('AMR:nodemo', 'No such demo'); end end function output = check_fun_eval_c() % Evaluate c1 and c2, given k, and check it against the dispersion relation % (c) Matthew Juniper 2013 clear clc % Input the parameters param.L = -0.9; param.S = 1; param.Sig = 1.3; param.h = 2.32; % Input the value of k k = complex(2*rand(1),0); % Create a cell array containing the names of the disp. rels to check scheme{1} = 'single'; scheme{2} = 'unconf_jetwake_sin'; scheme{3} = 'unconf_jetwake_var'; scheme{4} = 'conf_jetwake_sin'; scheme{5} = 'conf_jetwake_var'; % Cycle through the dispersion relations to check them for nn = 1:length(scheme) param.scheme = scheme{nn}; % Calculate omega1 and omega2 (w1 and w2 for short) [c1,c2] = fun_eval_c(param,k); w1 = c1*k; w2 = c2*k; % Calculate D1 and D2 D1 = fun_eval_D(param,k,w1); D2 = fun_eval_D(param,k,w2); % Check that both are zero to machine precision if (abs(D1)<10*eps)&&(abs(D2)<10*eps) disp(['Correct dispersion relation for ',param.scheme]) else disp(['Incorrect dispersion relation for ',param.scheme]) beep end end output = param; end function output = script_click(param) % With param already in memory, % click on a point in the figure and find the nearest saddle point. % Determine whether it is Convectively or Absolutely unstable. % (c) Matthew Juniper 2013 % Click on a point on the figure click = ginput(1); k_init = complex(click(1),click(2)); tol = 10^-6; % Converge to the nearest point, where dwdk = 0 [k,w] = fun_eval_dwdk0(param,k_init,tol); % Plot the point accurately % Determine whether absolutely or convectively unstable if imag(w) > 0 disp('Absolutely unstable') plot(k,'ro','MarkerFaceColor','r') elseif imag(w) < 0 disp('Convectively unstable') plot(k,'go','MarkerFaceColor','g') else disp('Marginally unstable') plot(k,'yo','MarkerFaceColor','y') end output = {}; end function output = script_groupvel_001() % Perform a temporal stability anaylsis % and plot the phase and group velocities of the permitted waves. % (c) Matthew Juniper 2013 % Set the dispersion relation param.scheme = 'single'; % Set the parameters param.L = 1; param.S = 1; param.Sig = 0.001; param.h = 1; % Set the sampling values of the wavenumber, k k = [0:0.01:4]'; % Evaluate the phase velocity [c1,c2] = fun_eval_c(param,k); % Evaluate the group velocity [dwdk1,dwdk2] = fun_eval_dwdk(param,k); % Plot the results on the same chart figure(1);clf subplot(2,2,1) title(['Phase and group velocities '... ' , $\Lambda = ',num2str(param.L), ... '$, $S = ',num2str(param.S), ... '$'],'Interpreter','Latex') % cla; hold on; set(gca,'FontSize',14,'FontName','Times') plot(k,imag(c1),'-') plot(k,imag(c2),'-') plot(k,imag(dwdk1),'--') plot(k,imag(dwdk2),'--') xlabel('wavenumber, $k$','Interpreter','Latex') ylabel('Imag($c_g$)','Interpreter','Latex') set(gca,'YLim',[-4 4]) han = legend('$c_1$','$c_2$','$c_{g1}$','$c_{g2}$'); set(han,'Interpreter','Latex') % subplot(2,2,2) cla; hold on; set(gca,'FontSize',14,'FontName','Times') plot(k,real(c1),'-') plot(k,real(c2),'-') plot(k,real(dwdk1),'--') plot(k,real(dwdk2),'--') xlabel('wavenumber, $k$','Interpreter','Latex') ylabel('Real($c_g$)','Interpreter','Latex') set(gca,'YLim',[-4 4]) han = legend('$c_1$','$c_2$','$c_{g1}$','$c_{g2}$',3); set(han,'Interpreter','Latex') % % print -deps 'script_groupvel_001.eps' output = {}; end function output = script_spatemp_001() % Perform a spatio-temporal stability anaylsis % (c) Matthew Juniper 2013 param.scheme = 'single'; % Input the parameters param.L = 0.9; param.S = 1; % param.Sig = 1; % param.h = 1; % Set the sampling values of the wavenumber, k [kr,ki] = meshgrid(0:0.02:2,-1:0.02:1); k = complex(kr,ki); % Calculate omega1 and omega2 at these values of k [w1,w2] = fun_eval_w(param,k); % Contour plot theses side by side figure(1);clf % Plot the real and imaginary parts of omega1 subplot(2,2,1) cla; hold all; set(gca,'FontSize',14,'FontName','Times') colormap(gray) xlabel('$k_r$','Interpreter','Latex') ylabel('$k_i$','Interpreter','Latex') title('$\omega_1(k)$','Interpreter','Latex') contourf(kr,ki,imag(w1),20) contour(kr,ki,imag(w1),[0 0],'LineColor','k','LineWidth',2) contour(kr,ki,real(w1),20,'LineColor',[0.6 0.6 0.6]) axis image colorbar % Plot the real and imaginary parts of omega2 subplot(2,2,2) cla; hold all; set(gca,'FontSize',14,'FontName','Times') xlabel('$k_r$','Interpreter','Latex') ylabel('$k_i$','Interpreter','Latex') title('$\omega_2(k)$','Interpreter','Latex') contourf(kr,ki,imag(w2),20) contour(kr,ki,imag(w2),[0 0],'LineColor','k','LineWidth',2) contour(kr,ki,real(w2),20,'LineColor',[0.6 0.6 0.6]) axis image colorbar % print -depsc2 'script_spatemp_001.eps' output = {}; end function output = script_spatemp_002() % Perform a spatio-temporal stability anaylsis % (c) Matthew Juniper 2013 clear clc param.scheme = 'conf_jetwake_var'; % Input the parameters param.L = 1; param.S = 1; param.Sig = 1; param.h = 1.3; % Set the sampling values of the wavenumber, k [kr,ki] = meshgrid(0:0.05:8,-3:0.05:1); k = complex(kr,ki); % Calculate omega1 and omega2 at these values of k [c1,c2] = fun_eval_c(param,k); w1 = c1.*k; w2 = c2.*k; % Set the limits for w CLim = [-1,3]; CLev = -8:0.2:8; % Contour plot theses side by side figure(1);clf % Plot the real and imaginary parts of omega1 cla; hold all; set(gca,'FontSize',14,'FontName','Times') colormap(gray) xlabel('$k_r$','Interpreter','Latex') ylabel('$k_i$','Interpreter','Latex') title('$\omega_1(k)$','Interpreter','Latex') contourf(kr,ki,imag(w1),CLev) contour(kr,ki,imag(w1),[0 0],'LineColor','k','LineWidth',2) contour(kr,ki,real(w1),CLev,'LineColor',[0.6 0.6 0.6]) set(gca,'CLim',CLim) axis image %print -dpdf 'script_spatemp_002.pdf' output = {}; end function output = script_spatemp_003() % Perform a spatio-temporal stability anaylsis % (c) Matthew Juniper 2013 clear clc param.scheme = 'unconf_jetwake_var'; % Input the parameters param.L = 1; param.S = 1; param.Sig = 0.0; % Set the sampling values of the wavenumber, k [kr,ki] = meshgrid(0:0.01:2,-2:0.01:0); k = complex(kr,ki); % Calculate omega1 and omega2 at these values of k [c1,c2] = fun_eval_c(param,k); w1 = c1.*k; w2 = c2.*k; % Set the limits for w CLim = [-2,2]; CLev = -4:0.1:4; % Contour plot theses side by side figure(1);clf % Plot the real and imaginary parts of omega1 cla; hold all; set(gca,'FontSize',14,'FontName','Times') colormap(gray) xlabel('$k_r$','Interpreter','Latex') ylabel('$k_i$','Interpreter','Latex') title('$\omega_1(k)$','Interpreter','Latex') contourf(kr,ki,imag(w1),CLev) contour(kr,ki,imag(w1),[0 0],'LineColor','k','LineWidth',2) contour(kr,ki,real(w1),CLev,'LineColor',[0.6 0.6 0.6]) set(gca,'CLim',CLim) axis image % print -dpdf 'script_spatemp_003.pdf' output = {}; end function output = script_spatial_001() % Perform a spatial stability anaylsis on a single shear layer % (c) Matthew Juniper 2013 clear clc % Input the parameters param.scheme = 'single'; param.L = 0.5; param.S = 1; % Set the sampling values of the angular frequency, w w = [0.01:0.01:1]'; % Input an initial guess for k k_init = complex(0.1,-0.02); % Input the tolerance for convergence to the final value of k tol = 10^-6; % Initialize k vector k = 0*w; % Loop through all the values of omega, finding the relevant value of k for nn = 1:length(w) k(nn) = fun_eval_k(param,k_init,w(nn),tol); end % Plot the results on the same chart figure(1);clf subplot(2,2,1) title(['Spatial; '... ' $\Lambda = ',num2str(param.L), ... '$, $S = ',num2str(param.S), ... '$'],'Interpreter','Latex') % cla; hold on; set(gca,'FontSize',14,'FontName','Times') plot(real(w),imag(k),'k') ylabel('Imag($k$)','Interpreter','Latex') axis([0 1 -0.15 0.05]) % subplot(2,2,3) cla; hold on; set(gca,'FontSize',14,'FontName','Times') plot(real(w),real(k),'k') xlabel('angular frequency, $\omega$','Interpreter','Latex') ylabel('Real($k$)','Interpreter','Latex') axis([0 1 0 1]) % print -deps 'script_spatial_001.eps' output = {}; end function output = script_spatial_002() % Perform a spatial stability anaylsis on a single shear layer % both directly and via Gaster's transformation. % (c) Matthew Juniper 2013 clear clc % Input the parameters param.scheme = 'single'; param.L = 0.5; param.S = 1; %%% TEMPORAL ANALYSIS % Set the sampling values of the wavenumber, k k = (0:0.01:2)'; % Evaluate the phase velocity [w1,w2] = fun_eval_w(param,k); %%% GASTER'S TRANSFORMATION % Evaluate the group velocity [dwdk1,dwdk2] = fun_eval_dwdk(param,k); % Find kr and ki (approximately) through Gaster's transformation krG = k; kiG = -imag(w1)./(real(dwdk1)); %%% SPATIAL ANALYSIS (taken from script_spatial_001.m) % Set the sampling values of the angular frequency, w w = [0.01:0.01:1]'; % Input the tolerance for convergence to the final value of k tol = 10^-6; % Initialize k vector k = 0*w; % Loop through all the values of omega, finding the relevant value of k for nn = 1:length(w) % Find the index of w1 that is closest to w ind = dsearchn(real(w1),w(nn)); % Find the value of kiG at that index k_init = complex(krG(ind),kiG(ind)); % Find the exact value of k from the spatial analysis k(nn) = fun_eval_k(param,k_init,w(nn),tol); end % Plot the results on the same chart figure(1);clf subplot(2,2,1) title(['Spatial'... ' ; $\Lambda = ',num2str(param.L), ... '$, $S = ',num2str(param.S), ... '$'],'Interpreter','Latex') % cla; hold on; set(gca,'FontSize',14,'FontName','Times') plot(real(w),imag(k),'k--') plot(real(w1),kiG,'k') ylabel('Imag($k$)','Interpreter','Latex') legend('Exact','Gaster',4) axis([0 1 -0.15 0.05]) % subplot(2,2,3) cla; hold on; set(gca,'FontSize',14,'FontName','Times') plot(real(w),real(k),'k--') plot(real(w1),krG,'k') xlabel('angular frequency, $\omega$','Interpreter','Latex') ylabel('Real($k$)','Interpreter','Latex') legend('Exact','Gaster',2) axis([0 1 0 1]) % print -deps 'script_spatial_002.eps' output = {}; end function output = script_temporal_001() % Perform a temporal stability anaylsis % (c) Matthew Juniper 2013 % Set the dispersion relation param.scheme = 'single'; % Set the parameters param.L = 0.9; param.S = 1; % Set the sampling values of the wavenumber, k k = (0:0.01:4)'; % Evaluate the phase velocity [w1,w2] = fun_eval_w(param,k); % Plot the results on the same chart figure(1);clf subplot(2,1,1) cla; hold on; set(gca,'FontSize',20,'FontName','Times') plot(k,imag(w1),'k-') plot(k,imag(w2),'k--') xlabel('wavenumber, $k$','Interpreter','Latex') ylabel('growth rate, $\omega_i$','Interpreter','Latex') title(['Single shear layer; ',... '$\Lambda = ',num2str(param.L), ... '$, $S = ',num2str(param.S),'$'],'Interpreter','Latex') legend('First eigenvalue','Second eigenvalue') % subplot(2,1,2) cla; hold on; set(gca,'FontSize',20,'FontName','Times') plot(k,real(w1),'k-') plot(k,real(w2),'k--') xlabel('wavenumber, $k$','Interpreter','Latex') ylabel('frequency, $\omega_r$','Interpreter','Latex') legend('First eigenvalue','Second eigenvalue',2) % % print -deps 'script_temporal_001.eps' output = {}; end function output = script_temporal_002() % Perform a temporal stability anaylsis for all the dispersion relations % (c) Matthew Juniper 2013 clear clc % Create a cell array containing the names of the disp. rels to check scheme{1} = 'single'; scheme{2} = 'unconf_jetwake_sin'; scheme{3} = 'unconf_jetwake_var'; scheme{4} = 'conf_jetwake_sin'; scheme{5} = 'conf_jetwake_var'; % Input the parameters param.L = 0.9; param.S = 1; param.Sig = 1; param.h = 2; % Set the sampling values of the wavenumber, k k = [0:0.01:2.5]'; % Set figure defaults set(gcf,'DefaultAxesColorOrder',[0 0 0],... 'DefaultAxesLineStyleOrder','.|o|s|+|x') % Open the figure figure(1);clf subplot(1,1,1) cla; hold all; set(gca,'FontSize',20,'FontName','Times') xlabel('wavenumber, $k$','Interpreter','Latex') ylabel('growth rate, $\omega_i$','Interpreter','Latex') title([' '... ' $\Lambda = ',num2str(param.L), ... '$, $S = ',num2str(param.S), ... '$, $\Sigma = ',num2str(param.Sig), ... '$, $h = ',num2str(param.h), ... '$'],'Interpreter','Latex') % Plot the symbols for nn = 1:length(scheme) % Set the dispersion relation param.scheme = scheme{nn}; % Evaluate the phase velocity [c1,c2] = fun_eval_c(param,k); % Evaluate the growth rates w1 = c1.*k; w2 = c2.*k; % Plot the first eigenvalue on the same chart plot(k(1:20:end),imag(w1(1:20:end)),'MarkerSize',6); end % Plot the lines for nn = 1:length(scheme) % Set the dispersion relation param.scheme = scheme{nn}; % Evaluate the phase velocity [c1,c2] = fun_eval_c(param,k); % Evaluate the growth rates w1 = c1.*k; w2 = c2.*k; % Plot the first eigenvalue on the same chart plot(k,imag(w1),'k-'); end han = legend(scheme); set(han,'Interpreter','none') % print -deps2 'script_temporal_002.eps' output = {}; end function [c1,c2] = fun_eval_c(param,k) % Evaluate c1 and c2, given k % (c) Matthew Juniper 2013 % % param.scheme contains the name of the dispersion relation switch param.scheme case 'single' [c1,c2] = fun_eval_c_single(param,k); case 'unconf_jetwake_sin' [c1,c2] = fun_eval_c_unconf_jetwake_sin(param,k); case 'unconf_jetwake_var' [c1,c2] = fun_eval_c_unconf_jetwake_var(param,k); case 'conf_jetwake_sin' [c1,c2] = fun_eval_c_conf_jetwake_sin(param,k); case 'conf_jetwake_var' [c1,c2] = fun_eval_c_conf_jetwake_var(param,k); otherwise disp('param.scheme not recognized in fun_eval_c') end % end switch end % end function function [c1,c2] = fun_eval_c_conf_jetwake_sin(param,k) % Dispersion relation for % sinuous perturbations of an % confined jet/wake flow % between two immiscible fluids. % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; Sig = param.Sig; h = param.h; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Create the coefficients of the quadratic formula A = (coth(k*h)+S*tanh(k)); B = -2*(S*tanh(k)*U1 + coth(k*h)*U2); C = S*U1^2*tanh(k) + U2^2*coth(k*h) - k*Sig; B2m4AC = B.^2 - 4.*A.*C; % Evaluate c1 and c2 with the quadratic formula c1r = (-B + sqrt(B2m4AC))./(2*A); c2r = (-B - sqrt(B2m4AC))./(2*A); % Generate a stencil stencil = logical(imag(B2m4AC)>=0); % Change the position of the branch cut c1 = c1r.*stencil + c2r.*(1-stencil); c2 = c2r.*stencil + c1r.*(1-stencil); end function [c1,c2] = fun_eval_c_conf_jetwake_var(param,k) % Dispersion relation for % varicose perturbations of an % confined jet/wake flow % between two immiscible fluids. % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; Sig = param.Sig; h = param.h; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Create the coefficients of the quadratic formula A = (coth(k*h)+S*coth(k)); B = -2*(S*coth(k)*U1 +coth(k*h)*U2); C = S*U1^2*coth(k) + U2^2*coth(k*h) - k*Sig; B2m4AC = B.^2 - 4.*A.*C; % Evaluate c1 and c2 with the quadratic formula c1r = (-B + sqrt(B2m4AC))./(2*A); c2r = (-B - sqrt(B2m4AC))./(2*A); % Generate a stencil stencil = logical(imag(B2m4AC)>=0); % Change the position of the branch cut c1 = c1r.*stencil + c2r.*(1-stencil); c2 = c2r.*stencil + c1r.*(1-stencil); end function [c1,c2] = fun_eval_c_single(param,k) % Dispersion relation for a single shear layer between two immiscible fluids % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Create the coefficients of the quadratic formula A = (1+S); B = -2*(S*U1 + U2); C = S*U1^2 + U2^2 - k; B2m4AC = B.^2 - 4.*A.*C; % Evaluate c1 and c2 with the quadratic formula c1r = (-B + sqrt(B2m4AC))./(2*A); c2r = (-B - sqrt(B2m4AC))./(2*A); % Generate a stencil stencil = logical((imag(k)>=0)); % Change the position of the branch cut c1 = c1r.*stencil + c2r.*(1-stencil); c2 = c2r.*stencil + c1r.*(1-stencil); end function [c1,c2] = fun_eval_c_unconf_jetwake_sin(param,k) % Dispersion relation for % sinuous perturbations of an % unconfined jet/wake flow % between two immiscible fluids. % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; Sig = param.Sig; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Create the coefficients of the quadratic formula A = (1+S*tanh(k)); B = -2*(S*tanh(k)*U1 + U2); C = S*U1^2*tanh(k) + U2^2 - k*Sig; B2m4AC = B.^2 - 4.*A.*C; % Evaluate c1 and c2 with the quadratic formula c1r = (-B + sqrt(B2m4AC))./(2*A); c2r = (-B - sqrt(B2m4AC))./(2*A); % Generate a stencil stencil = logical(imag(B2m4AC)>=0); % Change the position of the branch cut c1 = c1r.*stencil + c2r.*(1-stencil); c2 = c2r.*stencil + c1r.*(1-stencil); end function [c1,c2] = fun_eval_c_unconf_jetwake_var(param,k) % Dispersion relation for % varicose perturbations of an % unconfined jet/wake flow % between two immiscible fluids. % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; Sig = param.Sig; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Create the coefficients of the quadratic formula A = (1+S*coth(k)); B = -2*(S*coth(k)*U1 + U2); C = S*U1^2*coth(k) + U2^2 - k*Sig; B2m4AC = B.^2 - 4.*A.*C; % Evaluate c1 and c2 with the quadratic formula c1r = (-B + sqrt(B2m4AC))./(2*A); c2r = (-B - sqrt(B2m4AC))./(2*A); % Generate a stencil stencil = logical(imag(B2m4AC)>=0); % Change the position of the branch cut c1 = c1r.*stencil + c2r.*(1-stencil); c2 = c2r.*stencil + c1r.*(1-stencil); end function [D] = fun_eval_D(param,k,w) % Evaluate D given w and k % (c) Matthew Juniper 2013 % % param.scheme contains the name of the dispersion relation switch param.scheme case 'single' [D] = fun_eval_D_single(param,k,w); case 'unconf_jetwake_sin' [D] = fun_eval_D_unconf_jetwake_sin(param,k,w); case 'unconf_jetwake_var' [D] = fun_eval_D_unconf_jetwake_var(param,k,w); case 'conf_jetwake_sin' [D] = fun_eval_D_conf_jetwake_sin(param,k,w); case 'conf_jetwake_var' [D] = fun_eval_D_conf_jetwake_var(param,k,w); otherwise disp('param.scheme not recognized in fun_eval_D') end % end switch end % end function function [D] = fun_eval_D_conf_jetwake_sin(param,k,w) % Dispersion relation for % sinuous perturbations of an % confined jet/wake flow % between two immiscible fluids. % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; Sig = param.Sig; h = param.h; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Evaluate the phase speed c = w./k; % Evaluate D D = S.*(U1-c).^2.*tanh(k) + (U2-c).^2.*coth(k*h) - k*Sig; end function [D] = fun_eval_D_conf_jetwake_var(param,k,w) % Dispersion relation for % varicose perturbations of an % confined jet/wake flow % between two immiscible fluids. % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; Sig = param.Sig; h = param.h; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Evaluate the phase speed c = w./k; % Evaluate D D = S.*(U1-c).^2.*coth(k) + (U2-c).^2.*coth(k*h) - k*Sig; end function [D] = fun_eval_D_single(param,k,w) % Dispersion relation for a single shear layer between two immiscible fluids % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix containing wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Evaluate the phase speed c = w./k; % Evaluate D D = S.*(U1-c).^2 + (U2-c).^2 - k; end function [D] = fun_eval_D_unconf_jetwake_sin(param,k,w) % Dispersion relation for % sinuous perturbations of an % unconfined jet/wake flow % between two immiscible fluids. % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; Sig = param.Sig; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Evaluate the phase speed c = w./k; % Evaluate D D = S.*(U1-c).^2.*tanh(k) + (U2-c).^2 - k*Sig; end function [D] = fun_eval_D_unconf_jetwake_var(param,k,w) % Dispersion relation for % varicose perturbations of an % unconfined jet/wake flow % between two immiscible fluids. % (c) Matthew Juniper 2013 % % param is a structure containing % param.L Shear ratio (U1-U2)/(U1+U2) % param.S Density ratio rho1/rho2 % % k is a matrix contiaining wavenumbers % c1 is a matrix containing the 1st solutions for the phase speed, omega/k % c2 is a matrix containing the 2nd solutions for the phase speed, omega/k % Extract the parameters L = param.L; S = param.S; Sig = param.Sig; % Create the non-dimensional velocities U1 = 1+L; U2 = 1-L; % Evaluate the phase speed c = w./k; % Evaluate D D = S.*(U1-c).^2.*coth(k) + (U2-c).^2 - k*Sig; end function [dwdk1,dwdk2] = fun_eval_dwdk(param,k) % Evaluate dw1/dk and dw2/dk by finite difference, given k % (c) Matthew Juniper 2013 % % (n.b. this version will break if k is on a branch cut) % Input incremental k delta = 1e-6; % Calculate w1 and w2 at these values of k [w11,w21] = fun_eval_w(param,k); [w12,w22] = fun_eval_w(param,k+delta); % Calculate the gradients dwdk1 = (w12-w11)/delta; dwdk2 = (w22-w21)/delta; end % end function function [k,w] = fun_eval_dwdk0(param,k_init,tol) % Find the value of k that gives dw/dk = 0, given k_init % (c) Matthew Juniper 2013 % Set the options for fsolve options = optimset('Display','Off','TolFun',tol); % Converge to the exact value of k using Matlab's fsolve k = fsolve(@myfun,k_init,options); % Evaluate omega at this point [dwdk01,dwdk02] = fun_eval_dwdk(param,k); [w01,w02] = fun_eval_w(param,k); [~,i] = min(abs([dwdk01,dwdk02])); w = (i==1)*w01 + (i==2)*w02; % Embedded function to evaluate dwdk function [dwdk] = myfun(k) [dwdk1,dwdk2] = fun_eval_dwdk(param,k); dwdk = min(dwdk1,dwdk2); end % End of embedded function end % end function function [k_out] = fun_eval_k(param,k_init,w,tol) % Iterate towards k, given omega % (c) Matthew Juniper 2013 % % param.scheme is the name of the dispersion relation % k_init is the initial guess for k (complex) % tol is the tolerance required for the iteration % Set the options for fsolve options = optimset('Display','Off','TolFun',tol); % Converge to the exact value of k using Matlab's fsolve [k_out] = fsolve(@fun_eval_D_loc,k_init,options); % Embedded function to call the correct dispersion relation function [D] = fun_eval_D_loc(k) switch param.scheme case 'single' [D] = fun_eval_D_single(param,k,w); case 'unconf_jetwake_sin' [D] = fun_eval_D_unconf_jetwake_sin(param,k,w); case 'unconf_jetwake_var' [D] = fun_eval_D_unconf_jetwake_var(param,k,w); case 'conf_jetwake_sin' [D] = fun_eval_D_conf_jetwake_sin(param,k,w); case 'conf_jetwake_var' [D] = fun_eval_D_conf_jetwake_var(param,k,w); otherwise disp('param.scheme not recognized in fun_eval_D') end % end switch end % End of embedded function end % end function function [w1,w2] = fun_eval_w(param,k) % Evaluate w1 and w2, given k % (c) Matthew Juniper 2013 % % param.scheme contains the name of the dispersion relation switch param.scheme case 'single' [c1,c2] = fun_eval_c_single(param,k); case 'unconf_jetwake_sin' [c1,c2] = fun_eval_c_unconf_jetwake_sin(param,k); case 'unconf_jetwake_var' [c1,c2] = fun_eval_c_unconf_jetwake_var(param,k); case 'conf_jetwake_sin' [c1,c2] = fun_eval_c_conf_jetwake_sin(param,k); case 'conf_jetwake_var' [c1,c2] = fun_eval_c_conf_jetwake_var(param,k); otherwise disp('param.scheme not recognized in fun_eval_c') end % end switch % Evaluate w1 and w2 from c1 and c2 w1 = k.*c1; w2 = k.*c2; end % end function
github
Wendroff/ModalTheory-master
select_script.m
.m
ModalTheory-master/Supplementary_Material_AMR-13-1059/Hannifi/select_script.m
37,249
utf_8
d192d79e72917a3b725f50a0fd152ad5
function output = select_script(run) % This file contains Matlab codes for computing the eigenvalue % problem corresponding to the Orr-Sommerfeld and linearized % Navier-Stokes equations. These are parts of the tutorial: % "Modal Stability Theory" by Matthew Juniper, Ardeshir Hanifi, % and Vassilios Theofilis, published in Applied Mechanics Reviews, % 66(2), 2014. % % (c) Ardeshir Hanifi 2014 % The main programs are % % run_OS.m : run the temporal 1D stability code % run_LNS.m : run the temporal 1D stability problem % run_PSE.m : run the Parabolized Stability Equations % % Save the file as 'select_script.m'. % To execute replace the argument 'run' by the string obtained % from the corresponding function name, sans the suffix. switch run case 'run_OS' output = run_OS(); case 'run_LNS' output = run_LNS(); case 'run_PSE' output = run_PSE(); otherwise warning('AMR:nodemo', 'No such demo'); end end function output = run_OS() % This script runs the temporal 1D stability code % % (c) Ardeshir Hanifi 2014 clear all close all %% Numerical parameters N = 200; % number of Cehebychev modes %% Flow parameters Re=1e4; alpha=1; beta=0.4; %% Select the collocation nodes and set up derivative operator M=4; % Highest order of derivative required [y, D] = chebdif(N, M); %% Velocity profile corresponding to Plane Poiseuille Flow U.u=1-y.^2; U.uy=-2*y; U.uyy=-2+y*0; %% Set up the eigenvalue problem [A,B] = OS_temp(U, D, alpha, beta, Re); %% Solve the eigenvalue problem [eigvec, eigval] = eig(A,B); eigval=diag(eigval); %% Plot spectrum and eigenvectors header=strcat({'Re= '},{num2str(Re)},{', alpha= '},{num2str(alpha)},... {', beta= '},{num2str(beta)}); plot_OS(eigval,eigvec,y,header) output = {}; end function output = run_LNS() % This script runs the temporal 1D stability problem % % (c) Ardeshir Hanifi 2014 clear all close all %% Numerical parameters N = 200; % number of Cehebychev modes %% Flow parameters Re=1e4; alpha=1; beta=0.4; %% Select the collocation nodes and set up derivative operator [y, D] = chebdif(N, 2); %% Velocity profile corresponding to Plane Poiseuille Flow U.u=1-y.^2; U.uy=-2*y; U.w=zeros(size(y)); % This field is required as the code is written for a 3D flow U.wy=zeros(size(y)); % This field is required as the code is written for a 3D flow %% Set up the eigenvalue problem [A,B] = LNS_temp(U, D, alpha, beta, Re); %% Solve the eigenvalue problem [eigvec, eigval] = eig(A,B); eigval=diag(eigval); %% Plot spectrum and eigenvectors header=strcat({'Re= '},{num2str(Re)},{', alpha= '},{num2str(alpha)},... {', beta= '},{num2str(beta)}); plot_LNS(eigval,eigvec,y,header) output = {}; end %------------------------------------------------------------------ function []=plot_OS(eigval,eigvec,y,header) % []=plot_OS(eigval,eigvec,y,header) % This function plots the spectrum and the corresponding eigenvectors % % INPUT % eigval: array containing the eigenvalues % eigvec: matrix corresponding the eigenvectors % y: normal coordinates % header: string to appear as the header of plot % % (c) Ardeshir Hanifi 2014 eglist=find(abs(eigval)<10); eigval=eigval(eglist); eigvec=eigvec(:,eglist); % Choose eigenvalue to plot disp('Right click to pick the mode. Left click to stop'); button=1; while button==1 figure(1) plot(real(eigval),imag(eigval),'o',[0 1],[0 0],'r-'); ylim([-1,0.1]); title(header); ylabel('imag(\omega)') xlabel('real(\omega)') [xp,yp,button] = ginput(1); a=xp+sqrt(-1)*yp; [c,locate]=min(abs(eigval-a)); v=eigvec(:,locate); figure(2) plot(real(v),y,imag(v),y); legend('real(v)','imag(v)') title(strcat(header,{', omega= '},{num2str(eigval(locate))})); ylabel('y') end end %------------------------------------------------------------------ function []=plot_LNS(eigval,eigvec,y,header) % []=plot_LNS(eigval,eigvec,y,header) % This function plots the spectrum and selected eigenfunctions % % INPUT % eigval: array containing the eigenvalues % eigvec: matrix corresponding the eigenvectors % y: normal coordinates % header: string to appear as the header of plot % % (c) Ardeshir Hanifi 2014 % eglist=find(abs(eigval)<10); eigval=eigval(eglist); eigvec=eigvec(:,eglist); N=length(y); % Choose eigenvalue to plot disp('Right click to pick the mode. Left click to stop'); button=1; while button==1 figure(1) plot(real(eigval),imag(eigval),'o',[0 1],[0 0],'r-'); ylim([-1,0.1]); title(header); ylabel('imag(\omega)') xlabel('real(\omega)') ylim([-1,0.1]); [xp,yp,button] = ginput(1); a=xp+sqrt(-1)*yp; [c,locate]=min(abs(eigval-a)); u=eigvec(1:N,locate); v=eigvec(N+1:2*N,locate); w=eigvec(2*N+1:3*N,locate); p=eigvec(3*N+1:4*N,locate); figure(2) plot(abs(u),y,abs(v),y,abs(w),y,abs(p),y); legend('abs(u)','abs(v)','abs(w)','abs(p)') title(strcat(header,{', omega= '},{num2str(eigval(locate))})); ylabel('y') end end %------------------------------------------------------------------ function [A,B] = OS_temp(U, D, alpha, beta, Re) % [A,B]=OS_temp(U,D,ALPHA,BETA,RE) % OS_temp sets up the operator corrsponding to local temporal 1D stability % (Orr-Sommerfeldt) equation. % % INPUT % U: structure array containing meanflow quantities U.u, U.uy, U.uyy % D: spectral ifferential operator % alpha: stremwise wavenumber % beta: spanwise wavenumber % Re: Reynolds number % % OUTPUT % A and B: matrices corresponding to the eigenvalue problem A.q = omega.B.q % % (c) Ardeshir Hanifi 2014 N=length(U.u); D1=D(:,:,1); D2=D(:,:,2); D4=D(:,:,4); %------------------------------------------------------------------ % Set up operator matrices zi = sqrt(-1); k2 = alpha*alpha + beta*beta; I = eye(N); A=(D4-2*k2*D2)*zi/Re+diag(alpha*U.u)*(D2-k2*I)-diag(alpha*U.uyy); B=D2-k2*I; %------------------------------------------------------------------ % Boundary conditions % Replace the empty rows of B with a multiple of same rows in A. This % rmoves the singularity of the system and introduce eigenvalues which are % located far from the physical ones by approperiate choice of multiple, eps = 1e-4*zi; Ov = zeros(1,N); % v(ymax)=0 A(1,:) = Ov; A(1,1) = 1; B(1,:) = A(1,:)*eps; % dv/dy(ymax)=0 A(2,:) = D1(1,:); B(2,:) = A(2,:)*eps; % dv/dy(0)=0 A(N-1,:) = D1(N,:); B(N-1,:) = A(N-1,:)*eps; % v(0) = 0 A(N,:) = Ov; A(N,N) = 1; B(N,:) = A(N,:)*eps; end %------------------------------------------------------------------ function [A,B] = LNS_temp(U, D, alpha, beta, Re) % LNS_temp sets up the operator of general eigenvalue problem A.q = omega.B.q % corrsponding to local temporal 1D stability equations. % % [A,B]=LNS_tmp(U,D,ALPHA,BETA,RE). % % Input: % U: structure containig streamwise and spanwise velocities and their % first normal derivatives U.u, U.uy, U.w, U,wy % D: sepctral differential operator % ALPHA: streamwise wavenumber % BETA: spanwise wavenumber % RE: Reynolds number % % OUTPUT % A and B: matrices corresponding to the eigenvalue problem A.q = omega.B.q % % (c) Ardeshir Hanifi, 2014 N=length(U.u); D1=D(:,:,1); D2=D(:,:,2); %------------------------------------------------------------------ % Set up operator matrices zi = sqrt(-1); I = eye(N); O = zeros(N); xi=(D2-(beta^2+alpha^2)*I)/Re - zi*diag(alpha*U.u + beta*U.w); A11 = zi*alpha*I; A12 = D1; A13 = zi*beta*I; A21 = xi; A22 = -diag(U.uy); A24 = -zi*alpha*I; A32 = xi; A34 = -D1; A42 = -diag(U.wy); A43 = xi; A44 = -zi*beta*I; A = [A11, A12, A13, O ; ... A21, A22, O, A24; ... O, A32, O, A34; ... O, A42, A43, A44]; %------------------------------------------------------------------ B = [O, O, O, O; ... -zi*I, O, O, O; ... O, -zi*I, O, O; ... O, O, -zi*I, O]; %------------------------------------------------------------------ % Boundary conditions Ov = zeros(1,4*N); % u A(N+1,:) = Ov; A(N+1,1) = 1; B(N+1,:) = Ov; A(2*N,:) = Ov; A(2*N, N) = 1; B(2*N,:) = Ov; %v A(2*N+1,:) = Ov; A(2*N+1, N+1) = 1; B(2*N+1,:) = Ov; A(3*N,:) = Ov; A(3*N, 2*N) = 1; B(3*N,:) = Ov; %w A(3*N+1,:) = Ov; A(3*N+1, 2*N+1) = 1; B(3*N+1,:) = Ov; A(4*N,:) = Ov; A(4*N, 3*N) = 1; B(4*N,:) = Ov; end %------------------------------------------------------------------ function [x, DM] = chebdif(N, M) % The function [x, DM] = chebdif(N,M) computes the differentiation % matrices D1, D2, ..., DM on Chebyshev nodes. % % Input: % N: Size of differentiation matrix. % M: Number of derivatives required (integer). % Note: 0 < M <= N-1. % % Output: % DM: DM(1:N,1:N,ell) contains ell-th derivative matrix, ell=1..M. % % The code implements two strategies for enhanced % accuracy suggested by W. Don and S. Solomonoff in % SIAM J. Sci. Comp. Vol. 6, pp. 1253--1268 (1994). % The two strategies are (a) the use of trigonometric % identities to avoid the computation of differences % x(k)-x(j) and (b) the use of the "flipping trick" % which is necessary since sin t can be computed to high % relative precision when t is small whereas sin (pi-t) cannot. % Note added May 2003: It may, in fact, be slightly better not to % implement the strategies (a) and (b). Please consult the following % paper for details: "Spectral Differencing with a Twist", by % R. Baltensperger and M.R. Trummer, to appear in SIAM J. Sci. Comp. % J.A.C. Weideman, S.C. Reddy 1998. Help notes modified by % JACW, May 2003. I = eye(N); % Identity matrix. L = logical(I); % Logical identity matrix. n1 = floor(N/2); n2 = ceil(N/2); % Indices used for flipping trick. k = [0:N-1]'; % Compute theta vector. th = k*pi/(N-1); x = sin(pi*[N-1:-2:1-N]'/(2*(N-1))); % Compute Chebyshev points. T = repmat(th/2,1,N); DX = 2*sin(T'+T).*sin(T'-T); % Trigonometric identity. DX = [DX(1:n1,:); -flipud(fliplr(DX(1:n2,:)))]; % Flipping trick. DX(L) = ones(N,1); % Put 1's on the main diagonal of DX. C = toeplitz((-1).^k); % C is the matrix with C(1,:) = C(1,:)*2; C(N,:) = C(N,:)*2; % entries c(k)/c(j) C(:,1) = C(:,1)/2; C(:,N) = C(:,N)/2; Z = 1./DX; % Z contains entries 1/(x(k)-x(j)) Z(L) = zeros(N,1); % with zeros on the diagonal. D = eye(N); % D contains diff. matrices. for ell = 1:M D = ell*Z.*(C.*repmat(diag(D),1,N) - D); % Off-diagonals D(L) = -sum(D'); % Correct main diagonal of D DM(:,:,ell) = D; % Store current D in DM end end %------------------------------------------------------------------ function output = run_PSE() % pse.m is the main program for solving the PSE % pse.m is the main program to solbe the Parabolized Stability Equations (PSE) % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % %clear all %% -------------------------------------------------------------------------- % Numerical Parameters N=100; % Number of nodes in wall-normal direction ymax=70; % Height of last node in wall-normal direction stab=false; % if stab=true the stablization of PSE is active dpdx=1; % if this parameter is =0 the x-derivative of pressure disturbance is neglected FDorder='first'; % order of backward Euler discretization scheme (can be 'first' or 'second') iaux=1; % auxiliary condition is based integral norm if (iaux=1) else on u_max %% -------------------------------------------------------------------------- % Flow parameters Re=400; % Reynolds number at first x-station Re_end=1000; % Reynolds number at final x-station Nstation=80; % Number of x-stations mfac=0.0; % Falkner-Skan-Cook patrameter (U=x^mfac) sweep=0; % Sweep angle (in degree) at first x-station %% -------------------------------------------------------------------------- % Perturbation parameters beta=0.0; % Spanwise wavenumber F=1e-4; % Reduced frequency omega=F*Re; % Angular frequency %% -------------------------------------------------------------------------- % Spectral discretisation operators (Chebycheff) [y,D1,D2,W] = chebmat(N,ymax); %% -------------------------------------------------------------------------- % Generate meanflow disp('Computing mean flow') x = linspace(Re,(Re_end/Re)^(2/(mfac+1))*Re,Nstation); U = MeanFlow(x,y,Re,mfac,sweep); %% -------------------------------------------------------------------------- % Solve local Orr-Sommerfeld eigenvalue problem to use as initial solution alpha0=omega/0.36; % start approximation for TS waves [q0,alpha0] = localOSS(alpha0,U(1),D1,D2,beta,omega,Re); % Normalise initial disturbance to energy 1 q0 = q0/(0.5*sqrt(q0(1:3*N)'*blkdiag(W,W,W)*q0(1:3*N))); % Plot the eigenfunction c=['k','r','b','g']; figure(1);clf(1);hold on; for k=1:4;plot(abs(q0((k-1)*N+1:k*N)),y,c(k));end legend('u','v','w','p') %% -------------------------------------------------------------------------- % Integrate the Parabolized Stability Equations disp('Integrate Parabolized Stability Equations') [q, alpha, ncalc] = integratePSE(q0, alpha0, x, y, U, D1, D2, W,... beta, omega, Re, Nstation, stab, dpdx, FDorder, iaux); x=x(1:ncalc); % Compute growth rate sigma=growth( x,alpha,q,W ); % Compute N-factor Nfactor=cumtrapz(x,sigma); % Plot growth rate (scaled globally) and N-factor as function of local Re Rex=(x/x(1)).^((mfac+1)/2)*Re; figure(2);clf(2); plot(Rex,sigma); grid on; xlabel('Re'); ylabel('growth rate'); figure(3);clf(3); plot(Rex,Nfactor); grid on; xlabel('Re'); ylabel('N-factor'); d=([Rex' sigma]); save('sigma.dat','d','-ascii','-double') % %% -------------------------------------------------------------------------- % % % % This part of code is an example of how the local stability results could % % be obtained. % beta=0; % Spanwise wavenumber % F=1e-4; % Reduced frequency % % Rex=(400:20:800); % alpha_l=zeros(size(Rex)); % for k=1:length(Rex) % omega=F*Rex(k); % Angular frequency % alpha0=omega/0.36; % start approximation for TS waves % [q0,alpha_l(k)] = localOSS(alpha0,U(1),D1,D2,beta,omega,Rex(k)); % end % % % plot results scaled by local refernce values % figure(3);clf(3); plot(Rex,-imag(alpha_l));grid on; % % %% % % Data corresponding the neutral stability curve for Blasius flow % DNS_u=([340.4470 164.5750 % 329.7300 177.4480 % 323.2400 186.8020 % 317.8840 195.2120 % 313.7030 202.6430 % 310.5860 209.1890 % 308.1760 215.1470 % 306.0960 220.8290 % 304.1160 226.4280 % 302.3810 231.8230 % 301.0970 236.8430 % 300.4680 241.3180 % 300.5690 245.1850 % 301.2620 248.5580 % 302.4060 251.5560 % 304.1600 254.0470 % 306.9560 255.6700 % 311.2380 256.0560 % 317.4490 254.8360 % 326.0330 251.6400 % 337.4720 246.0680 % 352.6870 237.3510 % 371.0640 226.0020 % 388.6310 215.3270 % 403.5960 206.8190 % 416.9720 199.6340 % 429.6790 193.0060 % 441.8390 186.8330 % 453.4040 181.1550 % 464.3360 176.0050 % 474.6660 171.3550 % 484.4630 167.1500 % 493.7930 163.3330 % 502.7240 159.8480 % 511.3230 156.6400 % 519.6570 153.6520 % 527.7930 150.8290 % 535.8000 148.1140 % 543.7430 145.4510 % 551.6910 142.7850 % 559.7100 140.0600]); % DNS_v=([344.1080 141.2510 % 308.5680 180.1410 % 303.3240 188.9460 % 294.3010 201.5050 % 288.2350 211.1260 % 284.4440 218.4880 % 281.1580 225.3490 % 277.9410 232.1410 % 274.9910 238.6690 % 272.4850 244.7550 % 270.4170 250.4060 % 268.6960 255.7130 % 267.2280 260.7680 % 265.9630 265.6220 % 264.9510 270.2250 % 264.2570 274.5110 % 263.9500 278.4140 % 264.0880 281.8750 % 264.6310 284.9330 % 265.4500 287.7170 % 266.4150 290.3570 % 267.5720 292.8050 % 269.4370 294.5510 % 272.2990 295.3070 % 276.0330 295.1960 % 280.4850 294.3730 % 285.7990 292.6940 % 295.1960 286.9600 % 309.6490 276.2050 % 325.5660 263.9960 % 340.5280 252.7360 % 354.0170 242.9390 % 366.6280 234.0130 % 378.5010 225.8200 % 389.4760 218.5200 % 399.4880 212.1750 % 408.6910 206.6330 % 417.2660 201.7150 % 425.3880 197.2480 % 433.1590 193.1290 % 440.6300 189.3070 % 447.8520 185.7330 % 454.8730 182.3590 % 461.7440 179.1330 % 468.4980 176.0240 % 475.1410 173.0250 % 481.6740 170.1350 % 488.0990 167.3520 % 494.4180 164.6740 % 500.6340 162.1000 % 506.7480 159.6260 % 512.7620 157.2510 % 518.6780 154.9740 % 524.4980 152.7920 % 530.2240 150.7040 % 535.8580 148.7060 % 541.4030 146.7980 % 546.8590 144.9780 % 552.2290 143.2430 % 557.5150 141.5910 % 562.7190 140.0210]); % Exp_data=([430.9300 100.0000 % 711.4530 100.0000 % 337.3260 162.0000 % 473.8370 162.0000 % 310.9300 200.0000 % 405.0580 200.0000 % 284.4190 250.0000 % 324.8260 250.0000]); % plot(DNS_u(:,1),DNS_u(:,2),DNS_v(:,1),DNS_v(:,2),Exp_data(:,1),Exp_data(:,2),'o') % legend('DNS (u) (Berlin et al. 1998)','DNS (v) (Berlin et al. 1998)', 'Exp. (Klingmann et al 1993)') % ylim([0,300]);xlabel('Re');ylabel('F');title('Neutral stability curve for Blasius flow'); % grid on output = {}; end %------------------------------------------------------------------ function auxval = auxfunc(eulco, y, q1, q2, q3, W, iaux) % auxval = auxfunc(eulco, q1, q2, q, W) % This function computes the value of the auxiliary function % coresponding to integral of conjg(q)*dq/dx. % % eulco: contains the dsicretization coefficients % y: values of normal coordinates % q1, q2 and q3: the eigenfunctions at stations i-2, i-1 and i-th % (the currenet) streamwise station % W: contains spectral inetgral weights for Chebuychev polynomials % iaux: =1 integral norm, =2 max(u) % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % N=length(y); % Compute umax umax1 = findqmax(y,q1(1:N)); umax2 = findqmax(y,q2(1:N)); umax3 = findqmax(y,q3(1:N)); % Compute the auxiliary condition if (iaux==1) % Compute derivative of q dqdx = eulco(1)*q1 + eulco(2)*q2 + eulco(3)*q3; auxval = q3'*blkdiag(W,W,W,W)*dqdx; else auxval = (eulco(1)*umax1 + eulco(2)*umax2 + eulco(3)*umax3); end end %------------------------------------------------------------------ function [y,D1,D2,W] = chebmat(N,ymax) % [z,D1,D2,W] = chebmat(N,zmax) % This function sets up the integration weights and differential operatores % corresponding to the spectral discretization using Chenychev polynomials. % The differential operators are also transormed using a mapping from % the spectral domain [-1,1] to [0,ymax]. % % N: order of Chebychem polynomial is N-1 % ymax: Height of last node in wall-normal direction % % The output variable are % y: coordinates of Gauss-Lobbato nodes in physical space [0,ymax] % D1, D2: first and second derivative operatires % W: spectral integraation weights % % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % [yc, D] = chebdif(N, 2); D1 = D(:,:,1); D2 = D(:,:,2); % Define the mapping to the physical domain y=(yc+1)*ymax/2; % Map Derivative operators onto interval [0 ymax] D1 = D1*(2/ymax); D2 = D2*(2/ymax)^2; % Get integration weights W = iwt(N)*ymax/2; end %------------------------------------------------------------------ function [eulco] = compeulco(order, dx1, dx2) % [eulco] = compeulco(order, dx1, dx2) computes the coefficients for backward Euler FD scheme % % Input % order: 'first' or 'second' for first- or second-order backward Euler scheme % dx1: x(i)-x(i-1) % dx2: x(i-1)-x(i-2) % % Output: % eulco: an array containing the discretization coefficients such that % df/dx=eulco(1)*f(i-2)+eulco(2)*f(i-1)+eulco(3)*f(i) % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % if strcmp(order, 'first') eulco=([0, -1, 1])/dx1; elseif strcmp(order, 'second') d=dx2+dx1; eulco = ([dx1/(dx2*d), -d/(dx1*dx2), (2*dx1+dx2)/(dx1*d)]); end end %------------------------------------------------------------------ function [ fx ] = dfx( f,x,difforder ) % [ fx ] = dfx( f,x,difforder ) % DFX Computes derivatives of F with respect to x % % Input % f: funxtion values % x: values of the variable % difforder: =1 first-order Euler, =2 second-order Euler scheme % % Output % fx: df/dx % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % idim=length(f); fx=zeros(size(f)); fx(1)=(f(1)-f(2))/(x(1)-x(2)); for i=2:idim if (min(difforder,i-1)==1) % first order Euler dx1=x(i)-x(i-1); fx(i)=(f(i)-f(i-1))/dx1; else % second order Euler dx1=x(i)-x(i-1); dx2=x(i-1)-x(i-2); c2=dx1/(dx2*(dx2+dx1)); c1=-(dx2+dx1)/(dx1*dx2); c0=(2.*dx1+dx2)/(dx1*(dx2+dx1)); fx(i)=c2*f(i-2)+c1*f(i-1)+c0*f(i); end end end %------------------------------------------------------------------ function [ x, x2, f2 ] = extrapol( x1, x2, f1, f2, iter) % x = extrapol( x1, x2, f1, f2) % This function find x value such that f(x)=0 using a secant method. % % Input: % f1 and f2: function values corresponding to variables x1 and x2 % iter: index of iteration at curent iteration step % % Output: % x: estimated value of x correspopnding to f(x)=0 % x2 and f2: same as in the input. % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % if (iter==1) x = x2*1.001; else x = x2 - (x2 - x1)/(f2 - f1)*f2; end end %------------------------------------------------------------------ function [qmax] = findqmax(y,q) % [qmax] = findqmax(q,y) % This function finds the value of q with the maximum absolute value % by ploynomial fitting. % % Input: % y: array containing coordinates of grid points % q: function values at gridpoints given in y % % Output: % qmax: estimated value of q with maximum absolute value % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % N=length(y); % Find the maximum of abs(q) on the original grid qabs=abs(q); [qmax, imax]=max(qabs); if (imax==1 || imax==N) disp('Findqmax: max values at boundaries') qmax=q(imax); return; end % Fit polynomial to data Np=2; % order of polynomial i1=max(1,imax-floor(Np/2)); i2=min(i1+Np,N); p = polyfit(y(i1:i2),qabs(i1:i2),Np); % find zero of derivative of the polynomial dp = polyder(p); y0=[y(i1) y(i2)]; fun=@(x)polyval(dp,x); ymax=fzero(fun,y0); % Find the maximum on the interpolated grid p = polyfit(y(i1:i2),q(i1:i2),Np); qmax=polyval(p,ymax); end %------------------------------------------------------------------ function dy = fsc(t,y,mfac) % dy = fsc(t,y,mfac) sets up the functions coresponding to % Falkner-Skan-Cooke simililarity soloution % % Input: % t: variable required by ode45 % y: array containing function values corresponding to differential equation for similarity solution % mfac: Falkne-Skan velocity parameter U=x^mfac % % Output: % dy: derivative of function y % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % dy=zeros(5,1); betaH=2*mfac/(mfac+1); dy(1)=y(2); dy(2)=y(3); dy(2)=y(3); dy(3)=-(y(1)*y(3)+betaH*(1-y(2)*y(2))); dy(4)=y(5); dy(5)=-y(1)*y(5); end %------------------------------------------------------------------ function [ sigma ] = growth( x,alpha,q,W ) % [ sigma ] = growth( x,alpha,q,W ) % GROWTH computes the nonlocal growthrate of perturbations % % Input % x: streamwise coordinate of stations % alpha: vector containig streamwise wavenumber at all x-stations % q: matrix containing eigenfunctions at all x-stations % W: is the weightfunction of spectral integration % % Output % sigma: the nonlocal growth rate. % % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % N=length(q(:,1))/4; % Growthrate based on disturbance energy energy=zeros(size(alpha)); umax=zeros(size(alpha)); for k=1:length(x) energy(k)=abs(0.5*q(1:3*N,k)'*blkdiag(W,W,W)*q(1:3*N,k)); end sigma=-imag(alpha)+dfx( log(sqrt(energy)),x,1 ); sigma(1)=-imag(alpha(1)); % Local growth rate end %------------------------------------------------------------------ function [q, alphax, ncalc] = integratePSE(q0, alpha0, x, y, U, D1, D2, W,... beta, omega, Re, Nstation, stab, dpdx, FDorder, iaux) % [q,alphax,ncalc] = integratePSE(q0, alpha0, x, y, U, D1, D2, W,... % beta, omega, Re, Nstation, stab, dpdx, FDorder, iaux) % Thuis function integrates the Parabolised Stability Equations (PSE). % % Input % q0, alpha0: complex eigenfunction and stermawise wavenumber at initial station % x, y: arrays containing streamwise and normal coordinates of the grid % U: structure array containing the meanflow quantities % D1, D2, W: first- and second derivative operators and spectral integration weights % beta, omega, Re: spanwise wavenumber, frequency and Reynolds number % Nstation: number of stations in x-direction to compute % stab: if stab=true the stablization of PSE is active % dpdx: if =0 the x-derivative of pressure disturbance is neglected % FDorder: order of backward Euler discretization scheme (can be 'first' or 'second') % iaux: auxiliary condition is based integral norm if (iaux=1) else on u_max % % Output % q: complex array contatining eigen functions (u,v,w,p) at computed x-stations % alphax: complex array containing streamwise wavenumber at computed x-stations % ncalc: number of sucessfully computed stations % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % %initialise variables N=length(y); q=zeros(N*4,Nstation); q(:,1) = q0; alphax=zeros(Nstation,1); alphax(1) = alpha0; alpha = alpha0; local=false; dx= [0 diff(x)]; alpha1=0; auxval1=0; % integration loop n=1; ncalc=Nstation; while (n < Nstation) n=n+1; disp(' '); disp(['Station: ', num2str(n)]); %decide which FDorder for backward scheme if (n == 2 || strcmp(FDorder, 'first')) scheme_order = 'first'; elseif (n ~= 2 && strcmp(FDorder, 'second')) scheme_order = 'second'; end %get coefficients for backward scheme [eulco] = compeulco(scheme_order, dx(n), dx(n-1)); %loop over alpha to satisfy auxiliary condition iloop = 0; auxval = 1e8; while abs(auxval) > 1e-08 && (iloop<50) iloop = iloop + 1; %stablization coefficient s = 0; if stab if ( real(alpha) ~= 0 && dx(n) <= 1/abs(real(alpha))*1.01 ) s = (0.5/abs(real(alpha)) - dx(n)*.5)*2; end %disp(['stabilisation: s = ' num2str(s)]); end %set up operator matrices with boundary conditions [RHS, LHS] = operator(local,U(n),alpha, D1, D2,... beta,omega,Re,eulco,q(:,max(1,n-2)),q(:,n-1),s,dpdx); %solve equation system q(:,n) = LHS\RHS; %compute the auxiliary condition auxval = auxfunc(eulco, y, q(:,max(1,n-2)), q(:,n-1), q(:,n), W, iaux); disp(['It: ', num2str(iloop), ' ,alpha: ', num2str(alpha), ' , auxval: ', num2str(abs(auxval))]); alphax(n) = alpha; %estimate new alpha [ alpha, alpha1, auxval1 ] = extrapol( alpha1, alpha, auxval1, auxval, iloop); end if abs(auxval) > 1e-08 ncalc=n-1; q=q(:,1:ncalc); alphax=alphax(1:ncalc); n=Nstation+100; end end end %------------------------------------------------------------------ function W = iwt(N) % IWT: sets up the weigth function for the spectral integration and % form the matrix used for computation of disturbance energy. % % Input % N: order of Chebychev olynomial is N-1 % % Output: % W: array containing the integration weights % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % N1=N-1; %compute chebycheff integration weights n = 0:1:N1; j = 0:1:N1; b = ones(1, N); b([1 N]) = 0.5; c = 2*b; b = b/N1; S = cos(n(3:N)'*j*(pi/N1)); W = diag(b.*((2+(c(3:N).*((1+(-1).^n(3:N))./(1-n(3:N).^2)))*S))); end %------------------------------------------------------------------ function [q,alpha] = localOSS(alphainit, U, D1, D2, beta, omega, Re) % [q,alpha] = localOSS(alphainit, U, D1, D2, beta, omega, Re) computes eigenvalue of % local spatial stability equation % % Input: % alphainit: start approximation of eigenvalue % U: structure containing mean flow velocity field and its derivatives % D1 and D2: matrices corresponding to operator of first- and second derivative % beta: spanwise wavenumber of perurbation % omega: angular frequency of perturbation % Re: Reynolds number % % Outout: % q: eigenfunction % alpha: eigenvalue (streamwise wavenumber) % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % % Find eigenvalue of spatial OSS system using a secant method loop = true; iloop = 0; alpha = alphainit; local=true; N=length(U.u); alpha1=0; v01=0; disp([' ']); disp(['**** Local analysis for Re= ',num2str(Re),', F=',num2str(omega/Re)]); disp([' ']); while loop iloop = iloop +1; [RHS,LHS] = operator(local, U, alpha, D1, D2, beta, omega, Re); q = LHS\RHS; v02 = q(2*N); [ alpha, alpha1, v01 ] = extrapol( alpha1, alpha, v01, v02, iloop); disp(['It: ', num2str(iloop), ' ,alpha: ', num2str(alpha), ' , w0: ', num2str(abs(v02))]); if abs(v02) <= 2e-8 loop = false; end if (iloop>50) error ('**** No converged solution found'); end end end %------------------------------------------------------------------ function U = MeanFlow(x,y,Re,mfac,sweep) % U = MeanFlow(x,z,Re,mfac,sweep) % This function computes the mean flow quantities for a Falkner-Skan-Cooke % boundary layer. % % x: array containing coordinates of grid in x-direction % y: array containing coordinates of grid in z-direction % Re: Reynolds number at initial x-station % mfac: Falkner-Skan-Cooke parameter U=C*x^mfac % sweep: flowsweep angle at initial x-station % % Output is the structre array 'U' which contains % U(i).u, U(i).v, U(i).w: streamwise, normal and spanwise velocity % U(i).uy, U(i).vy, U(i).wy: normal derivatives of u, v and w % U(i).ux, U(i).wx: streawwise derivatives of u and w % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % Nstations = length(x); % generate self-semilar Falkner-Skan-Cooke profiles Ufsc = similar_fsc(y,mfac); % generate meanflow data at first station we=tan(sweep*pi/180); U(1).u = Ufsc.u; U(1).v = Ufsc.v/Re; U(1).w = Ufsc.w*we; U(1).uy = Ufsc.uy; U(1).wy = Ufsc.wy*tan(sweep*pi/180); U(1).vy = Ufsc.vy/Re; U(1).ux = Ufsc.uy.*( y*(mfac-1)*0.5 )/Re + mfac*Ufsc.u/Re; U(1).wx = Ufsc.wy.*( y*(mfac-1)*0.5 )*we/Re; % set global reference scales method = 'spline'; % rescale meanflow such that all quantities are based on reference scales of % first station and interpolate onto Gauss-Lobatto Grid for i = 1:Nstations ue = (x(i)/x(1))^mfac; lscale = sqrt(x(i)/x(1)/ue); rescale = sqrt(ue*x(i)/x(1)); yi=y*lscale; ve = U(1).v(1)*ue/rescale-U(1).ux(1)*ue/rescale*(yi(1)-y(1)); U(i).u=interp1(yi,U(1).u*ue,y,method,ue); U(i).w=interp1(yi,U(1).w ,y,method,we); U(i).v=interp1(yi,U(1).v*ue/rescale,y,method,ve); U(i).uy=interp1(yi,U(1).uy*ue/lscale,y,method,0); U(i).wy=interp1(yi,U(1).wy/lscale ,y,method,0); U(i).vy=interp1(yi,U(1).vy*ue/lscale/rescale,y,method,U(1).vy(1)*ue/lscale/rescale); U(i).ux=interp1(yi,U(1).ux*ue/rescale^2,y,method,U(1).ux(1)*ue/rescale^2); U(i).wx=interp1(yi,U(1).wx/rescale^2 ,y,method,U(1).wx(1)/rescale^2); end end %------------------------------------------------------------------ function [RHS,LHS] = operator(local, U, alpha, D1, D2, beta, omega, ... Re, varargin) % OPERATOR sets up the operator corrsponding to local and nonlocal stability % equations. % % [RHS,LHS]=OPERATOR(LOCAL,U,ALPHA,D1,D2,BETA,OMEGA,RE,N,EULCO,Q1,Q2,S) % If LOCAL=false parameters EULCO, Q1, Q2 and S are optional. % % Input % local: if =true the local operator corresponding to local stability theory is set up % U: structure containing meanflow field and its derivatives % alpha: streamwise wavenumber % D1 and D2: matrices corresponding to first- and second derivative operators % beta: spanwise wavenumber % omega: angular frequency % Re: Reynolds number % eulco: coefficients of Euler backward discretization scheme % q1 and q2: amplitudefunctions at x(i-1) and x(i-2) % s: coefficient of stabilization term % dpdx: if =0 the x-derivative of pressure disturbance is neglected % % Output % LHS and RHS: matrices corresponding to PSE, LHS.q=RHS % % (c) Ardeshir Hanifi & David Tempelmann, 2014 % %------------------------------------------------------------------ N=length(U.u); if (local==true) eulco = zeros(3,1); q1 = zeros(N*4,1); q2 = zeros(N*4,1); s = 0; dpdx = 0; elseif (local==false) if (nargin~=13) disp('**** OPERATOR: Wrong number of parameters') disp('[RHS,LHS] = operator(local,U,alpha,D1,D2,beta,omega,Re,eulco,q1,q2,s)') error('Stopping programe'); else eulco = varargin{1}; q1 = varargin{2}; q2 = varargin{3}; s = varargin{4}; dpdx = varargin{5}; if (dpdx~=0); dpdx=1; end end end %------------------------------------------------------------------ % Set up operator matrices % A.q + B.q_y + C.q_yy + D.q_x=0 if (local==true); inoloc=0; else inoloc=1; end i = sqrt(-1); I = eye(size(D1)); O = zeros(size(D1)); xi=diag(-i*omega + (beta^2+alpha^2)/Re + i*(alpha*U.u + beta*U.w)); A11 = i*alpha*I; A13 = i*beta*I; A21 = xi+diag(U.ux)*inoloc; A22 = diag(U.uy); A24 = i*alpha*I; A32 = xi+diag(U.vy)*inoloc; A41 = diag(U.wx)*inoloc; A42 = diag(U.wy); A43 = xi; A44 = i*beta*I; A = [A11, O, A13, O ; ... A21, A22, O , A24; ... O, A32, O , O ; A41, A42, A43, A44]; ... %------------------------------------------------------------------ VD1 = diag(U.v)*D1*inoloc; B = [O, D1, O, O; ... VD1, O, O, O; ... O, VD1, O, D1; ... O, O, VD1, O ]; %------------------------------------------------------------------ C = [O, O, O, O; ... -D2/Re, O, O, O; ... O, -D2/Re, O, O; ... O, O, -D2/Re, O]; %------------------------------------------------------------------ if (local) D=zeros(size(A)); else u = diag(U.u); D = [I, O, O, O ; ... u, O, O, I*dpdx; ... O, u, O, O ; ... O, O, u, O ]; D = D + s*(A+B+C); %Include stabilisation term end %Left-hand-side and Right-hand-side of equation system LHS = A + B + C + D*eulco(3); RHS = -D*(eulco(1)*q1 + eulco(2)*q2); %--------------------------------------------------------------------- %Boundary conditions Ov = zeros(1,4*N); % u(ymax)=0 LHS(N+1,:) = Ov; LHS(N+1,1) = 1; RHS(N+1) = 0; % u(0)=0 LHS(2*N,:) = Ov; LHS(2*N, N) = 1; RHS(2*N) = 0; % v(ymax)=0 LHS(2*N+1,:) = Ov; LHS(2*N+1, N+1) = 1; RHS(2*N+1) = 0; if (local) % p(0)=1 LHS(3*N,:) = Ov; LHS(3*N, 4*N) = 1; RHS(3*N) = 1.0; else % v(0)=0 LHS(3*N,:) = Ov; LHS(3*N, 2*N) = 1; RHS(3*N) = 0; end % w(ymax)=0 LHS(3*N+1,:) = Ov; LHS(3*N+1, 2*N+1) = 1; RHS(3*N+1) = 0; % w(0)=0 LHS(4*N,:) = Ov; LHS(4*N, 3*N) = 1; RHS(4*N) = 0; end %------------------------------------------------------------------ function Ufsc=similar_fsc(y,mfac) % Ufsc=SIMILAR_FSC(YIN,MFAC) % This function computes the selfsimilar Falkner-Skan-Cook boundary-layer profiles % % Input % y: contains normal coordinates weher velocity values are required. % mfac: Falkner-Skan-Cooke parameter U=C*x^mfac. % % Output % Ufsc.u, Ufsc.v, Ufsc.w: streamwise, normal and spanwise velocity % Ufsc.uy, Ufsc.vy, Ufsc.wy: normal derivatives of u, v, and w % % (c) Ardeshir Hanifi & David Tempelmann % %------------------------------------------------------------------------------- % Start approximation for f'' and g' fbis= -0.0791*mfac^4+0.7414*mfac^3-1.4302*mfac^2+1.6813*mfac+0.3318; fbis=fbis*2/(mfac+1); gprim= -1.3429*mfac^4+2.6745*mfac^3-1.8293*mfac^2+0.7102*mfac+0.3244; gprim=gprim*2/(mfac+1); % Options for ODE solver options = odeset('RelTol',1e-12,'AbsTol',[1e-8 1e-8 1e-8 1e-8 1e-8]); tspan=[0 max(y)]; ic=[0 0 fbis 0 gprim]; % Integrate equations until convergend solution is found [yt,f]=ode45(@(t,y) fsc(t,y,mfac),tspan,ic,options); ue=f(end,2); ue1=ue; fbis1=fbis; fbis=fbis+0.01; tol=1e-8; while abs(ue-1)>tol ic=[0 0 fbis 0 1]; [yt,f]=ode45(@(t,y) fsc(t,y,mfac),tspan,ic,options); ue=f(end,2); dfbis=(1-ue)*(fbis-fbis1)/(ue-ue1); fbis1=fbis; ue1=ue; fbis=fbis+dfbis; end % Interpolate the velocity profiles on the input grid c=1/sqrt((mfac+1)/2); vv=((1.0-mfac)*f(:,2).*yt-(1.0+mfac)*f(:,1))*.5*c; vvz=((1.0-mfac)*f(:,2)+(1.0-mfac)*f(:,3).*yt-(1.0+mfac)*f(:,2))*.5*c; Ufsc.u=interp1(yt*c,f(:,2),y,'cubic'); Ufsc.w=interp1(yt*c,f(:,4)/f(end,4),y,'cubic'); Ufsc.v=interp1(yt*c,vv,y,'cubic'); Ufsc.uy=interp1(yt*c,f(:,3)/c,y,'cubic'); Ufsc.wy=interp1(yt*c,f(:,5)/f(end,4)/c,y,'cubic'); Ufsc.vy=interp1(yt*c,vvz/c,y,'cubic'); end
github
ShaocongDong/QF4102-Financial-Modelling-master
New_Euro_float_lookback_put.m
.m
QF4102-Financial-Modelling-master/Assignment1/New_Euro_float_lookback_put.m
961
utf_8
2b319b5fcf97e0826c4520d7cf4c4e91
%Group G04 %Dong Shaocong A0148008J %He Xinyi A0141132B function opt_value = New_Euro_float_lookback_put(S0, r, T, sigma, q, N) % Sample BTM program for European floating strike options % q: the continuous dividend rate % S0: current underlier price % X: strike price % T: time to maturity, in years % sigma: volatility of the underlier % r: risk free interest rate % N: number of periods % set up lattice parameters dt=T/N; dx=sigma*sqrt(dt); u=exp(dx); d=1/u; df=exp(-r*dt); p=(exp((r-q)*dt)-d)/(u-d); % initialization jshift = 1; nshift = 1; V = rand(N+1,N+1); j = 0:1:N; V(j+jshift,N+nshift) = exp(j*dx)-1; % backward recursive through time for n = N-1:-1:0 V(0+jshift,n+nshift) = df*(p*u*V(0+jshift,n+1+nshift)... + (1-p)*d*V(1+jshift, n+1+nshift)); for j = 1:1:n V(j+jshift,n+nshift) = df*(p*u*V(j-1+jshift,n+1+nshift)... + (1-p)*d*V(j+1+jshift, n+1+nshift)); end end % opt_value=S0*V(0+jshift, 0+nshift); end
github
ShaocongDong/QF4102-Financial-Modelling-master
BTM_Euro_down_out_call.m
.m
QF4102-Financial-Modelling-master/Assignment1/BTM_Euro_down_out_call.m
1,005
utf_8
36b8f3a55934275392a20b6d8659fc8f
%Group G04 %Dong Shaocong A0148008J %He Xinyi A0141132B function opt_value = BTM_Euro_down_out_call(S0, X, r, T, sigma, q, N, H) % Sample BTM program for European down and out call options % q: the continuous dividend rate % H: the barrier level % S0: current underlier price % X: strike price % T: time to maturity, in years % sigma: volatility of the underlier % r: risk free interest rate % N: number of periods % set up lattice parameters dt=T/N; dx=sigma*sqrt(dt); u=exp(dx); d=1/u; df=exp(-r*dt); p=(exp((r-q)*dt)-d)/(u-d); % initialization jshift = 1; V = rand(N+1,1); for j = 0:1:N price = S0*u^(2*j-N); if (price<H) V(j+jshift) = 0; else V(j+jshift) = max(price - X,0); end end % backward recursive through time for n = N-1:-1:0 for j = 0:1:n price = S0*u^(2*j-n); if (price<H) V(j+jshift) = 0; else V(j+jshift) = df*(p*V(j+1+jshift) + (1-p)*V(j+jshift)); end end end % opt_value=V(0+jshift); end
github
ShaocongDong/QF4102-Financial-Modelling-master
Euro_down_out_call.m
.m
QF4102-Financial-Modelling-master/Assignment1/Euro_down_out_call.m
1,426
utf_8
626cfa9ccddf91ede6649c83bbd97d73
%Group G04 %Dong Shaocong A0148008J %He Xinyi A0141132B function opt_value = Euro_down_out_call (q, H, S0, X, t, r, sigma) % Exact solution for European down-and-out call option % This function is able to work with the intial underlier price S0 in a % vector form; whereas the rest of the inputs are real numbers. % Cdo: option price for the down-and-out call % C: Black-Schole price for the equivalent vanilla call % q: the continuous dividend rate % H: the barrier level % S0: current underlier price % X: strike price % t: time to matuirity, in years % sigma: volatility of the underlier % r: risk free interest rate %Initialization lambda = (r-q+sigma^2/2)/(sigma^2); %constant y = log((H^2/X)./S0)./(sigma*sqrt(t)) + lambda*sigma*sqrt(t); %vector x1 = log(S0./H)./(sigma*sqrt(t)) + lambda*sigma*sqrt(t); %vector y1 = log(H./S0)./(sigma*sqrt(t)) + lambda*sigma*sqrt(t); %vector C = Black_Scholes (t, S0, X, r, q, sigma); %constant %Cp = Black_Scholes (t, H^2./S0, X, r, q, sigma); %vector %Main Logic if (H<X || H==X) opt_value = C - (S0.*exp(-q*t)).*(H./S0).^(2*lambda).*normcdf(y)... + (X*exp(-r*t)).*(H./S0).^(2*lambda-2).*normcdf(y-sigma*sqrt(t)); else opt_value = S0.*(normcdf(x1)*exp(-q*t))... - X*exp(-r*t)*normcdf(x1-sigma*sqrt(t))... - S0.*exp(-q*t).*(H./S0).^(2*lambda).*normcdf(y1)... + (X*exp(-r*t)).*(H./S0).^(2*lambda -2).*normcdf(y1-sigma*sqrt(t)); end end
github
ShaocongDong/QF4102-Financial-Modelling-master
Black_Scholes.m
.m
QF4102-Financial-Modelling-master/Assignment1/Black_Scholes.m
517
utf_8
68a903751b9c44dadabd1a836e326948
%Group G04 %Dong Shaocong A0148008J %He Xinyi A0141132B function c = Black_Scholes (t, S0, X, r, q, sigma) % t: time to maturity % S0: the current spot price of the underlying asset % X: the strike price % r: the risk free rate % q: continuous dividend yield % sigma: the volatility of the underlying asset's return % One can also directly use the normcdf to calculate the N value d1=(log(S0/X)+(r-q+sigma^2/2)*t)/sigma/sqrt(t); d2=d1-sigma*sqrt(t); c=exp(-q*t)*S0.*normcdf(d1)-exp(-r*t)*X*normcdf(d2); return end
github
ShaocongDong/QF4102-Financial-Modelling-master
Old_Euro_float_lookback_put.m
.m
QF4102-Financial-Modelling-master/Assignment1/Old_Euro_float_lookback_put.m
1,222
utf_8
3cb484039bab04db4f78aca5300f21bc
%Group G04 %Dong Shaocong A0148008J %He Xinyi A0141132B function opt_value = Old_Euro_float_lookback_put(S0, r, T, sigma, q, N, running) % Sample BTM program for European floating strike options % q: the continuous dividend rate % S0: current underlier price % X: strike price % T: time to maturity, in years % sigma: volatility of the underlier % r: risk free interest rate % N: number of periods % set up lattice parameters dt=T/N; dx=sigma*sqrt(dt); u=exp(dx); d=1/u; df=exp(-r*dt); p=(exp((r-q)*dt)-d)/(u-d); x0 = log(max(S0,running)/S0); k = floor(x0/dx); % initialization jshift = 1; nshift = 1; initial = max(k-N,0); V = rand(k+N+2,N+1); j = initial:1:(k+N+1); V(j+jshift,N+nshift) = exp(j*dx)-1; % backward recursive through time for n = N-1:-1:0 if (k-n <= 0) V(0+jshift,n+nshift) = df*(p*u*V(0+jshift,n+1+nshift)... + (1-p)*d*V(1+jshift, n+1+nshift)); end for j = max((k-n),1):1:(k+n+1) V(j+jshift,n+nshift) = df*(p*u*V(j-1+jshift,n+1+nshift)... + (1-p)*d*V(j+1+jshift, n+1+nshift)); end end % interpolation y1=S0*V(k+jshift, 0+nshift); y2=S0*V(k+1+jshift, 0+nshift); x1=k*dx; x2=(k+1)*dx; opt_value = ((x0-x2)/(x1-x2))*y1 + ((x0-x1)/(x2-x1))*y2; end
github
ShaocongDong/QF4102-Financial-Modelling-master
FD_ids_call_trans.m
.m
QF4102-Financial-Modelling-master/Assignment3/FD_ids_call_trans.m
2,099
utf_8
a865de9a4b5114142dbbdff9e1e790f5
%% Finite Difference - fully implicit scheme for: % transformed European vanilla call options % calling syntax: % v=FD_ids_call_trans(S0, X, r, q, T, sigma, I, N, xmax) %function fd_v=FD_ids_put(S0, X, r, T, sig, N, dS) function OptVal=FD_ids_call_trans(S0, X, r, q, T, sigma, I, N, xmax) %% Initialization dt = T/N; dx = xmax/I; % as defined in the question VGrid=zeros(2*I+1,N+1); % finite difference grid (-xmax, xmax) so 2*I+1 %% Boundary conditions VGrid(1,:) = 0; % at -xmax, too small stock price, value 0 VGrid(2*I+1,:) = exp(xmax)*exp(-q*(T-(0:dt:T))) - X*exp(-r*(T-(0:dt:T))); %% Terminal condition VGrid(:,N+1)=max((exp(-xmax:dx:xmax)-X), 0); % for every possible x %% Looping and parameters setup alpha = sigma^2*dt/(dx^2); beta = dt*(r-q-sigma^2/2)/(2*dx); a = (beta - alpha/2) * ones(2*I-1,1); b = (1 + alpha + r*dt) * ones(2*I-1,1); c = (-alpha/2 - beta) * ones(2*I-1,1); CoeffMatrix=spdiags ([c, b, a],-1:1, 2*I-1, 2*I-1)'; %% Loop ishift=1; for n=N:-1:1 % backward time recursive RhsB = VGrid(1+ishift:2*I-1+ishift, n+1); RhsB(1) =RhsB(1) -a(1)*VGrid(0+ishift,n); RhsB(2*I-1)=RhsB(2*I-1)-c(2*I-1)*VGrid(2*I+ishift,n); VGrid(1+ishift:2*I-1+ishift,n)=CoeffMatrix\RhsB; end; %% Linear Interpolation and Value comparisons ExactValue=Ce(S0,X,r,T,sigma,q); lower_index = floor(round(log(S0)/dx,1)) + I; higher_index = lower_index+1; Low_Val=VGrid(lower_index+ishift,1); High_Val=VGrid(higher_index+ishift,1); OptVal = LinearInterpolate(S0, exp(lower_index*dx-xmax),... exp(higher_index*dx-xmax), Low_Val, High_Val); disp(['At S0=',num2str(S0),' exact value=',... num2str(ExactValue),' FD value=',num2str(OptVal)]); end function y=Ce(S,X,r,t,sigma,q) %% European vanilla call exact value solution d1=(log(S/X)+(r-q+sigma*sigma/2)*t)/sigma/sqrt(t); d2=d1-sigma*sqrt(t); y=-X*exp(-r*t)*normcdf(d2)+S*exp(-q*t)*normcdf(d1); end function sol = LinearInterpolate(x, x0, x1, f0, f1) %% Linear interpolation function sol = (x - x1) / (x0 - x1) * f0 + (x - x0) / (x1 - x0) * f1; end
github
ShaocongDong/QF4102-Financial-Modelling-master
FD_ids_Acall_trans.m
.m
QF4102-Financial-Modelling-master/Assignment3/FD_ids_Acall_trans.m
1,839
utf_8
4b15fa5ad23d4c4ada6d9013371c4959
%% Finite Difference - fully implicit scheme for: % transformed American vanilla call options % calling syntax: % v=FD_ids_Acall_trans(S0, X, r, q, T, sigma, I, N, xmax, omega, eps) function OptVal=FD_ids_Acall_trans(S0, X, r, q, T, sigma, I, N, xmax, omega, eps) %% Initialization dt = T/N; dx = xmax/I; % as defined in the question %% Looping and parameters setup alpha = sigma^2*dt/(dx^2); beta = dt*(r-q-sigma^2/2)/(2*dx); a = (beta - alpha/2); b = (1 + alpha + r*dt); c = (-alpha/2 - beta); %CoeffMatrix=spdiags ([c, b, a],-1:1, 2*I-1, 2*I-1)'; priceVector = exp(-xmax:dx:xmax)'; payoffVector = max((priceVector(:)-X), 0); VGrid = payoffVector; %% Loop ishift=1; for n=N:-1:1 % backward time recursive VGrid = psor(I, a, b, c, VGrid, eps, omega, payoffVector); end; %% Linear Interpolation and Value comparisons lower_index = floor(log(S0)/dx) + I; higher_index = lower_index+1; Low_Val=VGrid(lower_index+ishift,1); High_Val=VGrid(higher_index+ishift,1); OptVal = LinearInterpolate(S0, exp(lower_index*dx-xmax),... exp(higher_index*dx-xmax), Low_Val, High_Val); disp(['At S0=',num2str(S0), ' FD value=',num2str(OptVal)]); end function sol = LinearInterpolate(x, x0, x1, f0, f1) %% Linear interpolation function sol = (x - x1) / (x0 - x1) * f0 + (x - x0) / (x1 - x0) * f1; end function Vn = psor(I, a, b, c, Vnplus, eps, omega, fai) %% Function for psor iterative algorithm converged = false; Vk = Vnplus; Vkplus = Vk; Vgs = Vkplus; while (converged == false) for i=2:1:2*I-1 % compute iterate k+1 Vgs(i) = 1/b * (-a*Vkplus(i-1) - c*Vk(i+1) + Vnplus(i)); Vkplus(i) = max(((1-omega)*Vk(i) + omega*Vgs(i)), fai(i)); end if ((norm(Vk-Vkplus)) < eps) converged = true; end Vk = Vkplus; end Vn = Vk; end
github
ShaocongDong/QF4102-Financial-Modelling-master
BS_DigitalCall.m
.m
QF4102-Financial-Modelling-master/Assignment3/BS_DigitalCall.m
207
utf_8
c58a36f5849fde5195c493183cd275e9
%% Function for exact solution of digital option % Call syntax: function OptVal=BS_DigitalCall(S0, X, r, q, T, sigma) x = (log(S0/X)+(r-q-sigma^2/2)*T) / (sigma*sqrt(T)); OptVal = exp(-r*T)*normcdf(x); end
github
ShaocongDong/QF4102-Financial-Modelling-master
FD_eds_put.m
.m
QF4102-Financial-Modelling-master/lec_code/FD_eds_put.m
2,083
utf_8
5ec896974d4bde947988dc3b0a19b0e7
% Finite Difference - explicit scheme(S) for vanilla put options % % calling syntax: % v=FD_eds_put(S0, X, r, T, sig, N, dS) % function fd_v=FD_eds_put(S0, X, r, T, sig, N, dS) % For Explicit schemes, N has to be chosen large enough to avoid % violating the monotinicity condition % Smax=3*X; % set maximum S to be three times the strike value dt=T/N; I=round(Smax/dS); % VGrid=zeros(I+1,N+1); % finite difference grid ishift=1; % Boundary conditions VGrid(1,:)=X*exp(-r*(T-(0:dt:T))); % at S=0; VGrid(I+1,:)=0; % at Smax, unlikely to have positive payoff for large S % Terminal condition VGrid(:,N+1)=max(X-(0:I)*dS,0); i=(1:I-1)'; isq=i.^2; % Explicit Scheme I c=(0.5*sig^2*isq+0.5*r*i)*dt; b=1-sig^2*isq*dt-r*dt; a=(0.5*sig^2*isq-0.5*r*i)*dt; % Explicit Scheme II % c=(0.5*sig^2*isq+0.5*r*i)*dt/(1+r*dt); % b=(1-sig^2*isq*dt)/(1+r*dt); % a=(0.5*sig^2*isq-0.5*r*i)*dt/(1+r*dt); % Explicit Scheme III % c=(0.5*sig^2*isq+r*i)*dt/(1+r*dt); % b=(1-sig^2*isq*dt-r*i*dt)/(1+r*dt); % a=(0.5*sig^2*isq)*dt/(1+r*dt); % Check on monotonicity len01=length(a); len02=length(find(a<0)); disp(['Coeff a, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); len01=length(b); len02=length(find(b<0)); disp(['Coeff b, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); len01=length(c); len02=length(find(c<0)); disp(['Coeff c, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); i=(1:I-1)'+ishift; for n=N:-1:1 % backward time recursive VGrid(i,n)=a.*VGrid(i-1,n+1)+b.*VGrid(i,n+1)+c.*VGrid(i+1,n+1); % plot(VGrid(i,n)); title(num2str(n)); % pause(0.15); end; ExactValue=Pe(S0,X,r,T,sig,0); fd_v=VGrid(round(S0/dS)+ishift,1); disp(['At S0=',num2str(S0),' exact value=',num2str(ExactValue),' FD value=',num2str(fd_v)]); function y=Pe(S,X,r,t,sigma,q) d1=(log(S/X)+(r-q+sigma*sigma/2)*t)/sigma/sqrt(t); d2=d1-sigma*sqrt(t); y=X*exp(-r*t)*normcdf(-d2)-S*exp(-q*t)*normcdf(-d1);
github
ShaocongDong/QF4102-Financial-Modelling-master
BS_call.m
.m
QF4102-Financial-Modelling-master/lec_code/BS_call.m
284
utf_8
672dbaf1f5822d05c7d3802698694d91
% Black-Scholes formulae for European vanilla call % call syntax: c = BS_call(S0, X, r, T, sigma, q) function c = bs_call(S0, X, r, T, sigma, q) d1=(log(S0/X)+(r-q+sigma^2/2)*T)/sigma/sqrt(T); d2=d1-sigma*sqrt(T); c=exp(-q*T)*S0.*normcdf(d1)-exp(-r*T)*X*normcdf(d2); return
github
ShaocongDong/QF4102-Financial-Modelling-master
FD_ids_put.m
.m
QF4102-Financial-Modelling-master/lec_code/FD_ids_put.m
1,268
utf_8
1470caec9a1007a8e7efb71debc7475d
% Finite Difference - fully implicit scheme for vanilla put options % calling syntax: % v=FD_ids_put(S0, X, r, T, sig, N, dS) function fd_v=FD_ids_put(S0, X, r, T, sig, N, dS) Smax=3*X; % set maximum S to be three times the strike value dt=T/N; I=round(Smax/dS); % VGrid=zeros(I+1,N+1); % finite difference grid % Boundary conditions VGrid(1,:)=X*exp(-r*(T-(0:dt:T))); % at S=0; VGrid(I+1,:)=0; % at Smax, unlikely to have positive payoff for large S % Terminal condition VGrid(:,N+1)=max(X-(0:I)*dS,0); i=(1:I-1)'; isq=i.^2; a= -0.5*(sig^2*isq - r*i)*dt; b=(1 + sig^2*isq*dt + r*dt); c= -0.5*(sig^2*isq + r*i)*dt; CoeffMatrix=spdiags([c, b, a],-1:1, I-1, I-1)'; ishift=1; for n=N:-1:1 % backward time recursive RhsB=VGrid(i+ishift,n+1); RhsB(1) =RhsB(1) -a(1) *VGrid(0+ishift,n); RhsB(I-1)=RhsB(I-1)-c(I-1)*VGrid(I+ishift,n); VGrid(i+ishift,n)=CoeffMatrix\RhsB; end; ExactValue=Pe(S0,X,r,T,sig,0); fd_v=VGrid(round(S0/dS)+ishift,1); disp(['At S0=',num2str(S0),' exact value=',num2str(ExactValue),' FD value=',num2str(fd_v)]); function y=Pe(S,X,r,t,sigma,q) d1=(log(S/X)+(r-q+sigma*sigma/2)*t)/sigma/sqrt(t); d2=d1-sigma*sqrt(t); y=X*exp(-r*t)*normcdf(-d2)-S*exp(-q*t)*normcdf(-d1);
github
ShaocongDong/QF4102-Financial-Modelling-master
MC_EurCall.m
.m
QF4102-Financial-Modelling-master/lec_code/MC_EurCall.m
518
utf_8
9ddd38e0a761f588432d8b85cb4b5f1b
% Sample Monte-Carlo simulation program for European vanilla call options % % call syntax: Euro_vanilla_call=MC_EurCall(S0,X,r,T,sigma,q,no_samples) % function Euro_vanilla_call=MC_EurCall(S0,X,r,T,sigma,q,no_samples) % mu=r-q-sigma^2/2; epsv=randn(no_samples,1); % random standard normal numbers ST=S0*exp(mu*T+epsv*sigma*sqrt(T)); % terminal prices in a vector Euro_vanilla_call=exp(-r*T)*mean(max(ST-X,0)); % discounted expectation % of the payoffs
github
ShaocongDong/QF4102-Financial-Modelling-master
btm_EurCall.m
.m
QF4102-Financial-Modelling-master/lec_code/btm_EurCall.m
591
utf_8
e19760108661595bb5d310acf83fe071
% Sample BTM program for European vanilla call options % call syntax: OptVal=btm_EurCall(S0,X,r,T,sigma,q,N) function OptVal=btm_EurCall(S0,X,r,T,sigma,q,N) % set up lattice parameters dt=T/N; dx=sigma*sqrt(dt); u=exp(dx); d=1/u; df=exp(-r*dt); % discount factor p=(exp((r-q)*dt)-d)/(u-d); % risk-neutral probability % initialization j = 0:1:N; jshift = 1; % range of index for price states V(j+jshift)=max(S0*u.^(2*j-N)-X,0); % backward recursive through time for n=N-1:-1:0 j = 0:1:n; V=df*(p*V(j+1+jshift)+(1-p)*V(j+jshift)); end OptVal=V(0+jshift);
github
ShaocongDong/QF4102-Financial-Modelling-master
A2qivfunc.m
.m
QF4102-Financial-Modelling-master/Assignment2/A2qivfunc.m
1,356
utf_8
7b105144760b8e166b76648a79e7fb96
function fd_v=A2qivfunc(S0, X, r, q, T, sig, dt, dS) %% Meanings of the parameters % S0: the current underlier price % X: % r: the market's risk free rate % q: the underlier's dividend yield % T: the time to maturity of this option % sig: vollatility of the underlier price % dt: the small interval of time % dS: the small interval of underlier price %% Initial set up Smax=4*X; % set maximum S to be four times the strike value N = round(T/dt); I = round(Smax/dS); VGrid=zeros(I+1,N+1); % finite difference grid ishift=1; %% Conditions % Boundary conditions VGrid(1,:)=0; % at S=0; VGrid(I+1,:)=(Smax-X)*exp(-r*(T-(0:dt:T))); % at Smax, unlikely to have positive payoff for large S % Terminal condition VGrid(:,N+1)=max((0:I)*dS-X,0); i=(1:I-1)'; isq=i.^2; %% Explicit Scheme III c=(0.5*sig^2*isq+(r-q)*i)*dt/(1+r*dt); b=(1-sig^2*isq*dt-(r-q)*i*dt)/(1+r*dt); a=(0.5*sig^2*isq)*dt/(1+r*dt); i=(1:I-1)'+ishift; for n=N:-1:1 % backward time recursive VGrid(i,n)=max(a.*VGrid(i-1,n+1)+b.*VGrid(i,n+1)+c.*VGrid(i+1,n+1), (i*dS-X).*exp(-r*i*dt) ); end; ExactValue=Ce(S0,X,r,T,sig,q); fd_v=VGrid(round(S0/dS)+ishift,1); end function y=Ce(S,X,r,t,sigma,q) d1=(log(S/X)+(r-q+sigma*sigma/2)*t)/sigma/sqrt(t); d2=d1-sigma*sqrt(t); %y=X*exp(-r*t)*normcdf(-d2)-S*exp(-q*t)*normcdf(-d1); y = S*normcdf(d1) - normcdf(d2)*X*exp(-r*t); end
github
ShaocongDong/QF4102-Financial-Modelling-master
EDSiiiAmericanVanillaCall.m
.m
QF4102-Financial-Modelling-master/Assignment2/submission/EDSiiiAmericanVanillaCall.m
1,942
utf_8
3b7484c56d80fc4b7be438f817b2cd4b
function fd_v=EDSiiiAmericanVanillaCall(S0, X, r, q, T, sig, N, dS) %% Meanings of the parameters % S0: the current underlier price % X: % r: the market's risk free rate % q: the underlier's dividend yield % T: the time to maturity of this option % sig: vollatility of the underlier price % dt: the small interval of time % dS: the small interval of underlier price %% Initial set up Smax=4*X; % set maximum S to be four times the strike value dt = T/N; I = round(Smax/dS); VGrid=zeros(I+1,N+1); % finite difference grid ishift=1; %% Conditions % Boundary conditions VGrid(1,:)=0; % at S=0; VGrid(I+1,:)=(Smax-X)*exp(-r*(T-(0:dt:T))); % at Smax, unlikely to have positive payoff for large S % Terminal condition VGrid(:,N+1)=max((0:I)*dS-X,0); i=(1:I-1)'; isq=i.^2; %% Explicit Scheme III c=(0.5*sig^2*isq+(r-q)*i)*dt/(1+r*dt); b=(1-sig^2*isq*dt-(r-q)*i*dt)/(1+r*dt); a=(0.5*sig^2*isq)*dt/(1+r*dt); % Check on monotonicity len01=length(a); len02=length(find(a<0)); % disp(['Coeff a, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); len01=length(b); len02=length(find(b<0)); % disp(['Coeff b, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); len01=length(c); len02=length(find(c<0)); % disp(['Coeff c, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); i=(1:I-1)'+ishift; for n=N:-1:1 % backward time recursive VGrid(i,n)=max(a.*VGrid(i-1,n+1)+b.*VGrid(i,n+1)+c.*VGrid(i+1,n+1), (((i-ishift)*dS-X))*exp(-r*n*dt)); end ExactValue=Ce(S0,X,r,T,sig,q); fd_v=VGrid(round(S0/dS)+ishift,1); % disp(['At S0=',num2str(S0),' exact value=',num2str(ExactValue),' FD value=',num2str(fd_v)]); end function y=Ce(S,X,r,t,sigma,q) d1=(log(S/X)+(r-q+sigma*sigma/2)*t)/sigma/sqrt(t); d2=d1-sigma*sqrt(t); %y=X*exp(-r*t)*normcdf(-d2)-S*exp(-q*t)*normcdf(-d1); y = S*normcdf(d1) - normcdf(d2)*X*exp(-r*t); end
github
ShaocongDong/QF4102-Financial-Modelling-master
EDSiiiEuropeanVanillaCall.m
.m
QF4102-Financial-Modelling-master/Assignment2/submission/EDSiiiEuropeanVanillaCall.m
1,921
utf_8
2c3f8465dfbfe31b0632987464090015
function fd_v=EDSiiiEuropeanVanillaCall(S0, X, r, q, T, sig, N, dS) %% Meanings of the parameters % S0: the current underlier price % X: % r: the market's risk free rate % q: the underlier's dividend yield % T: the time to maturity of this option % sig: vollatility of the underlier price % dt: the small interval of time % dS: the small interval of underlier price %% Initial set up Smax=4*X; % set maximum S to be four times the strike value dt = T/N; I = round(Smax/dS); VGrid=zeros(I+1,N+1); % finite difference grid ishift=1; %% Conditions % Boundary conditions VGrid(1,:)=0; % at S=0; VGrid(I+1,:)=(Smax-X)*exp(-r*(T-(0:dt:T))); % at Smax, unlikely to have positive payoff for large S % Terminal condition VGrid(:,N+1)=max((0:I)*dS-X,0); i=(1:I-1)'; isq=i.^2; %% Explicit Scheme III c=(0.5*sig^2*isq+(r-q)*i)*dt/(1+r*dt); b=(1-sig^2*isq*dt-(r-q)*i*dt)/(1+r*dt); a=(0.5*sig^2*isq)*dt/(1+r*dt); % Check on monotonicity len01=length(a); len02=length(find(a<0)); % disp(['Coeff a, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); len01=length(b); len02=length(find(b<0)); % disp(['Coeff b, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); len01=length(c); len02=length(find(c<0)); % disp(['Coeff c, Of ',num2str(len01), ' elements, ', num2str(len02),' violated the positivity condition.']); i=(1:I-1)'+ishift; for n=N:-1:1 % backward time recursive VGrid(i,n)=a.*VGrid(i-1,n+1)+b.*VGrid(i,n+1)+c.*VGrid(i+1,n+1); end; ExactValue=Ce(S0,X,r,T,sig,q); fd_v=VGrid(round(S0/dS)+ishift,1); % disp(['At S0=',num2str(S0),' exact value=',num2str(ExactValue),' FD value=',num2str(fd_v)]); end function y=Ce(S,X,r,t,sigma,q) d1=(log(S/X)+(r-q+sigma*sigma/2)*t)/sigma/sqrt(t); d2=d1-sigma*sqrt(t); %y=X*exp(-r*t)*normcdf(-d2)-S*exp(-q*t)*normcdf(-d1); y = S*normcdf(d1)*exp(-q*t) - normcdf(d2)*X*exp(-r*t); end
github
mapDIA/mapDIA-master
NLOPT_GN_ORIG_DIRECT.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_ORIG_DIRECT.m
164
utf_8
43ae70342fc7484716698f445981512b
% NLOPT_GN_ORIG_DIRECT: Original DIRECT version (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_ORIG_DIRECT val = 6;
github
mapDIA/mapDIA-master
NLOPT_LN_BOBYQA.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_BOBYQA.m
189
utf_8
15ba6db5057c8907343184908e0ecf06
% NLOPT_LN_BOBYQA: BOBYQA bound-constrained optimization via quadratic models (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_BOBYQA val = 34;
github
mapDIA/mapDIA-master
NLOPT_GN_DIRECT.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_DIRECT.m
137
utf_8
915b9f3f3a223d681a10bfaa80318309
% NLOPT_GN_DIRECT: DIRECT (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT val = 0;
github
mapDIA/mapDIA-master
NLOPT_LD_MMA.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_MMA.m
155
utf_8
7e4519526e6353452086a1cf929b12ad
% NLOPT_LD_MMA: Method of Moving Asymptotes (MMA) (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_MMA val = 24;
github
mapDIA/mapDIA-master
NLOPT_GN_DIRECT_L.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_L.m
143
utf_8
ae13ecf48a1ee6d222444643f59c2993
% NLOPT_GN_DIRECT_L: DIRECT-L (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_L val = 1;
github
mapDIA/mapDIA-master
NLOPT_LD_VAR1.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_VAR1.m
168
utf_8
45d4388965becdc240350c73a2779757
% NLOPT_LD_VAR1: Limited-memory variable-metric, rank 1 (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_VAR1 val = 13;
github
mapDIA/mapDIA-master
NLOPT_GN_DIRECT_L_NOSCAL.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_L_NOSCAL.m
166
utf_8
c20477ea33399f3311ea6e533dc347ae
% NLOPT_GN_DIRECT_L_NOSCAL: Unscaled DIRECT-L (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_L_NOSCAL val = 4;
github
mapDIA/mapDIA-master
NLOPT_LN_COBYLA.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_COBYLA.m
189
utf_8
2c95152f70105c8ca20929fba67d12a2
% NLOPT_LN_COBYLA: COBYLA (Constrained Optimization BY Linear Approximations) (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_COBYLA val = 25;
github
mapDIA/mapDIA-master
NLOPT_LN_AUGLAG_EQ.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_AUGLAG_EQ.m
189
utf_8
5432778c9b81b5fdcfb98ca1bbbd6486
% NLOPT_LN_AUGLAG_EQ: Augmented Lagrangian method for equality constraints (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_AUGLAG_EQ val = 32;
github
mapDIA/mapDIA-master
NLOPT_GN_DIRECT_L_RAND.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_L_RAND.m
164
utf_8
2135dc3891b556738f41c2a35009b227
% NLOPT_GN_DIRECT_L_RAND: Randomized DIRECT-L (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_L_RAND val = 2;
github
mapDIA/mapDIA-master
NLOPT_GN_MLSL.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_MLSL.m
169
utf_8
93ab4e64e2760c4ca201fada42cb05c3
% NLOPT_GN_MLSL: Multi-level single-linkage (MLSL), random (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_MLSL val = 20;
github
mapDIA/mapDIA-master
NLOPT_GD_MLSL_LDS.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GD_MLSL_LDS.m
180
utf_8
7f41fd0094df543c2e45280f86c0b87b
% NLOPT_GD_MLSL_LDS: Multi-level single-linkage (MLSL), quasi-random (global, derivative) % % See nlopt_minimize for more information. function val = NLOPT_GD_MLSL_LDS val = 23;
github
mapDIA/mapDIA-master
NLOPT_LD_AUGLAG_EQ.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_AUGLAG_EQ.m
186
utf_8
41b81c30c553388e2ff1b6b1fb681618
% NLOPT_LD_AUGLAG_EQ: Augmented Lagrangian method for equality constraints (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_AUGLAG_EQ val = 33;
github
mapDIA/mapDIA-master
NLOPT_LD_CCSAQ.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_CCSAQ.m
214
utf_8
33892896fe470090edb583b50b9e7d93
% NLOPT_LD_CCSAQ: CCSA (Conservative Convex Separable Approximations) with simple quadratic approximations (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_CCSAQ val = 41;
github
mapDIA/mapDIA-master
NLOPT_LD_AUGLAG.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_AUGLAG.m
155
utf_8
2d7d515e911b5d0277490940a47f333e
% NLOPT_LD_AUGLAG: Augmented Lagrangian method (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_AUGLAG val = 31;
github
mapDIA/mapDIA-master
NLOPT_GN_DIRECT_L_RAND_NOSCAL.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_L_RAND_NOSCAL.m
187
utf_8
3287f776b0f2ac5e3495c2a4c95ba4e7
% NLOPT_GN_DIRECT_L_RAND_NOSCAL: Unscaled Randomized DIRECT-L (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_L_RAND_NOSCAL val = 5;
github
mapDIA/mapDIA-master
NLOPT_LN_SBPLX.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_SBPLX.m
196
utf_8
c99ee02eb277898e9c509dd359740680
% NLOPT_LN_SBPLX: Sbplx variant of Nelder-Mead (re-implementation of Rowan's Subplex) (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_SBPLX val = 29;
github
mapDIA/mapDIA-master
NLOPT_GN_ISRES.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_ISRES.m
173
utf_8
2c12964785aed0828a5ac17fc416f5be
% NLOPT_GN_ISRES: ISRES evolutionary constrained optimization (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_ISRES val = 35;
github
mapDIA/mapDIA-master
NLOPT_LD_VAR2.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_VAR2.m
168
utf_8
5ba0bd034c240547765a0fd4ce90c825
% NLOPT_LD_VAR2: Limited-memory variable-metric, rank 2 (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_VAR2 val = 14;
github
mapDIA/mapDIA-master
NLOPT_AUGLAG_EQ.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_AUGLAG_EQ.m
182
utf_8
2f8b59b483a4f2621264c7de9df58365
% NLOPT_AUGLAG_EQ: Augmented Lagrangian method for equality constraints (needs sub-algorithm) % % See nlopt_minimize for more information. function val = NLOPT_AUGLAG_EQ val = 37;
github
mapDIA/mapDIA-master
NLOPT_LN_NELDERMEAD.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_NELDERMEAD.m
168
utf_8
219928fdd3fc8317d321f9f0535d550f
% NLOPT_LN_NELDERMEAD: Nelder-Mead simplex algorithm (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_NELDERMEAD val = 28;
github
mapDIA/mapDIA-master
NLOPT_LN_NEWUOA.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_NEWUOA.m
185
utf_8
b318db6792885a5d23dcfd5b28fdc507
% NLOPT_LN_NEWUOA: NEWUOA unconstrained optimization via quadratic models (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_NEWUOA val = 26;
github
mapDIA/mapDIA-master
NLOPT_GN_CRS2_LM.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_CRS2_LM.m
185
utf_8
9a171159b83c77e07256a24704139d8a
% NLOPT_GN_CRS2_LM: Controlled random search (CRS2) with local mutation (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_CRS2_LM val = 19;
github
mapDIA/mapDIA-master
NLOPT_LN_PRAXIS.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_PRAXIS.m
153
utf_8
c7d354e0602183d0d3a7ff71641ab7b4
% NLOPT_LN_PRAXIS: Principal-axis, praxis (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_PRAXIS val = 12;
github
mapDIA/mapDIA-master
NLOPT_LD_SLSQP.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_SLSQP.m
164
utf_8
e767cc9cde902065e67a31664a571819
% NLOPT_LD_SLSQP: Sequential Quadratic Programming (SQP) (local, derivative) % % See nlopt_minimize for more information. function val = NLOPT_LD_SLSQP val = 40;
github
mapDIA/mapDIA-master
NLOPT_G_MLSL_LDS.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_G_MLSL_LDS.m
187
utf_8
dfafcdb44b43c59aa5e4d5b73542dc50
% NLOPT_G_MLSL_LDS: Multi-level single-linkage (MLSL), quasi-random (global, needs sub-algorithm) % % See nlopt_minimize for more information. function val = NLOPT_G_MLSL_LDS val = 39;
github
mapDIA/mapDIA-master
NLOPT_LD_TNEWTON.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_TNEWTON.m
152
utf_8
5e00532d1e34e85f395f6ace048d7d64
% NLOPT_LD_TNEWTON: Truncated Newton (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_TNEWTON val = 15;
github
mapDIA/mapDIA-master
NLOPT_LD_LBFGS_NOCEDAL.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_LBFGS_NOCEDAL.m
184
utf_8
7b1380ab03a2272b6e3f1c0f49e4babf
% NLOPT_LD_LBFGS_NOCEDAL: original NON-FREE L-BFGS code by Nocedal et al. (NOT COMPILED) % % See nlopt_minimize for more information. function val = NLOPT_LD_LBFGS_NOCEDAL val = 10;
github
mapDIA/mapDIA-master
NLOPT_GD_STOGO.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GD_STOGO.m
137
utf_8
1b374b07cc8dd1fd43998c8f60f49267
% NLOPT_GD_STOGO: StoGO (global, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_GD_STOGO val = 8;
github
mapDIA/mapDIA-master
NLOPT_AUGLAG.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_AUGLAG.m
151
utf_8
a4a6ef23ad60f4ceab26caae4276c02d
% NLOPT_AUGLAG: Augmented Lagrangian method (needs sub-algorithm) % % See nlopt_minimize for more information. function val = NLOPT_AUGLAG val = 36;
github
mapDIA/mapDIA-master
NLOPT_GD_MLSL.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GD_MLSL.m
166
utf_8
3735615f01a5de64ba710bfa7b7eba3a
% NLOPT_GD_MLSL: Multi-level single-linkage (MLSL), random (global, derivative) % % See nlopt_minimize for more information. function val = NLOPT_GD_MLSL val = 21;
github
mapDIA/mapDIA-master
NLOPT_GN_DIRECT_NOSCAL.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_DIRECT_NOSCAL.m
160
utf_8
9f11af031bd7ca9c9348de64f7169482
% NLOPT_GN_DIRECT_NOSCAL: Unscaled DIRECT (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_DIRECT_NOSCAL val = 3;
github
mapDIA/mapDIA-master
NLOPT_LN_AUGLAG.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_AUGLAG.m
158
utf_8
ec49cb21c2b454870a401a1c5afd1058
% NLOPT_LN_AUGLAG: Augmented Lagrangian method (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_AUGLAG val = 30;
github
mapDIA/mapDIA-master
NLOPT_GN_ESCH.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_ESCH.m
130
utf_8
6cad4da90ce4145ad2b1dafcf286286f
% NLOPT_GN_ESCH: ESCH evolutionary strategy % % See nlopt_minimize for more information. function val = NLOPT_GN_ESCH val = 42;
github
mapDIA/mapDIA-master
NLOPT_G_MLSL.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_G_MLSL.m
173
utf_8
fd60012f2c05bdeb027ee6dee44175fb
% NLOPT_G_MLSL: Multi-level single-linkage (MLSL), random (global, needs sub-algorithm) % % See nlopt_minimize for more information. function val = NLOPT_G_MLSL val = 38;
github
mapDIA/mapDIA-master
nlopt_minimize_constrained.m
.m
mapDIA-master/nlopt-2.4.2/octave/nlopt_minimize_constrained.m
5,174
utf_8
2093a6be53db585559168905f1fc1e4a
% Usage: [xopt, fmin, retcode] = nlopt_minimize_constrained % (algorithm, f, f_data, % fc, fc_data, lb, ub, % xinit, stop) % % Minimizes a nonlinear multivariable function f(x, f_data{:}), subject % to nonlinear constraints described by fc and fc_data (see below), where % x is a row vector, returning the optimal x found (xopt) along with % the minimum function value (fmin = f(xopt)) and a return code (retcode). % A variety of local and global optimization algorithms can be used, % as specified by the algorithm parameter described below. lb and ub % are row vectors giving the upper and lower bounds on x, xinit is % a row vector giving the initial guess for x, and stop is a struct % containing termination conditions (see below). % % This function is a front-end for the external routine % nlopt_minimize_constrained in the free NLopt nonlinear-optimization % library, which is a wrapper around a number of free/open-source % optimization subroutines. More details can be found on the NLopt % web page (ab-initio.mit.edu/nlopt) and also under % 'man nlopt_minimize_constrained' on Unix. % % f should be a handle (@) to a function of the form: % % [val, gradient] = f(x, ...) % % where x is a row vector, val is the function value f(x), and gradient % is a row vector giving the gradient of the function with respect to x. % The gradient is only used for gradient-based optimization algorithms; % some of the algorithms (below) are derivative-free and only require % f to return val (its value). f can take additional arguments (...) % which are passed via the argument f_data: f_data is a cell array % of the additional arguments to pass to f. (Recall that cell arrays % are specified by curly brackets { ... }. For example, pass f_data={} % for functions that require no additional arguments.) % % A few of the algorithms (below) support nonlinear constraints, % in particular NLOPT_LD_MMA and NLOPT_LN_COBYLA. These (if any) % are specified by fc and fc_data. fc is a cell array of % function handles, and fc_data is a cell array of cell arrays of the % corresponding arguments. Both must have the same length m, the % number of nonlinear constraints. That is, fc{i} is a handle % to a function of the form: % % [val, gradient] = fc(x, ...) % % (where the gradient is only used for gradient-based algorithms), % and the ... arguments are given by fc_data{i}{:}. % % If you have no nonlinear constraints, i.e. fc = fc_data = {}, then % it is equivalent to calling the the nlopt_minimize() function, % which omits the fc and fc_data arguments. % % stop describes the termination criteria, and is a struct with a % number of optional fields: % stop.ftol_rel = fractional tolerance on function value % stop.ftol_abs = absolute tolerance on function value % stop.xtol_rel = fractional tolerance on x % stop.xtol_abs = row vector of absolute tolerances on x components % stop.fmin_max = stop when f < fmin_max is found % stop.maxeval = maximum number of function evaluations % stop.maxtime = maximum run time in seconds % stop.verbose = > 0 indicates verbose output % Minimization stops when any one of these conditions is met; any % condition that is omitted from stop will be ignored. WARNING: % not all algorithms interpret the stopping criteria in exactly the % same way, and in any case ftol/xtol specify only a crude estimate % for the accuracy of the minimum function value/x. % % The algorithm should be one of the following constants (name and % interpretation are the same as for the C function). Names with % _G*_ are global optimization, and names with _L*_ are local % optimization. Names with _*N_ are derivative-free, while names % with _*D_ are gradient-based algorithms. Algorithms: % % NLOPT_GD_MLSL_LDS, NLOPT_GD_MLSL, NLOPT_GD_STOGO, NLOPT_GD_STOGO_RAND, % NLOPT_GN_CRS2_LM, NLOPT_GN_DIRECT_L, NLOPT_GN_DIRECT_L_NOSCAL, % NLOPT_GN_DIRECT_L_RAND, NLOPT_GN_DIRECT_L_RAND_NOSCAL, NLOPT_GN_DIRECT, % NLOPT_GN_DIRECT_NOSCAL, NLOPT_GN_ISRES, NLOPT_GN_MLSL_LDS, NLOPT_GN_MLSL, % NLOPT_GN_ORIG_DIRECT_L, NLOPT_GN_ORIG_DIRECT, NLOPT_LD_AUGLAG_EQ, % NLOPT_LD_AUGLAG, NLOPT_LD_LBFGS, NLOPT_LD_LBFGS_NOCEDAL, NLOPT_LD_MMA, % NLOPT_LD_TNEWTON, NLOPT_LD_TNEWTON_PRECOND, % NLOPT_LD_TNEWTON_PRECOND_RESTART, NLOPT_LD_TNEWTON_RESTART, % NLOPT_LD_VAR1, NLOPT_LD_VAR2, NLOPT_LN_AUGLAG_EQ, NLOPT_LN_AUGLAG, % NLOPT_LN_BOBYQA, NLOPT_LN_COBYLA, NLOPT_LN_NELDERMEAD, % NLOPT_LN_NEWUOA_BOUND, NLOPT_LN_NEWUOA, NLOPT_LN_PRAXIS, NLOPT_LN_SBPLX % % For more information on individual algorithms, see their individual % help pages (e.g. "help NLOPT_LN_SBPLX"). function [xopt, fmin, retcode] = nlopt_minimize_constrained(algorithm, f, f_data, fc, fc_data, lb, ub, xinit, stop) opt = stop; if (isfield(stop, 'minf_max')) opt.stopval = stop.minf_max; end opt.algorithm = algorithm; opt.min_objective = @(x) f(x, f_data{:}); opt.lower_bounds = lb; opt.upper_bounds = ub; for i = 1:length(fc) opt.fc{i} = @(x) fc{i}(x, fc_data{i}{:}); end [xopt, fmin, retcode] = nlopt_optimize(opt, xinit);
github
mapDIA/mapDIA-master
NLOPT_LN_NEWUOA_BOUND.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LN_NEWUOA_BOUND.m
207
utf_8
67ca43d03f5347c97069a86e3e73a7e4
% NLOPT_LN_NEWUOA_BOUND: Bound-constrained optimization via NEWUOA-based quadratic models (local, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_LN_NEWUOA_BOUND val = 27;
github
mapDIA/mapDIA-master
nlopt_minimize.m
.m
mapDIA-master/nlopt-2.4.2/octave/nlopt_minimize.m
3,978
utf_8
f71b68688b460e0440ff89bdf086d2a7
% Usage: [xopt, fmin, retcode] = nlopt_minimize(algorithm, f, f_data, lb, ub, % xinit, stop) % % Minimizes a nonlinear multivariable function f(x, f_data{:}), where % x is a row vector, returning the optimal x found (xopt) along with % the minimum function value (fmin = f(xopt)) and a return code (retcode). % A variety of local and global optimization algorithms can be used, % as specified by the algorithm parameter described below. lb and ub % are row vectors giving the upper and lower bounds on x, xinit is % a row vector giving the initial guess for x, and stop is a struct % containing termination conditions (see below). % % This function is a front-end for the external routine nlopt_minimize % in the free NLopt nonlinear-optimization library, which is a wrapper % around a number of free/open-source optimization subroutines. More % details can be found on the NLopt web page (ab-initio.mit.edu/nlopt) % and also under 'man nlopt_minimize' on Unix. % % f should be a handle (@) to a function of the form: % % [val, gradient] = f(x, ...) % % where x is a row vector, val is the function value f(x), and gradient % is a row vector giving the gradient of the function with respect to x. % The gradient is only used for gradient-based optimization algorithms; % some of the algorithms (below) are derivative-free and only require % f to return val (its value). f can take additional arguments (...) % which are passed via the argument f_data: f_data is a cell array % of the additional arguments to pass to f. (Recall that cell arrays % are specified by curly brackets { ... }. For example, pass f_data={} % for functions that require no additional arguments.) % % stop describes the termination criteria, and is a struct with a % number of optional fields: % stop.ftol_rel = fractional tolerance on function value % stop.ftol_abs = absolute tolerance on function value % stop.xtol_rel = fractional tolerance on x % stop.xtol_abs = row vector of absolute tolerances on x components % stop.fmin_max = stop when f < fmin_max is found % stop.maxeval = maximum number of function evaluations % stop.maxtime = maximum run time in seconds % stop.verbose = > 0 indicates verbose output % Minimization stops when any one of these conditions is met; any % condition that is omitted from stop will be ignored. WARNING: % not all algorithms interpret the stopping criteria in exactly the % same way, and in any case ftol/xtol specify only a crude estimate % for the accuracy of the minimum function value/x. % % The algorithm should be one of the following constants (name and % interpretation are the same as for the C function). Names with % _G*_ are global optimization, and names with _L*_ are local % optimization. Names with _*N_ are derivative-free, while names % with _*D_ are gradient-based algorithms. Algorithms: % % NLOPT_GD_MLSL_LDS, NLOPT_GD_MLSL, NLOPT_GD_STOGO, NLOPT_GD_STOGO_RAND, % NLOPT_GN_CRS2_LM, NLOPT_GN_DIRECT_L, NLOPT_GN_DIRECT_L_NOSCAL, % NLOPT_GN_DIRECT_L_RAND, NLOPT_GN_DIRECT_L_RAND_NOSCAL, NLOPT_GN_DIRECT, % NLOPT_GN_DIRECT_NOSCAL, NLOPT_GN_ISRES, NLOPT_GN_MLSL_LDS, NLOPT_GN_MLSL, % NLOPT_GN_ORIG_DIRECT_L, NLOPT_GN_ORIG_DIRECT, NLOPT_LD_AUGLAG_EQ, % NLOPT_LD_AUGLAG, NLOPT_LD_LBFGS, NLOPT_LD_LBFGS_NOCEDAL, NLOPT_LD_MMA, % NLOPT_LD_TNEWTON, NLOPT_LD_TNEWTON_PRECOND, % NLOPT_LD_TNEWTON_PRECOND_RESTART, NLOPT_LD_TNEWTON_RESTART, % NLOPT_LD_VAR1, NLOPT_LD_VAR2, NLOPT_LN_AUGLAG_EQ, NLOPT_LN_AUGLAG, % NLOPT_LN_BOBYQA, NLOPT_LN_COBYLA, NLOPT_LN_NELDERMEAD, % NLOPT_LN_NEWUOA_BOUND, NLOPT_LN_NEWUOA, NLOPT_LN_PRAXIS, NLOPT_LN_SBPLX % % For more information on individual algorithms, see their individual % help pages (e.g. "help NLOPT_LN_SBPLX"). function [xopt, fmin, retcode] = nlopt_minimize(algorithm, f, f_data, lb, ub, xinit, stop) [xopt, fmin, retcode] = nlopt_minimize_constrained(algorithm, f, f_data, {}, {}, lb, ub, xinit, stop);
github
mapDIA/mapDIA-master
NLOPT_GN_ORIG_DIRECT_L.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_ORIG_DIRECT_L.m
170
utf_8
d61c095f05bf7fd4fbbf2ddbe22c58a4
% NLOPT_GN_ORIG_DIRECT_L: Original DIRECT-L version (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_ORIG_DIRECT_L val = 7;
github
mapDIA/mapDIA-master
NLOPT_LD_TNEWTON_RESTART.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_TNEWTON_RESTART.m
184
utf_8
a482ddde1f6d6b386a3810fc142829a2
% NLOPT_LD_TNEWTON_RESTART: Truncated Newton with restarting (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_TNEWTON_RESTART val = 16;
github
mapDIA/mapDIA-master
NLOPT_LD_TNEWTON_PRECOND_RESTART.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_TNEWTON_PRECOND_RESTART.m
215
utf_8
1082f147b249cc1f7e564aa3b2462048
% NLOPT_LD_TNEWTON_PRECOND_RESTART: Preconditioned truncated Newton with restarting (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_TNEWTON_PRECOND_RESTART val = 18;
github
mapDIA/mapDIA-master
NLOPT_LD_TNEWTON_PRECOND.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_TNEWTON_PRECOND.m
183
utf_8
167e47e5e372152ffba7552308e1193f
% NLOPT_LD_TNEWTON_PRECOND: Preconditioned truncated Newton (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_TNEWTON_PRECOND val = 17;
github
mapDIA/mapDIA-master
NLOPT_GD_STOGO_RAND.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GD_STOGO_RAND.m
170
utf_8
fea04c6327afd49e02ff536330527f60
% NLOPT_GD_STOGO_RAND: StoGO with randomized search (global, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_GD_STOGO_RAND val = 9;
github
mapDIA/mapDIA-master
NLOPT_LD_LBFGS.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_LD_LBFGS.m
160
utf_8
02936ac48fc420cd73b5a6848808dd68
% NLOPT_LD_LBFGS: Limited-memory BFGS (L-BFGS) (local, derivative-based) % % See nlopt_minimize for more information. function val = NLOPT_LD_LBFGS val = 11;
github
mapDIA/mapDIA-master
NLOPT_GN_MLSL_LDS.m
.m
mapDIA-master/nlopt-2.4.2/octave/NLOPT_GN_MLSL_LDS.m
183
utf_8
0fb34e2ebed6204b06925782f5fc2417
% NLOPT_GN_MLSL_LDS: Multi-level single-linkage (MLSL), quasi-random (global, no-derivative) % % See nlopt_minimize for more information. function val = NLOPT_GN_MLSL_LDS val = 22;
github
fugro/displaz-master
dplot.m
.m
displaz-master/bindings/matlab/dplot.m
9,534
utf_8
4ced888f527c02de953a7627e4983c17
function dplot(position, varargin) % 3D plotting function for points and lines % % The interface is similar to plot() where possible and convenient. % % dplot(P) Plots the Nx3 array P as points, with a point in each row % (so X = P(:,1), Y = P(:,2), etc) % % dplot(P, S) Plots points P using the marker shape and color specified in % the string S. The following characters are supported: % % b blue . sphere - solid % g green o circle (none) no line % r red x x-mark % c cyan + plus % m magenta s square % y yellow % k black % w white % % dplot(P, [S, ] 'property1', value1, ...) accepts properties and values % which affect the way that the data series is plotted. Supported % properties are % color - a 1x3 array or Nx3 array of colors per point % markersize - a length 1 or N vector of marker sizes per point % markershape - a length 1 or N vector of integer marker shapes per point if isempty(position) return; end global g_DisplazHold; global g_DisplazDataSetNumber; if isempty(g_DisplazDataSetNumber) g_DisplazDataSetNumber = 1; end color = [1 1 1]; markersize = 0.1; markershape = 0; plotLine = false; plotMarkers = false; label = sprintf('DataSet%d', g_DisplazDataSetNumber); g_DisplazDataSetNumber = g_DisplazDataSetNumber + 1; skipArg = false; for i=1:length(varargin) if skipArg skipArg = false; continue; end arg = varargin{i}; if ~ischar(arg) error('Argument number %d to dplot not recognized', i+1) end arg = lower(arg); switch arg case 'color' color = varargin{i+1}; skipArg = true; case 'markersize' markersize = ensure_vec(varargin{i+1}, 'markersize'); skipArg = true; case 'markershape' markershape = ensure_vec(varargin{i+1}', 'markershape'); skipArg = true; case 'label' label = varargin{i+1}; skipArg = true; otherwise if i ~= 1 error('Argument "%s" to dplot unrecognized', varargin{i}); end % Try to parse first argument as color/markershape/linespec [color, markershape, plotLine, plotMarkers] = ... parse_plot_spec(arg, color, markershape, plotLine, plotMarkers); end end if ~plotLine && ~plotMarkers plotMarkers = true; end if size(position, 2) ~= 3; error('position must be a Nx3 array'); end if size(color, 2) ~= 3; error('color must be a Nx3 array'); end nvertices = size(position, 1); if size(color,1) == 1 color = repmat(color, nvertices, 1); end if length(markersize) == 1 markersize = repmat(markersize, nvertices, 1); end if length(markershape) == 1 markershape = repmat(markershape, nvertices, 1); end tmpLineFileName = ''; tmpPointFileName = ''; if plotLine tmpLineFileName = sprintf('%s_lines.ply',tempname); % Plot lines. This is currently rather limited due to the % inability to specify a shader for line primitives write_ply_lines(tmpLineFileName, position, color); end if plotMarkers tmpPointFileName = sprintf('%s_points.ply',tempname); % Ensure all fields are floats for now, to avoid surprising scaling in the % shader if size(color,1) ~= nvertices; error('color must have same number of rows as position array'); end fields = struct('name',{'position','color','markersize','markershape'},... 'semantic',{'vector_semantic','color_semantic','array_semantic','array_semantic'},... 'typeName',{'float64','float32','float32','uint8'},... 'value',{double(position),single(color),single(markersize),uint8(markershape)}... ); write_ply_points(tmpPointFileName, nvertices,fields); end if g_DisplazHold holdStr = ''; else holdStr = '-clear'; end fixLdLibPath = ''; if isunix() % Reset LD_LIBRARY_PATH on unix - matlab adds to it to get the % matlab version of libraries, which tend to conflict with the % libraries used when building displaz. fixLdLibPath = 'env LD_LIBRARY_PATH=""'; end displazCall=sprintf('%s displaz -script %s -shader generic_points.glsl -rmtemp -label %s %s %s', ... fixLdLibPath, holdStr, label, tmpPointFileName, tmpLineFileName); % disp(displazCall); system(displazCall); % FIXME: Calling displaz too often in a loop causes contention on the % socket which can cause a new instance to be launched. Pause a bit to % work around this for now (ugh!) pause(0.01); end function x = ensure_vec(x, name) if size(x,1) == 1 x = x'; end if size(x,2) ~= 1 error('Expected "%s" to be a vector', name); end end function write_ply_points(fileName, nvertices, fields) % Write a set of points to displaz-native ply format fid = fopen(fileName, 'w'); fprintf(fid,... ['ply\n',... 'format binary_little_endian 1.0\n',... 'comment Displaz native\n'... ]); for item = fields name = item.name; semantic = item.semantic; typeName = item.typeName; value = item.value; n = size(value,1); assert(n == nvertices || n == 1); fprintf(fid, 'element vertex_%s %d\n',name,n); for i = 1:size(value,2) propName = ply_property_name(semantic, i); fprintf(fid, 'property %s %s\n',typeName,propName); end end fprintf(fid, 'end_header\n'); for item = fields fwrite(fid, item.value',item.typeName,0,'ieee-le'); end fclose(fid); end function write_ply_lines(fileName, position, color) vertexValid = all(~isnan(position), 2); lineStarts = find(diff([0;vertexValid]) == 1); % Write a set of points to displaz-native ply format fid = fopen(fileName, 'w'); nvalidvertices = sum(vertexValid); fprintf(fid, ... ['ply\n', ... 'format binary_little_endian 1.0\n', ... 'element vertex %d\n', ... 'property double x\n', ... 'property double y\n', ... 'property double z\n', ... 'element color %d\n', ... 'property float r\n', ... 'property float g\n', ... 'property float b\n', ... 'element edge %d\n', ... 'property list int int vertex_index\n', ... 'end_header\n' ... ], ... nvalidvertices, ... nvalidvertices, ... length(lineStarts) ... ); fwrite(fid, position(vertexValid,:)', 'double', 0, 'ieee-le'); fwrite(fid, color(vertexValid,:)', 'float', 0, 'ieee-le'); % Write out line connectivity nvertices = size(position,1); realStart = 0; for i = lineStarts' j = i; while j <= nvertices && vertexValid(j) j = j + 1; end lineLen = j-i; fwrite(fid, lineLen, 'int32'); fwrite(fid, realStart:realStart+lineLen-1, 'int32', 0, 'ieee-le'); realStart = realStart + lineLen; end fclose(fid); end function plyProperty = ply_property_name(semantic, idx) if strcmp(semantic,'array_semantic') plyProperty = num2str(idx-1); elseif strcmp(semantic,'vector_semantic') vector_semantic = ['x', 'y', 'z', 'w']; plyProperty = vector_semantic(idx); elseif strcmp(semantic, 'color_semantic') color_semantic = ['r', 'g', 'b']; plyProperty = color_semantic(idx); end end function [color, markerShape, plotLine, plotMarkers] = parse_plot_spec(... spec, defaultColor, defaultShape, defaultPlotLine, defaultPlotMarkers) color = defaultColor; markerShape = defaultShape; plotLine = defaultPlotLine; plotMarkers = defaultPlotMarkers; for s = spec(:)' switch s % Colors case 'r' color = [1.0 0 0]; case 'g' color = [0.0 0.8 0]; case 'b' color = [0.0 0 0.8]; case 'c' color = [0.0 1 1]; case 'm' color = [1.0 0 1]; case 'y' color = [1.0 1 0]; case 'k' color = [0.0 0 0]; case 'w' color = [1.0 1 1]; % Line shapes case '-' plotLine = true; % Marker styles case '.' markerShape = 0; plotMarkers = true; case 's' markerShape = 1; plotMarkers = true; case 'o' markerShape = 2; plotMarkers = true; case 'x' markerShape = 3; plotMarkers = true; case '+' markerShape = 4; plotMarkers = true; otherwise error('Invalid plotspec character "%s"', s) end end end
github
meghanathmacha/xPACS-master
svd_solve.m
.m
xPACS-master/src/SVDD/svd_solve.m
475
utf_8
9f710ad1ada6d2e3e9674b1cd5aecf78
%% SVDD Margin Primal form function [d1, b, cSVDD,status]=svd_solve(dat,ldat,C) nx = diag(dat*dat'); yi = ldat; Xi = dat; dims = size(dat,2); ndat = length(dat); cvx_begin quiet cvx_precision best variables b(1) cSVDD(dims,1) xi(ndat,1) dual variables d1 p1 minimize( cSVDD'*cSVDD + b + C*sum(xi) ) subject to d1 : 2* diag(yi)*Xi*cSVDD >= yi.*(-b+nx) - xi; p1 : xi >=0; cvx_end status = 0; if(strcmp(cvx_status,'Solved')) status = 1; end
github
meghanathmacha/xPACS-master
singleSphere.m
.m
xPACS-master/src/SVDD/singleSphere.m
2,637
utf_8
ec64193bc977a2d4b691985a8b89a67a
%% Reading data function []=singleSphere(outerfolds,innerfolds,model,name) Cgrid = 0.1:0.2:2; fprobs = [ ]; for outerid = 1:outerfolds disp(outerid); sets = setdiff([1:outerfolds],outerid); delimiterIn = ','; headerlinesIn = 1; fdata = [ ]; for id = 1:sets filename = strcat(name,'trainouter',num2str(id),'.csv'); data = importdata(filename,delimiterIn,headerlinesIn); fdata = [fdata;data.data]; end dlabels = fdata(:,end); indices = crossvalind('Kfold',size(fdata,1),innerfolds); % indices has 1,2,3 for the three folds. bauc= [ ]; bC = [ ]; for innerid = 1:innerfolds isets = setdiff([1:innerfolds],innerid); test = fdata(indices == innerid,1:end); train = fdata(indices ~= innerid,1:end); traindat = train(:,1:end-1); trainlabels = train(:,end); auc = [ ]; innerauc = [ ]; for grid = Cgrid [d, b, c, status] = svd_solve(traindat,trainlabels,grid); AUC = 0; R = b + c'*c; testfeatures = test(:,1:end-1); testlabels = test(:,end); decision = sum((testfeatures - ones(length(testfeatures),1)*c').^2,2) - R*R; g = zeros(size(decision)); g = 1.0 ./ ( 1.0 + exp(-decision)); tlabels = test(:,end); if size(g,1) > 0 [X,Y,T,AUC] = perfcurve(~testlabels, 1 - g,false); end auc =[auc,AUC]; end bestC = Cgrid(find(auc == max(auc))); bC = [bC,bestC]; bauc = [bauc,max(auc)]; end hyperC = bC(find(bauc == max(bauc))); % Chose the best hyper C for that outer fold. filename = strcat(name,'trainouter',num2str(outerid),'.csv'); testdata = importdata(filename,delimiterIn,headerlinesIn); % Outerid has the test data. [d, b, c, status] = svd_solve(fdata(:,1:end-1),fdata(:,end),hyperC); R = b + c'*c; testfeatures = testdata.data(:,1:end-1); decision = sum((testfeatures - ones(length(testfeatures),1)*c').^2,2) - R*R; g = zeros(size(decision)); g = 1.0 ./ ( 1.0 + exp(-decision)); probs = [testdata.data (1-g) g]; dlmwrite(strcat(name,'trainouter',model,num2str(outerid),'probs.csv'),probs,'delimiter',','); fprobs = [fprobs;probs]; end dlmwrite(strcat(name,'trainouter',model,'probs.csv'),probs,'delimiter',','); end
github
9ich/kk-master
echo_diagnostic.m
.m
kk-master/code/libspeex/echo_diagnostic.m
2,076
utf_8
8d5e7563976fbd9bd2eda26711f7d8dc
% Attempts to diagnose AEC problems from recorded samples % % out = echo_diagnostic(rec_file, play_file, out_file, tail_length) % % Computes the full matrix inversion to cancel echo from the % recording 'rec_file' using the far end signal 'play_file' using % a filter length of 'tail_length'. The output is saved to 'out_file'. function out = echo_diagnostic(rec_file, play_file, out_file, tail_length) F=fopen(rec_file,'rb'); rec=fread(F,Inf,'short'); fclose (F); F=fopen(play_file,'rb'); play=fread(F,Inf,'short'); fclose (F); rec = [rec; zeros(1024,1)]; play = [play; zeros(1024,1)]; N = length(rec); corr = real(ifft(fft(rec).*conj(fft(play)))); acorr = real(ifft(fft(play).*conj(fft(play)))); [a,b] = max(corr); if b > N/2 b = b-N; end printf ("Far end to near end delay is %d samples\n", b); if (b > .3*tail_length) printf ('This is too much delay, try delaying the far-end signal a bit\n'); else if (b < 0) printf ('You have a negative delay, the echo canceller has no chance to cancel anything!\n'); else printf ('Delay looks OK.\n'); end end end N2 = round(N/2); corr1 = real(ifft(fft(rec(1:N2)).*conj(fft(play(1:N2))))); corr2 = real(ifft(fft(rec(N2+1:end)).*conj(fft(play(N2+1:end))))); [a,b1] = max(corr1); if b1 > N2/2 b1 = b1-N2; end [a,b2] = max(corr2); if b2 > N2/2 b2 = b2-N2; end drift = (b1-b2)/N2; printf ('Drift estimate is %f%% (%d samples)\n', 100*drift, b1-b2); if abs(b1-b2) < 10 printf ('A drift of a few (+-10) samples is normal.\n'); else if abs(b1-b2) < 30 printf ('There may be (not sure) excessive clock drift. Is the capture and playback done on the same soundcard?\n'); else printf ('Your clock is drifting! No way the AEC will be able to do anything with that. Most likely, you''re doing capture and playback from two different cards.\n'); end end end acorr(1) = .001+1.00001*acorr(1); AtA = toeplitz(acorr(1:tail_length)); bb = corr(1:tail_length); h = AtA\bb; out = (rec - filter(h, 1, play)); F=fopen(out_file,'w'); fwrite(F,out,'short'); fclose (F);
github
rmahieu/misaligned-dfd-master
computeColor.m
.m
misaligned-dfd-master/dependencies/OpticalFlow/computeColor.m
3,142
utf_8
a36a650437bc93d4d8ffe079fe712901
function img = computeColor(u,v) % computeColor color codes flow field U, V % According to the c++ source code of Daniel Scharstein % Contact: [email protected] % Author: Deqing Sun, Department of Computer Science, Brown University % Contact: [email protected] % $Date: 2007-10-31 21:20:30 (Wed, 31 Oct 2006) $ % Copyright 2007, Deqing Sun. % % All Rights Reserved % % Permission to use, copy, modify, and distribute this software and its % documentation for any purpose other than its incorporation into a % commercial product is hereby granted without fee, provided that the % above copyright notice appear in all copies and that both that % copyright notice and this permission notice appear in supporting % documentation, and that the name of the author and Brown University not be used in % advertising or publicity pertaining to distribution of the software % without specific, written prior permission. % % THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, % INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY % PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR OR BROWN UNIVERSITY BE LIABLE FOR % ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES % WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN % ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF % OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. nanIdx = isnan(u) | isnan(v); u(nanIdx) = 0; v(nanIdx) = 0; colorwheel = makeColorwheel(); ncols = size(colorwheel, 1); rad = sqrt(u.^2+v.^2); a = atan2(-v, -u)/pi; fk = (a+1) /2 * (ncols-1) + 1; % -1~1 maped to 1~ncols k0 = floor(fk); % 1, 2, ..., ncols k1 = k0+1; k1(k1==ncols+1) = 1; f = fk - k0; for i = 1:size(colorwheel,2) tmp = colorwheel(:,i); col0 = tmp(k0)/255; col1 = tmp(k1)/255; col = (1-f).*col0 + f.*col1; idx = rad <= 1; col(idx) = 1-rad(idx).*(1-col(idx)); % increase saturation with radius col(~idx) = col(~idx)*0.75; % out of range img(:,:, i) = uint8(floor(255*col.*(1-nanIdx))); end; %% function colorwheel = makeColorwheel() % color encoding scheme % adapted from the color circle idea described at % http://members.shaw.ca/quadibloc/other/colint.htm RY = 15; YG = 6; GC = 4; CB = 11; BM = 13; MR = 6; ncols = RY + YG + GC + CB + BM + MR; colorwheel = zeros(ncols, 3); % r g b col = 0; %RY colorwheel(1:RY, 1) = 255; colorwheel(1:RY, 2) = floor(255*(0:RY-1)/RY)'; col = col+RY; %YG colorwheel(col+(1:YG), 1) = 255 - floor(255*(0:YG-1)/YG)'; colorwheel(col+(1:YG), 2) = 255; col = col+YG; %GC colorwheel(col+(1:GC), 2) = 255; colorwheel(col+(1:GC), 3) = floor(255*(0:GC-1)/GC)'; col = col+GC; %CB colorwheel(col+(1:CB), 2) = 255 - floor(255*(0:CB-1)/CB)'; colorwheel(col+(1:CB), 3) = 255; col = col+CB; %BM colorwheel(col+(1:BM), 3) = 255; colorwheel(col+(1:BM), 1) = floor(255*(0:BM-1)/BM)'; col = col+BM; %MR colorwheel(col+(1:MR), 3) = 255 - floor(255*(0:MR-1)/MR)'; colorwheel(col+(1:MR), 1) = 255;
github
rmahieu/misaligned-dfd-master
iat_flow2rgb.m
.m
misaligned-dfd-master/dependencies/IAT_v0.9.2/misc/iat_flow2rgb.m
4,136
utf_8
fad3338a55cc2825fbace1f585065e42
function rgb = iat_flow2rgb( fx, fy, dispRange ) % RGBIM = IAT_FLOW2RGB( FX, FY, DISPRANGE ) % % IAT_FLOW2RGB creates a color image RGBIM from the dense displacements (flows) % FX and FY. The angle of each displacement vector is translated to a color % through a specific colomap. DISPRANGE is an optional parameter that defines % the allowable range of DISPLACEMENT (e.g. [min_flow, max_flow]). % % -->Input % FX: Array with horizontal displacements % FY: Array with vertical dispalcements % DISPRANGE: The allowable range of displacements (default: [-1e9, 1e9]) % % -->Output % % RGBIM: The RGB image that visualizes the displacements % % NOTE: This function was built based on Deqing Sun's flow visualization % function, while it uses exactly the same colormap with Deqing's function % (see below the function makeColorwheel()) % % ------------------- % Authors: Georgios Evangelidis % Copyright (C) 2013 Georgios Evangelidis % All rights reserved. % % For any bugs, please contact <[email protected]> or % <[email protected]> % % This file is part of the IAT library and is made available under % the terms of the GNU license (see the COPYING file). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~all(size(fx)==size(fy)) error('iat_flow2rgb:flow arrays must have the same size'); end if (length(size(fx))~=2) error('iat_flow2rgb:flows must be two dimensional arrays'); end if nargin==3 if dispRange(2)<=dispRange(1) error('iat_flow2rgb: non valid flow range'); end end if nargin<3 fr = [-1e9 1e9]; else fr = dispRange; end outOfRange = fx>fr(2) | fy>fr(2) | fx<fr(1) | fy <fr(1) | isnan(fx) | isnan(fy); fx(outOfRange) = 0; fy(outOfRange) = 0; % flow normalization mag = sqrt(fx.^2+fy.^2); maxmag = max(mag(:)); fx = fx/maxmag; fy = fy/maxmag; % Create palette of colors %palette = iat_flow_palette(); palette = makeColorwheel(); colors = size(palette,1); mag = sqrt(fx.^2+fy.^2); angle = atan2(-fy,-fx)/pi; % makes angles a color index map angle = (angle+1)/2; % angles in [0 1] angle = angle*(colors-1)+1; k0=floor(angle); k1=k0+1; k1(k1==colors+1)=1; f=angle-k0; [row,col] = size(fx); red = zeros(row,col); gre = red; blu = red; idx = mag<=1; red(:) = ((1-f(:)).*palette(k0,1)+f(:).*palette(k1,1))/255; red(idx) = 1-mag(idx).*(1-red(idx)); red(~idx) = red(~idx).*0.75; gre(:) = ((1-f(:)).*palette(k0,2)+f(:).*palette(k1,2))/255; gre(idx) = 1-mag(idx).*(1-gre(idx)); gre(~idx) = gre(~idx).*0.75; blu(:) = ((1-f(:)).*palette(k0,3)+f(:).*palette(k1,3))/255; blu(idx) = 1-mag(idx).*(1-blu(idx)); blu(~idx) = blu(~idx).*0.75; rgb = cat(3,red,gre,blu); rgb(repmat(outOfRange,[1,1,3]))=0; rgb = uint8(rgb*255); end function palette = iat_flow_palette() % IAT color palette % Create a palette of fully saturated colors palette(:,1)=0:1/54:1; palette(:,2)=1; palette(:,3)=1; % Convert HSV representation to RGB palette=floor(hsv2rgb(palette).*255); end function colorwheel = makeColorwheel() % Author: Deqing Sun, Department of Computer Science, Brown University % Contact: [email protected] % $Date: 2007-10-31 21:20:30 (Wed, 31 Oct 2006) $ % Copyright 2007, Deqing Sun. % color encoding scheme % adapted from the color circle idea described at % http://members.shaw.ca/quadibloc/other/colint.htm RY = 15; YG = 6; GC = 4; CB = 11; BM = 13; MR = 6; ncols = RY + YG + GC + CB + BM + MR; colorwheel = zeros(ncols, 3); % r g b col = 0; %RY colorwheel(1:RY, 1) = 255; colorwheel(1:RY, 2) = floor(255*(0:RY-1)/RY)'; col = col+RY; %YG colorwheel(col+(1:YG), 1) = 255 - floor(255*(0:YG-1)/YG)'; colorwheel(col+(1:YG), 2) = 255; col = col+YG; %GC colorwheel(col+(1:GC), 2) = 255; colorwheel(col+(1:GC), 3) = floor(255*(0:GC-1)/GC)'; col = col+GC; %CB colorwheel(col+(1:CB), 2) = 255 - floor(255*(0:CB-1)/CB)'; colorwheel(col+(1:CB), 3) = 255; col = col+CB; %BM colorwheel(col+(1:BM), 3) = 255; colorwheel(col+(1:BM), 1) = floor(255*(0:BM-1)/BM)'; col = col+BM; %MR colorwheel(col+(1:MR), 3) = 255 - floor(255*(0:MR-1)/MR)'; colorwheel(col+(1:MR), 1) = 255; end
github
rmahieu/misaligned-dfd-master
DIRT_Registration.m
.m
misaligned-dfd-master/dependencies/IAT_v0.9.2/dirt/DIRT_Registration.m
24,483
utf_8
cee4718fbdb5ea31e4166bf6ae7ea2fd
function reg = DIRT_Registration(tI, pre, varargin) % reg = DIRT_Registration(tI, pre, ...) % % Register the target image tI to the source image sI in pre, using the % pixels in some region of interest in pre. The registration model is: % sI[q] = P(tI[G(q)]) + noise % where P is a photometric transformation and G a geometric one. % The function iteratively minimizes the least squares discrepancy in the % above model. % % Mandatory inputs: % - tI [image] % The target image tI to be registered % - pre [struct from DIRT_Precomputation] % A structure containing precomputed quantities, obtained from the % DIRT_Precomputation function (it contains the source image sI and % the region of interest) % % Optional inputs (properties): % - 'FM_RC' [m x 2 matrix] Default: [] % * FM mode only * % A matrix containing the coordinates of points to be matched. % - 'gopt' Default: [] % * ROI mode only * % A structure parameter to be passed to the DIRT_GModel_* functions % Note that it is added to the pre.gopt structure % - 'ginit' [vector or matrix] Default: identity % The initial geometric registration % - 'pinit' [vector or matrix] Default: identity % The initial photometric registration % - 'verb' [scalar] Default: 1 in ROI mode and 0 in FM mode % The verbosity level % - 'FM_verb' [scalar] Default: 1 % * FM mode only * % The verbosity level for FM messages % - 'min_step_size' [scalar] Default: 1e-8 % Minimum size of the update vector for iterating % - 'max_nb_it' [scalar] Default: 100 % Maximum number of iterations % - 'pause_after_update' [boolean] Default: false % Pause after each parameter update % - 'unfilled_pixels_diff' [scalar or vector] Default: 0 or [ 0 0 0 ] % Default color for the pixels which are not filled in the difference % image. Only makes sense if pre.optPre.debug = true % - 'unfilled_pixels_warped' [scalar or vector] Default: 0 or [ 0 0 0 ] % Default color for the pixels which are not filled in the warped % image. Only makes sense if pre.optPre.debug = true % - 'write_res_path' [string] Default: [] % Write the results to the specified path % - 'no_max_nb_it' [boolean] % Do not stop after max_nb_it is passed % - 'no_min_step_size' [boolean] % Do not stop after min_step_size is passed % - 'max_init_error' [scalar] Default: +inf % Stop if the initial error is larger than max_init_error % Useful mainly in FM mode % - 'max_disparity' [scalar] Default: +inf % * FM mode only * % Do not compute OptSSD if the disparity between two points is larger % than this threshold % % Outputs: % - reg [struct] % In ROI mode: % Structure always containing: % * err [boolean] % Error in the registration process % * g [vector or matrix] % Geometric registration parameters % * p [vector or matrix] % Photometric registration parameters % * it [scalar] % Number of iterations % * cpu_time [scalar] % Total cpu time in seconds % * e_roi [scalar] % RMS fitting error for the ROI (in pixel value units) % * e_roi_init [scalar] % Initial RMS fitting error for the ROI (in pixel value units) % Structure that may contain: % * allReg [list of struct] % This parameter is returned if 'debug' has been activated in % DIRT_Precomputation % allReg{t} with t = 1 ... reg.it contains information about % the registration through at iteration t, in debug mode: % - g, p, cpu_time, e_roi [see above] % - e [scalar] % RMS fitting error for the whole image (in pixel % value units) % and in debug2 mode: % - wI [image] % Warped image wI[q] = P(tI[G(q)]) % - dI [image] % Difference image dI = wI - sI % In FM mode: % * DispMat [matrix] % The disparity matrix (DispMat(sj,tj) is the distance between % the sj-th and tj-th source and target points) % * RawSSD [matrix] % The raw SSD matrix % * OptSSD [matrix] % The optimized SSD matrix % * nb_OptSSD_comp [scalar] % Number of optimized SSD computed (i.e. number of point pairs % which passed the maximum disparity and maximum initial error % tests) % % This function goes with the DIRT Matlab image registration package. % Please cite my paper on this topic that you shall find on my web page if % you use this package. Adrien Bartoli. % check that the number of channels in the source and target images are identical if ABIsRGB(tI) ~= pre.optPre.color, error('the number of channels of the source and target images is different'); end; % normalization tI_norm = DIRT_PNorm_NormImage(pre.optPre.pnorm_params, tI); % check number of parameters if nargin < 2, error('not enough input arguments'); end; % setup default parameters and parse input parameters optReg = ParseVarargin(pre.optPre, varargin{:}); % run registration switch pre.optPre.Mode case 'ROI' reg = DIRT_Registration_ROI(pre, optReg, tI_norm); case 'FM' reg.nb_OptSSD_comp = 0; % make the disparity matrix reg.DispMat = sqrt( ... (repmat(pre.optPre.sRC(:,1),1,optReg.m) - repmat(optReg.tRC(:,1)',pre.optPre.m,1)).^2 + ... (repmat(pre.optPre.sRC(:,2),1,optReg.m) - repmat(optReg.tRC(:,2)',pre.optPre.m,1)).^2 ); for sj = 1:pre.optPre.m if optReg.FM_verb, fprintf('sj = %04d / %04d\n', sj, pre.optPre.m); end; optReg.gopt.sq = pre.optPre.sRC(sj,:)'; for tj = 1:optReg.m % if optReg.FM_verb, fprintf(' tj = %04d / %04d\n', tj, optReg.m); end; r1 = round(pre.optPre.sRC(sj,1)); c1 = round(pre.optPre.sRC(sj,2)); r2 = round(optReg.tRC(tj,1)); c2 = round(optReg.tRC(tj,2)); hs = pre.optPre.HalfMaskSize; % compute pixel level SSD if ~pre.optPre.color SSD = norm(pre.sI(r1-hs:r1+hs,c1-hs:c1+hs) - tI_norm(r2-hs:r2+hs,c2-hs:c2+hs),'fro') / (2*hs+1); else SSD = sqrt( ... norm(pre.sI(r1-hs:r1+hs,c1-hs:c1+hs,1) - tI_norm(r2-hs:r2+hs,c2-hs:c2+hs,1),'fro')^2 + ... norm(pre.sI(r1-hs:r1+hs,c1-hs:c1+hs,2) - tI_norm(r2-hs:r2+hs,c2-hs:c2+hs,2),'fro')^2 + ... norm(pre.sI(r1-hs:r1+hs,c1-hs:c1+hs,3) - tI_norm(r2-hs:r2+hs,c2-hs:c2+hs,3),'fro') ) / (3*(2*hs+1)); end; % disparity and pixel level SSD check if reg.DispMat(sj,tj) < optReg.max_disparity && SSD < optReg.max_init_error reg.nb_OptSSD_comp = reg.nb_OptSSD_comp + 1; optReg.gopt.tq = optReg.tRC(tj,:)'; optReg.ginit = DIRT_GModel_Identity(pre.optPre.gmodel, optReg.gopt); tmp_reg = DIRT_Registration_FM(pre, optReg, tI_norm, sj); if ~tmp_reg.err reg.RawSSD(sj,tj) = tmp_reg.e_roi_init; reg.OptSSD(sj,tj) = tmp_reg.e_roi; else reg.RawSSD(sj,tj) = SSD; reg.OptSSD(sj,tj) = SSD; end; else reg.RawSSD(sj,tj) = SSD; reg.OptSSD(sj,tj) = SSD; end; end; end; otherwise error('unknown mode'); end; %--- %- Property parsing and default option values %--- function optReg = ParseVarargin(optPre, varargin) % default values optReg.gopt = optPre.gopt; optReg.FM_verb = 1; optReg.min_step_size = 1e-8; optReg.pinit = DIRT_PModel_Identity(optPre.pmodel, optPre.color); optReg.max_nb_it = 100; optReg.pause_after_update = false; if ~optPre.color optReg.unfilled_pixels_warped = 0; optReg.unfilled_pixels_diff = 0; else optReg.unfilled_pixels_warped = [0 0 0]; optReg.unfilled_pixels_diff = [0 0 0]; end; optReg.write_res_path = []; optReg.no_max_nb_it = false; optReg.no_min_step_size = false; optReg.max_init_error = inf; optReg.max_disparity = inf; % varargin parsing z = 1; while z <= length(varargin) switch(lower(varargin{z})) case 'fm_rc' if strcmp(optPre.Mode,'ROI'), error('the rc property is useless in ROI mode'); end; optReg.tRC = varargin{z+1}; optReg.m = size(optReg.tRC,1); z = z + 2; case 'gopt' gopt = varargin{z+1}; z = z + 2; for f = fieldnames(gopt) tmp = strcat('optReg.gopt.',f,' = gopt.',f,';'); eval(tmp{1}); end; case 'verb' optReg.verb = varargin{z+1}; z = z + 2; case 'FM_verb' optReg.FM_verb = varargin{z+1}; z = z + 2; case 'min_step_size' optReg.min_step_size = varargin{z+1}; z = z + 2; case 'ginit' optReg.ginit = varargin{z+1}; z = z + 2; case 'pinit' optReg.pinit = varargin{z+1}; z = z + 2; case 'max_nb_it' optReg.max_nb_it = varargin{z+1}; z = z + 2; case 'pause_after_update' optReg.pause_after_update = true; z = z + 1; case 'unfilled_pixels_warped' optReg.unfilled_pixels_warped = varargin{z+1}; z = z + 2; case 'unfilled_pixels_diff' optReg.unfilled_pixels_diff = varargin{z+1}; z = z + 2; case 'write_res_path' optReg.write_res_path = varargin{z+1}; z = z + 2; case 'no_max_nb_it' optReg.no_max_nb_it = true; z = z + 1; case 'no_min_step_size' optReg.no_min_step_size = true; z = z + 1; case 'max_init_error' optReg.max_init_error = varargin{z+1}; z = z + 2; case 'max_disparity' optReg.max_disparity = varargin{z+1}; z = z + 2; otherwise error(['unknown property ' varargin{z}]); end; end; if ~isfield(optReg, 'ginit') if strcmp(optPre.Mode,'ROI') optReg.ginit = DIRT_GModel_Identity(optPre.gmodel, optReg.gopt); end; end; if strcmp(optPre.Mode,'FM') && ~isfield(optReg,'tRC') error('the FM_RC property is required in FM mode'); end; if ~isfield(optReg,'verb') optReg.verb = strcmp(optPre.Mode,'ROI'); end; %--- %- Main registration subfunction in ROI mode %--- function reg = DIRT_Registration_ROI(pre, optReg, tI_norm) % make directories for writing images if ~isempty(optReg.write_res_path) % base path if pre.optPre.poptim, pmodelname = pre.optPre.pmodel; else pmodelname = [ pre.optPre.pmodel 'NoOpt' ]; end; if pre.optPre.goptim, gmodelname = pre.optPre.gmodel; else gmodelname = [ pre.optPre.gmodel 'NoOpt' ]; end; mkdir(optReg.write_res_path, [ gmodelname '_' pmodelname sprintf('_%08d', length(pre.sI_roi)) ]); optReg.write_basepath = [ optReg.write_res_path '/' gmodelname '_' pmodelname sprintf('_%08d', length(pre.sI_roi)) ]; if pre.optPre.debug % difference images mkdir(optReg.write_basepath, 'dI'); optReg.write_dIfmtfn = [ optReg.write_basepath '/dI/%03d.png' ]; % warped images mkdir(optReg.write_basepath, 'wI'); optReg.write_wIfmtfn = [ optReg.write_basepath '/wI/%03d.png' ]; % warped images without photometric model mkdir(optReg.write_basepath, 'wI_no_pmodel'); optReg.write_wInopmodelfmtfn = [ optReg.write_basepath '/wI_no_pmodel/%03d.png' ]; % warped images without geometric model mkdir(optReg.write_basepath, 'wI_no_gmodel'); optReg.write_wInogmodelfmtfn = [ optReg.write_basepath '/wI_no_gmodel/%03d.png' ]; end; end; % initialize the registration reg.g = optReg.ginit; reg.p = DIRT_PNorm_Norm_PModel(pre.optPre.pnorm_params, pre.optPre.pmodel, pre.optPre.color, optReg.pinit); % iteration counter reg.it = 0; % total computational time reg.cpu_time = 0; % setup text display if optReg.verb || pre.optPre.debug fprintf('Iteration | RMS error (ROI) | cpu time (s)') end; if pre.optPre.debug fprintf(' | RMS error (total)'); end; if optReg.verb || pre.optPre.debug DIRT_GModel_DispInit(pre.optPre.gmodel); DIRT_PModel_DispInit(pre.optPre.pmodel, pre.optPre.color); fprintf('\n'); end; % structure for storing the registration through the iterations if pre.optPre.debug reg.allReg = {}; end; % main loop converged = false; while true % compute the warped and difference images and the RMS error tic; [reg.err, wI_roi, dI_roi, reg.e_roi] = DIRT_Warp(pre.optPre.gmodel, reg.g, pre.optPre.pmodel, reg.p, ... pre.optPre.color, pre.R_roi, pre.C_roi, tI_norm, false, 0, pre.sI_roi); reg.cpu_time = reg.cpu_time + toc; if reg.err fprintf('DIRT:Warping attempted outside the target image, exiting\n'); fprintf('DIRT:You may try to improve initialization with DIRT_GModel_Init and/or shrink the ROI with DIRT_MaskBorder\n'); return; end; % de-normalize the RMS error reg.e_roi = DIRT_PNorm_UnNormRMSError(pre.optPre.pnorm_params, reg.e_roi); % store initial error and check it if ~reg.it reg.e_roi_init = reg.e_roi; if reg.e_roi_init >= optReg.max_init_error if optReg.verb, fprintf('Initial error too large\n'); end; break; end; end; % de-normalize the photometric registration parameters p_unnorm = DIRT_PNorm_UnNorm_PModel(pre.optPre.pnorm_params, pre.optPre.pmodel, pre.optPre.color, reg.p); if pre.optPre.debug [err, wI, dI, e, wI_no_pmodel, wI_no_gmodel] = DIRT_Warp(pre.optPre.gmodel, reg.g, ..., pre.optPre.pmodel, p_unnorm, pre.optPre.color, pre.R_all, pre.C_all, tI_norm, true, ..., optReg.unfilled_pixels_warped, pre.sI, optReg.unfilled_pixels_diff); end; % store the current estimate if pre.optPre.debug reg.allReg{end+1}.g = reg.g; reg.allReg{end}.p = p_unnorm; reg.allReg{end}.e = e; reg.allReg{end}.cpu_time = reg.cpu_time; reg.allReg{end}.e_roi = reg.e_roi; if pre.optPre.debug2 reg.allReg{end}.wI = wI; reg.allReg{end}.dI = dI; end; end; % write images to disk if ~isempty(optReg.write_res_path) && pre.optPre.debug imwrite(uint8(abs(dI)), sprintf(optReg.write_dIfmtfn, reg.it)); imwrite(uint8(abs(wI)), sprintf(optReg.write_wIfmtfn, reg.it)); imwrite(uint8(abs(wI_no_pmodel)), sprintf(optReg.write_wInopmodelfmtfn, reg.it)); imwrite(uint8(abs(wI_no_gmodel)), sprintf(optReg.write_wInogmodelfmtfn, reg.it)); end; % display information if optReg.verb || pre.optPre.debug fprintf('%03d | %012.7f | %012.7f', reg.it, reg.e_roi, reg.cpu_time); end; if pre.optPre.debug fprintf(' | %012.7f ', e); end; if optReg.verb || pre.optPre.debug DIRT_GModel_Disp(pre.optPre.gmodel, reg.g); DIRT_PModel_Disp(pre.optPre.pmodel, pre.optPre.color, p_unnorm); fprintf('\n'); end; % if no optimization required if ~pre.optPre.goptim && ~pre.optPre.poptim if optReg.verb, fprintf('No optimization required\n'); end; converged = true; end; % convergence test if converged, break; end; tic; % compute the right hand side of the normal equations b = sum(pre.SD_roi' .* repmat(dI_roi', pre.optPre.no, 1), 2); % compute the update vector d = pre.invH * b; % norm of the update vector for convergence test normd = norm(d); % update the current geometric estimate if pre.optPre.goptim dg = d(1:pre.optPre.ng); d = d(pre.optPre.ng+1:end); reg.g = DIRT_GModel_Update(pre.optPre.gmodel, reg.g, dg, optReg.gopt); end; % update the current photometric estimate if pre.optPre.poptim dp = d(1:pre.optPre.np); reg.p = DIRT_PModel_Update(pre.optPre.pmodel, pre.optPre.color, reg.p, dp); end; reg.cpu_time = reg.cpu_time + toc; % convergence test if normd < optReg.min_step_size if optReg.verb, fprintf('Minimum step size reached\n'); end; converged = ~optReg.no_min_step_size; end; % increase iteration counter reg.it = reg.it + 1; % maximum number of iterations reached if reg.it >= optReg.max_nb_it if optReg.verb, fprintf('Maximum number of iterations reached\n'); end; converged = ~optReg.no_max_nb_it; end; % optional pause for debugging purposes if optReg.pause_after_update, pause; end; end; % main loop % de-normalize the photometric registration parameters reg.p = DIRT_PNorm_UnNorm_PModel(pre.optPre.pnorm_params, pre.optPre.pmodel, pre.optPre.color, reg.p); % save the registration structure and options, and pre-computations if ~isempty(optReg.write_res_path) save([optReg.write_basepath '/reg_optReg_pre.mat'], 'reg', 'optReg', 'pre'); end; %--- %- Main registration subfunction in FM mode %--- function reg = DIRT_Registration_FM(pre, optReg, tI_norm, sj) % % make directories for writing images % if ~isempty(optReg.write_res_path) % % base path % if pre.optPre.poptim, pmodelname = pre.optPre.pmodel; else pmodelname = [ pre.optPre.pmodel 'NoOpt' ]; end; % if pre.optPre.goptim, gmodelname = pre.optPre.gmodel; else gmodelname = [ pre.optPre.gmodel 'NoOpt' ]; end; % mkdir(optReg.write_res_path, [ gmodelname '_' pmodelname sprintf('_%08d', pre.ROI.Rn) ]); % optReg.write_basepath = [ optReg.write_res_path '/' gmodelname '_' pmodelname sprintf('_%08d', pre.ROI.Rn) ]; % if pre.optPre.debug % % difference images % mkdir(optReg.write_basepath, 'dI'); % optReg.write_dIfmtfn = [ optReg.write_basepath '/dI/%03d.png' ]; % % warped images % mkdir(optReg.write_basepath, 'wI'); % optReg.write_wIfmtfn = [ optReg.write_basepath '/wI/%03d.png' ]; % % warped images without photometric model % mkdir(optReg.write_basepath, 'wI_no_pmodel'); % optReg.write_wInopmodelfmtfn = [ optReg.write_basepath '/wI_no_pmodel/%03d.png' ]; % % warped images without geometric model % mkdir(optReg.write_basepath, 'wI_no_gmodel'); % optReg.write_wInogmodelfmtfn = [ optReg.write_basepath '/wI_no_gmodel/%03d.png' ]; % end; % end; % initialize the registration reg.g = optReg.ginit; reg.p = DIRT_PNorm_Norm_PModel(pre.optPre.pnorm_params, pre.optPre.pmodel, pre.optPre.color, optReg.pinit); % iteration counter reg.it = 0; % total computational time reg.cpu_time = 0; % setup text display if optReg.verb || pre.optPre.debug fprintf('Iteration | RMS error (ROI) | cpu time (s)') end; if pre.optPre.debug fprintf(' | RMS error (total)'); end; if optReg.verb || pre.optPre.debug DIRT_GModel_DispInit(pre.optPre.gmodel); DIRT_PModel_DispInit(pre.optPre.pmodel, pre.optPre.color); fprintf('\n'); end; % structure for the storing the registration through the iterations if pre.optPre.debug reg.allReg = {}; end; % main loop converged = false; while true % compute the warped and difference images and the RMS error tic; [reg.err, wI_roi, dI_roi, reg.e_roi] = DIRT_Warp(pre.optPre.gmodel, reg.g, pre.optPre.pmodel, reg.p, ... pre.optPre.color, pre.R_roi{sj}, pre.C_roi{sj}, tI_norm, false, 0, pre.sI_roi(pre.ROI_Rind{sj},:)); reg.cpu_time = reg.cpu_time + toc; if reg.err fprintf('Warping attempted outside the target image, exiting\n'); fprintf('You may try to improve initialization with DIRT_GModel_Init and/or shrink the ROI with DIRT_MaskBorder\n'); return; end; % de-normalize the RMS error reg.e_roi = DIRT_PNorm_UnNormRMSError(pre.optPre.pnorm_params, reg.e_roi); % store initial error and check it if reg.it == 0 reg.e_roi_init = reg.e_roi; if reg.e_roi_init >= optReg.max_init_error if optReg.verb, fprintf('Initial error too large\n'); end; break; end; end; % de-normalize the photometric registration parameters p_unnorm = DIRT_PNorm_UnNorm_PModel(pre.optPre.pnorm_params, pre.optPre.pmodel, pre.optPre.color, reg.p); % if pre.optPre.debug % [err, wI, dI, e, wI_no_pmodel, wI_no_gmodel] = DIRT_Warp(pre.optPre.gmodel, reg.g, ..., % pre.optPre.pmodel, p_unnorm, pre.optPre.color, pre.R_all, pre.C_all, tI, true, ..., % optReg.unfilled_pixels_warped, pre.sI, optReg.unfilled_pixels_diff); % end; % % store the current estimate % if pre.optPre.debug % reg.allReg{end+1}.g = reg.g; % reg.allReg{end}.p = p_unnorm; % reg.allReg{end}.e = e; % reg.allReg{end}.cpu_time = reg.cpu_time; % reg.allReg{end}.e_roi = reg.e_roi; % if pre.optPre.debug2 % reg.allReg{end}.wI = wI; % reg.allReg{end}.dI = dI; % end; % end; % % write images to disk % if ~isempty(optReg.write_res_path) && pre.optPre.debug % imwrite(uint8(abs(dI)), sprintf(optReg.write_dIfmtfn, reg.it)); % imwrite(uint8(abs(wI)), sprintf(optReg.write_wIfmtfn, reg.it)); % imwrite(uint8(abs(wI_no_pmodel)), sprintf(optReg.write_wInopmodelfmtfn, reg.it)); % imwrite(uint8(abs(wI_no_gmodel)), sprintf(optReg.write_wInogmodelfmtfn, reg.it)); % end; % display information if optReg.verb || pre.optPre.debug fprintf('%03d | %012.7f | %012.7f', reg.it, reg.e_roi, reg.cpu_time); end; if pre.optPre.debug fprintf(' | %012.7f ', e); end; if optReg.verb || pre.optPre.debug DIRT_GModel_Disp(pre.optPre.gmodel, reg.g); DIRT_PModel_Disp(pre.optPre.pmodel, pre.optPre.color, p_unnorm); fprintf('\n'); end; % if no optimization required if ~pre.optPre.goptim && ~pre.optPre.poptim if optReg.verb, fprintf('No optimization required\n'); end; converged = true; end; % convergence test if converged, break; end; tic; % compute the right hand side of the normal equations b = sum(pre.SD_roi{sj}' .* repmat(dI_roi', pre.optPre.no, 1), 2); % compute the update vector d = pre.invH{sj} * b; % norm of the update vector for convergence test normd = norm(d); % update the current geometric estimate if pre.optPre.goptim dg = d(1:pre.optPre.ng); d = d(pre.optPre.ng+1:end); reg.g = DIRT_GModel_Update(pre.optPre.gmodel, reg.g, dg, optReg.gopt); end; % update the current photometric estimate if pre.optPre.poptim dp = d(1:pre.optPre.np); reg.p = DIRT_PModel_Update(pre.optPre.pmodel, pre.optPre.color, reg.p, dp); end; reg.cpu_time = reg.cpu_time + toc; % convergence test if normd < optReg.min_step_size if optReg.verb, fprintf('Minimum step size reached\n'); end; converged = ~optReg.no_min_step_size; end; % increase iteration counter reg.it = reg.it + 1; % maximum number of iterations reached if reg.it >= optReg.max_nb_it if optReg.verb, fprintf('Maximum number of iterations reached\n'); end; converged = ~optReg.no_max_nb_it; end; % optional pause for debugging purposes if optReg.pause_after_update, pause; end; end; % main loop % de-normalize the photometric registration parameters reg.p = DIRT_PNorm_UnNorm_PModel(pre.optPre.pnorm_params, pre.optPre.pmodel, pre.optPre.color, reg.p); % % save the registration structure and options, and pre-computations % if ~isempty(optReg.write_res_path) % save([optReg.write_basepath '/reg_optReg_pre.mat'], 'reg', 'optReg', 'pre'); % end;
github
rmahieu/misaligned-dfd-master
DIRT_Precomputation.m
.m
misaligned-dfd-master/dependencies/IAT_v0.9.2/dirt/DIRT_Precomputation.m
15,279
utf_8
4d0d580de562775f1514e3b37e5e38ea
function pre = DIRT_Precomputation(sI, varargin) % pre = DIRT_Precomputation(sI, ...) % % Do some precomputations for image alignment using the DIRT_Registration % function. % % Mandatory inputs: % - sI [image] % The source image % % Optional inputs (properties): % - 'ROI' [struct from the DIRT_Mask2ROI function] Default: user is asked to enter a polygonal ROI % A structure describing the region of interest % - 'FM_RC' [m x 2 matrix] Default: [] % A matrix containing the coordinates of points to be matched to the % target image. This makes DIRT enters the FM mode. Only one of ROI and FM_RC can % be specified at the same time % - 'HalfMaskSize' [scalar] Default: 5 % * FM mode only * % Half the side length of the ROI around each point in FM mode % - 'gopt' [struct] Default: [] % * ROI mode only * % A structure parameter to be passed to the DIRT_GModel_* functions % - 'no_goptim' [boolean] % Toggle optimization of the geometric registration off % - 'gmodel' [string] Default: 'Homography' in ROI mode and '3PtHomography' in FM mode % The geometric registration model % For '3PtHomography', a source and a target point must be given in % gopt as column 2-vectors gopt.sq and gopt.tq % - 'no_poptim' [boolean] % Toggle optimization of the photometric registration off % - 'pmodel' [string] Default: 'GainAndBias' for gray-level images % The photometric registration model % - 'verb' [scalar] Default: 1 % The verbosity level % - 'debug' [boolean] % Toggle debug (slow) mode % - 'debug2' [boolean] % Toggle debug2 (very slow) mode - keeps everything % - 'filter_image_der_sigma' [scalar] Default: 1 % Scale of the Gaussian derivative filter used to differentiate the % source image sI % - 'no_pnorm' [boolean] % Toggle normalization of the pixel values off % - 'no_gnorm' [boolean] % Toggle normalization of the pixel coordinates off % % Outputs: % - pre [struct] % The sought-after structure, always containing: % * optPre [struct] % The precomputation options, defined from the properties % * sI_roi [image] % The source image pixels for the region of interest % * sIc_roi and sIr_roi [images] % The source image partial derivatives for the region of % interest % * R_roi and C_roi [columns vectors] % The coordinates of the pixels in the region of interest % In FM mode, these are cells with size m % * SD_roi [matrix] % The steepest descent images for the region of interest % * invH [matrix] % The inverse of the Hessian matrix for the normal equations % and that may contain, in debug mode: % * sI [image] % The source image % * sIc and sIr [images] % The source image partial derivatives % * R_all and C_all [columns vectors] % The coordinates of all pixels in the source image % * SD_all [matrix] % The steepest descent images for all pixels in the source % image % * H [matrix] % The Hessian matrix for the normal equations % % This function goes with the DIRT Matlab image registration package. % Please cite my paper on this topic that you shall find on my web page if % you use this package. Adrien Bartoli. % check number of parameters if nargin < 2, error('not enough input arguments'); end; % setup default parameters and parse input parameters pre.optPre = ParseVarargin(ABIsRGB(sI), sI, varargin{:}); % print a summary of the input parameters if required if pre.optPre.verb, DIRT_optPre_PrintSummary(pre.optPre); end; % image size nr = size(sI, 1); nc = size(sI, 2); % store the source image data if ~pre.optPre.color pre.sI_roi = sI(pre.optPre.ROI.Rind); else sI_1 = sI(:,:,1); pre.sI_roi(:, 1) = sI_1(pre.optPre.ROI.Rind); sI_2 = sI(:,:,2); pre.sI_roi(:, 2) = sI_2(pre.optPre.ROI.Rind); sI_3 = sI(:,:,3); pre.sI_roi(:, 3) = sI_3(pre.optPre.ROI.Rind); end; if pre.optPre.debug pre.sI = sI; end; if strcmp(pre.optPre.Mode,'FM'), pre.sI = sI; end; % photometric range normalization (pixel values) pre.optPre.pnorm_params = DIRT_PNorm_Params(pre.optPre.pnorm, pre.sI_roi); % photometrically normalized sI_roi pre.sI_roi = DIRT_PNorm_NormImage(pre.optPre.pnorm_params, pre.sI_roi); % the image derivatives if pre.optPre.filter_image_der_sigma == 0 filter = ABFilters1D('der_x'); else filter = ABFilters1D('gauss_der_x', pre.optPre.filter_image_der_sigma); end; if ~pre.optPre.color sIc = conv2(sI, - filter, 'same'); sIr = conv2(sI, - filter', 'same'); pre.sIc_roi = sIc(pre.optPre.ROI.Rind); pre.sIr_roi = sIr(pre.optPre.ROI.Rind); else for c = 1:3 sIc_c = conv2(sI(:, :, c), - filter, 'same'); pre.sIc_roi(:, c) = sIc_c(pre.optPre.ROI.Rind); sIr_c = conv2(sI(:, :, c), - filter', 'same'); pre.sIr_roi(:, c) = sIr_c(pre.optPre.ROI.Rind); end; end; if pre.optPre.debug2 if ~pre.optPre.color pre.sIc = sIc; pre.sIr = sIr; else for c = 1:3 pre.sIc(:, :, c) = conv2(sI(:, :, c), - filter, 'same'); pre.sIr(:, :, c) = conv2(sI(:, :, c), - filter', 'same'); end; end; end; % the image gradient must be normalized, assuming that the normalizing % transformation can be applied after derivation pre.sIc_roi = DIRT_PNorm_NormImage(pre.optPre.pnorm_params, pre.sIc_roi); pre.sIr_roi = DIRT_PNorm_NormImage(pre.optPre.pnorm_params, pre.sIr_roi); % columns and rows for all pixels in the ROI and in the image [C_all, R_all] = meshgrid(1:nc, 1:nr); % columns and rows for pixels of interest switch pre.optPre.Mode case 'ROI' pre.C_roi = C_all(pre.optPre.ROI.Rind); pre.R_roi = R_all(pre.optPre.ROI.Rind); if pre.optPre.debug pre.C_all = C_all(:); pre.R_all = R_all(:); end; case 'FM' for sj = 1:pre.optPre.m if pre.optPre.verb, fprintf('sj = %04d / %04d\n', sj, pre.optPre.m); end; ROI = DIRT_Mask2ROI(DIRT_MaskRectangle(sI, round(pre.optPre.sRC(sj,1)), round(pre.optPre.sRC(sj,2)), pre.optPre.HalfMaskSize, pre.optPre.HalfMaskSize)); pre.ROI_Rind{sj} = ROI.Rind; pre.C_roi{sj} = C_all(ROI.Rind); pre.R_roi{sj} = R_all(ROI.Rind); end; otherwise error('unknown mode'); end; % computation of the Jacobian and Hessian matrices switch pre.optPre.Mode case 'ROI' if pre.optPre.debug2 [pre.SD_roi, pre.invH, pre.H, pre.SD_all] = DIRT_Precomputation_ROI(pre); elseif pre.optPre.debug [pre.SD_roi, pre.invH, pre.H] = DIRT_Precomputation_ROI(pre); else [pre.SD_roi, pre.invH] = DIRT_Precomputation_ROI(pre); end; case 'FM' for j = 1:pre.optPre.m pre.optPre.gopt.sq = pre.optPre.sRC(j,:)'; if pre.optPre.debug [pre.SD_roi{j}, pre.invH{j}, pre.H{j}] = DIRT_Precomputation_FM(pre, pre.R_roi{j}, pre.C_roi{j}, pre.ROI_Rind{j}); else [pre.SD_roi{j}, pre.invH{j}] = DIRT_Precomputation_FM(pre, pre.R_roi{j}, pre.C_roi{j}, pre.ROI_Rind{j}); end; end; otherwise error('unknown mode'); end; %--- %- Property parsing and default option values %--- function optPre = ParseVarargin(color, sI, varargin) % default values optPre.gopt = []; optPre.color = color; optPre.goptim = true; optPre.poptim = true; if ~optPre.color optPre.pmodel = 'GainAndBias'; else optPre.pmodel = 'SingleGainAndBias'; end; optPre.np = DIRT_PModel_N(optPre.pmodel, optPre.color); optPre.verb = 1; optPre.debug = false; optPre.debug2 = false; optPre.filter_image_der_sigma = 1; optPre.gnorm = true; optPre.pnorm = true; optPre.HalfMaskSize = 5; optPre.Mode = 'UnassignedYet'; % varargin parsing z = 1; while z <= length(varargin) switch(lower(varargin{z})) case 'roi' if isfield(optPre,'FM_RC'), error('ROI is specified while FM_RC has already been'); end; optPre.ROI = varargin{z+1}; optPre.Mode = 'ROI'; z = z + 2; case 'fm_rc' if isfield(optPre,'ROI'), error('FM_RC is specified while ROI has already been'); end; optPre.sRC = varargin{z+1}; optPre.m = size(optPre.sRC, 1); optPre.Mode = 'FM'; optPre.ROI = DIRT_Mask2ROI(DIRT_MaskBorder(0,size(sI,1),size(sI,2))); z = z + 2; case 'halfmasksize' optPre.HalfMaskSize = varargin{z+1}; z = z + 2; case 'gopt' optPre.gopt = varargin{z+1}; z = z + 2; case 'no_goptim' optPre.goptim = false; z = z + 1; case 'gmodel' optPre.gmodel = varargin{z+1}; optPre.ng = DIRT_GModel_N(optPre.gmodel); z = z + 2; case 'no_poptim' optPre.poptim = false; z = z + 1; case 'pmodel' optPre.pmodel = varargin{z+1}; optPre.np = DIRT_PModel_N(optPre.pmodel, optPre.color); z = z + 2; case 'verb' optPre.verb = varargin{z+1}; z = z + 2; case 'debug' optPre.debug = true; z = z + 1; case 'debug2' optPre.debug = true; optPre.debug2 = true; z = z + 1; case 'filter_image_der_sigma' optPre.filter_image_der_sigma = varargin{z+1}; z = z + 2; case 'no_gnorm' optPre.gnorm = false; z = z + 1; case 'no_pnorm' optPre.pnorm = false; z = z + 1; otherwise error(['unknown property ' varargin{z}]); end; end; % ROI if strcmp(optPre.Mode,'UnassignedYet') %~isfield(optPre,'ROI') && ~isfield(optPre,'FM_RC') fprintf('Enter a polygonal ROI (Region Of Interest)\n'); optPre.ROI = DIRT_Mask2ROI(DIRT_MaskManual(sI)); optPre.Mode = 'ROI'; end; % gmodel if ~isfield(optPre,'gmodel') switch optPre.Mode case 'ROI' optPre.gmodel = 'Homography'; case 'FM' optPre.gmodel = '3PtHomography'; end; else if ~strcmp(optPre.gmodel,'Homography') ... && ~strcmp(optPre.gmodel,'3PtHomography') ... && ~strcmp(optPre.gmodel,'Affine') ... && ~strcmp(optPre.gmodel,'Rt') error('Unknown gmodel'); end; end; optPre.ng = DIRT_GModel_N(optPre.gmodel); % finish initialization % number of parameters to be optimized if optPre.goptim, optPre.no = optPre.ng; else optPre.no = 0; end; if optPre.poptim, optPre.no = optPre.no + optPre.np; end; %--- %- Computation of the constant Jacobian and Hessian for some pixels of interest in ROI mode %--- function [SD_roi, invH, oH, oSD_all] = DIRT_Precomputation_ROI(pre) % the steepest descent images for the geometric registration parameters if pre.optPre.goptim [Gr, Gc] = DIRT_GModel_GradientVectors(pre.optPre.gmodel, pre.R_roi, pre.C_roi, pre.optPre.gopt); if ~pre.optPre.color % in the grey-level case, SD_roi is (Rn x ng) SD_roi = repmat(pre.sIr_roi, 1, pre.optPre.ng).*Gr + repmat(pre.sIc_roi, 1, pre.optPre.ng).*Gc; else % in the color case, the SD_roi interlaces the RGB channels and is % (3*Rn x ng) SD_roi = zeros(pre.optPre.ROI.Rn*3, pre.optPre.ng); for c = 1:3 SD_roi(c:3:end, :) = repmat(pre.sIr_roi(:, c), 1, pre.optPre.ng).*Gr + repmat(pre.sIc_roi(:, c), 1, pre.optPre.ng).*Gc; end; end; if nargout > 3 [Gr, Gc] = DIRT_GModel_GradientVectors(pre.optPre.gmodel, pre.R_all, pre.C_all, pre.optPre.gopt); if ~pre.optPre.color % in the grey-level case, the columns of SD_all are the % vectorized steepest descent images SD_all = repmat(pre.sIr(:), 1, pre.optPre.ng).*Gr + repmat(pre.sIc(:), 1, pre.optPre.ng).*Gc; else % in the color case, a third dimension is added to the matrix, % so that the steepest descent images for all three channels % are represented. SD_all is thus (3*Rn x ng x 3) sIr_1 = pre.sIr(:,:,1); sIc_1 = pre.sIc(:,:,1); SD_all(:,:,1) = repmat(sIr_1(:), 1, pre.optPre.ng).*Gr + repmat(sIc_1(:), 1, pre.optPre.ng).*Gc; sIr_2 = pre.sIr(:,:,2); sIc_2 = pre.sIc(:,:,2); SD_all(:,:,2) = repmat(sIr_2(:), 1, pre.optPre.ng).*Gr + repmat(sIc_2(:), 1, pre.optPre.ng).*Gc; sIr_3 = pre.sIr(:,:,3); sIc_3 = pre.sIc(:,:,3); SD_all(:,:,3) = repmat(sIr_3(:), 1, pre.optPre.ng).*Gr + repmat(sIc_3(:), 1, pre.optPre.ng).*Gc; end; end; else SD_all = []; end; % the steepest descent images for the photometric part if pre.optPre.poptim SD_roi = [ SD_roi DIRT_PModel_GradientVectors(pre.optPre.pmodel, pre.optPre.color, pre.sI_roi) ]; if pre.optPre.debug2 if ~pre.optPre.color SD_all = [ SD_all DIRT_PModel_GradientVectors(pre.optPre.pmodel, pre.optPre.color, pre.sI(:)) ]; else % implementation to be done % sI_1 = pre.sI(:,:,1); % sI_2 = pre.sI(:,:,2); % sI_3 = pre.sI(:,:,3); % v_sI(:, 1) = sI_1(:); % v_sI(:, 2) = sI_2(:); % v_sI(:, 3) = sI_3(:); end; end; end; % the (Gauss-Newton approximation to the) Hessian matrix if pre.optPre.goptim || pre.optPre.poptim H = SD_roi' * SD_roi; if cond(H) > 10^15 error('The source ROI does not seem to contain enough information to register -- try a simpler gmodel/pmodel'); end; invH = inv(H); end; if nargout > 2, oH = H; end; if nargout > 3, oSD_all = SD_all; end; %--- %- Computation of the constant Jacobian and Hessian for some pixels of interest in FM mode %--- function [SD_roi, invH, oH] = DIRT_Precomputation_FM(pre, R_roi, C_roi, Rind) Rn = length(Rind); % the steepest descent images for the geometric registration parameters if pre.optPre.goptim [Gr, Gc] = DIRT_GModel_GradientVectors(pre.optPre.gmodel, R_roi, C_roi, pre.optPre.gopt); if ~pre.optPre.color % in the grey-level case, SD_roi is (Rn x ng) SD_roi = repmat(pre.sIr_roi(Rind), 1, pre.optPre.ng).*Gr + repmat(pre.sIc_roi(Rind), 1, pre.optPre.ng).*Gc; else % in the color case, the SD_roi interlaces the RGB channels and is % (3*Rn x ng) SD_roi = zeros(Rn*3, pre.optPre.ng); for c = 1:3 SD_roi(c:3:end, :) = repmat(pre.sIr_roi(Rind,c), 1, pre.optPre.ng).*Gr + repmat(pre.sIc_roi(Rind,c), 1, pre.optPre.ng).*Gc; end; end; end; % the steepest descent images for the photometric part if pre.optPre.poptim SD_roi = [ SD_roi DIRT_PModel_GradientVectors(pre.optPre.pmodel, pre.optPre.color, pre.sI_roi(Rind,:)) ]; end; % the (Gauss-Newton approximation to the) Hessian matrix if pre.optPre.goptim || pre.optPre.poptim H = SD_roi' * SD_roi; invH = inv(H); end; if nargout > 2, oH = H; end;
github
rmahieu/misaligned-dfd-master
DIRT_FM_Registration.m
.m
misaligned-dfd-master/dependencies/IAT_v0.9.2/dirt/DIRT_FM_Registration.m
2,749
utf_8
96862857a3ffd780c1b26d3d2732cf76
function reg_FM = DIRT_FM_Registration(tI, pre_FM, tR, tC, varargin) % reg_FM = DIRT_FM_Registration(tI, pre_FM, tR, tC, varargin) % % Compute the SSD and OptSSD between the points in the source image in pre_FM % and the points (tR,tC) in the target image. % % Mandatory inputs: % - tI [image] % The source image % - tR, tC [column vectors] % Rows and columns in the target image of the points to be matched % % Optional inputs (properties): % % Outputs: % - reg_FM [struct] % Contains the computed RawSSD and OptSSD scores % % This function goes with the DIRT Matlab image registration package. % Please cite my paper on this topic that you shall find on my web page if % you use this package. Adrien Bartoli. % check number of parameters if nargin < 4 error('not enough input arguments'); end; % setup default parameters and parse input parameters optReg_FM = ParseVarargin(pre_FM.optPre_FM, varargin{:}); m = length(tR); for sj = 1:pre_FM.m if optReg_FM.verb fprintf('sj = %04d / %04d\n', sj, pre_FM.m); end; for tj = 1:m if optReg_FM.verb fprintf(' tj = %04d / %04d\n', tj, m); end; gopt.tq = [tR(tj);tC(tj)]; reg = DIRT_Registration(tI, pre_FM.pre{sj}, 'verb', 0, 'max_nb_it', 1, 'gopt', gopt); reg_FM.RawSSD(sj,tj) = reg.e_roi_init; if reg.e_roi_init < optReg_FM.max_RawSSD4OptSSD && norm(pre_FM.pre{sj}.optPre.gopt.sq-gopt.tq) < optReg_FM.max_disparity reg = DIRT_Registration(tI, pre_FM.pre{sj}, 'verb', 0, 'min_step_size', optReg_FM.min_step_size, ... 'max_nb_it', optReg_FM.max_nb_it, 'gopt', gopt); end; if reg.err reg_FM.OptSSD(sj,tj) = reg.e_roi_init; else reg_FM.OptSSD(sj,tj) = reg.e_roi; end; end; end; function optReg_FM = ParseVarargin(optPre_FM, varargin) % default values optReg_FM.max_RawSSD4OptSSD = 30; optReg_FM.max_disparity = 300; optReg_FM.verb = 1; optReg_FM.min_step_size = 1e-2; optReg_FM.max_nb_it = 10; % varargin parsing z = 1; while z <= length(varargin) switch(lower(varargin{z})) case 'max_rawssd4optssd' optReg_FM.max_RawSSD4OptSSD = varargin{z+1}; z = z + 2; case 'max_disparity' optReg_FM.max_disparity = varargin{z+1}; z = z + 2; case 'verb' optReg_FM.verb = varargin{z+1}; z = z + 2; case 'min_step_size' optReg_FM.min_step_size = varargin{z+1}; z = z + 2; case 'max_nb_it' optReg_FM.max_nb_it = varargin{z+1}; z = z + 2; otherwise error(['unknown property ' varargin{z}]); end; end;
github
rmahieu/misaligned-dfd-master
DIRT_FM_Precomputation.m
.m
misaligned-dfd-master/dependencies/IAT_v0.9.2/dirt/DIRT_FM_Precomputation.m
2,514
utf_8
bcbdd3a7c94000f185b6d5c867e50183
function pre_FM = DIRT_FM_Precomputation(sI, sR, sC, varargin) % pre_FM = DIRT_FM_Precomputation(sI, sR, sC, varargin) % % Do some precomputations for two-image feature matching using the % DIRT_FM_Registration function. % % Mandatory inputs: % - sI [image] % The source image % - sR, sC [column vectors] % Rows and columns in the source image of the points to be matched % % Optional inputs (properties): % % Outputs: % - pre_FM [struct] % Contains the precomputations % % This function goes with the DIRT Matlab image registration package. % Please cite my paper on this topic that you shall find on my web page if % you use this package. Adrien Bartoli. % check number of parameters if nargin < 3, error('not enough input arguments'); end; % setup default parameters and parse input parameters pre_FM.optPre_FM = ParseVarargin(varargin{:}); % store the source image data pre_FM.sI = sI; % the number of features pre_FM.m = length(sR); % % the image derivatives % if pre.optPre.filter_image_der_sigma == 0 % filter = ABFilters1D('der_x'); % else % filter = ABFilters1D('gauss_der_x', pre.optPre.filter_image_der_sigma); % end; % if ~pre.optPre.color % pre.sIc = conv2(sI, - filter, 'same'); % pre.sIr = conv2(sI, - filter', 'same'); % else % for c = 1:3 % pre.sIc(:,:,c) = conv2(sI(:, :, c), - filter, 'same'); % pre.sIr(:,:,c) = conv2(sI(:, :, c), - filter', 'same'); % end; % end; for sj = 1:pre_FM.m if pre_FM.optPre_FM.verb, fprintf('sj = %04d / %04d\n', sj, pre_FM.m); end; M = DIRT_MaskRectangle(sI, round(sR(sj)), round(sC(sj)), pre_FM.optPre_FM.HalfMaskSize, pre_FM.optPre_FM.HalfMaskSize); gopt.sq = [sR(sj);sC(sj)]; lear pre_FM.pre{sj} = DIRT_Precomputation(sI, DIRT_Mask2ROI(M), 'no_poptim', ... 'gmodel', pre_FM.optPre_FM.gmodel, ... 'gopt', gopt, ... 'verb', 0); end; function optPre_FM = ParseVarargin(varargin) % default values optPre_FM.HalfMaskSize = 5; optPre_FM.gmodel = '3PtHomography'; optPre_FM.verb = 1; % varargin parsing z = 1; while z <= length(varargin) switch(lower(varargin{z})) case 'halfmasksize' optPre_FM.HalfMaskSize = varargin{z+1}; z = z + 2; case 'gmodel' optPre_FM.gmodel = varargin{z+1}; z = z + 2; case 'verb' optPre_FM.verb = varargin{z+1}; z = z + 2; otherwise error(['unknown property ' varargin{z}]); end; end;
github
rmahieu/misaligned-dfd-master
iat_dense_sift.m
.m
misaligned-dfd-master/dependencies/IAT_v0.9.2/nonrigid/siftflow/iat_dense_sift.m
6,587
utf_8
49eede0370fe71dfff65c0b3cce8cf81
function [siftImage, gridX, gridY] = iat_dense_sift(im, patch_size, grid_spacing, varargin) % [SIFTIMAGE, GRIDX,GRIDY] = IAT_DENSE_SIFT(IMAGE, PS, GSPACING) % IAT_DENSE_SIFT creates SIFTIMAGE from IMAGE, when the pixels of latter % are replaced by SIFT descriptors [1] that describe their surrounding % area od size PSxPS. SIFTIMAGE is defined on the meshgrid [GRIDX,GRIDy] % which results from IMAGE's sampling with GRIDSPACING factor (and % after ignoring PS/2 rows and columns from all image sides). % % Input arguments: % IMAGE: the input image % PS: The width (=height) of the square patch % that is described by SIFT vectors. % GRIDSPACING: the donwscale factor that defines the resolution of % SIFTIMAGE % % % -->Optional Paramaters: % [SIFTIMAGE, GRIDX,GRIDY] = iat_dense_sift(IMAGE, PS, GSPACING, 'PARAM1', PARAM1VALUE,...) % The user can define his own parameter values insted of default ones. % These parameters are: % % 'numAngles': The quantization step (angle) for gradient orientation % (default: 8) % % 'numBins': The number of spatial bins in each dimension. The % size of each SIFT descriptor is numAngles*numBins*numBins % (default: 4) % % 'alpha': The attenuation of angles; it must be odd number % (default: 9) % % 'sigma': The scale of gaussian kernel for computing % DOG (default: 1). When sigma is scalar, the size of % kernel is (4*ceil(sigma)+1)X(4*ceil(sigma)+1). When % sigma is a 2-element vector, i.e. [sigmaX, sigmaY], % the size of the kernel is % (4*ceil(sigmaY)+1)X(4*ceil(sigmaX)+1) % % Output arguments % SIFTIMAGE: the output image % GRIDX & GRIDY: the meshgrid of SIFTIMAGE's support area. % % % % ------------------- % Authors: Ce Liu, Georgios Evangelidis % Copyright (C) 2013 Ce Liu % All rights reserved. % % This function is a minor modification of the original function written by % Ce Liu. For any bugs, please contact <[email protected]> or % <[email protected]> % % This file is part of the IAT library and is made available under % the terms of the GNU license (see the COPYING file). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% im = double(im); im = mean(im,3); im = im /max(im(:)); % input parser par = inputParser; addOptional(par,'numAngles',8); addOptional(par,'numBins',4); addOptional(par,'alpha',9); addOptional(par,'sigma',1); % merge default with provided values parse(par,varargin{:}); % get the parameters num_angles = par.Results.numAngles; num_bins = par.Results.numBins; alpha = par.Results.alpha; sigma_edge = par.Results.sigma; if (mod(alpha,2)~=1) error('iat_dense_sift: Parameter "alpha" must be odd number'); end angle_step = 2 * pi / num_angles; angles = 0:angle_step:2*pi; angles(num_angles+1) = []; % bin centers [height, width] = size(im); [GX,GY] = gradient(gen_gauss(sigma_edge)); GX = GX * 2 ./ sum(sum(abs(GX))); GY = GY * 2 ./ sum(sum(abs(GY))); I_X = filter2(GX, im, 'same'); % vertical edges I_Y = filter2(GY, im, 'same'); % horizontal edges I_mag = sqrt(I_X.^2 + I_Y.^2); % gradient magnitude I_theta = atan2(I_Y,I_X); I_theta(isnan(I_theta)) = 0; % grid of SIFTIMAGE gridX = patch_size/2+1:grid_spacing:width-patch_size/2; gridY = patch_size/2+1:grid_spacing:height-patch_size/2; % orientation images I_ori = zeros([height, width, num_angles], 'single'); % for each histogram angle cosI = cos(I_theta); sinI = sin(I_theta); for a=1:num_angles % compute each orientation channel tmp = (cosI*cos(angles(a))+sinI*sin(angles(a))).^alpha; tmp = tmp .* (tmp > 0); % weight by magnitude I_ori(:,:,a) = tmp .* I_mag; end % Convolution formulation: r = patch_size/2; cx = r - 0.5; sample_res = patch_size/num_bins; weight_x = abs((1:patch_size) - cx)/sample_res; weight_x = (1 - weight_x) .* (weight_x <= 1); for a = 1:num_angles I_ori(:,:,a) = conv2(weight_x, weight_x', I_ori(:,:,a), 'same'); end % Sample SIFT bins at valid locations (without boundary artifacts) % find coordinates of sample points (bin centers) [sample_x, sample_y] = meshgrid(linspace(1,patch_size+1,num_bins+1)); sample_x = sample_x(1:num_bins,1:num_bins); sample_x = sample_x(:)-patch_size/2; sample_y = sample_y(1:num_bins,1:num_bins); sample_y = sample_y(:)-patch_size/2; siftImage = zeros([length(gridY) length(gridX) num_angles*num_bins*num_bins], 'single'); b = 0; for n = 1:num_bins*num_bins siftImage(:,:,b+1:b+num_angles) = I_ori(round(gridY+sample_y(n)), round(gridX+sample_x(n)), :); b = b+num_angles; end % Outputs: [gridX,gridY] = meshgrid(gridX, gridY); [nrows, ncols, cols] = size(siftImage); % normalize SIFT descriptors siftImage = reshape(siftImage, [nrows*ncols num_angles*num_bins*num_bins]); siftImage = normalize_sift(siftImage); siftImage = reshape(siftImage, [nrows ncols num_angles*num_bins*num_bins]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = pad(x, D) [nrows, ncols, cols] = size(siftImage); hgt = nrows+2*D; wid = ncols+2*D; PADVAL = 0; x = [repmat(PADVAL, [hgt Dx cols]) ... [repmat(PADVAL, [Dy ncols cols]); x; repmat(PADVAL, [Dy-1 ncols cols])] ... repmat(PADVAL, [hgt Dx-1 cols])]; function G=gen_gauss(sigma) % generate a gauss kernel if all(size(sigma)==[1, 1]) % isotropic gaussian f_wid = 4 * ceil(sigma) + 1; G = fspecial('gaussian', f_wid, sigma); else % anisotropic gaussian f_wid_x = 2 * ceil(sigma(1)); f_wid_y = 2 * ceil(sigma(2)); G_x = normpdf(-f_wid_x:f_wid_x,0,sigma(1)); G_y = normpdf(-f_wid_y:f_wid_y,0,sigma(2)); G = G_y' * G_x; G = G/sum(G(:)); end function sift_arr = normalize_sift(sift_arr) % normalize SIFT descriptors of input sift_arr (each row is a descriptor) % find indices of descriptors to be normalized (those whose norm is larger than 1) tmp = sqrt(sum(sift_arr.^2, 2)); normalize_ind = (tmp > 1); sift_arr_norm = sift_arr(normalize_ind,:); sift_arr_norm = sift_arr_norm ./ repmat(tmp(normalize_ind,:), [1 size(sift_arr,2)]); % suppress large gradients sift_arr_norm(sift_arr_norm > 0.2) = 0.2; % finally, renormalize to unit length tmp = sqrt(sum(sift_arr_norm.^2, 2)); sift_arr_norm = sift_arr_norm ./ repmat(tmp, [1 size(sift_arr,2)]); sift_arr(normalize_ind,:) = sift_arr_norm;
github
waps101/polarisation_optimisation-master
SfPol_full.m
.m
polarisation_optimisation-master/SfPol_full.m
11,666
utf_8
0974392d46c902c538bfa0c958e46a57
function [height1, Jacob] = SfPol_full(img, theta_pol, mask, spec_mask, process_type, opt_weights, init_z, s) % Shape-from-polarisation full model % Inputs: % img: image matrix with shape H*W*Nimgs % theta_pol: polariser angles for input images % mask: object mask % spec_mask: mask on specularity % process_type: {'light_est', 'albedo_est'} % 'light_est': estimate light source firstly, followed by SfP optimisation, which is suitable for uniform albedo % 'albedo_est': given light source, algorithm estimate albedo firstly, followed by SfP optimisation, which is suitable for varying albedo and known light source % init_z: initial guess of height map % define coordinates system [x, y] = meshgrid(1:size(mask,2), size(mask,1):-1:1); % gradient calculation matrix and refine mask [ D_x,D_y,mask ] = gradMatrices( mask,'SmoothedCentral' ); spec_mask = spec_mask(mask); % process boundary pixels [bd_penalty, ind, weights] = boundaryPpg(mask); % locate boundary pixels as indices indMask = []; for i = 1:length(ind) indMask = [indMask; ind{i}]; end % indices of most outside boundary pix bd = ind{1}; % transform raw image cell into a long vector containing masked pixs only imgVector = []; for i = 1:size(img,3) temp = img(:,:,i); imgVector = [imgVector; temp(mask)]; end % pre-process mask to calculated necessary parameter matrix [ bd_Dx,bd_Dy ] = bdMatrices( mask,'SmoothedCentral',ind ); % define optimisation mode options1 = optimoptions( 'lsqnonlin', 'Jacobian', 'on', 'display', 'iter', 'MaxIterations', 10, 'FunctionTolerance', 1e-4, 'StepTolerance', 1e-4 ); options2 = optimoptions( 'lsqnonlin', 'Jacobian', 'on', 'display', 'iter', 'MaxIterations', 50, 'FunctionTolerance', 1e-4, 'StepTolerance', 1e-4 ); if strcmp(process_type, 'albedo_est') G = [D_x; D_y]*init_z(mask); albedo = albedo_est(G, mask, img, theta_pol, s); save albedo.mat albedo albedo = load('albedo.mat'); albedo = albedo.albedo; % setup new configuration for optimisation zNeigh = kernelFromModel(mask); [ smooth_L,smooth_counter ] = CorrMat( mask, zNeigh ); % convert to vector opt_z1 = init_z(mask); % construct a vector stacking local area of over-smoothed result smooth_kernel = smooth_L * init_z(mask); [init_cost, ~] = polResidualsFromZ( opt_z1,D_x,D_y,1.5,s,albedo,theta_pol,imgVector,spec_mask); cost_scale = mean(abs(init_cost))/opt_weights.scale; % smooth_weight = cost_scale*50*mean(abs(init_cost)); % weights for non-cost_scale angel=15,watergun=3,bunny=15 smooth_weight = cost_scale*opt_weights.smooth*mean(abs(init_cost)); % weights for non-cost_scale angel=15,watergun=3,bunny=15 bd_weight = cost_scale*opt_weights.bd*mean(abs(init_cost)).*weights;% angel=0.5,bear=.1 for iter = 1:5 [opt_z1,~,~,exitflag,~,~, Jacob ] = lsqnonlin( @(z)polResidualsFromZ( z,D_x,D_y,1.5,s,albedo,theta_pol,imgVector,spec_mask,'fine_tune',bd_Dx,bd_Dy,bd_weight,bd_penalty,smooth_L,smooth_weight,smooth_counter,smooth_kernel ), opt_z1(:), [], [], options1); if exitflag ~= 0 break end [temp_cost, ~] = polResidualsFromZ( opt_z1,D_x,D_y,1.5,s,albedo,theta_pol,imgVector,spec_mask); smooth_weight = cost_scale*opt_weights.smooth*mean(abs(temp_cost)); % 0.01 bd_weight = cost_scale*opt_weights.bd*mean(abs(temp_cost)).*weights; % 0.001 end elseif strcmp(process_type, 'light_est') G = [D_x; D_y]*init_z(mask); light = light_est(G, mask, img, theta_pol); save light.mat light % light = load('light.mat'); % light = light.light; % setup new configuration for optimisation zNeigh = kernelFromModel(mask); [ smooth_L,smooth_counter ] = CorrMat( mask, zNeigh ); % convert to vector opt_z1 = init_z(mask); % construct a vector stacking local area of over-smoothed result smooth_kernel = smooth_L * init_z(mask); [init_cost, ~] = polResidualsFromZ( opt_z1,D_x,D_y,1.5,light,1,theta_pol,imgVector,spec_mask); cost_scale = mean(abs(init_cost))/opt_weights.scale; smooth_weight = cost_scale*opt_weights.smooth*mean(abs(init_cost)); % weights for non-cost_scale angel=15,watergun=3,bunny=15 bd_weight = cost_scale*opt_weights.bd*mean(abs(init_cost)).*weights;% angel=0.5,bear=.1 for iter = 1:5 [opt_z1,~,~,exitflag,~,~, Jacob ] = lsqnonlin( @(z)polResidualsFromZ( z,D_x,D_y,1.5,light,1,theta_pol,imgVector,spec_mask,'fine_tune',bd_Dx,bd_Dy,bd_weight,bd_penalty,smooth_L,smooth_weight,smooth_counter,smooth_kernel ), opt_z1(:), [], [], options1); if exitflag ~= 0 break end [temp_cost, ~] = polResidualsFromZ( opt_z1,D_x,D_y,1.5,light,1,theta_pol,imgVector,spec_mask); smooth_weight = cost_scale*opt_weights.smooth*mean(abs(temp_cost)); bd_weight = cost_scale*opt_weights.bd*mean(abs(temp_cost)).*weights; end end z = zeros(size(mask)); z(mask) = opt_z1; height2 = reshape(z, size(mask)); % height2(not(mask)) = 0; height1 = height2; height1(not(mask)) = nan; figure surf(x, y, height1) title 'Optimal Result' axis equal function albedo = albedo_est(G, mask, img, theta_pol, s) npix = size(G,1)/2; N = [-G; ones(npix,1)]; Nx = N(1:npix); Ny = N(npix+1:2*npix); Nz = N(2*npix+1:3*npix); norms = sqrt(Nx.^2 + Ny.^2 + Nz.^2); barN = [Nx./norms; ... Ny./norms; ... Nz./norms]; Nz = barN(2*npix+1:3*npix); theta = acos(Nz); Nx = barN(1:npix); Ny = barN(npix+1:2*npix); alpha = atan2(Ny,Nx); eta = 1.5; phi_v = alpha; rho_v = (sin(theta) .* sin(theta) * (eta - 1/eta)^2) ./ (4 * cos(theta) .* sqrt(eta^2 - sin(theta).^2) ... - sin(theta).^2 * (eta + 1/eta)^2 + 2*eta^2 + 2); phi = zeros(size(mask)); rho = zeros(size(mask)); n = zeros(numel(mask),3); phi(mask) = phi_v; rho(mask) = rho_v; n(mask,:) = [Nx, Ny, Nz]; albedo = []; for i = 1:length(theta_pol) factors = 1 + rho .* cos( 2*( theta_pol(i) - phi ) ); image = img(:,:,i); iun = image./factors; non_shadow = iun(:)>0 & mask(:)>0; temp = zeros(size(iun)); temp(non_shadow) = iun(non_shadow)./(n(non_shadow,:) * s); albedo(:,:,i) = temp; end albedo = mean(albedo,3); albedo = albedo(mask); function light = light_est(G, mask, img, theta_pol) npix = size(G,1)/2; N = [-G; ones(npix,1)]; Nx = N(1:npix); Ny = N(npix+1:2*npix); Nz = N(2*npix+1:3*npix); norms = sqrt(Nx.^2 + Ny.^2 + Nz.^2); barN = [Nx./norms; ... Ny./norms; ... Nz./norms]; Nz = barN(2*npix+1:3*npix); theta = acos(Nz); Nx = barN(1:npix); Ny = barN(npix+1:2*npix); alpha = atan2(Ny,Nx); eta = 1.5; phi_v = alpha; rho_v = (sin(theta) .* sin(theta) * (eta - 1/eta)^2) ./ (4 * cos(theta) .* sqrt(eta^2 - sin(theta).^2) ... - sin(theta).^2 * (eta + 1/eta)^2 + 2*eta^2 + 2); phi = zeros(size(mask)); rho = zeros(size(mask)); n = zeros(numel(mask),3); phi(mask) = phi_v; rho(mask) = rho_v; n(mask,:) = [Nx, Ny, Nz]; light = []; for i = 1:length(theta_pol) factors = 1 + rho .* cos( 2*( theta_pol(i) - phi ) ); image = img(:,:,i); iun = image./factors; non_shadow = iun(:)>0 & mask(:)>0; light(:,i) = n(non_shadow,:) \ iun(non_shadow); end light = mean(light,2); function [boundary, ind, weights] = boundaryPpg(mask) % penalise boundary zs pointing inwards bdAlpha = []; bdTheta = []; ind = []; weights = []; % [theta, alpha, ~] = de_pol(z, mask); % find 2nd and 3rd most outside boundary layers temp_mask = mask; layers = ceil(size(mask,1)/4); % for i = 1:layers i=0; while true i=i+1; boundaries = bwboundaries(temp_mask, 4, 'noholes'); if isempty(boundaries) break end b = []; ref_b_next = []; ref_b_last = []; for j = 1:length(boundaries) if size(boundaries{j},1)<=2 continue end temp_b = boundaries{j}; b = [b; temp_b(1:end-1,:)]; ref_b_next = [ref_b_next; temp_b(2:end-1,:); temp_b(1,:)]; ref_b_last = [ref_b_last; temp_b(end-1,:); temp_b(1:end-2,:)]; end if isempty(b) break end % end pixel on thin boundary branchEnd = ref_b_next(:,1)==ref_b_last(:,1) & ref_b_next(:,2)==ref_b_last(:,2); % find thin boundary that is one-way route [~,bd_pixs_ind,~] = unique(b, 'rows', 'stable'); dup_bd_ind = not(ismember(1:size(b,1), bd_pixs_ind)); dup_bd = b(dup_bd_ind,:); dup_bd = unique(dup_bd, 'rows', 'stable');% duplicate pixels redun_bd_ind = {}; bad_bd_ind = []; bad_bd_start = []; for j = 1:size(dup_bd,1) % index of duplicate pixels in b dup_bd_ind = find(b(:,1)==dup_bd(j,1)&b(:,2)==dup_bd(j,2)); bad_bd_ind(j) = dup_bd_ind(1); % first of duplicate pixels redun_bd_ind = [redun_bd_ind, {dup_bd_ind(2:end)'}]; % redundance of duplicate pixels end % find out start pixel of thin boundary % start pixel of thin boundary need to be treated distinctively from % thin boundary temp1 = cell2mat(redun_bd_ind); if not(isempty(redun_bd_ind)) temp2 = diff(temp1); bad_bd_start = b(temp1([temp2~=1, true]),:); % pixel of start of thin boundary [~,~,bad_bd_start] = intersect(bad_bd_start, dup_bd, 'rows', 'stable'); % rows number in dup_bd matrix for pixels end % take out start pixel from redun_bd_ind and bad_bd_ind bad_bd_start_ind = bad_bd_ind(bad_bd_start); bad_bd_ind(bad_bd_start) = []; % bad_bd_ind has the same height with dup_bd redun_bd_start_ind = redun_bd_ind(bad_bd_start); redun_bd_ind(bad_bd_start) = []; % transfer indexing vector to indicating vector % bad_bd pixels should be treated individually bad_bd = zeros(size(b,1),1); bad_bd(bad_bd_ind) = 1; % save indices of extracted boundary points based on subsripts % remove redundant pixels on thin boundary(redun_bd_ind) temp_ind = sub2ind(size(mask), b(bd_pixs_ind,1), b(bd_pixs_ind,2)); temp_mask(temp_ind) = 0; ind= [ind; {temp_ind}]; p = ref_b_next(:,2) - b(:,2) + b(:,2) - ref_b_last(:,2); q = -(ref_b_next(:,1) - b(:,1) + b(:,1) - ref_b_last(:,1)); % pixels on branch_end dont have two neighbours, so use one p(branchEnd) = b(branchEnd,2) - ref_b_last(branchEnd,2); q(branchEnd) = b(branchEnd,1) - ref_b_last(branchEnd,1); temp_bdTheta = pi/2 * ones(size(q)); temp_bdTheta([cell2mat(redun_bd_ind),cell2mat(redun_bd_start_ind)]) = []; temp_bdAlpha = atan2(q,p); temp_bdAlpha = temp_bdAlpha + pi/2; % rotate alpha to perpendicular direction temp_bdAlpha(bad_bd | branchEnd) = temp_bdAlpha(bad_bd | branchEnd) - pi/2; for k = 1:length(redun_bd_start_ind) temp_bdAlpha(bad_bd_start_ind(k)) = mean([temp_bdAlpha(bad_bd_start_ind(k)),temp_bdAlpha(redun_bd_start_ind{k})']); end temp_bdAlpha(temp_bdAlpha > pi) = temp_bdAlpha(temp_bdAlpha > pi) - 2*pi; temp_bdAlpha(temp_bdAlpha < -pi) = temp_bdAlpha(temp_bdAlpha < -pi) +2*pi; temp_bdAlpha([cell2mat(redun_bd_ind),cell2mat(redun_bd_start_ind)]) = []; weights = [weights; ones(length(temp_ind), 1)/i]; bdTheta = [bdTheta; temp_bdTheta]; bdAlpha = [bdAlpha; temp_bdAlpha]; if sum(temp_mask(:)) == 0 break end end weights = [weights; weights]; boundary = [bdAlpha; bdTheta/1000]; function zNeigh = kernelFromModel(sm_mask) [gap_hzNeigh, ~] = size(sm_mask); ind = find(sm_mask == 1); neighbours = [ind-gap_hzNeigh-1, ind-gap_hzNeigh, ... ind-gap_hzNeigh+1, ind-1, ind+1, ... ind+gap_hzNeigh-1, ind+gap_hzNeigh, ind+gap_hzNeigh+1]; zNeigh = [ind, neighbours]'; % shape = 9*npix % kernel_hs = {z(zNeigh), zNeigh, [0 -1 0; -1 -4 -1; 0 -1 0]};
github
waps101/polarisation_optimisation-master
SfPol_ratio.m
.m
polarisation_optimisation-master/SfPol_ratio.m
11,400
utf_8
0039d33ba9e00120865374a21dfebaa0
function [height1, Jacob] = SfPol_ratio(img, theta_pol, mask, spec_mask, process_type, opt_weights, init_z) % Shape-from-polarisation ratio-base model % Inputs: % img: image matrix with shape H*W*Nimgs % theta_pol: polariser angles for input images % mask: object mask % spec_mask: mask on specularity % process_type: {'over_smooth', 'fine_tune'} % 'over_smooth': upsample initial height, apply smoothness constraint by Laplacian operator in optimisation % 'fine_tune': no npsampling and no smooth constraint but apply shape correlation constraint instead % init_z: initial guess of height map % define coordinates system [x, y] = meshgrid(1:size(mask,2), size(mask,1):-1:1); % gradient calculation matrix and refine mask [ D_x,D_y,mask ] = gradMatrices( mask,'SmoothedCentral' ); spec_mask = spec_mask(mask); if nargin <7 [h,w] = size(mask); centre = [ceil(h/2), ceil(w/2)]; init_z1 = zeros(size(img(:,:,1))); % initialise guess with hemisphere temp = (x-centre(2)).^2 + (y-centre(1)).^2; temp = sqrt(max(temp(:)) - temp); init_z1(mask) = temp(mask); opt_z1 = init_z1(mask); figure surf(x,y,init_z1); title 'initialisation' elseif strcmp(process_type, 'over_smooth') % lift depth map over zero plane lowest = min(init_z(:)); init_z(init_z<0) = init_z(init_z<0)-lowest; diff_scale = 2; [samples_row, samples_col] = meshgrid(1:diff_scale:size(mask,2), 1:diff_scale:size(mask,1)); [interp_row, interp_col] = meshgrid(1:size(mask,2), 1:size(mask,1)); init_z1 = interp2(samples_row, samples_col, init_z, interp_row, interp_col); init_z1(end,:) = init_z1(end-1,:); init_z1(isnan(init_z1)) = 0; opt_z1 = init_z1(mask); figure surf(x,y,init_z1); title 'initialisation' end % process boundary pixels [bd_penalty, ind, weights] = boundaryPpg(mask); % locate boundary pixels as indices indMask = []; for i = 1:length(ind) indMask = [indMask; ind{i}]; end % adjust mask to exclude boundary pixels smallMask = mask; smallMask([ind{1}]) = 0; % indices of most outside boundary pix bd = ind{1}; % transform raw image cell into a long vector containing masked pixs only imgVector = []; for i = 1:size(img,3) temp = img(:,:,i); imgVector = [imgVector; temp(mask)]; end % pre-process mask to calculated necessary parameter matrix [ smooth_L ] = LaplacianMat( mask ); % [ smooth_L ] = SmoothMatrix( mask ); [ bd_Dx,bd_Dy ] = bdMatrices( mask,'SmoothedCentral',ind ); % define optimisation mode options1 = optimoptions( 'lsqnonlin', 'Jacobian', 'on', 'display', 'iter', 'MaxIterations', 10, 'FunctionTolerance', 1e-4, 'StepTolerance', 1e-4 ); options2 = optimoptions( 'lsqnonlin', 'Jacobian', 'on', 'display', 'iter', 'MaxIterations', 50, 'FunctionTolerance', 1e-4, 'StepTolerance', 1e-4 ); if strcmp(process_type, 'over_smooth') % find proper weights for smooth term and boundary condition [init_cost, ~] = ratioResidualsFromZ( opt_z1,D_x,D_y,1.5,theta_pol,imgVector,spec_mask); % cost_scale = mean(abs(init_cost))/0.05; % bear=20000, angle=1, gun=1, bunny=50000, noisy_bunny cost_scale = mean(abs(init_cost))/opt_weights.scale; % bear=20000, angle=1, gun=1, bunny=50000, noisy_bunny smooth_weight = opt_weights.smooth*cost_scale*mean(abs(init_cost)); % bear=1.5,angle=2,gun=2,bunny=3,noisy_bunny=2,VarMNBunny=.5,vase=4(extra_smooth),mozart=4,HNmozart=2 bd_weight = opt_weights.bd*cost_scale*mean(abs(init_cost)).*weights; % bear=1.5,gun=5,angel=2,bunny=3,noisy_bunny=2,VarMNBunny=.5,vase=4(extra_smooth),mozart=5,HNmozart=3 for iter = 1:10 [opt_z1,~,~,exitflag,~,~, Jacob ] = lsqnonlin( @(z)ratioResidualsFromZ( z,D_x,D_y,1.5,theta_pol,imgVector,spec_mask,'over_smooth',bd_Dx,bd_Dy,bd_weight,bd_penalty,smooth_L,smooth_weight ), opt_z1(:), [], [], options1); if exitflag ~= 0 break end % update weights [temp_cost, ~] = ratioResidualsFromZ( opt_z1,D_x,D_y,1.5,theta_pol,imgVector,spec_mask); % cost_scale = mean(abs(init_cost))/0.05; smooth_weight = opt_weights.smooth*cost_scale*mean(abs(temp_cost)); bd_weight = opt_weights.bd*cost_scale*mean(abs(temp_cost)).*weights; end if exitflag == 0 [opt_z1,~,~,~,~,~, Jacob ] = lsqnonlin( @(z)ratioResidualsFromZ( z,D_x,D_y,1.5,theta_pol,imgVector,spec_mask,'over_smooth',bd_Dx,bd_Dy,bd_weight,bd_penalty,smooth_L,smooth_weight ), opt_z1(:), [], [], options2); end elseif strcmp(process_type, 'fine_tune') % setup new configuration for optimisation zNeigh = kernelFromModel(mask); [ smooth_L,smooth_counter ] = CorrMat( mask, zNeigh ); % convert to vector opt_z1 = init_z(mask); % construct a vector stacking local area of over-smoothed result smooth_kernel = smooth_L * init_z(mask); [init_cost, ~] = ratioResidualsFromZ( opt_z1,D_x,D_y,1.5,theta_pol,imgVector,spec_mask); cost_scale = mean(abs(init_cost))/opt_weights.scale; smooth_weight = cost_scale*opt_weights.smooth*mean(abs(init_cost)); % angel=10,watergun=3 bd_weight = cost_scale*opt_weights.bd*mean(abs(init_cost)).*weights; for iter = 1:20 [opt_z1,~,~,exitflag,~,~, Jacob ] = lsqnonlin( @(z)ratioResidualsFromZ( z,D_x,D_y,1.5,theta_pol,imgVector,spec_mask,'fine_tune',bd_Dx,bd_Dy,bd_weight,bd_penalty,smooth_L,smooth_weight,smooth_counter,smooth_kernel ), opt_z1(:), [], [], options1); if exitflag ~= 0 break end [temp_cost, ~] = ratioResidualsFromZ( opt_z1,D_x,D_y,1.5,theta_pol,imgVector,spec_mask); smooth_weight = cost_scale*10*mean(abs(temp_cost)); % angel=10,watergun=3 bd_weight = cost_scale*.5*mean(abs(temp_cost)).*weights; end end z = zeros(size(mask)); z(mask) = opt_z1; height2 = reshape(z, size(mask)); % height2(not(mask)) = 0; height1 = height2; height1(not(mask)) = nan; figure surf(x, y, height1) title 'Optimal Result' axis equal function light = light_est(G, mask, img, theta_pol) npix = size(G,1)/2; N = [-G; ones(npix,1)]; Nx = N(1:npix); Ny = N(npix+1:2*npix); Nz = N(2*npix+1:3*npix); norms = sqrt(Nx.^2 + Ny.^2 + Nz.^2); barN = [Nx./norms; ... Ny./norms; ... Nz./norms]; Nz = barN(2*npix+1:3*npix); theta = acos(Nz); Nx = barN(1:npix); Ny = barN(npix+1:2*npix); alpha = atan2(Ny,Nx); eta = 1.5; phi_v = alpha; rho_v = (sin(theta) .* sin(theta) * (eta - 1/eta)^2) ./ (4 * cos(theta) .* sqrt(eta^2 - sin(theta).^2) ... - sin(theta).^2 * (eta + 1/eta)^2 + 2*eta^2 + 2); phi = zeros(size(mask)); rho = zeros(size(mask)); n = zeros(numel(mask),3); phi(mask) = phi_v; rho(mask) = rho_v; n(mask,:) = [Nx, Ny, Nz]; light = []; for i = 1:length(theta_pol) factors = 1 + rho .* cos( 2*( theta_pol(i) - phi ) ); image = img{i}; iun = image./factors; non_shadow = iun(:)>0 & mask(:)>0; light(:,i) = n(non_shadow,:) \ iun(non_shadow); end light = mean(light,2); function [boundary, ind, weights] = boundaryPpg(mask) % penalise boundary zs pointing inwards bdAlpha = []; bdTheta = []; ind = []; weights = []; % [theta, alpha, ~] = de_pol(z, mask); % find boundary layers inwardsly temp_mask = mask; layers = ceil(size(mask,1)/4); % for i = 1:layers i=0; while true i=i+1; boundaries = bwboundaries(temp_mask, 4, 'noholes'); if isempty(boundaries) break end b = []; ref_b_next = []; ref_b_last = []; for j = 1:length(boundaries) if size(boundaries{j},1)<=2 continue end temp_b = boundaries{j}; b = [b; temp_b(1:end-1,:)]; ref_b_next = [ref_b_next; temp_b(2:end-1,:); temp_b(1,:)]; ref_b_last = [ref_b_last; temp_b(end-1,:); temp_b(1:end-2,:)]; end if isempty(b) break end % end pixel on thin boundary branchEnd = ref_b_next(:,1)==ref_b_last(:,1) & ref_b_next(:,2)==ref_b_last(:,2); % find thin boundary -- one-way route [~,bd_pixs_ind,~] = unique(b, 'rows', 'stable'); dup_bd_ind = not(ismember(1:size(b,1), bd_pixs_ind)); dup_bd = b(dup_bd_ind,:); dup_bd = unique(dup_bd, 'rows', 'stable');% duplicate pixels redun_bd_ind = {}; bad_bd_ind = []; bad_bd_start = []; for j = 1:size(dup_bd,1) % index of duplicate pixels in b dup_bd_ind = find(b(:,1)==dup_bd(j,1)&b(:,2)==dup_bd(j,2)); bad_bd_ind(j) = dup_bd_ind(1); % first of duplicate pixels redun_bd_ind = [redun_bd_ind, {dup_bd_ind(2:end)'}]; % redundance of duplicate pixels end % find out start pixel of thin boundary % start pixel of thin boundary need to be treated distinctively from % thin boundary temp1 = cell2mat(redun_bd_ind); if not(isempty(redun_bd_ind)) temp2 = diff(temp1); bad_bd_start = b(temp1([temp2~=1, true]),:); % pixel of start of thin boundary [~,~,bad_bd_start] = intersect(bad_bd_start, dup_bd, 'rows', 'stable'); % rows number in dup_bd matrix for pixels end % take out start pixel from redun_bd_ind and bad_bd_ind bad_bd_start_ind = bad_bd_ind(bad_bd_start); bad_bd_ind(bad_bd_start) = []; % bad_bd_ind has the same height with dup_bd redun_bd_start_ind = redun_bd_ind(bad_bd_start); redun_bd_ind(bad_bd_start) = []; % transfer indexing vector to indicating vector % bad_bd pixels should be treated individually bad_bd = zeros(size(b,1),1); bad_bd(bad_bd_ind) = 1; % save indices of extracted boundary points based on subsripts % remove redundant pixels on thin boundary(redun_bd_ind) temp_ind = sub2ind(size(mask), b(bd_pixs_ind,1), b(bd_pixs_ind,2)); temp_mask(temp_ind) = 0; ind= [ind; {temp_ind}]; p = ref_b_next(:,2) - b(:,2) + b(:,2) - ref_b_last(:,2); q = -(ref_b_next(:,1) - b(:,1) + b(:,1) - ref_b_last(:,1)); % pixels on branch_end dont have two neighbours, so use one p(branchEnd) = b(branchEnd,2) - ref_b_last(branchEnd,2); q(branchEnd) = b(branchEnd,1) - ref_b_last(branchEnd,1); temp_bdTheta = pi/2 * ones(size(q)); temp_bdTheta([cell2mat(redun_bd_ind),cell2mat(redun_bd_start_ind)]) = []; temp_bdAlpha = atan2(q,p); temp_bdAlpha = temp_bdAlpha + pi/2; % rotate alpha to perpendicular direction temp_bdAlpha(bad_bd | branchEnd) = temp_bdAlpha(bad_bd | branchEnd) - pi/2; for k = 1:length(redun_bd_start_ind) temp_bdAlpha(bad_bd_start_ind(k)) = mean([temp_bdAlpha(bad_bd_start_ind(k)),temp_bdAlpha(redun_bd_start_ind{k})']); end temp_bdAlpha(temp_bdAlpha > pi) = temp_bdAlpha(temp_bdAlpha > pi) - 2*pi; temp_bdAlpha(temp_bdAlpha < -pi) = temp_bdAlpha(temp_bdAlpha < -pi) +2*pi; temp_bdAlpha([cell2mat(redun_bd_ind),cell2mat(redun_bd_start_ind)]) = []; weights = [weights; ones(length(temp_ind), 1)/i]; bdTheta = [bdTheta; temp_bdTheta]; bdAlpha = [bdAlpha; temp_bdAlpha]; if sum(temp_mask(:)) == 0 break end end weights = [weights; weights]; boundary = [bdAlpha; bdTheta/1000]; function zNeigh = kernelFromModel(sm_mask) [gap_hzNeigh, ~] = size(sm_mask); ind = find(sm_mask == 1); neighbours = [ind-gap_hzNeigh-1, ind-gap_hzNeigh, ... ind-gap_hzNeigh+1, ind-1, ind+1, ... ind+gap_hzNeigh-1, ind+gap_hzNeigh, ind+gap_hzNeigh+1]; zNeigh = [ind, neighbours]'; % shape = 9*npix % kernel_hs = {z(zNeigh), zNeigh, [0 -1 0; -1 -4 -1; 0 -1 0]};
github
waps101/polarisation_optimisation-master
comp_result.m
.m
polarisation_optimisation-master/utils/comp_result.m
11,720
utf_8
ff25163764175ce643c25cada6950686
function comp_result(z, mask) % show comparison between gradient map of input and ground truth sphere % [GTx, GTy] = meshgrid(-1:2/128:1, -1:2/128:1); % GTmask = (GTx.^2 + GTy.^2)<=1; % GTz = zeros(size(GTmask)); % GTz(GTmask) = sqrt(1 - GTx(GTmask).^2 - GTy(GTmask).^2); % GTnx = GTx ./ sqrt(GTx.^2+GTy.^2+1); % GTny = GTy ./ sqrt(GTx.^2+GTy.^2+1); % GTnz = GTz ./ sqrt(GTx.^2+GTy.^2+1); % % rescale it into range (0,1) % GTnx = (GTnx+1)/2; % GTny = (GTny+1)/2; % GTnz = (GTnz+1)/2; % GTn = cat(3,GTnx, GTny, GTnz); % GTn = GTn .* repmat(GTmask, 1,1,3); Gx = 1/12*[-1 0 1; -4 0 4; -1 0 1]; Gy = 1/12*[1 4 1; 0 0 0; -1 -4 -1]; p = conv2(z, Gx, 'same'); q = conv2(z, Gy, 'same'); [~, ind, ~] = boundaryPpg(mask); bd = ind{1}; % indices of boundary pad_mask = padarray(mask, [1,1], 'post'); % pad mask to make bd not lay on boudaries of mask [rows, cols] = ind2sub(size(mask), bd); bd_padmask = sub2ind(size(pad_mask), rows, cols); gap_hNeigh = size(pad_mask, 1); u = pad_mask(bd_padmask-1)==1; l = pad_mask(bd_padmask-gap_hNeigh)==1; r = pad_mask(bd_padmask+gap_hNeigh)==1; d = pad_mask(bd_padmask+1)==1; bdPixType = {u, l, r, d}; bdType = bd_type(mask, bd, bdPixType); [bd_p, bd_q] = bd_grad(z, bd, bdType); p(bd) = bd_p; q(bd) = bd_q; nx = p ./ sqrt(p.^2+q.^2+1); ny = q ./ sqrt(p.^2+q.^2+1); nz = 1 ./ sqrt(p.^2+q.^2+1); % rescale it into range (0,1) nx = (nx+1)/2; ny = (ny+1)/2; nz = (nz+1)/2; n = cat(3, nx, ny, nz); n = n .* repmat(mask, 1,1,3); % figure; imshow(GTn) figure; imshow(n) function [boundary, ind, weights] = boundaryPpg(mask) % penalise boundary zs pointing inwards bdAlpha = []; bdTheta = []; ind = []; weights = []; % [theta, alpha, ~] = de_pol(z, mask); % find 2nd and 3rd most outside boundary layers temp_mask = mask; layers = ceil(size(mask,1)/4); for i = 1:layers boundaries = bwboundaries(temp_mask, 4, 'noholes'); b = []; ref_b_next = []; ref_b_last = []; for j = 1:length(boundaries) % for j = 1:1 % if sum(ismember(sub2ind(size(mask),boundaries{j}(:,1),boundaries{j}(:,2)),find(specular_mask))) % continue % end if size(boundaries{j},1)<=2 continue end temp_b = boundaries{j}; b = [b; temp_b(1:end-1,:)]; ref_b_next = [ref_b_next; temp_b(2:end-1,:); temp_b(1,:)]; ref_b_last = [ref_b_last; temp_b(end-1,:); temp_b(1:end-2,:)]; end if isempty(b) break end % end pixel on thin boundary branchEnd = ref_b_next(:,1)==ref_b_last(:,1) & ref_b_next(:,2)==ref_b_last(:,2); % find thin boundary that is one-way route [~,bd_pixs_ind,~] = unique(b, 'rows', 'stable'); dup_bd_ind = not(ismember(1:size(b,1), bd_pixs_ind)); dup_bd = b(dup_bd_ind,:); dup_bd = unique(dup_bd, 'rows', 'stable');% duplicate pixels % dup_bd = mat2cell(dup_bd, ones(size(dup_bd,1),1), 2); % redun_bd_ind = []; redun_bd_ind = {}; bad_bd_ind = []; bad_bd_start = []; for j = 1:size(dup_bd,1) % index of duplicate pixels in b dup_bd_ind = find(b(:,1)==dup_bd(j,1)&b(:,2)==dup_bd(j,2)); bad_bd_ind(j) = dup_bd_ind(1); % first of duplicate pixels % redun_bd_ind = [redun_bd_ind, dup_bd_ind(2:end)']; % redundance of duplicate pixels redun_bd_ind = [redun_bd_ind, {dup_bd_ind(2:end)'}]; % redundance of duplicate pixels end % find out start pixel of thin boundary % start pixel of thin boundary need to be treated distinctively from % thin boundary temp1 = cell2mat(redun_bd_ind); if not(isempty(redun_bd_ind)) temp2 = diff(temp1); bad_bd_start = b(temp1([temp2~=1, true]),:); % pixel of start of thin boundary [~,~,bad_bd_start] = intersect(bad_bd_start, dup_bd, 'rows', 'stable'); % rows number in dup_bd matrix for pixels end % take out start pixel from redun_bd_ind and bad_bd_ind bad_bd_start_ind = bad_bd_ind(bad_bd_start); bad_bd_ind(bad_bd_start) = []; % bad_bd_ind has the same height with dup_bd redun_bd_start_ind = redun_bd_ind(bad_bd_start); redun_bd_ind(bad_bd_start) = []; % transfer indexing vector to indicating vector % bad_bd pixels should be treated individually bad_bd = zeros(size(b,1),1); bad_bd(bad_bd_ind) = 1; % save indices of extracted boundary points based on subsripts % remove redundant pixels on thin boundary(redun_bd_ind) temp_ind = sub2ind(size(mask), b(bd_pixs_ind,1), b(bd_pixs_ind,2)); temp_mask(temp_ind) = 0; ind= [ind; {temp_ind}]; p = ref_b_next(:,2) - b(:,2) + b(:,2) - ref_b_last(:,2); q = ref_b_next(:,1) - b(:,1) + b(:,1) - ref_b_last(:,1); % pixels on branch_end dont have two neighbours, so use one p(branchEnd) = b(branchEnd,2) - ref_b_last(branchEnd,2); q(branchEnd) = b(branchEnd,1) - ref_b_last(branchEnd,1); temp_bdTheta = pi/2 * ones(size(q)); temp_bdTheta([cell2mat(redun_bd_ind),cell2mat(redun_bd_start_ind)]) = []; temp_bdAlpha = atan2(p, q); temp_bdAlpha = temp_bdAlpha - pi/2; % rotate alpha to perpendicular direction temp_bdAlpha(bad_bd | branchEnd) = temp_bdAlpha(bad_bd | branchEnd) - pi/2; for k = 1:length(redun_bd_start_ind) temp_bdAlpha(bad_bd_start_ind(k)) = mean([temp_bdAlpha(bad_bd_start_ind(k)),temp_bdAlpha(redun_bd_start_ind{k})']); % if temp_bdAlpha(bad_bd_start_ind(k))>pi % temp_bdAlpha(bad_bd_start_ind(k)) = 2*pi - temp_bdAlpha(bad_bd_start_ind(k)); % end end % temp_bdAlpha(bad_bd_ind(bad_bd_start_ind)) = temp_bdAlpha(bad_bd_ind(bad_bd_start_ind)) + pi/2; % temp_bdAlpha(bad_bd_ind(bad_bd_start_ind)) = mean(temp_bdAlpha(bad_bd_ind(bad_bd_start_ind)), ) % temp_bdAlpha(branchEnd) = temp_bdAlpha(branchEnd) - pi/2; temp_bdAlpha(temp_bdAlpha > 2*pi) = temp_bdAlpha(temp_bdAlpha > 2*pi) - 2*pi; temp_bdAlpha(temp_bdAlpha < 0) = temp_bdAlpha(temp_bdAlpha < 0) +2*pi; temp_bdAlpha([cell2mat(redun_bd_ind),cell2mat(redun_bd_start_ind)]) = []; % rm = []; % for k = 1:length(rm_ind) % temp_bdAlpha(bad_bd_ind(k)) = mean(temp_bdAlpha(bad_bd_ind(k)) + temp_bdAlpha(rm_ind{k})); % rm = [rm, rm_ind{k}]; % end % temp_bdTheta(rm) = []; % temp_bdAlpha(rm) = []; % % temp_bdAlpha(temp_bdAlpha > 2*pi) = temp_bdAlpha(temp_bdAlpha > 2*pi) - 2*pi; % temp_bdAlpha(temp_bdAlpha < 0) = temp_bdAlpha(temp_bdAlpha < 0) +2*pi; weights = [weights; ones(length(temp_ind), 1)/i]; bdTheta = [bdTheta; temp_bdTheta]; bdAlpha = [bdAlpha; temp_bdAlpha]; if sum(temp_mask(:)) == 0 break end end weights = [weights; weights]; boundary = [bdTheta/100; bdAlpha]; function bdtype = bd_type(mask, bd, bdPixType) % gap_hNeigh = size(z, 1); bdtype = zeros(size(mask)); % four main neighbour fourNeighPix = bd(bdPixType{1} & bdPixType{2} & bdPixType{3} & bdPixType{4}); bdtype(fourNeighPix) = 4; % three main neighbour % no u threeNeighPix = bd(not(bdPixType{1}) & bdPixType{2} & bdPixType{3} & bdPixType{4}); bdtype(threeNeighPix) = 31; % no l threeNeighPix = bd(not(bdPixType{2}) & bdPixType{1} & bdPixType{3} & bdPixType{4}); bdtype(threeNeighPix) = 32; % no r threeNeighPix = bd(not(bdPixType{3}) & bdPixType{2} & bdPixType{1} & bdPixType{4}); bdtype(threeNeighPix) = 33; % no d threeNeighPix = bd(not(bdPixType{4}) & bdPixType{2} & bdPixType{3} & bdPixType{1}); bdtype(threeNeighPix) = 34; % two main neighbour % no u l twoNeighPix = bd(not(bdPixType{1}) & not(bdPixType{2}) & bdPixType{3} & bdPixType{4}); bdtype(twoNeighPix) = 21; % no u r twoNeighPix = bd(not(bdPixType{1}) & not(bdPixType{3}) & bdPixType{2} & bdPixType{4}); bdtype(twoNeighPix) = 22; % no u d twoNeighPix = bd(not(bdPixType{1}) & not(bdPixType{4}) & bdPixType{2} & bdPixType{3}); bdtype(twoNeighPix) = 23; % no l r twoNeighPix = bd(not(bdPixType{3}) & not(bdPixType{2}) & bdPixType{1} & bdPixType{4}); bdtype(twoNeighPix) = 24; % no l d twoNeighPix = bd(not(bdPixType{4}) & not(bdPixType{2}) & bdPixType{1} & bdPixType{3}); bdtype(twoNeighPix) = 25; % no r d twoNeighPix = bd(not(bdPixType{3}) & not(bdPixType{4}) & bdPixType{1} & bdPixType{2}); bdtype(twoNeighPix) = 26; % one main neighbour % only u oneNeighPix = bd(not(bdPixType{3}) & not(bdPixType{4}) & not(bdPixType{2}) & bdPixType{1}); bdtype(oneNeighPix) = 11; % only l oneNeighPix = bd(not(bdPixType{3}) & not(bdPixType{4}) & not(bdPixType{1}) & bdPixType{2}); bdtype(oneNeighPix) = 12; % only r oneNeighPix = bd(not(bdPixType{1}) & not(bdPixType{4}) & not(bdPixType{2}) & bdPixType{3}); bdtype(oneNeighPix) = 13; % only d oneNeighPix = bd(not(bdPixType{3}) & not(bdPixType{1}) & not(bdPixType{2}) & bdPixType{4}); bdtype(oneNeighPix) = 14; bdtype = bdtype(bd); % bdtype contains neighbour type code for boundary pixel, bd is boudnary pixel indices function [bd_p, bd_q] = bd_grad(z, bd, bdType) gap_hNeigh = size(z, 1); output_p = zeros(size(z)); output_q = zeros(size(z)); pix = bd(bdType==4); %% four main neighbour output_p(pix) = (z(pix-gap_hNeigh) - z(pix+gap_hNeigh))/2; output_q(pix) = (z(pix+1) - z(pix-1))/2; %% three main neighbour % no u pix = bd(bdType==31); output_p(pix) = (z(pix-gap_hNeigh) - z(pix+gap_hNeigh))/2; output_q(pix) = (z(pix+1) - z(pix)); % no l pix = bd(bdType==32); output_p(pix) = (z(pix) - z(pix+gap_hNeigh)); output_q(pix) = (z(pix+1) - z(pix-1))/2; % no r pix = bd(bdType==33); output_p(pix) = (z(pix-gap_hNeigh) - z(pix)); output_q(pix) = (z(pix+1) - z(pix-1))/2; % no d pix = bd(bdType==34); output_p(pix) = (z(pix-gap_hNeigh) - z(pix+gap_hNeigh))/2; output_q(pix) = (z(pix) - z(pix-1)); %% two main neighbour % no u l pix = bd(bdType==21); output_p(pix) = (z(pix) - z(pix+gap_hNeigh)); output_q(pix) = (z(pix+1) - z(pix)); % no u r pix = bd(bdType==22); output_p(pix) = (z(pix-gap_hNeigh) - z(pix)); output_q(pix) = (z(pix+1) - z(pix)); % no u d pix = bd(bdType==23); output_p(pix) = (z(pix-gap_hNeigh) - z(pix+gap_hNeigh))/2; output_q(pix) = 0; % no l r pix = bd(bdType==24); output_p(pix) = 0; output_q(pix) = (z(pix+1) - z(pix-1))/2; % no l d pix = bd(bdType==25); output_p(pix) = (z(pix) - z(pix+gap_hNeigh)); output_q(pix) = (z(pix) - z(pix-1)); % no r d pix = bd(bdType==26); output_p(pix) = (z(pix-gap_hNeigh) - z(pix)); output_q(pix) = (z(pix) - z(pix-1)); %% one main neighbour % only u pix = bd(bdType==11); output_p(pix) = 0; output_q(pix) = (z(pix) - z(pix-1)); % only l pix = bd(bdType==12); output_p(pix) = (z(pix-gap_hNeigh) - z(pix)); output_q(pix) = 0; % only r pix = bd(bdType==13); output_p(pix) = (z(pix) - z(pix+gap_hNeigh)); output_q(pix) = 0; % only d pix = bd(bdType==14); output_p(pix) = 0; output_q(pix) = (z(pix+1) - z(pix)); %% bd_p = output_p(bd); bd_q = output_q(bd);
github
waps101/polarisation_optimisation-master
ratioResidualsFromZ.m
.m
polarisation_optimisation-master/utils/ratioResidualsFromZ.m
16,260
utf_8
5e291719016510881e46a021e78ef4b8
function [ residuals,J ] = ratioResidualsFromZ( z,D_x,D_y,eta,pol_angles,I_obs,spec,smooth_type,bd_Dx,bd_Dy,bd_weight,bd_penalty,smooth_L,smooth_weight, smooth_counter, smooth_kernel) % compare boundary convexity through [cos, sin] vector %polResidualsFromZ Residuals between observed intensities and diffuse %polarisation model % % Inputs: % z is vector of height values of length npix % D_x*z computes x gradient of height, similarly for D_y and y % eta index of refraction % s point light source % albedo scalar or vector of length npix containing albedo % pol_angles vector of length npolang containing polariser orientations % in radians % I_obs is a vector of length npix*npolang with all intensities for first % spec is a vector indicating specular pixels in z % polariser angle first, followed by all for second angle etc. % Compute gradients G = [D_x; D_y]*z; % Compute polarisation image from gradients: [F,J_F] = G2F(G,eta,spec); % Compute intensities from polarisation image: allI = []; allJ_I = []; num_polang=length(pol_angles); for i=1:num_polang [I,J_I] = F2I(F,pol_angles(i)); allI = [allI; I]; allJ_I = [allJ_I; J_I]; end % Compute ratios between intensities from intensity vector npix = size(allI,1)/num_polang; % circulate pixels to perform full ratio allI = [allI; allI(1:npix)]; allJ_I = [allJ_I; allJ_I(1:npix,:)]; I_obs = [I_obs; I_obs(1:npix)]; allRatio = []; allJ_Ratio = []; for j=1:num_polang [Ratio, J_Ratio] = I2Ratio(allI, j, npix, num_polang); % [Ratio, J_Ratio] = I2Ratio(allI((j-1)*npix+1:(j+1)*npix)); allRatio = [allRatio; Ratio]; allJ_Ratio = [allJ_Ratio; J_Ratio]; end % Derivatives of intensity ratio with respect to intensities: J_R_I = allJ_Ratio*allJ_I; % Derivatives of intensities with respect to gradient: J_R_F = J_R_I*J_F; % Dimension: NpixNpol * 2Npix % Derivatives of intensities with respect to surface height: J_R_Z = J_R_F*[D_x; D_y]; % Dimension NpixNpol * Npix % Derivatives of residuals with respect to surface height: J = -speye(size(J_R_Z,1))*J_R_Z; residuals = I_obs(1:num_polang*npix)./I_obs(npix+1:end)-allRatio; residuals(isnan(residuals)) = 1; residuals(residuals==inf | residuals==-inf) = 1; if nargin > 7 if strcmp(smooth_type,'over_smooth') % Add residuals and derivatives for Laplacian smoothness residuals = [residuals; smooth_weight.*smooth_L*z]; % Add derivatives for smoothness term J = [J;smooth_weight*smooth_L]; elseif strcmp(smooth_type,'fine_tune') nsmt_pix = size(smooth_L,1); % sum((localz - mean(localz)) ./ sqrt(sum((localz - mean(localz).^2))) .* local_kernel ) localZs = smooth_L * z; [smoothness, J_smooth] = correlation(localZs, smooth_counter, smooth_kernel); % Add residuals and derivatives for Laplacian smoothness residuals = [residuals; smooth_weight.*(smoothness-1)]; % Add derivatives for smoothness term % J_ressmt_smtL = sparse(1:nsmt_pix,1:nsmt_pix,-1./(smooth_L*z).^2,nsmt_pix,nsmt_pix); % J = [J;smooth_weight*J_ressmt_smtL*smooth_L]; J = [J;smooth_weight*J_smooth*smooth_L]; end % Add residuals and derivatives for convex Boundary % only G(gredients) on boundary pixels nbd_pix = size(bd_Dx,1); G_bd = [bd_Dx; bd_Dy]*z; [A, J_A] = G2A(G_bd); J_bd_Z = J_A * [bd_Dx;bd_Dy]; % diff_alpha = A(1:nbd_pix) - bd_penalty(1:nbd_pix); diff_alpha = [cos(A(1:nbd_pix)); sin(A(1:nbd_pix))] - [cos(bd_penalty(1:nbd_pix)); sin(bd_penalty(1:nbd_pix))]; diff_theta = A(nbd_pix+1:end)/1000 - bd_penalty(nbd_pix+1:end); % find small angels < pi between two % add 2*pi on angles greater than pi % only element-wise operations % res_bd_alpha = - sqrt(diff_alpha.^2) + 2*pi*((diff_alpha.^2 - pi^2)./(sqrt((diff_alpha.^2 - pi^2).^2)+10e-8)+1)/2; residuals = [residuals; [bd_weight(1:nbd_pix);bd_weight].*[diff_alpha;diff_theta]]; % Add derivatives for smoothness term % J = [J;bd_weight.*J_bd_Z]; % J_resbd_bd = [sparse(1:nbd_pix,1:nbd_pix, ... % pi*((2*diff_alpha)./(((pi^2 - diff_alpha.^2).^2).^(1/2)+ 10e-8) - ... % (2*diff_alpha.*(pi^2 - diff_alpha.^2).^2)./((((pi^2 - diff_alpha.^2).^2).^(1/2)).^2.*((pi^2 - diff_alpha.^2).^2).^(1/2)+ 10e-8)) - diff_alpha./((diff_alpha.^2).^(1/2)+ 10e-8) ... % ,nbd_pix,nbd_pix) ... % sparse(nbd_pix,nbd_pix); ... % sparse(nbd_pix,nbd_pix) ... % speye(nbd_pix)/100]; J_resbd_bd = [sparse(1:nbd_pix,1:nbd_pix,bd_weight(1:nbd_pix).*(-sin(A(1:nbd_pix))),nbd_pix,nbd_pix), sparse(nbd_pix,nbd_pix); ... sparse(1:nbd_pix,1:nbd_pix,bd_weight(1:nbd_pix).*cos(A(1:nbd_pix)),nbd_pix,nbd_pix), sparse(nbd_pix,nbd_pix); ... sparse(nbd_pix,nbd_pix), sparse(1:nbd_pix,1:nbd_pix, bd_weight(nbd_pix+1:end)/1000, nbd_pix, nbd_pix)]; J = [J;J_resbd_bd*J_bd_Z]; end end function [Ratio,J_Ratio] = I2Ratio(allI, equ, npix, nequ) % I1I2 is a long vector containing stacked intensitys under pol1 and pol2 I1 = allI((equ-1)*npix+1:equ*npix); I2 = allI(equ*npix+1:(equ+1)*npix); Ratio = I1./I2; if equ == 1 J_Ratio = [sparse(1:npix,1:npix,1./I2,npix,npix) ... sparse(1:npix,1:npix,-I1./I2.^2,npix,npix) ... sparse(npix,(nequ-1)*npix)]; elseif equ == nequ J_Ratio = [sparse(1:npix,1:npix,-I1./I2.^2,npix,npix) ... sparse(npix,(nequ-1)*npix) ... sparse(1:npix,1:npix,1./I2,npix,npix)]; else J_Ratio = [sparse(npix,(equ-1)*npix) ... sparse(1:npix,1:npix,1./I2,npix,npix) ... sparse(1:npix,1:npix,-I1./I2.^2,npix,npix) ... sparse(npix,(nequ-equ)*npix)]; end end function [I,J_I] = F2I(F,pol_ang) % Function to transform polarisation image into factorization given a polariser % angle. F is a vector containing all phis, followed by all i_un followed % by all rho. npix = size(F,1)/2; phi = F(1:npix); rho = F(npix+1:end); % factorisation in ratio-based expression I = 1+rho.*cos(2*pol_ang - 2.*phi); % [J_phi, J_rho] J_I = [sparse(1:npix,1:npix,2.*rho.*sin(2.*pol_ang-2.*phi),npix,npix) ... sparse(1:npix,1:npix,cos(2.*pol_ang-2.*phi),npix,npix)]; end function [A, J_A] = G2A(G) % Compute theta and alpha from surface gradients % Output is vector of length 2*npix % Compute unnormalised surface normal vectors [ N,J_N ] = G2N(G); % Compute normalised surface normal vectors [barN,J_barN] = N2barN(N); % Derivative of normalised normals with respect to gradients: J_barN_N = J_barN*J_N; % DoP % Compute zenith angle [theta,J_theta] = barN2theta(barN); % Phase % Compute azimuth angle: [alpha,J_alpha] = barN2alpha(barN); A = [alpha; theta] ; J_A = [J_alpha*J_barN_N; J_theta*J_barN_N]; end function [F,J_F] = G2F(G,eta,spec) % Compute phi and rho from surface gradients and index of refraction % Output is vector of length 3*npix % Normal % Compute unnormalised surface normal vectors [ N,J_N ] = G2N(G); % Compute normalised surface normal vectors [barN,J_barN] = N2barN(N); % Derivative of normalised normals with respect to gradients: J_barN_N = J_barN*J_N; % DoP % Compute zenith angle [theta,J_theta] = barN2theta(barN); % Derivative of zenith angle with respect to gradients: J_theta_barN_N = J_theta*J_barN_N; % Compute degree of polarisation: [rho,J_rho] = theta2rho(theta,eta,spec); % Derivative of degree of polarisation with respect to gradients: J_rho_theta_barN_N = J_rho*J_theta_barN_N; % Phase % Compute azimuth angle: [alpha,J_alpha] = barN2alpha(barN); % Compute phase angle: [phi,J_phi] = alpha2phi(alpha,spec); % Derivative of phase angle with respect to gradients: J_phi_alpha_barN_N = J_phi*J_alpha*J_barN_N; % Conclusion % Polarisation image as long vector: F = [phi; rho]; % Jacobian of polarisation image with respect to gradients: J_F = [J_phi_alpha_barN_N; J_rho_theta_barN_N]; end function [ N,J_N ] = G2N(G) % Function to transform vector containing gradients: [p_1, ..., p_n, q_1, % ..., q_n]^T into vector containing unnormalised surface normal vectors: % [n_x1, ..., n_xn, n_y1, ..., n_yn, n_z1, ..., n_zn]^T and also return the % Jacobian matrix of this function npix = size(G,1)/2; N = [-G; ones(npix,1)]; J_N = [-speye(npix) sparse(npix,npix); ... sparse(npix,npix) -speye(npix); ... sparse(npix,2*npix)]; end function [barN,J_barN] = N2barN(N) % Function to transform vector containing unnormalised surface normal vectors: % [n_x1, ..., n_xn, n_y1, ..., n_yn, n_z1, ..., n_zn]^T and return % normalised vectors in vector of same size. Also return Jacobian matrix of % this function. npix = size(N,1)/3; Nx = N(1:npix); Ny = N(npix+1:2*npix); Nz = N(2*npix+1:3*npix); norms = sqrt(Nx.^2 + Ny.^2 + Nz.^2); normsc = norms.^3; barN = [Nx./norms; ... Ny./norms; ... Nz./norms]; % Computation for derivative: % syms nx ny nz normn real % n = [nx; ny; nz] % eye(3)/normn-(n*n')./normn^3 % [ 1/normn - nx^2/normn^3, -(nx*ny)/normn^3, -(nx*nz)/normn^3] % [ -(nx*ny)/normn^3, 1/normn - ny^2/normn^3, -(ny*nz)/normn^3] % [ -(nx*nz)/normn^3, -(ny*nz)/normn^3, 1/normn - nz^2/normn^3] J_barN = [sparse(1:npix,1:npix, 1./norms - Nx.^2 ./ normsc ,npix,npix) ... sparse(1:npix,1:npix,-(Nx.*Ny)./normsc,npix,npix) ... sparse(1:npix,1:npix,-(Nx.*Nz)./normsc,npix,npix); sparse(1:npix,1:npix,-(Nx.*Ny)./normsc,npix,npix) ... sparse(1:npix,1:npix,1./norms - Ny.^2 ./ normsc,npix,npix) ... sparse(1:npix,1:npix,-(Ny.*Nz)./normsc,npix,npix); sparse(1:npix,1:npix,-(Nx.*Nz)./normsc,npix,npix) ... sparse(1:npix,1:npix,-(Ny.*Nz)./normsc,npix,npix) ... sparse(1:npix,1:npix,1./norms - Nz.^2 ./ normsc,npix,npix)]; end function [theta,J_theta] = barN2theta(barN) % Convert surface normal to zenith angle npix = size(barN,1)/3; Nz = barN(2*npix+1:3*npix); theta = acos(Nz); J_theta = [sparse(npix,2*npix) sparse(1:npix,1:npix,-1./(sqrt(1-Nz.^2)+10e-8),npix,npix)]; end function [rho,J_rho] = theta2rho(theta,eta,spec) % Convert zenith angle to (diffuse) degree of polarisation given index of % refraction % separate diffuse and specular pixels diffuse = not(spec); npix = size(theta,1); % diffuse rhoD = (sin(theta(diffuse)).^2.*(eta-1/eta)^2)./(4.*cos(theta(diffuse)).*sqrt(eta^2-sin(theta(diffuse)).^2)-sin(theta(diffuse)).^2*(eta+1/eta)^2+2*eta^2+2); % Obtained by: % diff((sin(theta(diffuse))^2*(eta-1/eta)^2)/(4*cos(theta(diffuse))*sqrt(eta^2-sin(theta(diffuse))^2)-sin(theta(diffuse))^2*(eta+1/eta)^2+2*eta^2+2),theta(diffuse)) J_rhoD = (2.*cos(theta(diffuse)).*sin(theta(diffuse)).*(eta - 1/eta).^2)./(4.*cos(theta(diffuse)).*(eta.^2 - sin(theta(diffuse)).^2).^(1/2) - sin(theta(diffuse)).^2.*(eta + 1/eta).^2 + 2*eta^2 + 2) + (sin(theta(diffuse)).^2.*(eta - 1/eta).^2.*(4.*sin(theta(diffuse)).*(eta^2 - sin(theta(diffuse)).^2).^(1/2) + 2.*cos(theta(diffuse)).*sin(theta(diffuse)).*(eta + 1/eta).^2 + (4.*cos(theta(diffuse)).^2.*sin(theta(diffuse)))./(eta^2 - sin(theta(diffuse)).^2).^(1/2)))./(4.*cos(theta(diffuse)).*(eta^2 - sin(theta(diffuse)).^2).^(1/2) - sin(theta(diffuse)).^2.*(eta + 1/eta).^2 + 2*eta^2 + 2).^2; % specular rhoS = (2.*sin(theta(spec)).^2.*cos(theta(spec)).*sqrt(eta.^2-sin(theta(spec)).^2))./(eta.^2-sin(theta(spec)).^2-eta.^2.*sin(theta(spec)).^2+2.*sin(theta(spec)).^4); J_rhoS = (2.*sin(theta(spec)).^3.*(eta^2 - sin(theta(spec)).^2).^(1/2))./(sin(theta(spec)).^2 - 2.*sin(theta(spec)).^4 + eta^2.*sin(theta(spec)).^2 - eta^2) + (2*cos(theta(spec)).^2.*sin(theta(spec)).^3)./((eta^2 - sin(theta(spec)).^2).^(1/2).*(sin(theta(spec)).^2 - 2.*sin(theta(spec)).^4 + eta^2.*sin(theta(spec)).^2 - eta^2)) - (4.*cos(theta(spec)).^2.*sin(theta(spec)).*(eta^2 - sin(theta(spec)).^2).^(1/2))./(sin(theta(spec)).^2 - 2.*sin(theta(spec)).^4 + eta^2.*sin(theta(spec)).^2 - eta^2) + (2.*cos(theta(spec)).*sin(theta(spec)).^2.*(eta^2 - sin(theta(spec)).^2).^(1/2).*(2*cos(theta(spec)).*sin(theta(spec)) - 8.*cos(theta(spec)).*sin(theta(spec)).^3 + 2.*eta^2.*cos(theta(spec)).*sin(theta(spec))))./(eta^2.*sin(theta(spec)).^2 - eta^2 - 2.*sin(theta(spec)).^4 + sin(theta(spec)).^2).^2; % merge rho = zeros(npix,1); J_rho_s = zeros(npix,1); rho(diffuse) = rhoD; rho(spec) = rhoS; J_rho_s(diffuse) = J_rhoD; J_rho_s(spec) = J_rhoS; J_rho = sparse(1:npix,1:npix,J_rho_s,npix,npix); end function [alpha,J_alpha] = barN2alpha(barN) % Convert surface normal to azimuth angle npix = size(barN,1)/3; Nx = barN(1:npix); Ny = barN(npix+1:2*npix); alpha = atan2(Ny,Nx); demoninator = Nx.^2+Ny.^2+10e-8; J_alpha = [sparse(1:npix,1:npix,-Ny./demoninator,npix,npix) ... sparse(1:npix,1:npix,Nx./demoninator,npix,npix) ... sparse(npix,npix) ]; end function [phi,J_phi] = alpha2phi(alpha,spec) % Convert azimuth to phase angle % separate diffuse and specular pixels diffuse = not(spec); npix = length(alpha); % diffuse phiD = mod(alpha(diffuse),pi); % specular phiS = mod(alpha(spec),pi)+pi; % merge phi = zeros(npix,1); phi(diffuse) = phiD; phi(spec) = phiS; J_phi = speye(npix); end %% correlation: function description function [corrCoeff, J_corr] = correlation(z, z_size, kernel) % nblocks = size(z_size,1); npix = length(z); corrCoeff = []; J_finalz_centralz = sparse(npix,npix); J_corr_finalz = []; J_centralz_localz = sparse(npix,npix); processed=0; % process blocks in parallel block_type{1} = find(z_size(:,1)==4); block_type{2} = find(z_size(:,1)==5); block_type{3} = find(z_size(:,1)==6); block_type{4} = find(z_size(:,1)==7); block_type{5} = find(z_size(:,1)==8); block_type{6} = find(z_size(:,1)==9); for i = 1:length(block_type) if isempty(block_type{i}) continue end % number of blocks in this type nblocks = length(block_type{i}); % find all z's indices for current block type block_ind = []; % first stack in index for start pixel block_ind = [block_ind, z_size(block_type{i},2)]; for j = 1:i+2 % block_ind is a matrix having size nblocks-by-(i+3) block_ind = [block_ind, z_size(block_type{i},2)+j]; end block_ind = block_ind'; % localz is matrix (i+3)-by-nblocks localz = z(block_ind); centralz = bsxfun(@minus, localz, mean(localz,1)); finalz = bsxfun(@times, centralz, 1./(sqrt(sum(centralz.^2,1))+10e-8)); finalz_denominator = 1./(sqrt(sum(centralz.^2,1))+10e-8); local_kernel = kernel(block_ind); local_kernel = bsxfun(@minus, local_kernel, mean(local_kernel,1)); local_kernel = bsxfun(@times, local_kernel, 1./(sqrt(sum(local_kernel.^2,1))+10e-8)); corrCoeff = [corrCoeff; sum(finalz.*local_kernel, 1)']; m = repmat((1:nblocks),i+3,1); m = m(:); n = block_ind(:); s = local_kernel; s = s(:); J_corr_finalz = [J_corr_finalz; sparse(m,n,s,nblocks,npix)]; m = repmat(block_ind(:)', i+2, 1); m = m(:); n=[]; temp1 = []; temp2 = []; for j =1:i+3 n = [n;block_ind(1:j-1,:)]; n = [n;block_ind(j+1:end,:)]; temp1 = [temp1; centralz(1:j-1,:)]; temp1 = [temp1; centralz(j+1:end,:)]; temp2 = [temp2; repmat(centralz(j,:),i+2,1)]; end n = n(:); s1 = repmat(finalz_denominator,i+3,1) - centralz.^2.*repmat(finalz_denominator,i+3,1).^3; s2 = -(temp1.*temp2).*repmat(finalz_denominator,(i+2)*(i+3),1).^3; J_finalz_centralz = J_finalz_centralz + sparse(m,n,s2(:),npix,npix)+sparse(block_ind(:),block_ind(:),s1(:),npix,npix); m = repmat(block_ind(:)',i+3,1); m = m(:); n = repmat(block_ind,i+3,1); n = n(:); J_centralz_localz = J_centralz_localz + sparse(m,n,-1/(i+3),npix,npix)+sparse(block_ind(:),block_ind(:),1,npix,npix); end J_corr = J_corr_finalz * J_finalz_centralz * J_centralz_localz; % for i = 1:nblocks % localz = z(processed+1:processed+z_size(i)); % centralz = localz - sum(localz(:))/z_size(i); % finalz = centralz ./ sqrt(sum(centralz.^2)); % % local_kernel = kernel(processed+1:processed+z_size(i)); % local_kernel = local_kernel - sum(local_kernel(:))/z_size(i); % local_kernel = local_kernel ./ sqrt(sum(local_kernel.^2)); % % corrCoeff = [corrCoeff; sum(finalz.*local_kernel)]; % % J_corr = [J_corr; sparse(1,processed+1:processed+z_size(i),local_kernel.*(finalz - localz.^2./finalz.^3),1,npix)]; % % processed = processed+z_size(i); % end end
github
waps101/polarisation_optimisation-master
polResidualsFromZ.m
.m
polarisation_optimisation-master/utils/polResidualsFromZ.m
14,707
utf_8
aa10d848fcb4838e8c1ee39d26c8cec7
function [ residuals,J ] = polResidualsFromZ( z,D_x,D_y,eta,s,albedo,pol_angles,I_obs,spec,smooth_type,bd_Dx,bd_Dy,bd_weight,bd_penalty,smooth_L,smooth_weight, smooth_counter, smooth_kernel) %polResidualsFromZ Residuals between observed intensities and diffuse %polarisation model % % Inputs: % z is vector of height values of length npix % D_x*z computes x gradient of height, similarly for D_y and y % eta index of refraction % s point light source % albedo scalar or vector of length npix containing albedo % pol_angles vector of length npolang containing polariser orientations % in radians % I_obs is a vector of length npix*npolang with all intensities for first % polariser angle first, followed by all for second angle etc. % Compute gradients G = [D_x; D_y]*z; % Compute polarisation image from gradients: [F,J_F] = G2F(G,eta,s,albedo,spec); % Compute intensities from polarisation image: allI = []; allJ_I = []; for i=1:length(pol_angles) [I,J_I] = F2I(F,pol_angles(i)); allI = [allI; I]; allJ_I = [allJ_I; J_I]; end % Derivatives of intensities with respect to gradient: J_I_F = allJ_I*J_F; % Dimension: NpixNpol * 2Npix % Derivatives of intensities with respect to surface height: J_I_Z = J_I_F*[D_x; D_y]; % Dimension NpixNpol * Npix % Derivatives of residuals with respect to surface height: J = -speye(size(J_I_Z,1))*J_I_Z; residuals = I_obs-allI; if nargin > 9 if strcmp(smooth_type,'over_smooth') % Add residuals and derivatives for Laplacian smoothness residuals = [residuals; smooth_weight.*smooth_L*z]; % Add derivatives for smoothness term J = [J;smooth_weight*smooth_L]; elseif strcmp(smooth_type,'fine_tune') % sum((localz - mean(localz)) ./ sqrt(sum((localz - mean(localz).^2))) .* local_kernel ) localZs = smooth_L * z; [smoothness, J_smooth] = correlation(localZs, smooth_counter, smooth_kernel); % Add residuals and derivatives for Laplacian smoothness residuals = [residuals; smooth_weight.*(smoothness-1)]; % Add derivatives for smoothness term % J_ressmt_smtL = sparse(1:nsmt_pix,1:nsmt_pix,-1./(smooth_L*z).^2,nsmt_pix,nsmt_pix); % J = [J;smooth_weight*J_ressmt_smtL*smooth_L]; J = [J;smooth_weight*J_smooth*smooth_L]; end % Add residuals and derivatives for convex Boundary % only G(gredients) on boundary pixels nbd_pix = size(bd_Dx,1); G_bd = [bd_Dx; bd_Dy]*z; [A, J_A] = G2A(G_bd); J_bd_Z = J_A * [bd_Dx;bd_Dy]; diff_alpha = [cos(A(1:nbd_pix)); sin(A(1:nbd_pix))] - [cos(bd_penalty(1:nbd_pix)); sin(bd_penalty(1:nbd_pix))]; diff_theta = A(nbd_pix+1:end)/1000 - bd_penalty(nbd_pix+1:end); % find small angels < pi between two % add 2*pi on angles greater than pi % only element-wise operations residuals = [residuals; [bd_weight(1:nbd_pix);bd_weight].*[diff_alpha;diff_theta]]; % Add derivatives for smoothness term % J = [J;bd_weight.*J_bd_Z]; J_resbd_bd = [sparse(1:nbd_pix,1:nbd_pix,bd_weight(1:nbd_pix).*(-sin(A(1:nbd_pix))),nbd_pix,nbd_pix), sparse(nbd_pix,nbd_pix); ... sparse(1:nbd_pix,1:nbd_pix,bd_weight(1:nbd_pix).*cos(A(1:nbd_pix)),nbd_pix,nbd_pix), sparse(nbd_pix,nbd_pix); ... sparse(nbd_pix,nbd_pix), sparse(1:nbd_pix,1:nbd_pix, bd_weight(nbd_pix+1:end)/1000, nbd_pix, nbd_pix)]; J = [J;J_resbd_bd*J_bd_Z]; end residuals(isnan(residuals)) = 1; residuals(residuals==inf | residuals==-inf) = 1; J(isnan(J)) = 1; J(J==inf | J==-inf) = 1; end function [A, J_A] = G2A(G) % Compute theta and alpha from surface gradients % Output is vector of length 2*npix % Compute unnormalised surface normal vectors [ N,J_N ] = G2N(G); % Compute normalised surface normal vectors [barN,J_barN] = N2barN(N); % Derivative of normalised normals with respect to gradients: J_barN_N = J_barN*J_N; % DoP % Compute zenith angle [theta,J_theta] = barN2theta(barN); % Phase % Compute azimuth angle: [alpha,J_alpha] = barN2alpha(barN); A = [alpha; theta] ; J_A = [J_alpha*J_barN_N; J_theta*J_barN_N]; end function [I,J_I] = F2I(F,pol_ang) % Function to transform polarisation image into intensity given a polariser % angle. F is a vector containing all phis, followed by all i_un followed % by all rho. npix = size(F,1)/3; phi = F(1:npix); i_un = F(npix+1:2*npix); rho = F(2*npix+1:3*npix); I = i_un.*(1+rho.*cos(2*pol_ang - 2.*phi)); J_I = [sparse(1:npix,1:npix,2.*i_un.*rho.*sin(2.*pol_ang-2.*phi),npix,npix) ... sparse(1:npix,1:npix,1+rho.*cos(2.*pol_ang-2.*phi),npix,npix) ... sparse(1:npix,1:npix,i_un.*cos(2.*pol_ang-2.*phi),npix,npix)]; end function [ N,J_N ] = G2N(G) % Function to transform vector containing gradients: [p_1, ..., p_n, q_1, % ..., q_n]^T into vector containing unnormalised surface normal vectors: % [n_x1, ..., n_xn, n_y1, ..., n_yn, n_z1, ..., n_zn]^T and also return the % Jacobian matrix of this function npix = size(G,1)/2; N = [-G; ones(npix,1)]; J_N = [-speye(npix) sparse(npix,npix); ... sparse(npix,npix) -speye(npix); ... sparse(npix,2*npix)]; end function [barN,J_barN] = N2barN(N) % Function to transform vector containing unnormalised surface normal vectors: % [n_x1, ..., n_xn, n_y1, ..., n_yn, n_z1, ..., n_zn]^T and return % normalised vectors in vector of same size. Also return Jacobian matrix of % this function. npix = size(N,1)/3; Nx = N(1:npix); Ny = N(npix+1:2*npix); Nz = N(2*npix+1:3*npix); norms = sqrt(Nx.^2 + Ny.^2 + Nz.^2); normsc = norms.^3; barN = [Nx./norms; ... Ny./norms; ... Nz./norms]; % Computation for derivative: % syms nx ny nz normn real % n = [nx; ny; nz] % eye(3)/normn-(n*n')./normn^3 % [ 1/normn - nx^2/normn^3, -(nx*ny)/normn^3, -(nx*nz)/normn^3] % [ -(nx*ny)/normn^3, 1/normn - ny^2/normn^3, -(ny*nz)/normn^3] % [ -(nx*nz)/normn^3, -(ny*nz)/normn^3, 1/normn - nz^2/normn^3] J_barN = [sparse(1:npix,1:npix,1./norms - Nx.^2 ./ normsc,npix,npix) ... sparse(1:npix,1:npix,-(Nx.*Ny)./normsc,npix,npix) ... sparse(1:npix,1:npix,-(Nx.*Nz)./normsc,npix,npix); sparse(1:npix,1:npix,-(Nx.*Ny)./normsc,npix,npix) ... sparse(1:npix,1:npix,1./norms - Ny.^2 ./ normsc,npix,npix) ... sparse(1:npix,1:npix,-(Ny.*Nz)./normsc,npix,npix); sparse(1:npix,1:npix,-(Nx.*Nz)./normsc,npix,npix) ... sparse(1:npix,1:npix,-(Ny.*Nz)./normsc,npix,npix) ... sparse(1:npix,1:npix,1./norms - Nz.^2 ./ normsc,npix,npix)]; end function [theta,J_theta] = barN2theta(barN) % Convert surface normal to zenith angle npix = size(barN,1)/3; Nz = barN(2*npix+1:3*npix); theta = acos(Nz); J_theta = [sparse(npix,2*npix) sparse(1:npix,1:npix,-1./sqrt(1-Nz.^2),npix,npix)]; end function [rho,J_rho] = theta2rho(theta,eta,spec) % Convert zenith angle to (diffuse) degree of polarisation given index of % refraction % separate diffuse and specular pixels diffuse = not(spec); npix = size(theta,1); % diffuse rhoD = (sin(theta(diffuse)).^2.*(eta-1/eta)^2)./(4.*cos(theta(diffuse)).*sqrt(eta^2-sin(theta(diffuse)).^2)-sin(theta(diffuse)).^2*(eta+1/eta)^2+2*eta^2+2); % Obtained by: % diff((sin(theta(diffuse))^2*(eta-1/eta)^2)/(4*cos(theta(diffuse))*sqrt(eta^2-sin(theta(diffuse))^2)-sin(theta(diffuse))^2*(eta+1/eta)^2+2*eta^2+2),theta(diffuse)) J_rhoD = (2.*cos(theta(diffuse)).*sin(theta(diffuse)).*(eta - 1/eta).^2)./(4.*cos(theta(diffuse)).*(eta.^2 - sin(theta(diffuse)).^2).^(1/2) - sin(theta(diffuse)).^2.*(eta + 1/eta).^2 + 2*eta^2 + 2) + (sin(theta(diffuse)).^2.*(eta - 1/eta).^2.*(4.*sin(theta(diffuse)).*(eta^2 - sin(theta(diffuse)).^2).^(1/2) + 2.*cos(theta(diffuse)).*sin(theta(diffuse)).*(eta + 1/eta).^2 + (4.*cos(theta(diffuse)).^2.*sin(theta(diffuse)))./(eta^2 - sin(theta(diffuse)).^2).^(1/2)))./(4.*cos(theta(diffuse)).*(eta^2 - sin(theta(diffuse)).^2).^(1/2) - sin(theta(diffuse)).^2.*(eta + 1/eta).^2 + 2*eta^2 + 2).^2; % specular rhoS = (2.*sin(theta(spec)).^2.*cos(theta(spec)).*sqrt(eta.^2-sin(theta(spec)).^2))./(eta.^2-sin(theta(spec)).^2-eta.^2.*sin(theta(spec)).^2+2.*sin(theta(spec)).^4); J_rhoS = (2.*sin(theta(spec)).^3.*(eta^2 - sin(theta(spec)).^2).^(1/2))./(sin(theta(spec)).^2 - 2.*sin(theta(spec)).^4 + eta^2.*sin(theta(spec)).^2 - eta^2) + (2*cos(theta(spec)).^2.*sin(theta(spec)).^3)./((eta^2 - sin(theta(spec)).^2).^(1/2).*(sin(theta(spec)).^2 - 2.*sin(theta(spec)).^4 + eta^2.*sin(theta(spec)).^2 - eta^2)) - (4.*cos(theta(spec)).^2.*sin(theta(spec)).*(eta^2 - sin(theta(spec)).^2).^(1/2))./(sin(theta(spec)).^2 - 2.*sin(theta(spec)).^4 + eta^2.*sin(theta(spec)).^2 - eta^2) + (2.*cos(theta(spec)).*sin(theta(spec)).^2.*(eta^2 - sin(theta(spec)).^2).^(1/2).*(2*cos(theta(spec)).*sin(theta(spec)) - 8.*cos(theta(spec)).*sin(theta(spec)).^3 + 2.*eta^2.*cos(theta(spec)).*sin(theta(spec))))./(eta^2.*sin(theta(spec)).^2 - eta^2 - 2.*sin(theta(spec)).^4 + sin(theta(spec)).^2).^2; % merge rho = zeros(npix,1); J_rho_s = zeros(npix,1); rho(diffuse) = rhoD; rho(spec) = rhoS; J_rho_s(diffuse) = J_rhoD; J_rho_s(spec) = J_rhoS; J_rho = sparse(1:npix,1:npix,J_rho_s,npix,npix); end function [alpha,J_alpha] = barN2alpha(barN) % Convert surface normal to azimuth angle npix = size(barN,1)/3; Nx = barN(1:npix); Ny = barN(npix+1:2*npix); alpha = atan2(Ny,Nx); demoninator = Nx.^2+Ny.^2+10e-6; J_alpha = [sparse(1:npix,1:npix,-Ny./demoninator,npix,npix) ... sparse(1:npix,1:npix,Nx./demoninator,npix,npix) ... sparse(npix,npix) ]; end function [phi,J_phi] = alpha2phi(alpha,spec) % Convert azimuth to phase angle % separate diffuse and specular pixels diffuse = not(spec); npix = length(alpha); % diffuse phiD = mod(alpha(diffuse),pi); % specular phiS = mod(alpha(spec),pi)+pi; % merge phi = zeros(npix,1); phi(diffuse) = phiD; phi(spec) = phiS; J_phi = speye(npix); end function [i_un,J_i_un] = barN2iun(barN,s,albedo,spec) % Compute unpolarised intensity assuming Lambertian point source model. % albedo can be scalar or vector of length npix npix = size(barN,1)/3; Nx = barN(1:npix); Ny = barN(npix+1:2*npix); Nz = barN(2*npix+1:3*npix); albedo = albedo .* ones(npix,1); albedo(spec) = 2^16-1; % specular albedo for uint16 % albedo(spec) = 1; % specular albedo for double ~ [0,1] i_un = albedo.*(Nx.*s(1) + Ny.*s(2) + Nz.*s(3)); % rectified linear unit % pos = (i_un./sqrt(i_un.^2)+1)/2; % i_un = pos .* i_un; i_un = (i_un + sqrt(i_un.^2))/2; % temp = i_un.*(1./(2.*(i_un.^2).^(1/2)) - i_un.^2./(2.*(i_un.^2).^(3/2))) + i_un./(2.*(i_un.^2).^(1/2)) + 1/2; temp = i_un./(2.*(i_un.^2).^(1/2)) + 1/2; J_i_un = [sparse(1:npix,1:npix,temp.*albedo.*s(1),npix,npix) ... sparse(1:npix,1:npix,temp.*albedo.*s(2),npix,npix) ... sparse(1:npix,1:npix,temp.*albedo.*s(3),npix,npix)]; end function [F,J_F] = G2F(G,eta,s,albedo,spec) % Compute polarisation image from surface gradients and index of refraction % Output is vector of length 3*npix % Compute unnormalised surface normal vectors [ N,J_N ] = G2N(G); % Compute normalised surface normal vectors [barN,J_barN] = N2barN(N); % Derivative of normalised normals with respect to gradients: J_barN_N = J_barN*J_N; % Compute zenith angle [theta,J_theta] = barN2theta(barN); % Derivative of zenith angle with respect to gradients: J_theta_barN_N = J_theta*J_barN_N; % Compute degree of polarisation: [rho,J_rho] = theta2rho(theta,eta,spec); % Derivative of degree of polarisation with respect to gradients: J_rho_theta_barN_N = J_rho*J_theta_barN_N; % Compute azimuth angle: [alpha,J_alpha] = barN2alpha(barN); % Compute phase angle: [phi,J_phi] = alpha2phi(alpha,spec); % Derivative of phase angle with respect to gradients: J_phi_alpha_barN_N = J_phi*J_alpha*J_barN_N; % Compute unpolarised intensity: [i_un,J_i_un] = barN2iun(barN,s,albedo,spec); % Derivative of unpol intensity with respect to gradients: J_i_un_barN_N = J_i_un*J_barN_N; % Polarisation image as long vector: F = [phi; i_un; rho]; % Jacobian of polarisation image with respect to gradients: J_F = [J_phi_alpha_barN_N; J_i_un_barN_N; J_rho_theta_barN_N]; end %% correlation: function description function [corrCoeff, J_corr] = correlation(z, z_size, kernel) % nblocks = size(z_size,1); npix = length(z); corrCoeff = []; J_finalz_centralz = sparse(npix,npix); J_corr_finalz = []; J_centralz_localz = sparse(npix,npix); processed=0; % process blocks in parallel block_type{1} = find(z_size(:,1)==4); block_type{2} = find(z_size(:,1)==5); block_type{3} = find(z_size(:,1)==6); block_type{4} = find(z_size(:,1)==7); block_type{5} = find(z_size(:,1)==8); block_type{6} = find(z_size(:,1)==9); for i = 1:length(block_type) if isempty(block_type{i}) continue end % number of blocks in this type nblocks = length(block_type{i}); % find all z's indices for current block type block_ind = []; % first stack in index for start pixel block_ind = [block_ind, z_size(block_type{i},2)]; for j = 1:i+2 % block_ind is a matrix having size nblocks-by-(i+3) block_ind = [block_ind, z_size(block_type{i},2)+j]; end block_ind = block_ind'; % localz is matrix (i+3)-by-nblocks localz = z(block_ind); centralz = bsxfun(@minus, localz, mean(localz,1)); finalz = bsxfun(@times, centralz, 1./sqrt(sum(centralz.^2,1))); finalz_denominator = 1./sqrt(sum(centralz.^2,1)); local_kernel = kernel(block_ind); local_kernel = bsxfun(@minus, local_kernel, mean(local_kernel,1)); local_kernel = bsxfun(@times, local_kernel, 1./sqrt(sum(local_kernel.^2,1))); corrCoeff = [corrCoeff; sum(finalz.*local_kernel, 1)']; m = repmat((1:nblocks),i+3,1); m = m(:); n = block_ind(:); s = local_kernel; s = s(:); J_corr_finalz = [J_corr_finalz; sparse(m,n,s,nblocks,npix)]; m = repmat(block_ind(:)', i+2, 1); m = m(:); n=[]; temp1 = []; temp2 = []; for j =1:i+3 n = [n;block_ind(1:j-1,:)]; n = [n;block_ind(j+1:end,:)]; temp1 = [temp1; centralz(1:j-1,:)]; temp1 = [temp1; centralz(j+1:end,:)]; temp2 = [temp2; repmat(centralz(j,:),i+2,1)]; end n = n(:); s1 = repmat(finalz_denominator,i+3,1) - centralz.^2.*repmat(finalz_denominator,i+3,1).^3; s2 = -(temp1.*temp2).*repmat(finalz_denominator,(i+2)*(i+3),1).^3; J_finalz_centralz = J_finalz_centralz + sparse(m,n,s2(:),npix,npix)+sparse(block_ind(:),block_ind(:),s1(:),npix,npix); m = repmat(block_ind(:)',i+3,1); m = m(:); n = repmat(block_ind,i+3,1); n = n(:); J_centralz_localz = J_centralz_localz + sparse(m,n,-1/(i+3),npix,npix)+sparse(block_ind(:),block_ind(:),1,npix,npix); end J_corr = J_corr_finalz * J_finalz_centralz * J_centralz_localz; end
github
aranyadan/WENO5_2D_NSsolver_FORTRAN-master
WENOcaller.m
.m
WENO5_2D_NSsolver_FORTRAN-master/matlab version/WENOcaller.m
2,379
utf_8
55551064eb675f6f09cdf3c12df2571f
function [dFx,dFy] = WENOcaller(lambda,q,dx,dy) %% Calls WENO % Setting up ghost cells [nx,ny,eqns] = size(q); qnew = zeros(nx+5,ny+5,eqns); qnew(3:2+nx,3:2+ny,:) = q(:,:,:); qnew(1:2,:,:) = repmat(qnew(3,:,:),[2,1,1]); qnew(nx+3:nx+5,:,:) = repmat(qnew(nx+2,:,:),[3,1,1]); qnew(:,1:2,:) = repmat(qnew(:,3,:),[1,2,1]); qnew(:,ny+3:ny+5,:) = repmat(qnew(:,ny+2,:),[1,3,1]); w = qnew; % Constructing fluxes to send [G1,G2] = F(qnew,dx,dy); % Sending for derivative along x turn=[1 0 0]; % G = F(qnew,1); dFx=WENO5LF2d(lambda,qnew,G1,dx,turn); dFx = dFx(3:2+nx,3:2+ny,:); % Sending for derivative along y turn=[0 1 0]; % G = F(qnew,2); dFy=WENO5LF2d(lambda,qnew,G2,dy,turn); dFy = dFy(3:2+nx,3:2+ny,:); end %% Compute flux vector function [G1,G2] = F(q,dx,dy) global gamma global R_gas_const % primary properties rho=q(:,:,1); u=q(:,:,2)./rho; v=q(:,:,3)./rho; E=q(:,:,4)./rho; p=(gamma-1)*rho.*(E-0.5*(u.^2 + v.^2)); temp = p./rho; [tauxx,tauyy,tauxy,q_x,q_y] = visc_stress(u,v,temp,dx,dy); % flux vector of conserved properties G1=reshape([rho.*u (rho.*u.^2+p-tauxx) (rho.*u.*v-tauxy) (u.*(rho.*E+p-tauxx)-v.*tauxy)-q_x], size(q)); G2=reshape([rho.*v (rho.*u.*v-tauxy) (rho.*v.^2+p-tauyy) (v.*(rho.*E+p-tauyy)-u.*tauxy)-q_y], size(q)); end %% Compute viscous stress terms function [tauxx,tauyy,tauxy,q_x,q_y] = visc_stress(u,v,T,dx,dy) global Suth_const global Re global Pr global gamma Therm_const = gamma / ((gamma-1.0)*Pr*Re); [u_x,u_y] = first_der(u,dx,dy); [v_x,v_y] = first_der(v,dx,dy); [T_x,T_y] = first_der(T,dx,dy); T_x(1,:) = 0; T_x(end,:) = 0; meu = 1;%(T.^(3/2)) .* ((1 + Suth_const)./(T + Suth_const)); lambda = (-2/3) .* meu; tauxx = (lambda.*(u_x+v_y) + 2.*meu.*u_x)./Re; tauyy = (lambda.*(u_x+v_y) + 2.*meu.*v_y)./Re; tauxy = (meu.*(u_y+v_x))./Re; q_x = Therm_const.*T_x; q_y = Therm_const.*T_y; end %% Compute first derivatives function [u_x,u_y] = first_der(u,dx,dy) u_x = [ (1/20).*circshift(u,[2,0]) + (-0.5).*circshift(u,[1,0]) + (-1/3).*u + ... circshift(u,[-1,0]) + (-0.25).*circshift(u,[-2,0]) + (1/30).*circshift(u,[-3,0]) ]./dx; u_y = [ (1/20).*circshift(u,[0,2]) + (-0.5).*circshift(u,[0,1]) + (-1/3).*u + ... circshift(u,[0,-1]) + (-0.25).*circshift(u,[0,-2]) + (1/30).*circshift(u,[0,-3]) ]./dy; end
github
aranyadan/WENO5_2D_NSsolver_FORTRAN-master
set_boundary.m
.m
WENO5_2D_NSsolver_FORTRAN-master/matlab version/set_boundary.m
626
utf_8
6ac8f78a95ad0e25b67c1f2c6da8932b
%% Function to set BC function q0 = set_boundary(q) global gamma rho=q(:,:,1); u=q(:,:,2)./rho; v=q(:,:,3)./rho; E=q(:,:,4)./rho; p=(gamma-1)*rho.*(E-0.5*(u.^2+v.^2)); u(:,end) = u(:,end-1); v(:,end) = v(:,end-1); p(:,end) = p(:,end-1); rho(:,end) = rho(:,end-1); u(:,1) = 0; v(:,1) = 0; u(1,:) = 0; v(1,:) = 0; u(end,:) = 0; v(end,:) = 0; % Adiabatic p(1,:) = (p(2,:)./rho(2,:)).*rho(1,:); p(end,:) = (p(end-1,:)./rho(end-1,:)).*rho(end,:); E = p./((gamma-1).*rho) + 0.5.*(u.^2+v.^2); q0=reshape([rho rho.*u rho.*v rho.*E],size(q)); end
github
madkn/MultiregionBilinearCNN-ReId-master
classification_demo.m
.m
MultiregionBilinearCNN-ReId-master/caffe-bilinear/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
cmjiang/FASTGE2-master
quadedgep.m
.m
FASTGE2-master/ncutfiles/quadedgep.m
3,327
utf_8
4e0cc45e71e843887beae643eb7bcb8b
% function [x,y,gx,gy,par,threshold,mag,mage,g,FIe,FIo,mago] = quadedgep(I,par,threshold); % Input: % I = image % par = vector for 4 parameters % [number of filter orientations, number of scales, filter size, elongation] % To use default values, put 0. % threshold = threshold on edge strength % Output: % [x,y,gx,gy] = locations and gradients of an ordered list of edgels % x,y could be horizontal or vertical or 45 between pixel sites % but it is guaranteed that there [floor(y) + (floor(x)-1)*nr] % is ordered and unique. In other words, each edgel has a unique pixel id. % par = actual par used % threshold = actual threshold used % mag = edge magnitude % mage = phase map % g = gradient map at each pixel % [FIe,FIo] = odd and even filter outputs % mago = odd filter output of optimum orientation % % Stella X. Yu, 2001 function [x,y,gx,gy,par,threshold,mag,mage,g,FIe,FIo,mago] = quadedgep(I,par,threshold); if nargin<3 | isempty(threshold), threshold = 0.2; end [r,c] = size(I); def_par = [8,1,20,3]; % take care of parameters, any missing value is substituted by a default value if nargin<2 | isempty(par), par = def_par; end par(end+1:4)=0; par = par(:); j = (par>0); have_value = [ j, 1-j ]; j = 1; n_filter = have_value(j,:) * [par(j); def_par(j)]; j = 2; n_scale = have_value(j,:) * [par(j); def_par(j)]; j = 3; winsz = have_value(j,:) * [par(j); def_par(j)]; j = 4; enlong = have_value(j,:) * [par(j); def_par(j)]; % always make filter size an odd number so that the results will not be skewed j = winsz/2; if not(j > fix(j) + 0.1), winsz = winsz + 1; end % filter the image with quadrature filters FBo = make_filterbank_odd2(n_filter,n_scale,winsz,enlong); FBe = make_filterbank_even2(n_filter,n_scale,winsz,enlong); n = ceil(winsz/2); f = [fliplr(I(:,2:n+1)), I, fliplr(I(:,c-n:c-1))]; f = [flipud(f(2:n+1,:)); f; flipud(f(r-n:r-1,:))]; FIo = fft_filt_2(f,FBo,1); FIo = FIo(n+[1:r],n+[1:c],:); FIe = fft_filt_2(f,FBe,1); FIe = FIe(n+[1:r],n+[1:c],:); % compute the orientation energy and recover a smooth edge map % pick up the maximum energy across scale and orientation % even filter's output: as it is the second derivative, zero cross localize the edge % odd filter's output: orientation mag = sqrt(sum(FIo.^2,3)+sum(FIe.^2,3)); mag_a = sqrt(FIo.^2+FIe.^2); [tmp,max_id] = max(mag_a,[],3); base_size = r * c; id = [1:base_size]'; mage = reshape(FIe(id+(max_id(:)-1)*base_size),[r,c]); mage = (mage>0) - (mage<0); ori_incr=pi/n_filter; % to convert jshi's coords to conventional image xy ori_offset=ori_incr/2; theta = ori_offset+([1:n_filter]-1)*ori_incr; % orientation detectors % [gx,gy] are image gradient in image xy coords, winner take all mago = reshape(FIo(id+(max_id(:)-1)*base_size),[r,c]); ori = theta(max_id); ori = ori .* (mago>0) + (ori + pi).*(mago<0); gy = mag .* cos(ori); gx = -mag .* sin(ori); g = cat(3,gx,gy); % phase map: edges are where the phase changes mag_th = max(mag(:)) * threshold; eg = (mag>mag_th); h = eg & [(mage(2:r,:) ~= mage(1:r-1,:)); zeros(1,c)]; v = eg & [(mage(:,2:c) ~= mage(:,1:c-1)), zeros(r,1)]; [y,x] = find(h | v); k = y + (x-1) * r; h = h(k); v = v(k); y = y + h * 0.5; % i x = x + v * 0.5; % j t = h + v * r; gx = g(k) + g(k+t); k = k + (r * c); gy = g(k) + g(k+t);
github
pringithub/sfrmat3-master
rotate90.m
.m
sfrmat3-master/rotate90.m
803
utf_8
c9c61e6d53b87cdb4b52d3e2630f465a
function out = rotate90(in, n) %[out] = rotate90(in, n) 90 degree counterclockwise rotations of matrix % in = input matrix (n,m) or (n,m,k) % n = number of 90 degree rotation % out = rotated matrix % default = 1 % Usage: % out = rotate90(in) % out = rotate90(in, n) % Needs: % r90 (in this file) % % Author: Peter Burns, 1 Oct. 2008 % Copyright (c) 2007 Peter D. Burns if nargin < 2; n = 1; end nd = ndims(in); if nd < 1 error('input to rotate90 must be a matrix'); return end for i = 1:n out = r90(in); in = out; end return function [out] = r90(in) [nlin, npix, nc] = size(in); temp = zeros (npix, nlin); out = zeros (npix, nlin, nc); for c = 1: nc; temp = in(:,:,c); temp = temp.'; out(:,:,c) = temp(npix:-1:1, :); end out = squeeze(out);
github
pringithub/sfrmat3-master
legendTitle.m
.m
sfrmat3-master/legendTitle.m
3,440
utf_8
6f2c2e8f163c7c5c1067dea3a386c075
% legendTitle - add a title to a legend % % Add a title to a legend % hTitle = legentTitle ( hLegend, string, argPairs ) % % hLegent = handle to the legend for the title to be added % string = text string of title % argPairs = all valid arg pairs for a title object % % example: % % To add a title: % plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x)); % hLegend = legend('First','Second','Third','Location','NorthEastOutside'); % hTitle = legendTitle ( hLegend, 'Leg Title', 'FontWeight', 'bold' ); % % % To remove a title: % hTitle = legendTitle ( hLegend ) % % Copyright Robert Cumming @ Matpi Ltd. Covered by BSD License % www.matpi.com % function h = legendTitle ( hLegend, string, varargin ) h = []; % check if HG2 %if ~verLessThan('matlab', '8.4') if 0 if nargin == 1; % method for deleting the title delete ( hLegend.UserData.legendTitle.ax ); return end % check if this is a subsequent call to the legend if ~isfield ( hLegend.UserData, 'legendTitle' ) % get the position on the legend initPosition = hLegend.Position; % set the height to be very small initPosition(4) = 1e-2; % create an axes (we do it this way to mimick the original method) ax = axes ( 'parent', hLegend.Axes.Parent, 'position', initPosition, 'HandleVisibility', 'off' ); % store the axes in the legend user data hLegend.UserData.legendTitle.ax = ax; % add listeners for figure position, legend position & location and legend being deleted addlistener ( ancestor ( hLegend, 'figure' ), 'SizeChanged', @(obj,event)UpdateLegendTitlePosition( hLegend, ax )); addlistener ( hLegend, 'Position', 'PostSet', @(obj,event)UpdateLegendTitlePosition( hLegend, ax )); addlistener ( hLegend, 'Location', 'PostSet', @(obj,event)UpdateLegendTitlePosition( hLegend, ax )); addlistener ( hLegend, 'ObjectBeingDestroyed', @(obj,event)legendTitle( hLegend )); else % extract the pointer to the axes ax = hLegend.UserData.legendTitle.ax; end % give the axes a title, passing in all the extra args h = title ( ax, string, varargin{:} ); % update the position UpdateLegendTitlePosition( hLegend, ax ); else % to give both methods the same appearance - delete the title by % setting the string to ''; if nargin == 1 h = get ( hLegend, 'title' ); set ( h, 'string', '' ); else % get the handle tot he title h = get ( hLegend, 'title' ); % set the string properties. set ( h, 'string', string, varargin{:} ); end end end % callback to update the legend position. function UpdateLegendTitlePosition( hLegend, hAxes ) % flag for changing positions or not changeUnits = false; % Check legend units if ~strcmp ( hLegend.Units, 'normalized' ) % take a copy of the user units userUnits = hLegend.Units; % update the internal flag changeUnits = true; % change the units to normalised hLegend.Units = 'normalized'; end % extract the legend position position = hLegend.Position; % update the position of the axes hAxes.Position(1:3) = [position(1) position(2) + position(4) position(3)]; % hide the axes hAxes.Visible = 'off'; % show the title hAxes.Title.Visible = 'on'; % if we changed the units set them back if changeUnits hLegend.Units = userUnits; end end
github
ElisNycander/vsc_opf-master
vscopf_f_minCurtail.m
.m
vsc_opf-master/vscopf_f_minCurtail.m
1,748
utf_8
669a5ff4393e4e63fccf04f587520913
function [f, df, d2f] = vscopf_f_minCurtail(x, om) % Objective function: maximize sum of active generation from generators % with gen2(:,PMAXIMIZE) == 1 define_constants; %% unpack data mpc = get_mpc(om); vv = get_idx(om); wind = mpc.contingencies.wind/mpc.baseMVA; % wind scenarios prob = mpc.contingencies.probabilities; %nCurtail = length(find(mpc.gen2(mpc.gen2(:,PTYPE) == PCUR))); nCurtail = length(find(mpc.gen2(:,PTYPE) == PCUR)); %% problem dimensions nxyz = length(x); %% total number of control vars of all types idx = false(1,nxyz); for i=2:mpc.contingencies.N % note: no curtailment for base case sidx = num2str(i); idx(vv.i1.(['Beta' sidx]):vv.iN.(['Beta' sidx])) = true; end % repeat probabilities for contingencies, excluding base case probability prob = zeros(nCurtail*(mpc.contingencies.N-1),1); for i=1:mpc.contingencies.N-1 prob(1+(i-1)*nCurtail:i*nCurtail) = mpc.contingencies.probabilities(i+1); end % Note: base case excluded (as no curtailment in base case) f = sum( x(idx) .* wind(nCurtail+1:end) .* prob ); % idx(vv.i1.Vm:vv.iN.Vm) = 1; % idx = logical(idx); % maximize injected active power % if isfield(vv.i1,'Pg') % idx(vv.i1.Pg:vv.iN.Pg) = 1; % end % flag = 1; % nr = 1; % while flag % if isfield(vv.i1,['Pg' num2str(nr)]) % idx(vv.i1.(['Pg' num2str(nr)]):idx.iN.(['Pg' num2str(nr)])) = 1; % else % flag = 0; % end % end % maximize Qg from generator 1 % idx(vv.i1.Qg) = 1; % % idx = logical(idx); % % % % F: negative sum of wind % f = -sum(x(idx)); %x(idx) if nargout > 1 %% gradient df = zeros(nxyz,1); df(idx) = wind(nCurtail+1:end) .* prob; %% Hessian if nargout > 2 d2f = sparse(zeros(nxyz)); end end
github
ElisNycander/vsc_opf-master
vscopf_f_maxPg.m
.m
vsc_opf-master/vscopf_f_maxPg.m
707
utf_8
0a2beb6f0474902e6ffcd231e04365d8
function [f, df, d2f] = vscopf_f_maxPg(x, om) % Objective function: maximize sum of active generation from generators % with gen2(:,PMAXIMIZE) == 1 define_constants; %% unpack data mpc = get_mpc(om); vv = get_idx(om); %% problem dimensions nxyz = length(x); %% total number of control vars of all types %% grab Pg & Qg %Pg = x(vv.i1.Pg:vv.iN.Pg); %% active generation in p.u. widx = find(mpc.gen2(:,PMAXIMIZE)); idx = zeros(1,nxyz); idx(vv.i1.Pg+widx-1) = 1; idx = logical(idx); % F: negative sum of wind f = -sum(x(idx)); %x(idx) if nargout > 1 %% gradient df = zeros(nxyz,1); df(idx) = -1; %% Hessian if nargout > 2 d2f = sparse(zeros(nxyz)); end end
github
zhehedream/UAV-Path-Optimization-master
Is_Plane_In_Radar.m
.m
UAV-Path-Optimization-master/sub/Is_Plane_In_Radar.m
475
utf_8
df849bf70008208815758c292c1a2366
% Is_Plane_In_Radar % Input: point % Vectors of radars % Input: p_point % Coordinate of plane % Input: distance % Radar scanning radius % Output: result % 1-in_radar; 0-not_in_radar function result=Is_Plane_In_Radar(point,p_point,distance) for i=1:size(point,1) if point(i,1)==-1000 continue; end if sqrt((p_point(1,1)-point(i,1))^2+(p_point(1,2)-point(i,2))^2)<distance result=1; return; end end result=0;
github
zhehedream/UAV-Path-Optimization-master
Get_Points_Order.m
.m
UAV-Path-Optimization-master/sub/Get_Points_Order.m
704
utf_8
b6d84cbae5ca3345c36fa4c9ba0c77af
% Get_Points_Order % Get the minimum point order which shows how to travel through all % the points to achieve the minimum distance % Input: point % Output: opoint % point order % Output: dist % minimum travel distance function [opoint,dist]=Get_Points_Order(point) n=size(point,1); seq=perms(1:n); min_d=1e12; min_index=0; for i=1:size(seq,1) d=0; for j=1:length(seq(i,:))-1 d=d+sqrt((point(seq(i,j),1)-point(seq(i,j+1),1))^2+(point(seq(i,j),2)-point(seq(i,j+1),2))^2); end if d<min_d min_d=d; min_index=i; end end dist=min_d; opoint=[]; tmp=seq(min_index,:); for i=1:length(tmp) opoint=[opoint;point(tmp(1,i),1) point(tmp(1,i),2)]; end
github
zhehedream/UAV-Path-Optimization-master
Get_Point_Center.m
.m
UAV-Path-Optimization-master/sub/Get_Point_Center.m
196
utf_8
d76613e7098932ca775f37a3ecc1b34a
% Get_Point_Center % Get the coordinate of the weight center function [x,y]=Get_Point_Center(A,vec) n=length(vec); x=0; y=0; for i=1:n x=x+A(vec(i),1); y=y+A(vec(i),2); end x=x/n; y=y/n;