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
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
setup_hover_configuration.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR Discret variable por gradiente/setup_hover_configuration.m
1,251
utf_8
64adcf1fe19761bf7637c5f4ced7cb21
% SETUP_HOVER_CONFIGURATION % % SETUP_HOVER_CONFIGURATION sets and returns the model model parameters % of the Quanser 3 DOF Hover plant. % % % Copyright (C) 2010 Quanser Consulting Inc. % Quanser Consulting Inc. % % function [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration( ) % % Gravitational Constant (m/s^2) g = 9.81; % Motor Armature Resistance (Ohm) Rm = 0.83; % Motor Current-Torque Constant (N.m/A) Kt_m = 0.0182; % Motor Rotor Moment of Inertia (kg.m^2) Jm = 1.91e-6; % Moving Mass of the Hover system (kg) m_hover = 2.85; % Mass of each Propeller Section = motor + shield + propeller + body (kg) m_prop = m_hover / 4; % Distance between Pivot to each Motor (m) l = 7.75*0.0254; % Propeller Force-Thrust Constant found Experimentally (N/V) Kf = 0.1188; % Propeller Torque-Thrust Constant found Experimentally (N.m/V) Kt_prop = 0.0036; % Normal Rotation Propeller Torque-Thrust Constant (N.m/V) Ktn = Kt_prop; % Counter Rotation Propeller Torque-Thrust Constant (N.m/V) Ktc = -Kt_prop; % Equivalent Moment of Inertia of each Propeller Section (kg.m^2) Jeq_prop = Jm + m_prop*l^2; % Equivalent Moment of Inertia about each Axis (kg.m^2) Jp = 2*Jeq_prop; Jy = 4*Jeq_prop; Jr = 2*Jeq_prop; % % end of setup_hover_configuration()
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
LQRDiscretoGradiente.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR Discret variable por gradiente/LQRDiscretoGradiente.m
3,665
utf_8
13e8e428d22e76f8e2b9eae5df76100f
function LQRDiscretoGradiente() clc; clear all %%Comentarios de este metodo % Se confia solo un parametro la accion de ponderacion entre la K calculada % y el Gradiente obtenido de la prediccion d ela accion. % El dejar solo un aprmetro de ponderacion seria MENOS efectivo usar los % parametro Q y R en el LQR que son parametro de ponderacion. Lo ideal % seria poder calcularlos en funcion de X_actual y r_requerida [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration(); HOVER_ABCD_eqns; %% LQR suministrado por el fabricante Q = diag([500 350 350 0 20 20] ); R = 0.01*diag([1 1 1 1]); % Automatically calculate the LQR controller gain K = lqr( A, B, Q, R ) %% LQR calculado optimizando coste de forma discreta % Definimos el vector de estado x =[psi,theta,phi,psi',theta',phi'] x_k= zeros(6,1); % Este valor puede estar dado o por la integracion o por los sensores r_k=transpose( [0,0,0,0,0,0.1]); % Referencia dada en el paso anterior r_k1= transpose( [0,0,0,0,0,0.5]); % Referencia a donde queremos ir At=0.01; beta=10;% Se confia a beta la accion de ponderar la importancia del gradiente initial_K=K; % Cojemos por ahora la K del fabricante; La inicial deberia ser la del paso anterior initial_K = reshape(initial_K,size(initial_K,1)*size(initial_K,2),1); [J,Grad] = FuncionCoste(A,B,At,x_k,r_k,r_k1,initial_K); Grad=reshape(Grad,size(K)); display(J) display(Grad) fprintf(' Coste inicial y gradiente\n'); fprintf(' Se procedera a encontrar la K optima\n'); % pause K_optima=reshape(initial_K,size(K)) + beta*reshape(Grad,size(K)); % Se confia a beta la accion de ponderar la importancia del gradiente fprintf(' K optima y evolucion del coste\n'); display(K_optima) display(K) close all fprintf(' Pasaremos a hacer una simulacion\n'); pause %% Simulacion % Intentaremos integrar con un RK3 las ecuaciones usando ambas K's x(:,1)= zeros(6,1); % Psicion inicial r=transpose( [0,0,0.1,0,0,0.1]); % Referencia dada en el primer paso r_obj= transpose( [0,0,0.5,0,0,0.5]); % K del fabricante for j=1:20 if j>1 r=r_obj; end k1=A*x(:,j) - B*K*(x(:,j)-r); k2=A*( x(:,j) + At*k1/2) - B*K*( x(:,j) + At*k1/2 -r); k3=A*( x(:,j) + At*(2*k1-k1) ) - B*K*( x(:,j) + At*(2*k1-k1) -r); x(:,j+1) = x(:,j) +At/6*( k1+4*k2 + k3 ); end subplot(2,1,1) plot(x(6,:)) hold on plot(x(2,:),'r') plot(x(3,:),'g') hold off fprintf('K discreta optima\n'); % pause % K Opt discreta for j=1:20 if j>1 r=r_obj; end K = reshape(K,size(K,1)*size(K,2),1); [Coste,Grad] = FuncionCoste(A,B,At,x(:,j),r,r_obj,K); K = reshape(K,4,6) + beta*reshape(Grad,4,6) k1=A*x(:,j) - B*K*(x(:,j)-r); k2=A*( x(:,j) + At*k1/2) - B*K*( x(:,j) + At*k1/2 -r); k3=A*( x(:,j) + At*(2*k1-k1) ) - B*K*( x(:,j) + At*(2*k1-k1) -r); x(:,j+1) = x(:,j) +At/6*( k1+4*k2 + k3 ); end subplot(2,1,2) plot(x(6,:)) hold on plot(x(2,:),'r') plot(x(3,:),'g') hold off end function [J,Grad]=FuncionCoste(A,B,At,x_k,r_k,r_k1,K) K=reshape(K, 4 , 6); % CUIDADO CON ESTO!!!! Cuando se cambien las dimesiones de los vectores J= transpose ( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )* ( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 ); % Grad=-2*( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )*At*B* [ (x_k-r_k)'; (x_k-r_k)' ; (x_k-r_k)' ; (x_k-r_k)' ] ; for i=1:size(B,2) Grad ( i, : ) = -2*( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )' * At*B(:,i) * (x_k-r_k)'; end Grad = reshape(Grad,size(Grad,1)*size(Grad,2),1); % Para usar fmingc hay que usar un vector como gradiente tambien end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
setup_hover_configuration.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto 2 steps/setup_hover_configuration.m
1,251
utf_8
64adcf1fe19761bf7637c5f4ced7cb21
% SETUP_HOVER_CONFIGURATION % % SETUP_HOVER_CONFIGURATION sets and returns the model model parameters % of the Quanser 3 DOF Hover plant. % % % Copyright (C) 2010 Quanser Consulting Inc. % Quanser Consulting Inc. % % function [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration( ) % % Gravitational Constant (m/s^2) g = 9.81; % Motor Armature Resistance (Ohm) Rm = 0.83; % Motor Current-Torque Constant (N.m/A) Kt_m = 0.0182; % Motor Rotor Moment of Inertia (kg.m^2) Jm = 1.91e-6; % Moving Mass of the Hover system (kg) m_hover = 2.85; % Mass of each Propeller Section = motor + shield + propeller + body (kg) m_prop = m_hover / 4; % Distance between Pivot to each Motor (m) l = 7.75*0.0254; % Propeller Force-Thrust Constant found Experimentally (N/V) Kf = 0.1188; % Propeller Torque-Thrust Constant found Experimentally (N.m/V) Kt_prop = 0.0036; % Normal Rotation Propeller Torque-Thrust Constant (N.m/V) Ktn = Kt_prop; % Counter Rotation Propeller Torque-Thrust Constant (N.m/V) Ktc = -Kt_prop; % Equivalent Moment of Inertia of each Propeller Section (kg.m^2) Jeq_prop = Jm + m_prop*l^2; % Equivalent Moment of Inertia about each Axis (kg.m^2) Jp = 2*Jeq_prop; Jy = 4*Jeq_prop; Jr = 2*Jeq_prop; % % end of setup_hover_configuration()
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
LQRDiscretoControlador.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto 2 steps/LQRDiscretoControlador.m
4,329
utf_8
203f1bb38ac4878e5a89eeb58398e36a
function LQRDiscretoControlador() clc; clear all global A B % Set the model parameters of the 3DOF HOVER. % These parameters are used for model representation and controller design. [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration(); % % For the following state vector: X = [ theta; psi; theta_dot; psi_dot] % Initialization the state-Space representation of the open-loop System HOVER_ABCD_eqns; %% LQR suministrado por el fabricante Q = diag([500 350 350 0 20 20] ); R = 0.01*diag([1 1 1 1]); % Automatically calculate the LQR controller gain K = lqr( A, B, Q, R ) %% LQR calculado optimizando coste de forma discreta % Definimos el vector de estado x =[psi,theta,phi,psi',theta',phi'] x_k_1= transpose( [0.1,0,0,0,0,0]); % Este valor puede estar dado o por la integracion o por los sensores x_k= transpose( [0.1,0,0,0,0,0]); r_k_1=transpose( [0.5,0,0,0,0,0]); % Referencia dada At=0.1; initial_K=K; % Cojemos por ahora la K del fabricante; La inicial deberia ser la del paso anterior initial_K = reshape(initial_K,size(initial_K,1)*size(initial_K,2),1) % Para usar fmingc hay que usar un ector como parametro a optimizar [J,Grad] = FuncionCoste(A,B,At,x_k_1,x_k,r_k_1,initial_K); Grad=reshape(Grad,size(K)); display(J) display(Grad) fprintf(' Coste inicial y gradiente\n'); fprintf(' Se procedera a encontrar la K optima\n'); % pause FunciondeCoste = @(t) FuncionCoste(A,B,At,x_k_1,x_k,r_k_1,t); options = optimset('MaxIter', 1); [K_optima, Coste] = fmincg(FunciondeCoste, initial_K, options); fprintf(' K optima y evolucion del coste\n'); K_optima=reshape(K_optima,size(K)); display(K_optima) display(K) fprintf(' Pasaremos a hacer una simulacion\n'); pause %% Simulacion % Intentaremos integrar con un RK3 las ecuaciones usando ambas K's x(:,1)= transpose( [0.1,0,0,0,0,0]); % Posicion inicial x(:,2)= transpose( [0.1,0,0,0,0,0]); r= transpose( [0.5,0,0,0,0,0]); % K del fabricante for j=1:40 % r=j/100 +0.1; k1=A*x(:,j) - B*K*(x(:,j)-r); k2=A*( x(:,j) + At*k1/2) - B*K*( x(:,j) + At*k1/2 -r); k3=A*( x(:,j) + At*(2*k1-k1) ) - B*K*( x(:,j) + At*(2*k1-k1) -r); x(:,j+1) = x(:,j) +At/6*( k1+4*k2 + k3 ); end subplot(2,1,1) plot(x(1,:)) hold on % plot(x(4,:),'g') hold off fprintf('K discreta optima\n'); % pause % K Opt discreta for j=2:40 % r=j/100 + 0.1; initial_K=K; % La primera K la cogemos del LQR normal. Hacemos la optimizacion desde la K anterior % Se podria evitar oscilaciones de la solucion optimizando siempre % desde una misma K_opt por ejemplo la K del LQR normal initial_K = reshape(initial_K,size(initial_K,1)*size(initial_K,2),1); % % % FunciondeCoste = @(t) FuncionCoste(A,B,At,x(:,j-1),x(:,j),r,t); % % % [K_optima, Coste] = fmincg(FunciondeCoste, initial_K, options); K_optima = LQRDiscretoFUNC(At,x(:,j-1),x(:,j),r,initial_K); K=reshape(K_optima,size(K)); k1=A*x(:,j) - B*K*(x(:,j)-r); k2=A*( x(:,j) + At*k1/2) - B*K*( x(:,j) + At*k1/2 -r); k3=A*( x(:,j) + At*(2*k1-k1) ) - B*K*( x(:,j) + At*(2*k1-k1) -r); x(:,j+1) = x(:,j) +At/6*( k1+4*k2 + k3 ); end subplot(2,1,2) plot(x(1,:)) hold on % plot(x(4,:),'g') hold off end function [J,Grad]=FuncionCoste(A,B,At,x_k_1,x_k,r_k_1,K) K=reshape(K, 4 , 6); % CUIDADO CON ESTO!!!! Cuando se cambien las dimesiones de los vectores % Se observa que puede tener un mejor comportamiento cuando el estado % actual (K) se desprecia y se estima a partir del antrior x_k_1 % % % % % % % x_k=( eye(6)+At*A )*x_k_1 -At*B*K*( x_k_1 - r_k_1 ); % % Cambiar esto cuando se queira!!!! J= transpose ( ( eye(6)+At*A )*x_k -At*B*K*( x_k - r_k_1 ) -r_k_1 ) * ( ( eye(6)+At*A )*x_k -At*B*K*( x_k - r_k_1 ) -r_k_1 ); % % Grad=-2*( ( eye(6)+At*A )*x_k_1 -At*B*K*(x_k_1-r_k_1) - r_k_1 )*At*B* [ (x_k_1-r_k_1)'; (x_k_1-r_k_1)' ; (x_k_1-r_k_1)' ; (x_k_1-r_k_1)' ] ; for i=1:size(B,2) Grad ( i, : ) = 2*( ( eye(6)+At*A )*x_k - At*B*K*( x_k - r_k_1 ) - r_k_1 )' * ( -At*B(:,i)*( x_k -r_k_1 )' - ( ( eye(6)+At*A )-At*B*K ) * At*B(:,i)* (x_k_1 -r_k_1 )' ); end Grad = reshape(Grad,size(Grad,1)*size(Grad,2),1); % Para usar fmingc hay que usar un vector como gradiente tambien end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
LQRDiscretoFUNC.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto 2 steps/LQRDiscretoFUNC.m
10,697
utf_8
bc88d145dce1b4d9ca8aca19412ff81c
function K_optima = LQRDiscretoFUNC(At,x_k_1,x_k,r_k_1,initial_K) % % % % % % % Set the model parameters of the 3DOF HOVER. % % % % These parameters are used for model representation and controller design. % % % [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration(); % % % % % % % % For the following state vector: X = [ theta; psi; theta_dot; psi_dot] % % % % Initialization the state-Space representation of the open-loop System % % % HOVER_ABCD_eqns; % % % %% LQR suministrado por el fabricante % % % Q = diag([500 350 350 0 20 20] ); % % % R = 0.01*diag([1 1 1 1]); % % % % Automatically calculate the LQR controller gain % % % K = lqr( A, B, Q, R ) global A B %% LQR calculado optimizando coste de forma discreta % Definimos el vector de estado x =[theta,theta',phi,phi',psi,psi'] FunciondeCoste = @(t) FuncionCoste(A,B,At,x_k_1,x_k,r_k_1,t); options = optimset('MaxIter', 100); [K_optima, Coste] = fmincg(FunciondeCoste, initial_K, options); K_optima=reshape(K_optima, 4 , 6); end %% Funciones usadas function [J,Grad]=FuncionCoste(A,B,At,x_k_1,x_k,r_k_1,K) K=reshape(K, 4 , 6); % CUIDADO CON ESTO!!!! Cuando se cambien las dimesiones de los vectores x_k=( eye(6)+At*A )*x_k_1 -At*B*K*( x_k_1 - r_k_1 ); J= transpose ( ( eye(6)+At*A )*x_k -At*B*K*( x_k - r_k_1 ) -r_k_1 ) * ( ( eye(6)+At*A )*x_k -At*B*K*( x_k - r_k_1 ) -r_k_1 ); % % Grad=-2*( ( eye(6)+At*A )*x_k_1 -At*B*K*(x_k_1-r_k_1) - r_k_1 )*At*B* [ (x_k_1-r_k_1)'; (x_k_1-r_k_1)' ; (x_k_1-r_k_1)' ; (x_k_1-r_k_1)' ] ; for i=1:size(B,2) Grad ( i, : ) = 2*( ( eye(6)+At*A )*x_k - At*B*K*( x_k - r_k_1 ) - r_k_1 )' * ( -At*B(:,i)*( x_k -r_k_1 )' - ( ( eye(6)+At*A )-At*B*K ) * At*B(:,i)* (x_k_1 -r_k_1 )' ); end Grad = reshape(Grad,size(Grad,1)*size(Grad,2),1); % Para usar fmingc hay que usar un vector como gradiente tambien end function [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5) % Minimize a continuous differentialble multivariate function. Starting point % is given by "X" (D by 1), and the function named in the string "f", must % return a function value and a vector of partial derivatives. The Polack- % Ribiere flavour of conjugate gradients is used to compute search directions, % and a line search using quadratic and cubic polynomial approximations and the % Wolfe-Powell stopping criteria is used together with the slope ratio method % for guessing initial step sizes. Additionally a bunch of checks are made to % make sure that exploration is taking place and that extrapolation will not % be unboundedly large. The "length" gives the length of the run: if it is % positive, it gives the maximum number of line searches, if negative its % absolute gives the maximum allowed number of function evaluations. You can % (optionally) give "length" a second component, which will indicate the % reduction in function value to be expected in the first line-search (defaults % to 1.0). The function returns when either its length is up, or if no further % progress can be made (ie, we are at a minimum, or so close that due to % numerical problems, we cannot get any closer). If the function terminates % within a few iterations, it could be an indication that the function value % and derivatives are not consistent (ie, there may be a bug in the % implementation of your "f" function). The function returns the found % solution "X", a vector of function values "fX" indicating the progress made % and "i" the number of iterations (line searches or function evaluations, % depending on the sign of "length") used. % % Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5) % % See also: checkgrad % % Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13 % % % (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen % % Permission is granted for anyone to copy, use, or modify these % programs and accompanying documents for purposes of research or % education, provided this copyright notice is retained, and note is % made of any changes that have been made. % % These programs and documents are distributed without any warranty, % express or implied. As the programs were written for research % purposes only, they have not been tested to the degree that would be % advisable in any important application. All use of these programs is % entirely at the user's own risk. % % [ml-class] Changes Made: % 1) Function name and argument specifications % 2) Output display % % Read options if exist('options', 'var') && ~isempty(options) && isfield(options, 'MaxIter') length = options.MaxIter; else length = 100; end RHO = 0.01; % a bunch of constants for line searches SIG = 0.5; % RHO and SIG are the constants in the Wolfe-Powell conditions INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket EXT = 3.0; % extrapolate maximum 3 times the current bracket MAX = 20; % max 20 function evaluations per line search RATIO = 100; % maximum allowed slope ratio argstr = ['feval(f, X']; % compose string used to call function for i = 1:(nargin - 3) argstr = [argstr, ',P', int2str(i)]; end argstr = [argstr, ')']; if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end S=['Iteration ']; i = 0; % zero the run length counter ls_failed = 0; % no previous line search has failed fX = []; [f1 df1] = eval(argstr); % get function value and gradient i = i + (length<0); % count epochs?! s = -df1; % search direction is steepest d1 = -s'*s; % this is the slope z1 = red/(1-d1); % initial step is red/(|s|+1) while i < abs(length) % while not finished i = i + (length>0); % count iterations?! X0 = X; f0 = f1; df0 = df1; % make a copy of current values X = X + z1*s; % begin line search [f2 df2] = eval(argstr); i = i + (length<0); % count epochs?! d2 = df2'*s; f3 = f1; d3 = d1; z3 = -z1; % initialize point 3 equal to point 1 if length>0, M = MAX; else M = min(MAX, -length-i); end success = 0; limit = -1; % initialize quanteties while 1 while ((f2 > f1+z1*RHO*d1) | (d2 > -SIG*d1)) & (M > 0) limit = z1; % tighten the bracket if f2 > f1 z2 = z3 - (0.5*d3*z3*z3)/(d3*z3+f2-f3); % quadratic fit else A = 6*(f2-f3)/z3+3*(d2+d3); % cubic fit B = 3*(f3-f2)-z3*(d3+2*d2); z2 = (sqrt(B*B-A*d2*z3*z3)-B)/A; % numerical error possible - ok! end if isnan(z2) | isinf(z2) z2 = z3/2; % if we had a numerical problem then bisect end z2 = max(min(z2, INT*z3),(1-INT)*z3); % don't accept too close to limits z1 = z1 + z2; % update the step X = X + z2*s; [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; z3 = z3-z2; % z3 is now relative to the location of z2 end if f2 > f1+z1*RHO*d1 | d2 > -SIG*d1 break; % this is a failure elseif d2 > SIG*d1 success = 1; break; % success elseif M == 0 break; % failure end A = 6*(f2-f3)/z3+3*(d2+d3); % make cubic extrapolation B = 3*(f3-f2)-z3*(d3+2*d2); z2 = -d2*z3*z3/(B+sqrt(B*B-A*d2*z3*z3)); % num. error possible - ok! if ~isreal(z2) | isnan(z2) | isinf(z2) | z2 < 0 % num prob or wrong sign? if limit < -0.5 % if we have no upper limit z2 = z1 * (EXT-1); % the extrapolate the maximum amount else z2 = (limit-z1)/2; % otherwise bisect end elseif (limit > -0.5) & (z2+z1 > limit) % extraplation beyond max? z2 = (limit-z1)/2; % bisect elseif (limit < -0.5) & (z2+z1 > z1*EXT) % extrapolation beyond limit z2 = z1*(EXT-1.0); % set to extrapolation limit elseif z2 < -z3*INT z2 = -z3*INT; elseif (limit > -0.5) & (z2 < (limit-z1)*(1.0-INT)) % too close to limit? z2 = (limit-z1)*(1.0-INT); end f3 = f2; d3 = d2; z3 = -z2; % set point 3 equal to point 2 z1 = z1 + z2; X = X + z2*s; % update current estimates [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; end % end of line search if success % if line search succeeded f1 = f2; fX = [fX' f1]'; % % fprintf('%s %4i | Cost: %4.6e\r', S, i, f1); s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2; % Polack-Ribiere direction tmp = df1; df1 = df2; df2 = tmp; % swap derivatives d2 = df1'*s; if d2 > 0 % new slope must be negative s = -df1; % otherwise use steepest direction d2 = -s'*s; end z1 = z1 * min(RATIO, d1/(d2-realmin)); % slope ratio but max RATIO d1 = d2; ls_failed = 0; % this line search did not fail else X = X0; f1 = f0; df1 = df0; % restore point from before failed line search if ls_failed | i > abs(length) % line search failed twice in a row break; % or we ran out of time, so we give up end tmp = df1; df1 = df2; df2 = tmp; % swap derivatives s = -df1; % try steepest d1 = -s'*s; z1 = 1/(1-d1); ls_failed = 1; % this line search failed end if exist('OCTAVE_VERSION') fflush(stdout); end end % % fprintf('\n'); end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
setup_hover_configuration.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto 2 steps/Simulacion en Simulink/setup_hover_configuration.m
1,251
utf_8
64adcf1fe19761bf7637c5f4ced7cb21
% SETUP_HOVER_CONFIGURATION % % SETUP_HOVER_CONFIGURATION sets and returns the model model parameters % of the Quanser 3 DOF Hover plant. % % % Copyright (C) 2010 Quanser Consulting Inc. % Quanser Consulting Inc. % % function [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration( ) % % Gravitational Constant (m/s^2) g = 9.81; % Motor Armature Resistance (Ohm) Rm = 0.83; % Motor Current-Torque Constant (N.m/A) Kt_m = 0.0182; % Motor Rotor Moment of Inertia (kg.m^2) Jm = 1.91e-6; % Moving Mass of the Hover system (kg) m_hover = 2.85; % Mass of each Propeller Section = motor + shield + propeller + body (kg) m_prop = m_hover / 4; % Distance between Pivot to each Motor (m) l = 7.75*0.0254; % Propeller Force-Thrust Constant found Experimentally (N/V) Kf = 0.1188; % Propeller Torque-Thrust Constant found Experimentally (N.m/V) Kt_prop = 0.0036; % Normal Rotation Propeller Torque-Thrust Constant (N.m/V) Ktn = Kt_prop; % Counter Rotation Propeller Torque-Thrust Constant (N.m/V) Ktc = -Kt_prop; % Equivalent Moment of Inertia of each Propeller Section (kg.m^2) Jeq_prop = Jm + m_prop*l^2; % Equivalent Moment of Inertia about each Axis (kg.m^2) Jp = 2*Jeq_prop; Jy = 4*Jeq_prop; Jr = 2*Jeq_prop; % % end of setup_hover_configuration()
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
LQRDiscretoFUNC.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto 2 steps/Simulacion en Simulink/LQRDiscretoFUNC.m
10,695
utf_8
a46dd8ac4bd18ae4baf7779ffc8dfc29
function K_optima = LQRDiscretoFUNC(At,x_k_1,x_k,r_k_1,initial_K) % % % % % % % Set the model parameters of the 3DOF HOVER. % % % % These parameters are used for model representation and controller design. % % % [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration(); % % % % % % % % For the following state vector: X = [ theta; psi; theta_dot; psi_dot] % % % % Initialization the state-Space representation of the open-loop System % % % HOVER_ABCD_eqns; % % % %% LQR suministrado por el fabricante % % % Q = diag([500 350 350 0 20 20] ); % % % R = 0.01*diag([1 1 1 1]); % % % % Automatically calculate the LQR controller gain % % % K = lqr( A, B, Q, R ) global A B %% LQR calculado optimizando coste de forma discreta % Definimos el vector de estado x =[theta,theta',phi,phi',psi,psi'] FunciondeCoste = @(t) FuncionCoste(A,B,At,x_k_1,x_k,r_k_1,t); options = optimset('MaxIter', 2); [K_optima, Coste] = fmincg(FunciondeCoste, initial_K, options); K_optima=reshape(K_optima, 4 , 6); end %% Funciones usadas function [J,Grad]=FuncionCoste(A,B,At,x_k_1,x_k,r_k_1,K) K=reshape(K, 4 , 6); % CUIDADO CON ESTO!!!! Cuando se cambien las dimesiones de los vectores x_k=( eye(6)+At*A )*x_k_1 -At*B*K*( x_k_1 - r_k_1 ); J= transpose ( ( eye(6)+At*A )*x_k -At*B*K*( x_k - r_k_1 ) -r_k_1 ) * ( ( eye(6)+At*A )*x_k -At*B*K*( x_k - r_k_1 ) -r_k_1 ); % % Grad=-2*( ( eye(6)+At*A )*x_k_1 -At*B*K*(x_k_1-r_k_1) - r_k_1 )*At*B* [ (x_k_1-r_k_1)'; (x_k_1-r_k_1)' ; (x_k_1-r_k_1)' ; (x_k_1-r_k_1)' ] ; for i=1:size(B,2) Grad ( i, : ) = 2*( ( eye(6)+At*A )*x_k - At*B*K*( x_k - r_k_1 ) - r_k_1 )' * ( -At*B(:,i)*( x_k -r_k_1 )' - ( ( eye(6)+At*A )-At*B*K ) * At*B(:,i)* (x_k_1 -r_k_1 )' ); end Grad = reshape(Grad,size(Grad,1)*size(Grad,2),1); % Para usar fmingc hay que usar un vector como gradiente tambien end function [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5) % Minimize a continuous differentialble multivariate function. Starting point % is given by "X" (D by 1), and the function named in the string "f", must % return a function value and a vector of partial derivatives. The Polack- % Ribiere flavour of conjugate gradients is used to compute search directions, % and a line search using quadratic and cubic polynomial approximations and the % Wolfe-Powell stopping criteria is used together with the slope ratio method % for guessing initial step sizes. Additionally a bunch of checks are made to % make sure that exploration is taking place and that extrapolation will not % be unboundedly large. The "length" gives the length of the run: if it is % positive, it gives the maximum number of line searches, if negative its % absolute gives the maximum allowed number of function evaluations. You can % (optionally) give "length" a second component, which will indicate the % reduction in function value to be expected in the first line-search (defaults % to 1.0). The function returns when either its length is up, or if no further % progress can be made (ie, we are at a minimum, or so close that due to % numerical problems, we cannot get any closer). If the function terminates % within a few iterations, it could be an indication that the function value % and derivatives are not consistent (ie, there may be a bug in the % implementation of your "f" function). The function returns the found % solution "X", a vector of function values "fX" indicating the progress made % and "i" the number of iterations (line searches or function evaluations, % depending on the sign of "length") used. % % Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5) % % See also: checkgrad % % Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13 % % % (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen % % Permission is granted for anyone to copy, use, or modify these % programs and accompanying documents for purposes of research or % education, provided this copyright notice is retained, and note is % made of any changes that have been made. % % These programs and documents are distributed without any warranty, % express or implied. As the programs were written for research % purposes only, they have not been tested to the degree that would be % advisable in any important application. All use of these programs is % entirely at the user's own risk. % % [ml-class] Changes Made: % 1) Function name and argument specifications % 2) Output display % % Read options if exist('options', 'var') && ~isempty(options) && isfield(options, 'MaxIter') length = options.MaxIter; else length = 100; end RHO = 0.01; % a bunch of constants for line searches SIG = 0.5; % RHO and SIG are the constants in the Wolfe-Powell conditions INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket EXT = 3.0; % extrapolate maximum 3 times the current bracket MAX = 20; % max 20 function evaluations per line search RATIO = 100; % maximum allowed slope ratio argstr = ['feval(f, X']; % compose string used to call function for i = 1:(nargin - 3) argstr = [argstr, ',P', int2str(i)]; end argstr = [argstr, ')']; if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end S=['Iteration ']; i = 0; % zero the run length counter ls_failed = 0; % no previous line search has failed fX = []; [f1 df1] = eval(argstr); % get function value and gradient i = i + (length<0); % count epochs?! s = -df1; % search direction is steepest d1 = -s'*s; % this is the slope z1 = red/(1-d1); % initial step is red/(|s|+1) while i < abs(length) % while not finished i = i + (length>0); % count iterations?! X0 = X; f0 = f1; df0 = df1; % make a copy of current values X = X + z1*s; % begin line search [f2 df2] = eval(argstr); i = i + (length<0); % count epochs?! d2 = df2'*s; f3 = f1; d3 = d1; z3 = -z1; % initialize point 3 equal to point 1 if length>0, M = MAX; else M = min(MAX, -length-i); end success = 0; limit = -1; % initialize quanteties while 1 while ((f2 > f1+z1*RHO*d1) | (d2 > -SIG*d1)) & (M > 0) limit = z1; % tighten the bracket if f2 > f1 z2 = z3 - (0.5*d3*z3*z3)/(d3*z3+f2-f3); % quadratic fit else A = 6*(f2-f3)/z3+3*(d2+d3); % cubic fit B = 3*(f3-f2)-z3*(d3+2*d2); z2 = (sqrt(B*B-A*d2*z3*z3)-B)/A; % numerical error possible - ok! end if isnan(z2) | isinf(z2) z2 = z3/2; % if we had a numerical problem then bisect end z2 = max(min(z2, INT*z3),(1-INT)*z3); % don't accept too close to limits z1 = z1 + z2; % update the step X = X + z2*s; [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; z3 = z3-z2; % z3 is now relative to the location of z2 end if f2 > f1+z1*RHO*d1 | d2 > -SIG*d1 break; % this is a failure elseif d2 > SIG*d1 success = 1; break; % success elseif M == 0 break; % failure end A = 6*(f2-f3)/z3+3*(d2+d3); % make cubic extrapolation B = 3*(f3-f2)-z3*(d3+2*d2); z2 = -d2*z3*z3/(B+sqrt(B*B-A*d2*z3*z3)); % num. error possible - ok! if ~isreal(z2) | isnan(z2) | isinf(z2) | z2 < 0 % num prob or wrong sign? if limit < -0.5 % if we have no upper limit z2 = z1 * (EXT-1); % the extrapolate the maximum amount else z2 = (limit-z1)/2; % otherwise bisect end elseif (limit > -0.5) & (z2+z1 > limit) % extraplation beyond max? z2 = (limit-z1)/2; % bisect elseif (limit < -0.5) & (z2+z1 > z1*EXT) % extrapolation beyond limit z2 = z1*(EXT-1.0); % set to extrapolation limit elseif z2 < -z3*INT z2 = -z3*INT; elseif (limit > -0.5) & (z2 < (limit-z1)*(1.0-INT)) % too close to limit? z2 = (limit-z1)*(1.0-INT); end f3 = f2; d3 = d2; z3 = -z2; % set point 3 equal to point 2 z1 = z1 + z2; X = X + z2*s; % update current estimates [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; end % end of line search if success % if line search succeeded f1 = f2; fX = [fX' f1]'; % % fprintf('%s %4i | Cost: %4.6e\r', S, i, f1); s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2; % Polack-Ribiere direction tmp = df1; df1 = df2; df2 = tmp; % swap derivatives d2 = df1'*s; if d2 > 0 % new slope must be negative s = -df1; % otherwise use steepest direction d2 = -s'*s; end z1 = z1 * min(RATIO, d1/(d2-realmin)); % slope ratio but max RATIO d1 = d2; ls_failed = 0; % this line search did not fail else X = X0; f1 = f0; df1 = df0; % restore point from before failed line search if ls_failed | i > abs(length) % line search failed twice in a row break; % or we ran out of time, so we give up end tmp = df1; df1 = df2; df2 = tmp; % swap derivatives s = -df1; % try steepest d1 = -s'*s; z1 = 1/(1-d1); ls_failed = 1; % this line search failed end if exist('OCTAVE_VERSION') fflush(stdout); end end % % fprintf('\n'); end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
setup_hover_configuration.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto/setup_hover_configuration.m
1,251
utf_8
64adcf1fe19761bf7637c5f4ced7cb21
% SETUP_HOVER_CONFIGURATION % % SETUP_HOVER_CONFIGURATION sets and returns the model model parameters % of the Quanser 3 DOF Hover plant. % % % Copyright (C) 2010 Quanser Consulting Inc. % Quanser Consulting Inc. % % function [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration( ) % % Gravitational Constant (m/s^2) g = 9.81; % Motor Armature Resistance (Ohm) Rm = 0.83; % Motor Current-Torque Constant (N.m/A) Kt_m = 0.0182; % Motor Rotor Moment of Inertia (kg.m^2) Jm = 1.91e-6; % Moving Mass of the Hover system (kg) m_hover = 2.85; % Mass of each Propeller Section = motor + shield + propeller + body (kg) m_prop = m_hover / 4; % Distance between Pivot to each Motor (m) l = 7.75*0.0254; % Propeller Force-Thrust Constant found Experimentally (N/V) Kf = 0.1188; % Propeller Torque-Thrust Constant found Experimentally (N.m/V) Kt_prop = 0.0036; % Normal Rotation Propeller Torque-Thrust Constant (N.m/V) Ktn = Kt_prop; % Counter Rotation Propeller Torque-Thrust Constant (N.m/V) Ktc = -Kt_prop; % Equivalent Moment of Inertia of each Propeller Section (kg.m^2) Jeq_prop = Jm + m_prop*l^2; % Equivalent Moment of Inertia about each Axis (kg.m^2) Jp = 2*Jeq_prop; Jy = 4*Jeq_prop; Jr = 2*Jeq_prop; % % end of setup_hover_configuration()
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
LQRDiscretoControlador.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto/LQRDiscretoControlador.m
4,041
utf_8
49fa6e6fb5a7ffd6b252d4f1727b2792
function LQRDiscretoControlador() clc; clear all global A B % Set the model parameters of the 3DOF HOVER. % These parameters are used for model representation and controller design. [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration(); % % For the following state vector: X = [ theta; psi; theta_dot; psi_dot] % Initialization the state-Space representation of the open-loop System HOVER_ABCD_eqns; %% LQR suministrado por el fabricante Q = diag([500 350 350 0 20 20] ); R = 0.01*diag([1 1 1 1]); % Automatically calculate the LQR controller gain K = lqr( A, B, Q, R ) %% LQR calculado optimizando coste de forma discreta % Definimos el vector de estado x =[psi,theta,phi,psi',theta',phi'] x_k= zeros(6,1); % Este valor puede estar dado o por la integracion o por los sensores r_k=transpose( [0,0,0,0.1,0,0]); % Referencia dada en el paso anterior r_k1= transpose( [0,0,0,0.5,0,0]); % Referencia a donde queremos ir At=0.01; initial_K=K; % Cojemos por ahora la K del fabricante; La inicial deberia ser la del paso anterior initial_K = reshape(initial_K,size(initial_K,1)*size(initial_K,2),1) % Para usar fmingc hay que usar un ector como parametro a optimizar [J,Grad] = FuncionCoste(A,B,At,x_k,r_k,r_k1,initial_K); Grad=reshape(Grad,size(K)); display(J) display(Grad) fprintf(' Coste inicial y gradiente\n'); fprintf(' Se procedera a encontrar la K optima\n'); % pause FunciondeCoste = @(t) FuncionCoste(A,B,At,x_k,r_k,r_k1,t); options = optimset('MaxIter', 100); [K_optima, Coste] = fmincg(FunciondeCoste, initial_K, options); fprintf(' K optima y evolucion del coste\n'); K_optima=reshape(K_optima,size(K)); display(K_optima) display(K) plot(Coste) close all fprintf(' Pasaremos a hacer una simulacion\n'); pause %% Simulacion % Intentaremos integrar con un RK3 las ecuaciones usando ambas K's x(:,1)= transpose( [0,0,0,0,0.1,0]); % Posicion inicial r=transpose( [0,0,0,0,0.1,0]); % Referencia dada en el primer paso r_obj= transpose( [0,0,0,0,0.5,0]); % K del fabricante for j=1:20 if j>1 r=r_obj; end k1=A*x(:,j) - B*K*(x(:,j)-r); k2=A*( x(:,j) + At*k1/2) - B*K*( x(:,j) + At*k1/2 -r); k3=A*( x(:,j) + At*(2*k1-k1) ) - B*K*( x(:,j) + At*(2*k1-k1) -r); x(:,j+1) = x(:,j) +At/6*( k1+4*k2 + k3 ); end subplot(2,1,1) plot(x(2,:)) hold on plot(x(5,:),'g') hold off fprintf('K discreta optima\n'); % pause % K Opt discreta for j=1:20 if j>1 r=r_obj; end initial_K=K; % La primera K la cogemos del LQR normal. Hacemos la optimizacion desde la K anterior % Se podria evitar oscilaciones de la solucion optimizando siempre % desde una misma K_opt por ejemplo la K del LQR normal initial_K = reshape(initial_K,size(initial_K,1)*size(initial_K,2),1); % % % % % % FunciondeCoste = @(t) FuncionCoste(A,B,At,x(:,j),r,r_obj,t); % % % % % % [K_optima, Coste] = fmincg(FunciondeCoste, initial_K, options); K_optima = LQRDiscretoFUNC(At,x(:,j),r,r_obj,initial_K); K=reshape(K_optima,size(K)); k1=A*x(:,j) - B*K*(x(:,j)-r); k2=A*( x(:,j) + At*k1/2) - B*K*( x(:,j) + At*k1/2 -r); k3=A*( x(:,j) + At*(2*k1-k1) ) - B*K*( x(:,j) + At*(2*k1-k1) -r); x(:,j+1) = x(:,j) +At/6*( k1+4*k2 + k3 ); end subplot(2,1,2) plot(x(2,:)) hold on plot(x(5,:),'g') hold off end function [J,Grad]=FuncionCoste(A,B,At,x_k,r_k,r_k1,K) K=reshape(K, 4 , 6); % CUIDADO CON ESTO!!!! Cuando se cambien las dimesiones de los vectores J= transpose ( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )* ( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 ); % Grad=-2*( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )*At*B* [ (x_k-r_k)'; (x_k-r_k)' ; (x_k-r_k)' ; (x_k-r_k)' ] ; for i=1:size(B,2) Grad ( i, : ) = -2*( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )' * At*B(:,i) * (x_k-r_k)'; end Grad = reshape(Grad,size(Grad,1)*size(Grad,2),1); % Para usar fmingc hay que usar un vector como gradiente tambien end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
LQRDiscretoFUNC.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto/LQRDiscretoFUNC.m
10,486
utf_8
14e8eecb2067901be5d86b60fb4332e7
function K_optima = LQRDiscretoFUNC(At,x_k,r_k,r_k1,initial_K) % % % % % % % Set the model parameters of the 3DOF HOVER. % % % % These parameters are used for model representation and controller design. % % % [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration(); % % % % % % % % For the following state vector: X = [ theta; psi; theta_dot; psi_dot] % % % % Initialization the state-Space representation of the open-loop System % % % HOVER_ABCD_eqns; % % % %% LQR suministrado por el fabricante % % % Q = diag([500 350 350 0 20 20] ); % % % R = 0.01*diag([1 1 1 1]); % % % % Automatically calculate the LQR controller gain % % % K = lqr( A, B, Q, R ) global A B %% LQR calculado optimizando coste de forma discreta % Definimos el vector de estado x =[theta,theta',phi,phi',psi,psi'] FunciondeCoste = @(t) FuncionCoste(A,B,At,x_k,r_k,r_k1,t); options = optimset('MaxIter', 100); [K_optima, Coste] = fmincg(FunciondeCoste, initial_K, options); K_optima=reshape(K_optima, 4 , 6); end %% Funciones usadas function [J,Grad]=FuncionCoste(A,B,At,x_k,r_k,r_k1,K) K=reshape(K, 4 , 6); % CUIDADO CON ESTO!!!! Cuando se cambien las dimesiones de los vectores J= transpose ( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )* ( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 ); % Grad=-2*( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )*At*B* [ (x_k-r_k)'; (x_k-r_k)' ; (x_k-r_k)' ; (x_k-r_k)' ] ; for i=1:size(B,2) Grad ( i, : ) = -2*( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )' * At*B(:,i) * (x_k-r_k)'; end Grad = reshape(Grad,size(Grad,1)*size(Grad,2),1); % Para usar fmingc hay que usar un vector como gradiente tambien end function [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5) % Minimize a continuous differentialble multivariate function. Starting point % is given by "X" (D by 1), and the function named in the string "f", must % return a function value and a vector of partial derivatives. The Polack- % Ribiere flavour of conjugate gradients is used to compute search directions, % and a line search using quadratic and cubic polynomial approximations and the % Wolfe-Powell stopping criteria is used together with the slope ratio method % for guessing initial step sizes. Additionally a bunch of checks are made to % make sure that exploration is taking place and that extrapolation will not % be unboundedly large. The "length" gives the length of the run: if it is % positive, it gives the maximum number of line searches, if negative its % absolute gives the maximum allowed number of function evaluations. You can % (optionally) give "length" a second component, which will indicate the % reduction in function value to be expected in the first line-search (defaults % to 1.0). The function returns when either its length is up, or if no further % progress can be made (ie, we are at a minimum, or so close that due to % numerical problems, we cannot get any closer). If the function terminates % within a few iterations, it could be an indication that the function value % and derivatives are not consistent (ie, there may be a bug in the % implementation of your "f" function). The function returns the found % solution "X", a vector of function values "fX" indicating the progress made % and "i" the number of iterations (line searches or function evaluations, % depending on the sign of "length") used. % % Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5) % % See also: checkgrad % % Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13 % % % (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen % % Permission is granted for anyone to copy, use, or modify these % programs and accompanying documents for purposes of research or % education, provided this copyright notice is retained, and note is % made of any changes that have been made. % % These programs and documents are distributed without any warranty, % express or implied. As the programs were written for research % purposes only, they have not been tested to the degree that would be % advisable in any important application. All use of these programs is % entirely at the user's own risk. % % [ml-class] Changes Made: % 1) Function name and argument specifications % 2) Output display % % Read options if exist('options', 'var') && ~isempty(options) && isfield(options, 'MaxIter') length = options.MaxIter; else length = 100; end RHO = 0.01; % a bunch of constants for line searches SIG = 0.5; % RHO and SIG are the constants in the Wolfe-Powell conditions INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket EXT = 3.0; % extrapolate maximum 3 times the current bracket MAX = 20; % max 20 function evaluations per line search RATIO = 100; % maximum allowed slope ratio argstr = ['feval(f, X']; % compose string used to call function for i = 1:(nargin - 3) argstr = [argstr, ',P', int2str(i)]; end argstr = [argstr, ')']; if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end S=['Iteration ']; i = 0; % zero the run length counter ls_failed = 0; % no previous line search has failed fX = []; [f1 df1] = eval(argstr); % get function value and gradient i = i + (length<0); % count epochs?! s = -df1; % search direction is steepest d1 = -s'*s; % this is the slope z1 = red/(1-d1); % initial step is red/(|s|+1) while i < abs(length) % while not finished i = i + (length>0); % count iterations?! X0 = X; f0 = f1; df0 = df1; % make a copy of current values X = X + z1*s; % begin line search [f2 df2] = eval(argstr); i = i + (length<0); % count epochs?! d2 = df2'*s; f3 = f1; d3 = d1; z3 = -z1; % initialize point 3 equal to point 1 if length>0, M = MAX; else M = min(MAX, -length-i); end success = 0; limit = -1; % initialize quanteties while 1 while ((f2 > f1+z1*RHO*d1) | (d2 > -SIG*d1)) & (M > 0) limit = z1; % tighten the bracket if f2 > f1 z2 = z3 - (0.5*d3*z3*z3)/(d3*z3+f2-f3); % quadratic fit else A = 6*(f2-f3)/z3+3*(d2+d3); % cubic fit B = 3*(f3-f2)-z3*(d3+2*d2); z2 = (sqrt(B*B-A*d2*z3*z3)-B)/A; % numerical error possible - ok! end if isnan(z2) | isinf(z2) z2 = z3/2; % if we had a numerical problem then bisect end z2 = max(min(z2, INT*z3),(1-INT)*z3); % don't accept too close to limits z1 = z1 + z2; % update the step X = X + z2*s; [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; z3 = z3-z2; % z3 is now relative to the location of z2 end if f2 > f1+z1*RHO*d1 | d2 > -SIG*d1 break; % this is a failure elseif d2 > SIG*d1 success = 1; break; % success elseif M == 0 break; % failure end A = 6*(f2-f3)/z3+3*(d2+d3); % make cubic extrapolation B = 3*(f3-f2)-z3*(d3+2*d2); z2 = -d2*z3*z3/(B+sqrt(B*B-A*d2*z3*z3)); % num. error possible - ok! if ~isreal(z2) | isnan(z2) | isinf(z2) | z2 < 0 % num prob or wrong sign? if limit < -0.5 % if we have no upper limit z2 = z1 * (EXT-1); % the extrapolate the maximum amount else z2 = (limit-z1)/2; % otherwise bisect end elseif (limit > -0.5) & (z2+z1 > limit) % extraplation beyond max? z2 = (limit-z1)/2; % bisect elseif (limit < -0.5) & (z2+z1 > z1*EXT) % extrapolation beyond limit z2 = z1*(EXT-1.0); % set to extrapolation limit elseif z2 < -z3*INT z2 = -z3*INT; elseif (limit > -0.5) & (z2 < (limit-z1)*(1.0-INT)) % too close to limit? z2 = (limit-z1)*(1.0-INT); end f3 = f2; d3 = d2; z3 = -z2; % set point 3 equal to point 2 z1 = z1 + z2; X = X + z2*s; % update current estimates [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; end % end of line search if success % if line search succeeded f1 = f2; fX = [fX' f1]'; fprintf('%s %4i | Cost: %4.6e\r', S, i, f1); s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2; % Polack-Ribiere direction tmp = df1; df1 = df2; df2 = tmp; % swap derivatives d2 = df1'*s; if d2 > 0 % new slope must be negative s = -df1; % otherwise use steepest direction d2 = -s'*s; end z1 = z1 * min(RATIO, d1/(d2-realmin)); % slope ratio but max RATIO d1 = d2; ls_failed = 0; % this line search did not fail else X = X0; f1 = f0; df1 = df0; % restore point from before failed line search if ls_failed | i > abs(length) % line search failed twice in a row break; % or we ran out of time, so we give up end tmp = df1; df1 = df2; df2 = tmp; % swap derivatives s = -df1; % try steepest d1 = -s'*s; z1 = 1/(1-d1); ls_failed = 1; % this line search failed end if exist('OCTAVE_VERSION') fflush(stdout); end end fprintf('\n'); end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
setup_hover_configuration.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto/Simulacion en Simulink/setup_hover_configuration.m
1,251
utf_8
64adcf1fe19761bf7637c5f4ced7cb21
% SETUP_HOVER_CONFIGURATION % % SETUP_HOVER_CONFIGURATION sets and returns the model model parameters % of the Quanser 3 DOF Hover plant. % % % Copyright (C) 2010 Quanser Consulting Inc. % Quanser Consulting Inc. % % function [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration( ) % % Gravitational Constant (m/s^2) g = 9.81; % Motor Armature Resistance (Ohm) Rm = 0.83; % Motor Current-Torque Constant (N.m/A) Kt_m = 0.0182; % Motor Rotor Moment of Inertia (kg.m^2) Jm = 1.91e-6; % Moving Mass of the Hover system (kg) m_hover = 2.85; % Mass of each Propeller Section = motor + shield + propeller + body (kg) m_prop = m_hover / 4; % Distance between Pivot to each Motor (m) l = 7.75*0.0254; % Propeller Force-Thrust Constant found Experimentally (N/V) Kf = 0.1188; % Propeller Torque-Thrust Constant found Experimentally (N.m/V) Kt_prop = 0.0036; % Normal Rotation Propeller Torque-Thrust Constant (N.m/V) Ktn = Kt_prop; % Counter Rotation Propeller Torque-Thrust Constant (N.m/V) Ktc = -Kt_prop; % Equivalent Moment of Inertia of each Propeller Section (kg.m^2) Jeq_prop = Jm + m_prop*l^2; % Equivalent Moment of Inertia about each Axis (kg.m^2) Jp = 2*Jeq_prop; Jy = 4*Jeq_prop; Jr = 2*Jeq_prop; % % end of setup_hover_configuration()
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
LQRDiscretoFUNC.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/docs/Control Theory/Proporcional (LQR) predictivo/LQR optimo Discreto/Simulacion en Simulink/LQRDiscretoFUNC.m
10,481
utf_8
eb775de51e9fce3be563ab62100dda8d
function K_optima = LQRDiscretoFUNC(At,x_k,r_k,r_k1,initial_K) % % % % % % % Set the model parameters of the 3DOF HOVER. % % % % These parameters are used for model representation and controller design. % % % [ Ktn, Ktc, Kf, l, Jy, Jp, Jr, g ] = setup_hover_configuration(); % % % % % % % % For the following state vector: X = [ theta; psi; theta_dot; psi_dot] % % % % Initialization the state-Space representation of the open-loop System % % % HOVER_ABCD_eqns; % % % %% LQR suministrado por el fabricante % % % Q = diag([500 350 350 0 20 20] ); % % % R = 0.01*diag([1 1 1 1]); % % % % Automatically calculate the LQR controller gain % % % K = lqr( A, B, Q, R ) global A B %% LQR calculado optimizando coste de forma discreta % Definimos el vector de estado x =[theta,theta',phi,phi',psi,psi'] FunciondeCoste = @(t) FuncionCoste(A,B,At,x_k,r_k,r_k1,t); options = optimset('MaxIter', 100); [K_optima, Coste] = fmincg(FunciondeCoste, initial_K, options); K_optima=reshape(K_optima, 4 , 6); end %% Funciones usadas function [J,Grad]=FuncionCoste(A,B,At,x_k,r_k,r_k1,K) K=reshape(K, 4 , 6); % CUIDADO CON ESTO!!!! Cuando se cambien las dimesiones de los vectores J= transpose ( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )* ( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 ); % Grad=-2*( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )*At*B* [ (x_k-r_k)'; (x_k-r_k)' ; (x_k-r_k)' ; (x_k-r_k)' ] ; for i=1:size(B,2) Grad ( i, : ) = -2*( ( eye(6)+At*A )*x_k -At*B*K*(x_k-r_k) - r_k1 )' * At*B(:,i) * (x_k-r_k)'; end Grad = reshape(Grad,size(Grad,1)*size(Grad,2),1); % Para usar fmingc hay que usar un vector como gradiente tambien end function [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5) % Minimize a continuous differentialble multivariate function. Starting point % is given by "X" (D by 1), and the function named in the string "f", must % return a function value and a vector of partial derivatives. The Polack- % Ribiere flavour of conjugate gradients is used to compute search directions, % and a line search using quadratic and cubic polynomial approximations and the % Wolfe-Powell stopping criteria is used together with the slope ratio method % for guessing initial step sizes. Additionally a bunch of checks are made to % make sure that exploration is taking place and that extrapolation will not % be unboundedly large. The "length" gives the length of the run: if it is % positive, it gives the maximum number of line searches, if negative its % absolute gives the maximum allowed number of function evaluations. You can % (optionally) give "length" a second component, which will indicate the % reduction in function value to be expected in the first line-search (defaults % to 1.0). The function returns when either its length is up, or if no further % progress can be made (ie, we are at a minimum, or so close that due to % numerical problems, we cannot get any closer). If the function terminates % within a few iterations, it could be an indication that the function value % and derivatives are not consistent (ie, there may be a bug in the % implementation of your "f" function). The function returns the found % solution "X", a vector of function values "fX" indicating the progress made % and "i" the number of iterations (line searches or function evaluations, % depending on the sign of "length") used. % % Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5) % % See also: checkgrad % % Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13 % % % (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen % % Permission is granted for anyone to copy, use, or modify these % programs and accompanying documents for purposes of research or % education, provided this copyright notice is retained, and note is % made of any changes that have been made. % % These programs and documents are distributed without any warranty, % express or implied. As the programs were written for research % purposes only, they have not been tested to the degree that would be % advisable in any important application. All use of these programs is % entirely at the user's own risk. % % [ml-class] Changes Made: % 1) Function name and argument specifications % 2) Output display % % Read options if exist('options', 'var') && ~isempty(options) && isfield(options, 'MaxIter') length = options.MaxIter; else length = 100; end RHO = 0.01; % a bunch of constants for line searches SIG = 0.5; % RHO and SIG are the constants in the Wolfe-Powell conditions INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket EXT = 3.0; % extrapolate maximum 3 times the current bracket MAX = 20; % max 20 function evaluations per line search RATIO = 100; % maximum allowed slope ratio argstr = ['feval(f, X']; % compose string used to call function for i = 1:(nargin - 3) argstr = [argstr, ',P', int2str(i)]; end argstr = [argstr, ')']; if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end S=['Iteration ']; i = 0; % zero the run length counter ls_failed = 0; % no previous line search has failed fX = []; [f1 df1] = eval(argstr); % get function value and gradient i = i + (length<0); % count epochs?! s = -df1; % search direction is steepest d1 = -s'*s; % this is the slope z1 = red/(1-d1); % initial step is red/(|s|+1) while i < abs(length) % while not finished i = i + (length>0); % count iterations?! X0 = X; f0 = f1; df0 = df1; % make a copy of current values X = X + z1*s; % begin line search [f2 df2] = eval(argstr); i = i + (length<0); % count epochs?! d2 = df2'*s; f3 = f1; d3 = d1; z3 = -z1; % initialize point 3 equal to point 1 if length>0, M = MAX; else M = min(MAX, -length-i); end success = 0; limit = -1; % initialize quanteties while 1 while ((f2 > f1+z1*RHO*d1) | (d2 > -SIG*d1)) & (M > 0) limit = z1; % tighten the bracket if f2 > f1 z2 = z3 - (0.5*d3*z3*z3)/(d3*z3+f2-f3); % quadratic fit else A = 6*(f2-f3)/z3+3*(d2+d3); % cubic fit B = 3*(f3-f2)-z3*(d3+2*d2); z2 = (sqrt(B*B-A*d2*z3*z3)-B)/A; % numerical error possible - ok! end if isnan(z2) | isinf(z2) z2 = z3/2; % if we had a numerical problem then bisect end z2 = max(min(z2, INT*z3),(1-INT)*z3); % don't accept too close to limits z1 = z1 + z2; % update the step X = X + z2*s; [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; z3 = z3-z2; % z3 is now relative to the location of z2 end if f2 > f1+z1*RHO*d1 | d2 > -SIG*d1 break; % this is a failure elseif d2 > SIG*d1 success = 1; break; % success elseif M == 0 break; % failure end A = 6*(f2-f3)/z3+3*(d2+d3); % make cubic extrapolation B = 3*(f3-f2)-z3*(d3+2*d2); z2 = -d2*z3*z3/(B+sqrt(B*B-A*d2*z3*z3)); % num. error possible - ok! if ~isreal(z2) | isnan(z2) | isinf(z2) | z2 < 0 % num prob or wrong sign? if limit < -0.5 % if we have no upper limit z2 = z1 * (EXT-1); % the extrapolate the maximum amount else z2 = (limit-z1)/2; % otherwise bisect end elseif (limit > -0.5) & (z2+z1 > limit) % extraplation beyond max? z2 = (limit-z1)/2; % bisect elseif (limit < -0.5) & (z2+z1 > z1*EXT) % extrapolation beyond limit z2 = z1*(EXT-1.0); % set to extrapolation limit elseif z2 < -z3*INT z2 = -z3*INT; elseif (limit > -0.5) & (z2 < (limit-z1)*(1.0-INT)) % too close to limit? z2 = (limit-z1)*(1.0-INT); end f3 = f2; d3 = d2; z3 = -z2; % set point 3 equal to point 2 z1 = z1 + z2; X = X + z2*s; % update current estimates [f2 df2] = eval(argstr); M = M - 1; i = i + (length<0); % count epochs?! d2 = df2'*s; end % end of line search if success % if line search succeeded f1 = f2; fX = [fX' f1]'; % fprintf('%s %4i | Cost: %4.6e\r', S, i, f1); s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2; % Polack-Ribiere direction tmp = df1; df1 = df2; df2 = tmp; % swap derivatives d2 = df1'*s; if d2 > 0 % new slope must be negative s = -df1; % otherwise use steepest direction d2 = -s'*s; end z1 = z1 * min(RATIO, d1/(d2-realmin)); % slope ratio but max RATIO d1 = d2; ls_failed = 0; % this line search did not fail else X = X0; f1 = f0; df1 = df0; % restore point from before failed line search if ls_failed | i > abs(length) % line search failed twice in a row break; % or we ran out of time, so we give up end tmp = df1; df1 = df2; df2 = tmp; % swap derivatives s = -df1; % try steepest d1 = -s'*s; z1 = 1/(1-d1); ls_failed = 1; % this line search failed end if exist('OCTAVE_VERSION') fflush(stdout); end end % fprintf('\n'); end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
vview.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/lib/qcat1_2_1/QCAT/qcat/vview.m
6,443
utf_8
b3958410b2ea29230fa8cc7d5831170e
function ratio = vview(B,plim,P) % VVIEW - View the attainable virtual control set. % % 1) vview(B,plim) % % Shows the attainable virtual control set considering actuator % position constraints, given by { v : v = B*u, umin < u < umax }. % % 2) ratio = vview(B,plim,P) % % Compares the set of feasible virtual control inputs when % % a) the actuator redundancy is fully utilized (as above) [blue] % b) a linear allocation control law u = Pv is used (BP = I) [red] % % The second set is given by { v : umin < P*v < umax }. % % Inputs: % ------- % B control effectiveness matrix (k x m) % plim control position limits [min max] (m x 2) % P virtual control law matrix (m x k) % % Outputs: % -------- % ratio The ratio between the sizes (areas, volumes, ...) % of the two sets % % The result is only graphically illustrated for k = 1, 2, or 3. % % See also: VVIEW_DEMO % Model dimensions [k,m] = size(B); % ------------------------------------------------ % a) Find maximum attainable virtual control set % considering constraints. % ------------------------------------------------ % Generate matrix to index corners of feasible control set. idx = zeros(2^m,m); M = 1:m; for i = 1:2^m; cbin = dec2bin(i-1,m); % '001' c = str2num(cbin')'; % [0 0 1] c = c(end:-1:1); % [1 0 0] idx(i,:) = 2*M - c; end % Generate corner points of the feasible control set. plimT = plim'; U = plimT(idx)'; % Compute the corresponding points in the virtual control space V = B*U; if nargin > 2 % --------------------------------------------- % b) Find attainable virtual control set when % a linear control law u=Pv is used. % --------------------------------------------- % We want to determine where the k-dim. hyperplane Pv % intersects the m-dim. hyperbox of feasible controls. % To get the corner points of this set, solve % Pv = x where x has k specified entries. % % Example: m=3, k=1 -> points will lie on surfaces % m=3, k=2 -> points will lie on edges % Generate index matrix for all combinations of min and max indeces % in k dimensions. sub_idx = idx(1:2^k,1:k); Ulin = []; % Loop over all combinations of dimensions i_dim = nchoosek(1:m,k); for i = 1:size(i_dim,1) % For each combination, compute the intersections with all % possible min/max combinations. % k-dimensional min/max combinations sub_plimT = plimT(:,i_dim(i,:)); sub_u_boundary = sub_plimT(sub_idx)'; % Determine which virtual control sub_u_boundary corresponds to sub_P = P(i_dim(i,:),:); if rank(sub_P) == k % Avoid "parallel" cases % Solve sub_u_boundary = sub_P v for v v = sub_P\sub_u_boundary; % Determine the full countol vector (contains sub_u_boundary) u_boundary = P*v; % Store feasible points i_feas = feasible(u_boundary,plim); Ulin = [Ulin u_boundary(:,i_feas)]; end end % Compute the corresponing points in the virtual control space Vlin = B*Ulin; end % Compute and visualize the convex hull of the set(s) clf switch k case 1 K = [min(V) max(V)]; if nargin > 2 Klin = [min(Vlin) max(Vlin)]; ratio = diff(Klin)/diff(K); % Illustrate plot(K,[0 0],'b-o',Klin,-[0 0],'r-o') else plot(K,[0 0],'b-o') end xlabel('v') case 2 [K,area1] = convhull(V(1,:),V(2,:)); if nargin > 2 [Klin,area2] = convhull(Vlin(1,:),Vlin(2,:)); ratio = area2/area1; % Illustrate fill(V(1,K),V(2,K),[.95 .95 1],... Vlin(1,Klin),Vlin(2,Klin),[1 1 .9]) hold on; plot(Vlin(1,Klin),Vlin(2,Klin),'r',V(1,K),V(2,K),'b') hold off; else fill(V(1,K),V(2,K),[.95 .95 1]); hold on; plot(V(1,K),V(2,K),'b') hold off; end axis equal; xlabel('v_1') ylabel('v_2') otherwise [K,vol1] = convhulln(V'); if nargin > 2 [Klin,vol2] = convhulln(Vlin'); ratio = vol2/vol1; end if k == 3 % Illustrate if nargin > 2 % h = polyplot(Klin,Vlin',1); % set(h,'EdgeColor','r','FaceColor',[1 1 .9]); hold on; % Fix: Make V wireframe enclose Vlin V0 = repmat(mean(V')',1,size(V,2)); V = 1.0001*(V-V0)+V0; h = polyplot(K,V',1); set(h,'EdgeColor','b','FaceColor',[.95 .95 1]); alpha(0.4) hold off else h = polyplot(K,V',1); set(h,'EdgeColor','b','FaceColor',[.95 .95 1]); end xlabel('v_1') ylabel('v_2') zlabel('v_3') view(3); axis equal; axis vis3d; grid on; end end function f = feasible(x,plim) % x m*n % lb m % ub m m = size(x,1); % Mean point x0 = mean(plim,2); % Make the mean point the origin x = x - x0*ones(1,size(x,2)); lb = plim(:,1) - x0; % < 0 ub = plim(:,2) - x0; % > 0 % Check for feasibility tol = 1e-5; f = sum((diag(1./ub)*x <= 1+tol) & (diag(1./lb)*x <= 1+tol)) == m; function h = polyplot(face,vert,merge) if merge % Merge adjacent, parallel triangles to get fewer lines that % are not edges of the polyhedron. face4 = []; % Loop over all combinations of triangles k = 1; while k < size(face,1) l = k+1; while l <= size(face,1) iv = intersect(face(k,:),face(l,:)); % Intersecting vertices if length(iv) == 2 % Two common vertices % Are the faces parallel? niv = setxor(face(k,:),face(l,:)); % Non-intersecting vertices % Vectors from first common vertex to remaining three vertices A = [vert(iv(2),:) - vert(iv(1),:); vert(niv(1),:) - vert(iv(1),:); vert(niv(2),:) - vert(iv(1),:)]; if abs(det(A))<100*eps % Vectors lie in same plane -> create patch with four vertices face4 = [face4 ; iv(1) niv(1) iv(2) niv(2)]; % ... and remove the two triangles face = face([1:k-1 k+1:l-1 l+1:end],:); k = k-1; break end end l = l+1; end % inner loop k = k+1; end % outer loop h = [patch('Faces',face,'Vertices',vert) patch('Faces',face4,'Vertices',vert)]; else % Just plot the polyhedron made up by triangles h = patch('Faces',face,'Vertices',vert); end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
ip_alloc.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/lib/qcat1_2_1/QCAT/qcat/ip_alloc.m
5,473
utf_8
ad58dd244a7a2785cbffb745e1ffba9b
function [u,iter] = ip_alloc(B,v,umin,umax,ud,gam,tol,imax) % IP_ALLOC - Control allocation using interior point method. % % [u,iter] = ip_alloc(B,v,umin,umax,[ud,gamma,tol,imax]) % % Solves the weighted, bounded least-squares problem % % min ||u-ud||^2 + gamma ||Bu-v||^2 (unit weighting matrices) % % subj. to umin <= u <= umax % % using a primal dual interior point method. % % Inputs: % ------- % B control effectiveness matrix (k x m) % v commanded virtual control (k x 1) % umin lower position limits (m x 1) % umax upper position limits (m x 1) % ud desired control (m x 1) [0] % gamma weight (scalar) [1e4] % tol tolerance used in stopping criterion [1e-4] % imax max no. of iterations [100] % % Outputs: % ------- % u optimal control % iter no. of iterations % % See also: WLS_ALLOC, WLSC_ALLOC, FXP_ALLOC, QP_SIM. % % Contributed by John Petersen. % Set default values of optional arguments if nargin < 8 imax = 100; % Heuristic value [k,m] = size(B); if nargin < 7, tol = 1e-4; end if nargin < 6, gam = 1e4; end if nargin < 5, ud = zeros(m,1); end end % Reformulate min ||u-ud||^2 + gamma ||Bu-v||^2 % s.t. umin <= u <= umax % % as min ||Ax-b||^2 + h ||x-xd||^2 % s.t. 0 <= x <= xmax % % where x=u-umin, h=1/gamma, A=B, b=v-B*umin, xd=ud-umin, xmax=umax-umin h = 1/gam; A = B; b = v - B*umin; xd = ud - umin; xmax = umax - umin; % ||Ax-b||^2 + h ||x-xd||^2 = 1/2x'Hx + c'x + f(xd) c = -2*(b'*A + h*xd'); % Solve QP problem. [x,iter] = pdq(A,b,c',xmax,h,tol,imax); % Optimal control. u = x + umin; function [x,iter] = pdq(A,b,c,u,wc,tol,imax); % Primal dual IP solver [k,m] = size(A); % k = #constraints , m = #variables As2=A*sqrt(2); [s,w,x,z] = startpt(A,b,c,u,wc); rho = .9995; sig = 0.1; m2 = 2*m; xs = x.*s; wz = w.*z; mu = sig*(sum(xs + wz))/m2; % eq. (7) nxl=norm(x,1); iHd = 0; ru = 0; rc = 0; rb = 0; for iter = 1:imax+1 if (mu < tol) % Close enough to optimum, bail out. break; end; rxs = (xs - mu); iw = 1./w; rwz = (wz - mu); ix = 1./x; ixs = ix.*s; iwz = iw.*z; d = 2*wc + ixs + iwz; [ds,dw,dx,dz] = direct(d,As2,rb,rc,ru,rxs,rwz,ix,iw,ixs,iwz,z); alpha = stepsize(dx,ds,dw,dz,x,s,w,z); ralpha = rho*alpha; s = s + ralpha*ds; w = w + ralpha*dw; x = x + ralpha*dx; z = z + ralpha*dz; xs = x.*s; wz = w.*z; gap = sum(xs + wz)/m2; mu = min(.1,100*gap)*gap; end iter=iter-1; %True number of iterations is one less %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Initial starting point function [s,w,x,z] = startpt(A,b,c,u,wc); m = size(A,2); en = ones(m,1); % Start at the center of the constraint box x = u/2; w = u - x; z = en; s = en; if 0 AA = csm(A'); % csm efficiently computes cb'*cb for i=1:m AA(i,i) = AA(i,i) + wc; end % H = 2(A'A+wcI); else AA = A'*A + wc*eye(m); end ec = c + 2*AA*x; %initial residual error used to initialize z,s; g = .1; sg = 1+g; i = find(ec>0); s(i) = sg*ec(i); z(i) = g*ec(i); % Hx + c + z - s = 0; i = find(ec<0); z(i) = -sg*ec(i); s(i) = -g*ec(i); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Compute step direction function [ds,dw,dx,dz] = direct(d,As2,rb,rc,ru,rxs,rwz,ix,iw,ixs,iwz,z); ixrxs = ix.*rxs; iwrwz = iw.*rwz; rr = iwrwz - ixrxs; if 0 iHd = smwf(d,As2); % smwf is a fast smw for the specific form used here dx = iHd*rr; else % iHd = inv(diag(d)+As2'*As2); dx = (diag(d)+As2'*As2)\rr; end ds = -ixs.*dx - ixrxs; dw = -dx; dz = -iwz.*dw - iwrwz; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Compute stepsize function alpha = stepsize(dx,ds,dw,dz,x,s,w,z); i = find(ds<0); as = min(-s(i)./ds(i)); i = find(dw<0); aw = min(-w(i)./dw(i)); i = find(dx<0); ax = min(-x(i)./dx(i)); i = find(dz<0); az = min(-z(i)./dz(i)); alpha = min([aw ax as az 1]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % csm.m compute symmetric matrix from X = B*B' function X = csm(B); [m,n] = size(B); for i=1:m-1 for j=i+1:m X(i,j) = B(i,:)*B(j,:)'; X(j,i) = X(i,j); end; end; for i = 1:m; X(i,i) = B(i,:)*B(i,:)'; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % smwf.m computes the inverse of (A + B'B) using Sherman-Morrison-Woodbury formula % Fast version for specific matrices. % where A is a diagonal matrix, but designated only by a vector % i.e. the input is the vector of the diagonal % B is non-square matrices % H = inv(A) - inv(A)B'*inv(B*inv(A)B' + I)*B*inv(A); % function H = smwf(A,B); [k,m] = size(B); iA = 1./A; iAB = zeros(m,k); BiA = zeros(k,m); BAB = zeros(k); for i = 1:k iAB(:,i) = iA.*B(i,:)'; end; for i = 1:k BiA(i,:) = B(i,:).*iA'; end; for i=1:k-1 for j=i+1:k BAB(i,j) = B(i,:)*iAB(:,j); BAB(j,i) = BAB(i,j); end; end; for i = 1:k; BAB(i,i) = B(i,:)*iAB(:,i); end; Q = BAB; for i = 1:k; Q(i,i) = Q(i,i) + 1; end QBA = Q\iAB'; for i=1:m-1 for j=i+1:m ABQBA(i,j) = iAB(i,:)*QBA(:,j); ABQBA(j,i) = ABQBA(i,j); end; end; for i = 1:m; ABQBA(i,i) = iAB(i,:)*QBA(:,i); end H = -ABQBA; for i = 1:m H(i,i) = iA(i) + H(i,i); end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
Control_GUI.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/Scheduling design/Scheduling design ACC/Control_GUI.m
37,417
utf_8
385e097e99302c6cc85b41c7f39c5a64
function Control_GUI modelName = 'F16ASYM_Controlled'; % Do some simple error checking on the input if ~localValidateInputs(modelName) estr = sprintf('The model %s.mdl cannot be found.',modelName); errordlg(estr,'Model not found error','modal'); return end % Do some simple error checking on varargout error(nargoutchk(0,1,nargout)); % Create the UI if one does not already exist. % Bring the UI to the front if one does already exist. hfi = findall(0,'Name',sprintf('UI for faults and damages at %s.mdl',modelName)); if isempty(hfi) % Create a UI hfi = localCreateUI(modelName); figure(hfi); else % Bring it to the front figure(hfi); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Function to create the user interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hf = localCreateUI(modelName) % Create the figure, setting appropriate properties hf = figure('Toolbar','none',... 'MenuBar','none',... 'IntegerHandle','off',... 'Units','normalized',... 'Resize','on',... 'NumberTitle','off',... 'HandleVisibility','callback',... 'Name',sprintf('UI for faults and damages at %s.mdl',modelName),... 'CloseRequestFcn',@localCloseRequestFcn,... 'Visible','off'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Main Panel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MDL = 'F16ASYM_Controlled'; global oversize_param oversize_param=0; Main = uipanel('Parent',hf,'Title','Main Panel','FontSize',20,... 'BackgroundColor','white','Units','normalized',... 'Position',[0.02 -oversize_param 0.95 1+oversize_param]); uicontrol('Style','Slider','Parent',hf,... % Slider 'Units','normalized','Position',[0.97 0 0.03 1],... 'Value',1,'Callback',{@slider_callback1,Main}); uicontrol('Parent',Main,... 'Style','text','FontSize',16,... 'Units','normalized',... 'Position',[0 1-0.06 0.95 0.05],... 'String','This GUI allows the user to inputs faults, changes in control surfaces and airframe, as well as, control the learning proces of ANNs',... 'Backgroundcolor',[1 1 1]); %% Control surfaces panel_control = uipanel('Parent',Main,'Title','Control surfaces','FontSize',12, 'Units','normalized','Position',[.02 .25 .45 .7]); % Blockades panel_control_blockades = uipanel('Parent',panel_control,'Title','Blockades','FontSize',10, 'Units','normalized','Position',[.05 .5 .9 .49]); string={'Elev_L','Elev_R','Ail_L','Ail_R','Rudd','LEF_L','LEF_R'}; panel_control_blockades_at = uipanel('Parent',panel_control_blockades,'Title','Blockade at:','FontSize',10, 'Units','normalized','Position',[.01 .4 .98 .55]); % Individual for i=1:7 uicontrol('Parent',panel_control_blockades_at,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.15]); Val_h{i} = uicontrol('Parent',panel_control_blockades_at,'Style','edit','FontSize',10,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/7*(i-1),0.5,0.95/7,0.3]); uicontrol('Parent',panel_control_blockades_at,'Style','togglebutton','Tag',['Block_at',num2str(i)],'String','Block','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.3],... 'Callback',{@Blockat_CurrentValue_Callback,Val_h{i},i}) ; end panel_control_blockades_now = uipanel('Parent',panel_control_blockades,'Title','Blockade NOW','FontSize',10,'Units','normalized','Position',[.01 .02 .98 .36]); % Individual for i=1:7 uicontrol('Parent',panel_control_blockades_now,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.2]); uicontrol('Parent',panel_control_blockades_now,'Style','togglebutton','Tag',['Block_now',num2str(i)],'String','Block now','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.6],... 'Callback',{@Blocknow_CurrentValue_Callback,i}) ; end % Floating or loss panel_control_Float = uipanel('Parent',panel_control,'Title','Floating or loss','FontSize',10,'Units','normalized','Position',[.05 .30 .9 .17]); for i=1:7 uicontrol('Parent',panel_control_Float,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.2]); uicontrol('Parent',panel_control_Float,'Style','togglebutton','Tag',['Float',num2str(i)],'String','Lose or float','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.6],... 'Callback',{@Float_loss_Callback,i}) ; end % Lose effectivenes or surface panel_control_Area = uipanel('Parent',panel_control,'Title','Loss effectiveness or Surface: Input % lost','FontSize',10,'Units','normalized','Position',[.05 .02 .9 .27]); for i=1:7 uicontrol('Parent',panel_control_Area,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7-0.02,0.15]); Val_h{i} = uicontrol('Parent',panel_control_Area,'Style','edit','FontSize',10,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/7*(i-1),0.5,0.95/7-0.03,0.3]); uicontrol('Parent',panel_control_Area,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/7*(i)-0.03,0.4,0.03,0.3]); uicontrol('Parent',panel_control_Area,'Style','togglebutton','Tag',['Block_at',num2str(i)],'String','Affect','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.3],... 'Callback',{@Loss_area_Callback,Val_h{i},i}) ; end %% Structural changes panel_control2 = uipanel('Parent',Main,'Title','Airframe and global changes','FontSize',12,'Units','normalized','Position',[.5 .25 .48 .7]); panel_control_massprop = uipanel('Parent',panel_control2,'Title','Mass properties changes','FontSize',10,... 'Units','normalized','Position',[.05 .57 .9 .4]); Val_h={}; % mass and xcg i=1; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta mass(%) of 9295.4kg','Units','normalized','Position',[0.02+0.95/2*(i-1),0.8,0.95/2-0.03,0.15]); Val_h{1}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/2*(i-1),0.5,0.95/2-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/2*(i)-0.03,0.55,0.03,0.15]); i=2; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','x_cg position in% of CMA(0.3%)','Units','normalized','Position',[0.02+0.95/2*(i-1),0.8,0.95/2-0.03,0.15]); Val_h{2}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0.3','Units','normalized','Position',[0.02+0.95/2*(i-1),0.5,0.95/2-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/2*(i)-0.03,0.55,0.03,0.15]); % Moments of inertia i=1; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_y(%) of 75673.6kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{3}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=2; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_xz(%) of 1331.4kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{4}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',12,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=3; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_z(%) of 85552.1kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{5}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=4; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_x(%) of 12874.8kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{6}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); panel_control_AeroAndArea = uipanel('Parent',panel_control2,'Title','Aerodynamics and surfaces changes','FontSize',10,... 'Units','normalized','Position',[.05 .17 .9 .4]); % Surface changes i=1; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Left wing surface loss(%) of 11.14m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{7}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); i=2; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Right wing surface loss(%) of 11.14m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{8}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',12,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); i=3; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Fin surface loss(%) of 6.56m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{9}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); % DElta coeffs i=1; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_Lift (additionally to ~0.2)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{10}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); i=2; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_Drag (additionally to ~0.036)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{11}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); i=3; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_pitch_moment (additionally to ~ - 0.054)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{12}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control2,'String','Update Changes','FontSize',16,'Units','normalized',... 'Position',[0.65 0.02 0.3 0.13],'Callback',{@Surf_and_Mass_changes,Val_h}); %% ANN control panel_controlANN = uipanel('Parent',Main,'Title','ANNs control','FontSize',12,'Units','normalized','Position',[.02 .02 .96 .22]); % Roll panel_control_Roll = uipanel('Parent',panel_controlANN,'Title','Roll chanel','FontSize',12,... 'Units','normalized','Position',[.01 .02 .98/4-0.01 0.95]); % Learning rate uicontrol('Parent',panel_control_Roll,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Roll_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Roll,'Tag','Roll_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Roll_learn','up'}}); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Roll_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Roll,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Roll_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Roll,'Tag','Roll_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Roll_reg','up'}}); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Roll_reg','down'}}); % Long chanel panel_control_Long = uipanel('Parent',panel_controlANN,'Title','Long chanel','FontSize',12,... 'Units','normalized','Position',[0.98/4+0.005 .02 .98/4-0.005 0.95]); % Learning rate uicontrol('Parent',panel_control_Long,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Long_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Long,'Tag','Long_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Long_learn','up'}}); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Long_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Long,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Long_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Long,'Tag','Long_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Long_reg','up'}}); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Long_reg','down'}}); % Yaw chanel panel_control_Yaw = uipanel('Parent',panel_controlANN,'Title','Yaw chanel chanel','FontSize',12,... 'Units','normalized','Position',[2*.98/4+0.005 .02 .98/4 0.95]); % Learning rate uicontrol('Parent',panel_control_Yaw,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Yaw_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Yaw,'Tag','Yaw_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Yaw_learn','up'}}); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Yaw_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Yaw,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Yaw_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Yaw,'Tag','Yaw_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Yaw_reg','up'}}); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Yaw_reg','down'}}); % Complete ANN panel_control_Com = uipanel('Parent',panel_controlANN,'Title','Complete ANN','FontSize',12,... 'Units','normalized','Position',[3*.98/4+0.01 .02 .98/4 0.95]); % Learning rate uicontrol('Parent',panel_control_Com,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'C learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Com,'Tag','C_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'C_learn','up'}}); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'C_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Com,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'C reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Com,'Tag','C_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'C_reg','up'}}); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'C_reg','down'}}); function Change_params(hObject, eventdata,handles) MDL = 'F16ASYM_Controlled'; Str_to_change= findall(get(hObject,'parent'),'Tag',handles{1}); switch handles{1} % Roll case {'Roll_learn'} Block_search = find_system(MDL, 'Name', 'Roll_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Roll_reg'} Block_search = find_system(MDL, 'Name', 'Roll_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Long case {'Long_learn'} Block_search = find_system(MDL, 'Name', 'Long_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Long_reg'} Block_search = find_system(MDL, 'Name', 'Long_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Yaw case {'Yaw_learn'} Block_search = find_system(MDL, 'Name', 'Yaw_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Yaw_reg'} Block_search = find_system(MDL, 'Name', 'Yaw_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Completed case {'C_learn'} Block_search = find_system(MDL, 'Name', 'C learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'C_reg'} Block_search = find_system(MDL, 'Name', 'C reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); end function Surf_and_Mass_changes(hObject, eventdata,handles) % Data from mdl MDL = 'F16ASYM_Controlled'; str= {'delta_mass','xcg','Delta_J','Delta_J','Delta_J','Delta_J','delta_S_L','delta_S_R','delta_S_fin','delta_coef','delta_coef','delta_coef'}; % 'delta_mass','xcg' for i=1:2 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch str{i} case {'delta_mass'} NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal)/100; case {'xcg'} NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal); end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % Delta_J Block_search = find_system([MDL,'/Faults injection'], 'Name', str{5} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); for i=3:6 NewStrVal = get(handles{i}, 'String'); Actual_val(i-2) = str2double(NewStrVal)/100; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); % 'delta_S_L','delta_S_R','delta_S_fin' for i=7:9 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal)/100; set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % delta_coef Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{10} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); for i=10:12 NewStrVal = get(handles{i}, 'String'); Actual_val(i-9) = str2double(NewStrVal); end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Loss_area_Callback(hObject, eventdata,handles, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on NewStrVal = get(handles, 'String'); Actual_val(1,num) = 1-str2double(NewStrVal)/100; set(hObject,'String','Affected'); set(Elem,'Visible','off') else Actual_val(1,num) = 1; set(hObject,'String','Affect'); set(Elem,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Float_loss_Callback(hObject, eventdata, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_now',num2str(num)]); Elem2 = findall(hf,'Tag',['Block_at',num2str(num)]); on=get(hObject, 'Value'); if on Actual_val(1,num) = 0; set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = 1; set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Blockat_CurrentValue_Callback(hObject, eventdata, handles,num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades at'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_now',num2str(num)]); Elem2 = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on NewStrVal = get(handles, 'String'); Actual_val(1,num) = str2double(NewStrVal); set(hObject,'String','Blocked'); set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = NaN; set(hObject,'String','Block'); set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Blocknow_CurrentValue_Callback(hObject, eventdata, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades now'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_at',num2str(num)]); Elem2 = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on Actual_val(1,num) = 1; set(hObject,'String','Blocked'); set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = 0; set(hObject,'String','Block now'); set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function modelExists = localValidateInputs(modelName) num = exist(modelName,'file'); if num == 4 modelExists = true; else modelExists = false; end function slider_callback1(hObject, eventdata, handles) global oversize_param val = get(hObject,'Value'); set(handles,'Position',[0.02 -oversize_param*val 0.95 1+oversize_param]) function localCloseRequestFcn(hObject,eventdata,ad) %#ok MDL = 'F16ASYM_Controlled'; % Reseting effectiveness Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); set_param(char(Block_search),'Value',['[',num2str(ones(1,7)),']']); % Blockades at Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades at'); set_param(char(Block_search),'Value',['[',num2str(ones(1,7)*NaN),']']); % Blockades now Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades now'); set_param(char(Block_search),'Value',['[',num2str(zeros(1,7)),']']); % Airframe parameters str= {'delta_mass','xcg','Delta_J','Delta_J','Delta_J','Delta_J','delta_S_L','delta_S_R','delta_S_fin','delta_coef','delta_coef','delta_coef'}; % 'delta_mass','xcg' Actual_val=[]; for i=1:2 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); switch str{i} case {'delta_mass'} Actual_val = 0; case {'xcg'} Actual_val = 0.3; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % 'delta_S_L','delta_S_R','delta_S_fin' Actual_val=[]; for i=7:9 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = 0; set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % Delta_J Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{5} ); for i=3:6 Actual_val(i-2) = 0; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); % delta_coef Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{10} ); for i=10:12 Actual_val(i-9) = 0; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); delete(hObject) % close all Force
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
FE_plot.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/Scheduling design/Scheduling design ACC/FE_plot.m
2,767
utf_8
33f67ce7964a466b12f76d5a8029b6ce
function FE_plot modelName = 'F16ASYM_Controlled'; % Do some simple error checking on the input if ~localValidateInputs(modelName) estr = sprintf('The model %s.mdl cannot be found.',modelName); errordlg(estr,'Model not found error','modal'); return end % Do some simple error checking on varargout error(nargoutchk(0,1,nargout)); % Create the UI if one does not already exist. % Bring the UI to the front if one does already exist. hfi = findall(0,'Name',sprintf('Plot of Flight envelope position at %s.mdl',modelName)); if isempty(hfi) % Create a UI hfi = localCreateUI(modelName); figure(hfi); else % Bring it to the front figure(hfi); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Function to create the user interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hf = localCreateUI(modelName) % Create the figure, setting appropriate properties hf = figure('IntegerHandle','off',... 'Units','normalized',... 'Resize','on',... 'NumberTitle','off',... 'HandleVisibility','callback',... 'Name',sprintf('Plot of Flight envelope position at %s.mdl',modelName),... 'CloseRequestFcn',@localCloseRequestFcn,... 'Visible','off'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Main Panel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MDL = 'F16ASYM_Controlled'; Main = uipanel('Parent',hf,'Title','Flight Envelope plot','FontSize',15,... 'BackgroundColor','white','Units','normalized',... 'Position',[0.02 0.02 0.95 0.95]); % Plots and axis global hplot htext hlist AX=axes('Parent',Main,'Units','normalized ','Position',[0.1 0.1 0.85 0.85]); load('FlightEnvelope.mat') plot(AX,F_envelope.M_1g ,F_envelope.H_1g ,'r') xlabel(AX,'Mach') ylabel(AX,'Alt (m)') % PLot th epoint hold(AX) hplot=scatter(AX,0,0,'o','filled'); hChildren = get(hplot, 'Children'); set(hChildren, 'Markersize', 10) htext = text(0,0,[' YOU ';'\downarrow'],'HorizontalAlignment','Center','VerticalAlignment','Bottom','FontSize',18,'Parent', AX); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Add Listener %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Block_search = [MDL,'/Environment params Estimations/ALT_and_M_GAIN_LIST']; hlist = add_exec_event_listener(Block_search, 'PostOutputs', @localEventListener); function modelExists = localValidateInputs(modelName) num = exist(modelName,'file'); if num == 4 modelExists = true; else modelExists = false; end function localCloseRequestFcn(hObject,eventdata,ad) %#ok global hplot hlist try delete(hlist) delete(hObject) catch close all Force end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
tgear.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/Scheduling design/Scheduling design ACC/Used Functions/tgear.m
535
utf_8
f0c3d6ed53bf5e044ed13e3251d92c3b
%===================================================== % tgear.m % % Author : Ying Huo % % power command vs. thtl. relationship used % in F-16 model %===================================================== function tgear_value = tgear ( thtl ) if ( thtl <= 0.77 ) tgear_value = 64.94 * thtl; else tgear_value = 217.38 * thtl - 117.38; end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
trimfun.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/Scheduling design/Scheduling design ACC/Used Functions/trimfun.m
4,041
utf_8
908902ca2678a4efb48b714eddeca553
%===================================================== % F16 nonlinear model trim cost function % for longitudinal motion, steady level flight % (cost = sum of weighted squared state derivatives) % % Author: T. Keviczky % Date: April 29, 2002 % % Added addtional functionality. % This trim function can now trim at three % additional flight conditions % - Steady Turning Flight given turn rate % - Steady Pull-up flight - given pull-up rate % - Steady Roll - given roll rate % % Coauthor: Richard S. Russell % Date: November 7th, 2002 % % %===================================================== %%**********************************************%% % Altered to work as a trimming function % % for the HIFI F_16 Model % %%**********************************************%% function [cost, Xdot, xu] = trimfun(UX0) global phi psi p q r phi_weight theta_weight psi_weight pow global altitude velocity fi_flag_Simulink % UX0 = [throttle, elevator, beta, alpha, aileron, rudder] % Implementing limits: % Thrust limits if UX0(1) > 1 UX0(1) = 1; elseif UX0(1) < 0 UX0(1) = 0; end; % elevator limits if UX0(2) > 25 UX0(2) = 25; elseif UX0(2) < -25 UX0(2) = -25; end; % sideslip limits if (fi_flag_Simulink == 0) if UX0(3) > 45*pi/180 UX0(3) = 45*pi/180; elseif UX0(3) < -10*pi/180 UX0(3) = -10*pi/180; end elseif (fi_flag_Simulink == 1) if UX0(3) > 30*pi/180 UX0(3) = 30*pi/180; elseif UX0(3) < -20*pi/180 UX0(3) = -20*pi/180; end end % angle of attack limits if (fi_flag_Simulink == 0) if UX0(4) > 45*pi/180 UX0(4) = 45*pi/180; elseif UX0(4) < -10*pi/180 UX0(4) = -10*pi/180; end elseif (fi_flag_Simulink == 1) if UX0(4) > 90*pi/180 UX0(4) = 90*pi/180; elseif UX0(4) < -20*pi/180 UX0(4) = -20*pi/180; end end % Aileron limits if UX0(5) > 21.5 UX0(5) = 21.5; elseif UX0(5) < -21.5 UX0(5) = -21.5; end; % Rudder limits if UX0(6) > 30 UX0(6) = 30; elseif UX0(6) < -30 UX0(6) = -30; end; if (fi_flag_Simulink == 1) % Calculating qbar, ps and steady state leading edge flap deflection: % (see pg. 43 NASA report) rho0 = 1.225; tfac = 1 - 6.5e-3/288.15*altitude; temp = 288.15*tfac; if (altitude >= 11000) temp = 216.65; end; rho = rho0*(tfac.^4.2586); qbar = 0.5*rho*velocity^2; ps = 287*rho*temp; dLEF = 1.38*UX0(4)*180/pi - 9.05*qbar/ps + 1.45; elseif (fi_flag_Simulink == 0) dLEF = 0.0; end % Verify that the calculated leading edge flap % have not been violated. if (dLEF > 25) dLEF = 25; elseif (dLEF < 0) dLEF = 0; end; xu = [ 0 ... %npos (m) 0 ... %epos (m) altitude ... %altitude (m) phi*(pi/180) ... %phi (rad) UX0(4) ... %theta (rad) psi*(pi/180) ... %psi (rad) velocity ... %velocity (m/s) UX0(4) ... %alpha (rad) UX0(3) ... %beta (rad) p*(pi/180) ... %p (rad/s) q*(pi/180) ... %q (rad/s) r*(pi/180) ... %r (rad/s) tgear(UX0(1)) ... % pow UX0(1) ... %throttle (0-1) UX0(2) ... %ele (deg) UX0(5) ... %ail (deg) UX0(6) ... %rud (deg) dLEF ... %dLEF (deg) fi_flag_Simulink ...% fidelity flag ]'; OUT = feval('nlplant',xu); Xdot = OUT(1:13,1); % Create weight function weight = [ 0 ...%npos_dot 0 ...%epos_dot 5 ...%alt_dot phi_weight ...%phi_dot theta_weight ...%theta_dot psi_weight ...%psi_dot 2 ...%V_dot 10 ...%alpha_dpt 10 ...%beta_dot 10 ...%P_dot 10 ...%Q_dot 10 ...%R_dot 5 ...% pow_dot ]; cost = weight*(Xdot.*Xdot); % Mean Square to be minimized
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
Control_GUI.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/Scheduling design/Scheduling design AoA/Control_GUI.m
37,417
utf_8
385e097e99302c6cc85b41c7f39c5a64
function Control_GUI modelName = 'F16ASYM_Controlled'; % Do some simple error checking on the input if ~localValidateInputs(modelName) estr = sprintf('The model %s.mdl cannot be found.',modelName); errordlg(estr,'Model not found error','modal'); return end % Do some simple error checking on varargout error(nargoutchk(0,1,nargout)); % Create the UI if one does not already exist. % Bring the UI to the front if one does already exist. hfi = findall(0,'Name',sprintf('UI for faults and damages at %s.mdl',modelName)); if isempty(hfi) % Create a UI hfi = localCreateUI(modelName); figure(hfi); else % Bring it to the front figure(hfi); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Function to create the user interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hf = localCreateUI(modelName) % Create the figure, setting appropriate properties hf = figure('Toolbar','none',... 'MenuBar','none',... 'IntegerHandle','off',... 'Units','normalized',... 'Resize','on',... 'NumberTitle','off',... 'HandleVisibility','callback',... 'Name',sprintf('UI for faults and damages at %s.mdl',modelName),... 'CloseRequestFcn',@localCloseRequestFcn,... 'Visible','off'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Main Panel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MDL = 'F16ASYM_Controlled'; global oversize_param oversize_param=0; Main = uipanel('Parent',hf,'Title','Main Panel','FontSize',20,... 'BackgroundColor','white','Units','normalized',... 'Position',[0.02 -oversize_param 0.95 1+oversize_param]); uicontrol('Style','Slider','Parent',hf,... % Slider 'Units','normalized','Position',[0.97 0 0.03 1],... 'Value',1,'Callback',{@slider_callback1,Main}); uicontrol('Parent',Main,... 'Style','text','FontSize',16,... 'Units','normalized',... 'Position',[0 1-0.06 0.95 0.05],... 'String','This GUI allows the user to inputs faults, changes in control surfaces and airframe, as well as, control the learning proces of ANNs',... 'Backgroundcolor',[1 1 1]); %% Control surfaces panel_control = uipanel('Parent',Main,'Title','Control surfaces','FontSize',12, 'Units','normalized','Position',[.02 .25 .45 .7]); % Blockades panel_control_blockades = uipanel('Parent',panel_control,'Title','Blockades','FontSize',10, 'Units','normalized','Position',[.05 .5 .9 .49]); string={'Elev_L','Elev_R','Ail_L','Ail_R','Rudd','LEF_L','LEF_R'}; panel_control_blockades_at = uipanel('Parent',panel_control_blockades,'Title','Blockade at:','FontSize',10, 'Units','normalized','Position',[.01 .4 .98 .55]); % Individual for i=1:7 uicontrol('Parent',panel_control_blockades_at,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.15]); Val_h{i} = uicontrol('Parent',panel_control_blockades_at,'Style','edit','FontSize',10,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/7*(i-1),0.5,0.95/7,0.3]); uicontrol('Parent',panel_control_blockades_at,'Style','togglebutton','Tag',['Block_at',num2str(i)],'String','Block','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.3],... 'Callback',{@Blockat_CurrentValue_Callback,Val_h{i},i}) ; end panel_control_blockades_now = uipanel('Parent',panel_control_blockades,'Title','Blockade NOW','FontSize',10,'Units','normalized','Position',[.01 .02 .98 .36]); % Individual for i=1:7 uicontrol('Parent',panel_control_blockades_now,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.2]); uicontrol('Parent',panel_control_blockades_now,'Style','togglebutton','Tag',['Block_now',num2str(i)],'String','Block now','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.6],... 'Callback',{@Blocknow_CurrentValue_Callback,i}) ; end % Floating or loss panel_control_Float = uipanel('Parent',panel_control,'Title','Floating or loss','FontSize',10,'Units','normalized','Position',[.05 .30 .9 .17]); for i=1:7 uicontrol('Parent',panel_control_Float,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.2]); uicontrol('Parent',panel_control_Float,'Style','togglebutton','Tag',['Float',num2str(i)],'String','Lose or float','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.6],... 'Callback',{@Float_loss_Callback,i}) ; end % Lose effectivenes or surface panel_control_Area = uipanel('Parent',panel_control,'Title','Loss effectiveness or Surface: Input % lost','FontSize',10,'Units','normalized','Position',[.05 .02 .9 .27]); for i=1:7 uicontrol('Parent',panel_control_Area,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7-0.02,0.15]); Val_h{i} = uicontrol('Parent',panel_control_Area,'Style','edit','FontSize',10,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/7*(i-1),0.5,0.95/7-0.03,0.3]); uicontrol('Parent',panel_control_Area,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/7*(i)-0.03,0.4,0.03,0.3]); uicontrol('Parent',panel_control_Area,'Style','togglebutton','Tag',['Block_at',num2str(i)],'String','Affect','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.3],... 'Callback',{@Loss_area_Callback,Val_h{i},i}) ; end %% Structural changes panel_control2 = uipanel('Parent',Main,'Title','Airframe and global changes','FontSize',12,'Units','normalized','Position',[.5 .25 .48 .7]); panel_control_massprop = uipanel('Parent',panel_control2,'Title','Mass properties changes','FontSize',10,... 'Units','normalized','Position',[.05 .57 .9 .4]); Val_h={}; % mass and xcg i=1; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta mass(%) of 9295.4kg','Units','normalized','Position',[0.02+0.95/2*(i-1),0.8,0.95/2-0.03,0.15]); Val_h{1}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/2*(i-1),0.5,0.95/2-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/2*(i)-0.03,0.55,0.03,0.15]); i=2; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','x_cg position in% of CMA(0.3%)','Units','normalized','Position',[0.02+0.95/2*(i-1),0.8,0.95/2-0.03,0.15]); Val_h{2}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0.3','Units','normalized','Position',[0.02+0.95/2*(i-1),0.5,0.95/2-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/2*(i)-0.03,0.55,0.03,0.15]); % Moments of inertia i=1; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_y(%) of 75673.6kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{3}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=2; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_xz(%) of 1331.4kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{4}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',12,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=3; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_z(%) of 85552.1kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{5}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=4; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_x(%) of 12874.8kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{6}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); panel_control_AeroAndArea = uipanel('Parent',panel_control2,'Title','Aerodynamics and surfaces changes','FontSize',10,... 'Units','normalized','Position',[.05 .17 .9 .4]); % Surface changes i=1; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Left wing surface loss(%) of 11.14m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{7}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); i=2; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Right wing surface loss(%) of 11.14m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{8}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',12,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); i=3; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Fin surface loss(%) of 6.56m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{9}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); % DElta coeffs i=1; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_Lift (additionally to ~0.2)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{10}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); i=2; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_Drag (additionally to ~0.036)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{11}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); i=3; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_pitch_moment (additionally to ~ - 0.054)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{12}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control2,'String','Update Changes','FontSize',16,'Units','normalized',... 'Position',[0.65 0.02 0.3 0.13],'Callback',{@Surf_and_Mass_changes,Val_h}); %% ANN control panel_controlANN = uipanel('Parent',Main,'Title','ANNs control','FontSize',12,'Units','normalized','Position',[.02 .02 .96 .22]); % Roll panel_control_Roll = uipanel('Parent',panel_controlANN,'Title','Roll chanel','FontSize',12,... 'Units','normalized','Position',[.01 .02 .98/4-0.01 0.95]); % Learning rate uicontrol('Parent',panel_control_Roll,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Roll_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Roll,'Tag','Roll_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Roll_learn','up'}}); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Roll_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Roll,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Roll_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Roll,'Tag','Roll_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Roll_reg','up'}}); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Roll_reg','down'}}); % Long chanel panel_control_Long = uipanel('Parent',panel_controlANN,'Title','Long chanel','FontSize',12,... 'Units','normalized','Position',[0.98/4+0.005 .02 .98/4-0.005 0.95]); % Learning rate uicontrol('Parent',panel_control_Long,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Long_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Long,'Tag','Long_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Long_learn','up'}}); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Long_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Long,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Long_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Long,'Tag','Long_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Long_reg','up'}}); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Long_reg','down'}}); % Yaw chanel panel_control_Yaw = uipanel('Parent',panel_controlANN,'Title','Yaw chanel chanel','FontSize',12,... 'Units','normalized','Position',[2*.98/4+0.005 .02 .98/4 0.95]); % Learning rate uicontrol('Parent',panel_control_Yaw,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Yaw_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Yaw,'Tag','Yaw_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Yaw_learn','up'}}); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Yaw_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Yaw,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Yaw_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Yaw,'Tag','Yaw_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Yaw_reg','up'}}); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Yaw_reg','down'}}); % Complete ANN panel_control_Com = uipanel('Parent',panel_controlANN,'Title','Complete ANN','FontSize',12,... 'Units','normalized','Position',[3*.98/4+0.01 .02 .98/4 0.95]); % Learning rate uicontrol('Parent',panel_control_Com,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'C learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Com,'Tag','C_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'C_learn','up'}}); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'C_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Com,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'C reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Com,'Tag','C_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'C_reg','up'}}); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'C_reg','down'}}); function Change_params(hObject, eventdata,handles) MDL = 'F16ASYM_Controlled'; Str_to_change= findall(get(hObject,'parent'),'Tag',handles{1}); switch handles{1} % Roll case {'Roll_learn'} Block_search = find_system(MDL, 'Name', 'Roll_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Roll_reg'} Block_search = find_system(MDL, 'Name', 'Roll_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Long case {'Long_learn'} Block_search = find_system(MDL, 'Name', 'Long_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Long_reg'} Block_search = find_system(MDL, 'Name', 'Long_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Yaw case {'Yaw_learn'} Block_search = find_system(MDL, 'Name', 'Yaw_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Yaw_reg'} Block_search = find_system(MDL, 'Name', 'Yaw_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Completed case {'C_learn'} Block_search = find_system(MDL, 'Name', 'C learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'C_reg'} Block_search = find_system(MDL, 'Name', 'C reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); end function Surf_and_Mass_changes(hObject, eventdata,handles) % Data from mdl MDL = 'F16ASYM_Controlled'; str= {'delta_mass','xcg','Delta_J','Delta_J','Delta_J','Delta_J','delta_S_L','delta_S_R','delta_S_fin','delta_coef','delta_coef','delta_coef'}; % 'delta_mass','xcg' for i=1:2 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch str{i} case {'delta_mass'} NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal)/100; case {'xcg'} NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal); end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % Delta_J Block_search = find_system([MDL,'/Faults injection'], 'Name', str{5} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); for i=3:6 NewStrVal = get(handles{i}, 'String'); Actual_val(i-2) = str2double(NewStrVal)/100; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); % 'delta_S_L','delta_S_R','delta_S_fin' for i=7:9 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal)/100; set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % delta_coef Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{10} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); for i=10:12 NewStrVal = get(handles{i}, 'String'); Actual_val(i-9) = str2double(NewStrVal); end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Loss_area_Callback(hObject, eventdata,handles, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on NewStrVal = get(handles, 'String'); Actual_val(1,num) = 1-str2double(NewStrVal)/100; set(hObject,'String','Affected'); set(Elem,'Visible','off') else Actual_val(1,num) = 1; set(hObject,'String','Affect'); set(Elem,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Float_loss_Callback(hObject, eventdata, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_now',num2str(num)]); Elem2 = findall(hf,'Tag',['Block_at',num2str(num)]); on=get(hObject, 'Value'); if on Actual_val(1,num) = 0; set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = 1; set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Blockat_CurrentValue_Callback(hObject, eventdata, handles,num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades at'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_now',num2str(num)]); Elem2 = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on NewStrVal = get(handles, 'String'); Actual_val(1,num) = str2double(NewStrVal); set(hObject,'String','Blocked'); set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = NaN; set(hObject,'String','Block'); set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Blocknow_CurrentValue_Callback(hObject, eventdata, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades now'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_at',num2str(num)]); Elem2 = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on Actual_val(1,num) = 1; set(hObject,'String','Blocked'); set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = 0; set(hObject,'String','Block now'); set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function modelExists = localValidateInputs(modelName) num = exist(modelName,'file'); if num == 4 modelExists = true; else modelExists = false; end function slider_callback1(hObject, eventdata, handles) global oversize_param val = get(hObject,'Value'); set(handles,'Position',[0.02 -oversize_param*val 0.95 1+oversize_param]) function localCloseRequestFcn(hObject,eventdata,ad) %#ok MDL = 'F16ASYM_Controlled'; % Reseting effectiveness Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); set_param(char(Block_search),'Value',['[',num2str(ones(1,7)),']']); % Blockades at Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades at'); set_param(char(Block_search),'Value',['[',num2str(ones(1,7)*NaN),']']); % Blockades now Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades now'); set_param(char(Block_search),'Value',['[',num2str(zeros(1,7)),']']); % Airframe parameters str= {'delta_mass','xcg','Delta_J','Delta_J','Delta_J','Delta_J','delta_S_L','delta_S_R','delta_S_fin','delta_coef','delta_coef','delta_coef'}; % 'delta_mass','xcg' Actual_val=[]; for i=1:2 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); switch str{i} case {'delta_mass'} Actual_val = 0; case {'xcg'} Actual_val = 0.3; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % 'delta_S_L','delta_S_R','delta_S_fin' Actual_val=[]; for i=7:9 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = 0; set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % Delta_J Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{5} ); for i=3:6 Actual_val(i-2) = 0; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); % delta_coef Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{10} ); for i=10:12 Actual_val(i-9) = 0; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); delete(hObject) % close all Force
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
FE_plot.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/Scheduling design/Scheduling design AoA/FE_plot.m
2,767
utf_8
33f67ce7964a466b12f76d5a8029b6ce
function FE_plot modelName = 'F16ASYM_Controlled'; % Do some simple error checking on the input if ~localValidateInputs(modelName) estr = sprintf('The model %s.mdl cannot be found.',modelName); errordlg(estr,'Model not found error','modal'); return end % Do some simple error checking on varargout error(nargoutchk(0,1,nargout)); % Create the UI if one does not already exist. % Bring the UI to the front if one does already exist. hfi = findall(0,'Name',sprintf('Plot of Flight envelope position at %s.mdl',modelName)); if isempty(hfi) % Create a UI hfi = localCreateUI(modelName); figure(hfi); else % Bring it to the front figure(hfi); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Function to create the user interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hf = localCreateUI(modelName) % Create the figure, setting appropriate properties hf = figure('IntegerHandle','off',... 'Units','normalized',... 'Resize','on',... 'NumberTitle','off',... 'HandleVisibility','callback',... 'Name',sprintf('Plot of Flight envelope position at %s.mdl',modelName),... 'CloseRequestFcn',@localCloseRequestFcn,... 'Visible','off'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Main Panel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MDL = 'F16ASYM_Controlled'; Main = uipanel('Parent',hf,'Title','Flight Envelope plot','FontSize',15,... 'BackgroundColor','white','Units','normalized',... 'Position',[0.02 0.02 0.95 0.95]); % Plots and axis global hplot htext hlist AX=axes('Parent',Main,'Units','normalized ','Position',[0.1 0.1 0.85 0.85]); load('FlightEnvelope.mat') plot(AX,F_envelope.M_1g ,F_envelope.H_1g ,'r') xlabel(AX,'Mach') ylabel(AX,'Alt (m)') % PLot th epoint hold(AX) hplot=scatter(AX,0,0,'o','filled'); hChildren = get(hplot, 'Children'); set(hChildren, 'Markersize', 10) htext = text(0,0,[' YOU ';'\downarrow'],'HorizontalAlignment','Center','VerticalAlignment','Bottom','FontSize',18,'Parent', AX); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Add Listener %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Block_search = [MDL,'/Environment params Estimations/ALT_and_M_GAIN_LIST']; hlist = add_exec_event_listener(Block_search, 'PostOutputs', @localEventListener); function modelExists = localValidateInputs(modelName) num = exist(modelName,'file'); if num == 4 modelExists = true; else modelExists = false; end function localCloseRequestFcn(hObject,eventdata,ad) %#ok global hplot hlist try delete(hlist) delete(hObject) catch close all Force end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
tgear.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/Scheduling design/Scheduling design AoA/Used Functions/tgear.m
535
utf_8
f0c3d6ed53bf5e044ed13e3251d92c3b
%===================================================== % tgear.m % % Author : Ying Huo % % power command vs. thtl. relationship used % in F-16 model %===================================================== function tgear_value = tgear ( thtl ) if ( thtl <= 0.77 ) tgear_value = 64.94 * thtl; else tgear_value = 217.38 * thtl - 117.38; end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
trimfun.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/Scheduling design/Scheduling design AoA/Used Functions/trimfun.m
4,041
utf_8
908902ca2678a4efb48b714eddeca553
%===================================================== % F16 nonlinear model trim cost function % for longitudinal motion, steady level flight % (cost = sum of weighted squared state derivatives) % % Author: T. Keviczky % Date: April 29, 2002 % % Added addtional functionality. % This trim function can now trim at three % additional flight conditions % - Steady Turning Flight given turn rate % - Steady Pull-up flight - given pull-up rate % - Steady Roll - given roll rate % % Coauthor: Richard S. Russell % Date: November 7th, 2002 % % %===================================================== %%**********************************************%% % Altered to work as a trimming function % % for the HIFI F_16 Model % %%**********************************************%% function [cost, Xdot, xu] = trimfun(UX0) global phi psi p q r phi_weight theta_weight psi_weight pow global altitude velocity fi_flag_Simulink % UX0 = [throttle, elevator, beta, alpha, aileron, rudder] % Implementing limits: % Thrust limits if UX0(1) > 1 UX0(1) = 1; elseif UX0(1) < 0 UX0(1) = 0; end; % elevator limits if UX0(2) > 25 UX0(2) = 25; elseif UX0(2) < -25 UX0(2) = -25; end; % sideslip limits if (fi_flag_Simulink == 0) if UX0(3) > 45*pi/180 UX0(3) = 45*pi/180; elseif UX0(3) < -10*pi/180 UX0(3) = -10*pi/180; end elseif (fi_flag_Simulink == 1) if UX0(3) > 30*pi/180 UX0(3) = 30*pi/180; elseif UX0(3) < -20*pi/180 UX0(3) = -20*pi/180; end end % angle of attack limits if (fi_flag_Simulink == 0) if UX0(4) > 45*pi/180 UX0(4) = 45*pi/180; elseif UX0(4) < -10*pi/180 UX0(4) = -10*pi/180; end elseif (fi_flag_Simulink == 1) if UX0(4) > 90*pi/180 UX0(4) = 90*pi/180; elseif UX0(4) < -20*pi/180 UX0(4) = -20*pi/180; end end % Aileron limits if UX0(5) > 21.5 UX0(5) = 21.5; elseif UX0(5) < -21.5 UX0(5) = -21.5; end; % Rudder limits if UX0(6) > 30 UX0(6) = 30; elseif UX0(6) < -30 UX0(6) = -30; end; if (fi_flag_Simulink == 1) % Calculating qbar, ps and steady state leading edge flap deflection: % (see pg. 43 NASA report) rho0 = 1.225; tfac = 1 - 6.5e-3/288.15*altitude; temp = 288.15*tfac; if (altitude >= 11000) temp = 216.65; end; rho = rho0*(tfac.^4.2586); qbar = 0.5*rho*velocity^2; ps = 287*rho*temp; dLEF = 1.38*UX0(4)*180/pi - 9.05*qbar/ps + 1.45; elseif (fi_flag_Simulink == 0) dLEF = 0.0; end % Verify that the calculated leading edge flap % have not been violated. if (dLEF > 25) dLEF = 25; elseif (dLEF < 0) dLEF = 0; end; xu = [ 0 ... %npos (m) 0 ... %epos (m) altitude ... %altitude (m) phi*(pi/180) ... %phi (rad) UX0(4) ... %theta (rad) psi*(pi/180) ... %psi (rad) velocity ... %velocity (m/s) UX0(4) ... %alpha (rad) UX0(3) ... %beta (rad) p*(pi/180) ... %p (rad/s) q*(pi/180) ... %q (rad/s) r*(pi/180) ... %r (rad/s) tgear(UX0(1)) ... % pow UX0(1) ... %throttle (0-1) UX0(2) ... %ele (deg) UX0(5) ... %ail (deg) UX0(6) ... %rud (deg) dLEF ... %dLEF (deg) fi_flag_Simulink ...% fidelity flag ]'; OUT = feval('nlplant',xu); Xdot = OUT(1:13,1); % Create weight function weight = [ 0 ...%npos_dot 0 ...%epos_dot 5 ...%alt_dot phi_weight ...%phi_dot theta_weight ...%theta_dot psi_weight ...%psi_dot 2 ...%V_dot 10 ...%alpha_dpt 10 ...%beta_dot 10 ...%P_dot 10 ...%Q_dot 10 ...%R_dot 5 ...% pow_dot ]; cost = weight*(Xdot.*Xdot); % Mean Square to be minimized
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
Control_GUI.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/7dof FCS Development/Control_GUI.m
37,417
utf_8
385e097e99302c6cc85b41c7f39c5a64
function Control_GUI modelName = 'F16ASYM_Controlled'; % Do some simple error checking on the input if ~localValidateInputs(modelName) estr = sprintf('The model %s.mdl cannot be found.',modelName); errordlg(estr,'Model not found error','modal'); return end % Do some simple error checking on varargout error(nargoutchk(0,1,nargout)); % Create the UI if one does not already exist. % Bring the UI to the front if one does already exist. hfi = findall(0,'Name',sprintf('UI for faults and damages at %s.mdl',modelName)); if isempty(hfi) % Create a UI hfi = localCreateUI(modelName); figure(hfi); else % Bring it to the front figure(hfi); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Function to create the user interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hf = localCreateUI(modelName) % Create the figure, setting appropriate properties hf = figure('Toolbar','none',... 'MenuBar','none',... 'IntegerHandle','off',... 'Units','normalized',... 'Resize','on',... 'NumberTitle','off',... 'HandleVisibility','callback',... 'Name',sprintf('UI for faults and damages at %s.mdl',modelName),... 'CloseRequestFcn',@localCloseRequestFcn,... 'Visible','off'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Main Panel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MDL = 'F16ASYM_Controlled'; global oversize_param oversize_param=0; Main = uipanel('Parent',hf,'Title','Main Panel','FontSize',20,... 'BackgroundColor','white','Units','normalized',... 'Position',[0.02 -oversize_param 0.95 1+oversize_param]); uicontrol('Style','Slider','Parent',hf,... % Slider 'Units','normalized','Position',[0.97 0 0.03 1],... 'Value',1,'Callback',{@slider_callback1,Main}); uicontrol('Parent',Main,... 'Style','text','FontSize',16,... 'Units','normalized',... 'Position',[0 1-0.06 0.95 0.05],... 'String','This GUI allows the user to inputs faults, changes in control surfaces and airframe, as well as, control the learning proces of ANNs',... 'Backgroundcolor',[1 1 1]); %% Control surfaces panel_control = uipanel('Parent',Main,'Title','Control surfaces','FontSize',12, 'Units','normalized','Position',[.02 .25 .45 .7]); % Blockades panel_control_blockades = uipanel('Parent',panel_control,'Title','Blockades','FontSize',10, 'Units','normalized','Position',[.05 .5 .9 .49]); string={'Elev_L','Elev_R','Ail_L','Ail_R','Rudd','LEF_L','LEF_R'}; panel_control_blockades_at = uipanel('Parent',panel_control_blockades,'Title','Blockade at:','FontSize',10, 'Units','normalized','Position',[.01 .4 .98 .55]); % Individual for i=1:7 uicontrol('Parent',panel_control_blockades_at,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.15]); Val_h{i} = uicontrol('Parent',panel_control_blockades_at,'Style','edit','FontSize',10,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/7*(i-1),0.5,0.95/7,0.3]); uicontrol('Parent',panel_control_blockades_at,'Style','togglebutton','Tag',['Block_at',num2str(i)],'String','Block','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.3],... 'Callback',{@Blockat_CurrentValue_Callback,Val_h{i},i}) ; end panel_control_blockades_now = uipanel('Parent',panel_control_blockades,'Title','Blockade NOW','FontSize',10,'Units','normalized','Position',[.01 .02 .98 .36]); % Individual for i=1:7 uicontrol('Parent',panel_control_blockades_now,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.2]); uicontrol('Parent',panel_control_blockades_now,'Style','togglebutton','Tag',['Block_now',num2str(i)],'String','Block now','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.6],... 'Callback',{@Blocknow_CurrentValue_Callback,i}) ; end % Floating or loss panel_control_Float = uipanel('Parent',panel_control,'Title','Floating or loss','FontSize',10,'Units','normalized','Position',[.05 .30 .9 .17]); for i=1:7 uicontrol('Parent',panel_control_Float,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7,0.2]); uicontrol('Parent',panel_control_Float,'Style','togglebutton','Tag',['Float',num2str(i)],'String','Lose or float','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.6],... 'Callback',{@Float_loss_Callback,i}) ; end % Lose effectivenes or surface panel_control_Area = uipanel('Parent',panel_control,'Title','Loss effectiveness or Surface: Input % lost','FontSize',10,'Units','normalized','Position',[.05 .02 .9 .27]); for i=1:7 uicontrol('Parent',panel_control_Area,'Style','text','FontSize',10,'BackgroundColor','white','String',string{i},'Units','normalized','Position',[0.02+0.95/7*(i-1),0.8,0.95/7-0.02,0.15]); Val_h{i} = uicontrol('Parent',panel_control_Area,'Style','edit','FontSize',10,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/7*(i-1),0.5,0.95/7-0.03,0.3]); uicontrol('Parent',panel_control_Area,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/7*(i)-0.03,0.4,0.03,0.3]); uicontrol('Parent',panel_control_Area,'Style','togglebutton','Tag',['Block_at',num2str(i)],'String','Affect','Units','normalized','Position',[0.02+0.95/7*(i-1),0.1,0.95/7,0.3],... 'Callback',{@Loss_area_Callback,Val_h{i},i}) ; end %% Structural changes panel_control2 = uipanel('Parent',Main,'Title','Airframe and global changes','FontSize',12,'Units','normalized','Position',[.5 .25 .48 .7]); panel_control_massprop = uipanel('Parent',panel_control2,'Title','Mass properties changes','FontSize',10,... 'Units','normalized','Position',[.05 .57 .9 .4]); Val_h={}; % mass and xcg i=1; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta mass(%) of 9295.4kg','Units','normalized','Position',[0.02+0.95/2*(i-1),0.8,0.95/2-0.03,0.15]); Val_h{1}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/2*(i-1),0.5,0.95/2-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/2*(i)-0.03,0.55,0.03,0.15]); i=2; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','x_cg position in% of CMA(0.3%)','Units','normalized','Position',[0.02+0.95/2*(i-1),0.8,0.95/2-0.03,0.15]); Val_h{2}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0.3','Units','normalized','Position',[0.02+0.95/2*(i-1),0.5,0.95/2-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/2*(i)-0.03,0.55,0.03,0.15]); % Moments of inertia i=1; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_y(%) of 75673.6kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{3}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=2; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_xz(%) of 1331.4kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{4}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',12,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=3; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_z(%) of 85552.1kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{5}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); i=4; uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta J_x(%) of 12874.8kg.m^2','Units','normalized','Position',[0.02+0.95/4*(i-1),0.3,0.95/4-0.03,0.2]); Val_h{6}=uicontrol('Parent',panel_control_massprop,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/4*(i-1),0.0,0.95/4-0.03,0.3]); uicontrol('Parent',panel_control_massprop,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/4*(i)-0.03,0.05,0.03,0.15]); panel_control_AeroAndArea = uipanel('Parent',panel_control2,'Title','Aerodynamics and surfaces changes','FontSize',10,... 'Units','normalized','Position',[.05 .17 .9 .4]); % Surface changes i=1; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Left wing surface loss(%) of 11.14m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{7}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); i=2; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Right wing surface loss(%) of 11.14m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{8}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',12,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); i=3; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Fin surface loss(%) of 6.56m^2','Units','normalized','Position',[0.02+0.95/3*(i-1),0.75,0.95/3-0.03,0.2]); Val_h{9}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.5,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'String','%','Units','normalized','Position',[0.02+0.95/3*(i)-0.03,0.55,0.03,0.15]); % DElta coeffs i=1; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_Lift (additionally to ~0.2)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{10}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); i=2; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_Drag (additionally to ~0.036)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{11}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); i=3; uicontrol('Parent',panel_control_AeroAndArea,'Style','text','FontSize',10,'BackgroundColor','white','String','Delta C_pitch_moment (additionally to ~ - 0.054)','Units','normalized','Position',[0.02+0.95/3*(i-1),0.3,0.95/3-0.03,0.2]); Val_h{12}=uicontrol('Parent',panel_control_AeroAndArea,'Style','edit','FontSize',12,'BackgroundColor','white','String','0','Units','normalized','Position',[0.02+0.95/3*(i-1),0.0,0.95/3-0.03,0.3]); uicontrol('Parent',panel_control2,'String','Update Changes','FontSize',16,'Units','normalized',... 'Position',[0.65 0.02 0.3 0.13],'Callback',{@Surf_and_Mass_changes,Val_h}); %% ANN control panel_controlANN = uipanel('Parent',Main,'Title','ANNs control','FontSize',12,'Units','normalized','Position',[.02 .02 .96 .22]); % Roll panel_control_Roll = uipanel('Parent',panel_controlANN,'Title','Roll chanel','FontSize',12,... 'Units','normalized','Position',[.01 .02 .98/4-0.01 0.95]); % Learning rate uicontrol('Parent',panel_control_Roll,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Roll_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Roll,'Tag','Roll_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Roll_learn','up'}}); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Roll_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Roll,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Roll_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Roll,'Tag','Roll_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Roll_reg','up'}}); uicontrol('Parent',panel_control_Roll,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Roll_reg','down'}}); % Long chanel panel_control_Long = uipanel('Parent',panel_controlANN,'Title','Long chanel','FontSize',12,... 'Units','normalized','Position',[0.98/4+0.005 .02 .98/4-0.005 0.95]); % Learning rate uicontrol('Parent',panel_control_Long,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Long_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Long,'Tag','Long_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Long_learn','up'}}); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Long_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Long,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Long_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Long,'Tag','Long_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Long_reg','up'}}); uicontrol('Parent',panel_control_Long,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Long_reg','down'}}); % Yaw chanel panel_control_Yaw = uipanel('Parent',panel_controlANN,'Title','Yaw chanel chanel','FontSize',12,... 'Units','normalized','Position',[2*.98/4+0.005 .02 .98/4 0.95]); % Learning rate uicontrol('Parent',panel_control_Yaw,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Yaw_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Yaw,'Tag','Yaw_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'Yaw_learn','up'}}); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'Yaw_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Yaw,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'Yaw_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Yaw,'Tag','Yaw_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'Yaw_reg','up'}}); uicontrol('Parent',panel_control_Yaw,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'Yaw_reg','down'}}); % Complete ANN panel_control_Com = uipanel('Parent',panel_controlANN,'Title','Complete ANN','FontSize',12,... 'Units','normalized','Position',[3*.98/4+0.01 .02 .98/4 0.95]); % Learning rate uicontrol('Parent',panel_control_Com,'Style','text','FontSize',11,'BackgroundColor','white','String','Learning Rate (~20)','Units','normalized',... 'Position',[0.02 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'C learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Com,'Tag','C_learn','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.28 .35 .15 0.25]); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Speed-up','Units','normalized',... 'Position',[0.02 0.43 0.25 0.35],'Callback',{@Change_params,{'C_learn','up'}}); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Slow-down','Units','normalized',... 'Position',[0.02 0.05 0.25 0.35],'Callback',{@Change_params,{'C_learn','down'}}); % Regularization param uicontrol('Parent',panel_control_Com,'Style','text','FontSize',11,'BackgroundColor','white','String','Reg. Param (~1)','Units','normalized',... 'Position',[0.52 .82 .45 0.22]); Block_search = find_system(MDL, 'Name', 'C reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); uicontrol('Parent',panel_control_Com,'Tag','C_reg','Style','text','FontSize',14,'BackgroundColor','white','String',Actual_val,'Units','normalized',... 'Position',[0.78 .35 .15 0.25]); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Underfit','Units','normalized',... 'Position',[0.52 0.43 0.25 0.35],'Callback',{@Change_params,{'C_reg','up'}}); uicontrol('Parent',panel_control_Com,'FontSize',10,'String','Overfit','Units','normalized',... 'Position',[0.52 0.05 0.25 0.35],'Callback',{@Change_params,{'C_reg','down'}}); function Change_params(hObject, eventdata,handles) MDL = 'F16ASYM_Controlled'; Str_to_change= findall(get(hObject,'parent'),'Tag',handles{1}); switch handles{1} % Roll case {'Roll_learn'} Block_search = find_system(MDL, 'Name', 'Roll_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Roll_reg'} Block_search = find_system(MDL, 'Name', 'Roll_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Long case {'Long_learn'} Block_search = find_system(MDL, 'Name', 'Long_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Long_reg'} Block_search = find_system(MDL, 'Name', 'Long_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Yaw case {'Yaw_learn'} Block_search = find_system(MDL, 'Name', 'Yaw_learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'Yaw_reg'} Block_search = find_system(MDL, 'Name', 'Yaw_reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); % Completed case {'C_learn'} Block_search = find_system(MDL, 'Name', 'C learning rate','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); case{'C_reg'} Block_search = find_system(MDL, 'Name', 'C reg param','Blocktype','Constant'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch handles{2} case {'up'} Actual_val = Actual_val+0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); case {'down'} Actual_val = Actual_val-0.1; set_param(char(Block_search),'Value',num2str(Actual_val)); end Actual_val = get_param(Block_search,'Value'); set(Str_to_change,'String',Actual_val); end function Surf_and_Mass_changes(hObject, eventdata,handles) % Data from mdl MDL = 'F16ASYM_Controlled'; str= {'delta_mass','xcg','Delta_J','Delta_J','Delta_J','Delta_J','delta_S_L','delta_S_R','delta_S_fin','delta_coef','delta_coef','delta_coef'}; % 'delta_mass','xcg' for i=1:2 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); switch str{i} case {'delta_mass'} NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal)/100; case {'xcg'} NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal); end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % Delta_J Block_search = find_system([MDL,'/Faults injection'], 'Name', str{5} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); for i=3:6 NewStrVal = get(handles{i}, 'String'); Actual_val(i-2) = str2double(NewStrVal)/100; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); % 'delta_S_L','delta_S_R','delta_S_fin' for i=7:9 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); NewStrVal = get(handles{i}, 'String'); Actual_val = str2double(NewStrVal)/100; set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % delta_coef Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{10} ); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); for i=10:12 NewStrVal = get(handles{i}, 'String'); Actual_val(i-9) = str2double(NewStrVal); end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Loss_area_Callback(hObject, eventdata,handles, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on NewStrVal = get(handles, 'String'); Actual_val(1,num) = 1-str2double(NewStrVal)/100; set(hObject,'String','Affected'); set(Elem,'Visible','off') else Actual_val(1,num) = 1; set(hObject,'String','Affect'); set(Elem,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Float_loss_Callback(hObject, eventdata, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_now',num2str(num)]); Elem2 = findall(hf,'Tag',['Block_at',num2str(num)]); on=get(hObject, 'Value'); if on Actual_val(1,num) = 0; set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = 1; set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Blockat_CurrentValue_Callback(hObject, eventdata, handles,num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades at'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_now',num2str(num)]); Elem2 = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on NewStrVal = get(handles, 'String'); Actual_val(1,num) = str2double(NewStrVal); set(hObject,'String','Blocked'); set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = NaN; set(hObject,'String','Block'); set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function Blocknow_CurrentValue_Callback(hObject, eventdata, num) % Data from mdl MDL = 'F16ASYM_Controlled'; Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades now'); Actual_val = get_param(Block_search,'Value'); Actual_val = eval(char(Actual_val)); % Disappear the other blocking option hf = get(hObject,'parent'); hf = get(hf,'parent');hf = get(hf,'parent');hf = get(hf,'parent'); Elem = findall(hf,'Tag',['Block_at',num2str(num)]); Elem2 = findall(hf,'Tag',['Float',num2str(num)]); on=get(hObject, 'Value'); if on Actual_val(1,num) = 1; set(hObject,'String','Blocked'); set(Elem,'Visible','off') set(Elem2,'Visible','off') else Actual_val(1,num) = 0; set(hObject,'String','Block now'); set(Elem,'Visible','on') set(Elem2,'Visible','on') end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); function modelExists = localValidateInputs(modelName) num = exist(modelName,'file'); if num == 4 modelExists = true; else modelExists = false; end function slider_callback1(hObject, eventdata, handles) global oversize_param val = get(hObject,'Value'); set(handles,'Position',[0.02 -oversize_param*val 0.95 1+oversize_param]) function localCloseRequestFcn(hObject,eventdata,ad) %#ok MDL = 'F16ASYM_Controlled'; % Reseting effectiveness Block_search = find_system([MDL,'/Faults injection'], 'Name', 'effectiveness'); set_param(char(Block_search),'Value',['[',num2str(ones(1,7)),']']); % Blockades at Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades at'); set_param(char(Block_search),'Value',['[',num2str(ones(1,7)*NaN),']']); % Blockades now Block_search = find_system([MDL,'/Faults injection'], 'Name', 'Blockades now'); set_param(char(Block_search),'Value',['[',num2str(zeros(1,7)),']']); % Airframe parameters str= {'delta_mass','xcg','Delta_J','Delta_J','Delta_J','Delta_J','delta_S_L','delta_S_R','delta_S_fin','delta_coef','delta_coef','delta_coef'}; % 'delta_mass','xcg' Actual_val=[]; for i=1:2 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); switch str{i} case {'delta_mass'} Actual_val = 0; case {'xcg'} Actual_val = 0.3; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % 'delta_S_L','delta_S_R','delta_S_fin' Actual_val=[]; for i=7:9 Block_search = find_system([MDL,'/Faults injection'], 'Name', str{i} ); Actual_val = 0; set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); end % Delta_J Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{5} ); for i=3:6 Actual_val(i-2) = 0; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); % delta_coef Actual_val=[]; Block_search = find_system([MDL,'/Faults injection'], 'Name', str{10} ); for i=10:12 Actual_val(i-9) = 0; end set_param(char(Block_search),'Value',['[',num2str(Actual_val),']']); delete(hObject) % close all Force
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
FE_plot.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/7dof FCS Development/FE_plot.m
2,767
utf_8
33f67ce7964a466b12f76d5a8029b6ce
function FE_plot modelName = 'F16ASYM_Controlled'; % Do some simple error checking on the input if ~localValidateInputs(modelName) estr = sprintf('The model %s.mdl cannot be found.',modelName); errordlg(estr,'Model not found error','modal'); return end % Do some simple error checking on varargout error(nargoutchk(0,1,nargout)); % Create the UI if one does not already exist. % Bring the UI to the front if one does already exist. hfi = findall(0,'Name',sprintf('Plot of Flight envelope position at %s.mdl',modelName)); if isempty(hfi) % Create a UI hfi = localCreateUI(modelName); figure(hfi); else % Bring it to the front figure(hfi); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Function to create the user interface %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hf = localCreateUI(modelName) % Create the figure, setting appropriate properties hf = figure('IntegerHandle','off',... 'Units','normalized',... 'Resize','on',... 'NumberTitle','off',... 'HandleVisibility','callback',... 'Name',sprintf('Plot of Flight envelope position at %s.mdl',modelName),... 'CloseRequestFcn',@localCloseRequestFcn,... 'Visible','off'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Main Panel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MDL = 'F16ASYM_Controlled'; Main = uipanel('Parent',hf,'Title','Flight Envelope plot','FontSize',15,... 'BackgroundColor','white','Units','normalized',... 'Position',[0.02 0.02 0.95 0.95]); % Plots and axis global hplot htext hlist AX=axes('Parent',Main,'Units','normalized ','Position',[0.1 0.1 0.85 0.85]); load('FlightEnvelope.mat') plot(AX,F_envelope.M_1g ,F_envelope.H_1g ,'r') xlabel(AX,'Mach') ylabel(AX,'Alt (m)') % PLot th epoint hold(AX) hplot=scatter(AX,0,0,'o','filled'); hChildren = get(hplot, 'Children'); set(hChildren, 'Markersize', 10) htext = text(0,0,[' YOU ';'\downarrow'],'HorizontalAlignment','Center','VerticalAlignment','Bottom','FontSize',18,'Parent', AX); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Add Listener %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Block_search = [MDL,'/Environment params Estimations/ALT_and_M_GAIN_LIST']; hlist = add_exec_event_listener(Block_search, 'PostOutputs', @localEventListener); function modelExists = localValidateInputs(modelName) num = exist(modelName,'file'); if num == 4 modelExists = true; else modelExists = false; end function localCloseRequestFcn(hObject,eventdata,ad) %#ok global hplot hlist try delete(hlist) delete(hObject) catch close all Force end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
tgear.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/7dof FCS Development/Used Functions/tgear.m
535
utf_8
f0c3d6ed53bf5e044ed13e3251d92c3b
%===================================================== % tgear.m % % Author : Ying Huo % % power command vs. thtl. relationship used % in F-16 model %===================================================== function tgear_value = tgear ( thtl ) if ( thtl <= 0.77 ) tgear_value = 64.94 * thtl; else tgear_value = 217.38 * thtl - 117.38; end
github
DavidTorresOcana/Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master
trimfun.m
.m
Adaptive_and_Fault_Tolerant_Flight_Control_Systems-master/src/7dof FCS Development/Used Functions/trimfun.m
4,041
utf_8
908902ca2678a4efb48b714eddeca553
%===================================================== % F16 nonlinear model trim cost function % for longitudinal motion, steady level flight % (cost = sum of weighted squared state derivatives) % % Author: T. Keviczky % Date: April 29, 2002 % % Added addtional functionality. % This trim function can now trim at three % additional flight conditions % - Steady Turning Flight given turn rate % - Steady Pull-up flight - given pull-up rate % - Steady Roll - given roll rate % % Coauthor: Richard S. Russell % Date: November 7th, 2002 % % %===================================================== %%**********************************************%% % Altered to work as a trimming function % % for the HIFI F_16 Model % %%**********************************************%% function [cost, Xdot, xu] = trimfun(UX0) global phi psi p q r phi_weight theta_weight psi_weight pow global altitude velocity fi_flag_Simulink % UX0 = [throttle, elevator, beta, alpha, aileron, rudder] % Implementing limits: % Thrust limits if UX0(1) > 1 UX0(1) = 1; elseif UX0(1) < 0 UX0(1) = 0; end; % elevator limits if UX0(2) > 25 UX0(2) = 25; elseif UX0(2) < -25 UX0(2) = -25; end; % sideslip limits if (fi_flag_Simulink == 0) if UX0(3) > 45*pi/180 UX0(3) = 45*pi/180; elseif UX0(3) < -10*pi/180 UX0(3) = -10*pi/180; end elseif (fi_flag_Simulink == 1) if UX0(3) > 30*pi/180 UX0(3) = 30*pi/180; elseif UX0(3) < -20*pi/180 UX0(3) = -20*pi/180; end end % angle of attack limits if (fi_flag_Simulink == 0) if UX0(4) > 45*pi/180 UX0(4) = 45*pi/180; elseif UX0(4) < -10*pi/180 UX0(4) = -10*pi/180; end elseif (fi_flag_Simulink == 1) if UX0(4) > 90*pi/180 UX0(4) = 90*pi/180; elseif UX0(4) < -20*pi/180 UX0(4) = -20*pi/180; end end % Aileron limits if UX0(5) > 21.5 UX0(5) = 21.5; elseif UX0(5) < -21.5 UX0(5) = -21.5; end; % Rudder limits if UX0(6) > 30 UX0(6) = 30; elseif UX0(6) < -30 UX0(6) = -30; end; if (fi_flag_Simulink == 1) % Calculating qbar, ps and steady state leading edge flap deflection: % (see pg. 43 NASA report) rho0 = 1.225; tfac = 1 - 6.5e-3/288.15*altitude; temp = 288.15*tfac; if (altitude >= 11000) temp = 216.65; end; rho = rho0*(tfac.^4.2586); qbar = 0.5*rho*velocity^2; ps = 287*rho*temp; dLEF = 1.38*UX0(4)*180/pi - 9.05*qbar/ps + 1.45; elseif (fi_flag_Simulink == 0) dLEF = 0.0; end % Verify that the calculated leading edge flap % have not been violated. if (dLEF > 25) dLEF = 25; elseif (dLEF < 0) dLEF = 0; end; xu = [ 0 ... %npos (m) 0 ... %epos (m) altitude ... %altitude (m) phi*(pi/180) ... %phi (rad) UX0(4) ... %theta (rad) psi*(pi/180) ... %psi (rad) velocity ... %velocity (m/s) UX0(4) ... %alpha (rad) UX0(3) ... %beta (rad) p*(pi/180) ... %p (rad/s) q*(pi/180) ... %q (rad/s) r*(pi/180) ... %r (rad/s) tgear(UX0(1)) ... % pow UX0(1) ... %throttle (0-1) UX0(2) ... %ele (deg) UX0(5) ... %ail (deg) UX0(6) ... %rud (deg) dLEF ... %dLEF (deg) fi_flag_Simulink ...% fidelity flag ]'; OUT = feval('nlplant',xu); Xdot = OUT(1:13,1); % Create weight function weight = [ 0 ...%npos_dot 0 ...%epos_dot 5 ...%alt_dot phi_weight ...%phi_dot theta_weight ...%theta_dot psi_weight ...%psi_dot 2 ...%V_dot 10 ...%alpha_dpt 10 ...%beta_dot 10 ...%P_dot 10 ...%Q_dot 10 ...%R_dot 5 ...% pow_dot ]; cost = weight*(Xdot.*Xdot); % Mean Square to be minimized
github
dhirajhr/ECG-based-Biometric-Authentication-master
ardimat2.m
.m
ECG-based-Biometric-Authentication-master/ECG_MATLAB/ardimat2.m
2,232
utf_8
f0795d79ef6f7d685d3c6ba301b1ef69
% Yu Hin Hau % 7/9/2013 % **CLOSE PLOT TO END SESSION function ardimat2 instrumentObjects=instrfind; % don't pass it anything - find all of them. delete(instrumentObjects); clear all; clc; %User Defined Properties serialPort = 'COM1'; % define COM port # plotTitle = 'Serial Data Log'; % plot title xLabel = 'Elapsed Time (s)'; % x-axis label yLabel = 'Data'; % y-axis label plotGrid = 'on'; % 'off' to turn off grid min = -1.5; % set y-min max = 1.5; % set y-max scrollWidth = 10; % display period in plot, plot entire data log if <= 0 delay = .01; % make sure sample faster than resolution %Define Function Variables time = 0; data = 0; count = 0; %Set up Plot plotGraph = plot(time,data,'-mo',... 'LineWidth',1,... 'MarkerEdgeColor','k',... 'MarkerFaceColor',[.49 1 .63],... 'MarkerSize',2); title(plotTitle,'FontSize',25); xlabel(xLabel,'FontSize',15); ylabel(yLabel,'FontSize',15); axis([0 10 min max]); grid(plotGrid); %Open Serial COM Port s = serial(serialPort) disp('Close Plot to End Session'); fopen(s); tic while ishandle(plotGraph) %Loop when Plot is Active dat = fscanf(s); %Read Data from Serial as Float disp(dat); if(~isempty(dat)) %Make sure Data Type is Correct count = count + 1; time(count) = toc; %Extract Elapsed Time data(count) = dat(1); %Extract 1st Data Element %Set Axis according to Scroll Width if(scrollWidth > 0) set(plotGraph,'XData',time(time > time(count)-scrollWidth),'YData',data(time > time(count)-scrollWidth)); axis([time(count)-scrollWidth time(count) min max]); else set(plotGraph,'XData',time,'YData',data); axis([0 time(count) min max]); end %Allow MATLAB to Update Plot pause(delay); end end %Close Serial COM Port and Delete useless Variables fclose(s); clear count dat delay max min plotGraph plotGrid plotTitle s ... scrollWidth serialPort xLabel yLabel; disp('Session Terminated...');
github
dhirajhr/ECG-based-Biometric-Authentication-master
progressbar.m
.m
ECG-based-Biometric-Authentication-master/MATLAB_ECG/progressbar.m
11,767
utf_8
06705e480618e134da62478338e8251c
function progressbar(varargin) % Description: % progressbar() provides an indication of the progress of some task using % graphics and text. Calling progressbar repeatedly will update the figure and % automatically estimate the amount of time remaining. % This implementation of progressbar is intended to be extremely simple to use % while providing a high quality user experience. % % Features: % - Can add progressbar to existing m-files with a single line of code. % - Supports multiple bars in one figure to show progress of nested loops. % - Optional labels on bars. % - Figure closes automatically when task is complete. % - Only one figure can exist so old figures don't clutter the desktop. % - Remaining time estimate is accurate even if the figure gets closed. % - Minimal execution time. Won't slow down code. % - Randomized color. When a programmer gets bored... % % Example Function Calls For Single Bar Usage: % progressbar % Initialize/reset % progressbar(0) % Initialize/reset % progressbar('Label') % Initialize/reset and label the bar % progressbar(0.5) % Update % progressbar(1) % Close % % Example Function Calls For Multi Bar Usage: % progressbar(0, 0) % Initialize/reset two bars % progressbar('A', '') % Initialize/reset two bars with one label % progressbar('', 'B') % Initialize/reset two bars with one label % progressbar('A', 'B') % Initialize/reset two bars with two labels % progressbar(0.3) % Update 1st bar % progressbar(0.3, []) % Update 1st bar % progressbar([], 0.3) % Update 2nd bar % progressbar(0.7, 0.9) % Update both bars % progressbar(1) % Close % progressbar(1, []) % Close % progressbar(1, 0.4) % Close % % Notes: % For best results, call progressbar with all zero (or all string) inputs % before any processing. This sets the proper starting time reference to % calculate time remaining. % Bar color is choosen randomly when the figure is created or reset. Clicking % the bar will cause a random color change. % % Demos: % % Single bar % m = 500; % progressbar % Init single bar % for i = 1:m % pause(0.01) % Do something important % progressbar(i/m) % Update progress bar % end % % % Simple multi bar (update one bar at a time) % m = 4; % n = 3; % p = 100; % progressbar(0,0,0) % Init 3 bars % for i = 1:m % progressbar([],0) % Reset 2nd bar % for j = 1:n % progressbar([],[],0) % Reset 3rd bar % for k = 1:p % pause(0.01) % Do something important % progressbar([],[],k/p) % Update 3rd bar % end % progressbar([],j/n) % Update 2nd bar % end % progressbar(i/m) % Update 1st bar % end % % % Fancy multi bar (use labels and update all bars at once) % m = 4; % n = 3; % p = 100; % progressbar('Monte Carlo Trials','Simulation','Component') % Init 3 bars % for i = 1:m % for j = 1:n % for k = 1:p % pause(0.01) % Do something important % % Update all bars % frac3 = k/p; % frac2 = ((j-1) + frac3) / n; % frac1 = ((i-1) + frac2) / m; % progressbar(frac1, frac2, frac3) % end % end % end % % Author: % Steve Hoelzer % % Revisions: % 2002-Feb-27 Created function % 2002-Mar-19 Updated title text order % 2002-Apr-11 Use floor instead of round for percentdone % 2002-Jun-06 Updated for speed using patch (Thanks to waitbar.m) % 2002-Jun-19 Choose random patch color when a new figure is created % 2002-Jun-24 Click on bar or axes to choose new random color % 2002-Jun-27 Calc time left, reset progress bar when fractiondone == 0 % 2002-Jun-28 Remove extraText var, add position var % 2002-Jul-18 fractiondone input is optional % 2002-Jul-19 Allow position to specify screen coordinates % 2002-Jul-22 Clear vars used in color change callback routine % 2002-Jul-29 Position input is always specified in pixels % 2002-Sep-09 Change order of title bar text % 2003-Jun-13 Change 'min' to 'm' because of built in function 'min' % 2003-Sep-08 Use callback for changing color instead of string % 2003-Sep-10 Use persistent vars for speed, modify titlebarstr % 2003-Sep-25 Correct titlebarstr for 0% case % 2003-Nov-25 Clear all persistent vars when percentdone = 100 % 2004-Jan-22 Cleaner reset process, don't create figure if percentdone = 100 % 2004-Jan-27 Handle incorrect position input % 2004-Feb-16 Minimum time interval between updates % 2004-Apr-01 Cleaner process of enforcing minimum time interval % 2004-Oct-08 Seperate function for timeleftstr, expand to include days % 2004-Oct-20 Efficient if-else structure for sec2timestr % 2006-Sep-11 Width is a multiple of height (don't stretch on widescreens) % 2010-Sep-21 Major overhaul to support multiple bars and add labels % persistent progfig progdata lastupdate % Get inputs if nargin > 0 input = varargin; ninput = nargin; else % If no inputs, init with a single bar input = {0}; ninput = 1; end % If task completed, close figure and clear vars, then exit if input{1} == 1 if ishandle(progfig) delete(progfig) % Close progress bar end clear progfig progdata lastupdate % Clear persistent vars drawnow return end % Init reset flag resetflag = false; % Set reset flag if first input is a string if ischar(input{1}) resetflag = true; end % Set reset flag if all inputs are zero if input{1} == 0 % If the quick check above passes, need to check all inputs if all([input{:}] == 0) && (length([input{:}]) == ninput) resetflag = true; end end % Set reset flag if more inputs than bars if ninput > length(progdata) resetflag = true; end % If reset needed, close figure and forget old data if resetflag if ishandle(progfig) delete(progfig) % Close progress bar end progfig = []; progdata = []; % Forget obsolete data end % Create new progress bar if needed if ishandle(progfig) else % This strange if-else works when progfig is empty (~ishandle() does not) % Define figure size and axes padding for the single bar case height = 0.03; width = height * 8; hpad = 0.02; vpad = 0.25; % Figure out how many bars to draw nbars = max(ninput, length(progdata)); % Adjust figure size and axes padding for number of bars heightfactor = (1 - vpad) * nbars + vpad; height = height * heightfactor; vpad = vpad / heightfactor; % Initialize progress bar figure left = (1 - width) / 2; bottom = (1 - height) / 2; progfig = figure(... 'Units', 'normalized',... 'Position', [left bottom width height],... 'NumberTitle', 'off',... 'Resize', 'off',... 'MenuBar', 'none' ); % Initialize axes, patch, and text for each bar left = hpad; width = 1 - 2*hpad; vpadtotal = vpad * (nbars + 1); height = (1 - vpadtotal) / nbars; for ndx = 1:nbars % Create axes, patch, and text bottom = vpad + (vpad + height) * (nbars - ndx); progdata(ndx).progaxes = axes( ... 'Position', [left bottom width height], ... 'XLim', [0 1], ... 'YLim', [0 1], ... 'Box', 'on', ... 'ytick', [], ... 'xtick', [] ); progdata(ndx).progpatch = patch( ... 'XData', [0 0 0 0], ... 'YData', [0 0 1 1] ); progdata(ndx).progtext = text(0.99, 0.5, '', ... 'HorizontalAlignment', 'Right', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); progdata(ndx).proglabel = text(0.01, 0.5, '', ... 'HorizontalAlignment', 'Left', ... 'FontUnits', 'Normalized', ... 'FontSize', 0.7 ); if ischar(input{ndx}) set(progdata(ndx).proglabel, 'String', input{ndx}) input{ndx} = 0; end % Set callbacks to change color on mouse click set(progdata(ndx).progaxes, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progpatch, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).progtext, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) set(progdata(ndx).proglabel, 'ButtonDownFcn', {@changecolor, progdata(ndx).progpatch}) % Pick a random color for this patch changecolor([], [], progdata(ndx).progpatch) % Set starting time reference if ~isfield(progdata(ndx), 'starttime') || isempty(progdata(ndx).starttime) progdata(ndx).starttime = clock; end end % Set time of last update to ensure a redraw lastupdate = clock - 1; end % Process inputs and update state of progdata for ndx = 1:ninput if ~isempty(input{ndx}) progdata(ndx).fractiondone = input{ndx}; progdata(ndx).clock = clock; end end % Enforce a minimum time interval between graphics updates myclock = clock; if abs(myclock(6) - lastupdate(6)) < 0.01 % Could use etime() but this is faster return end % Update progress patch for ndx = 1:length(progdata) set(progdata(ndx).progpatch, 'XData', ... [0, progdata(ndx).fractiondone, progdata(ndx).fractiondone, 0]) end % Update progress text if there is more than one bar if length(progdata) > 1 for ndx = 1:length(progdata) set(progdata(ndx).progtext, 'String', ... sprintf('%1d%%', floor(100*progdata(ndx).fractiondone))) end end % Update progress figure title bar if progdata(1).fractiondone > 0 runtime = etime(progdata(1).clock, progdata(1).starttime); timeleft = runtime / progdata(1).fractiondone - runtime; timeleftstr = sec2timestr(timeleft); titlebarstr = sprintf('%2d%% %s remaining', ... floor(100*progdata(1).fractiondone), timeleftstr); else titlebarstr = ' 0%'; end set(progfig, 'Name', titlebarstr) % Force redraw to show changes drawnow % Record time of this update lastupdate = clock; % ------------------------------------------------------------------------------ function changecolor(h, e, progpatch) %#ok<INUSL> % Change the color of the progress bar patch % Prevent color from being too dark or too light colormin = 1.5; colormax = 2.8; thiscolor = rand(1, 3); while (sum(thiscolor) < colormin) || (sum(thiscolor) > colormax) thiscolor = rand(1, 3); end set(progpatch, 'FaceColor', thiscolor) % ------------------------------------------------------------------------------ function timestr = sec2timestr(sec) % Convert a time measurement from seconds into a human readable string. % Convert seconds to other units w = floor(sec/604800); % Weeks sec = sec - w*604800; d = floor(sec/86400); % Days sec = sec - d*86400; h = floor(sec/3600); % Hours sec = sec - h*3600; m = floor(sec/60); % Minutes sec = sec - m*60; s = floor(sec); % Seconds % Create time string if w > 0 if w > 9 timestr = sprintf('%d week', w); else timestr = sprintf('%d week, %d day', w, d); end elseif d > 0 if d > 9 timestr = sprintf('%d day', d); else timestr = sprintf('%d day, %d hr', d, h); end elseif h > 0 if h > 9 timestr = sprintf('%d hr', h); else timestr = sprintf('%d hr, %d min', h, m); end elseif m > 0 if m > 9 timestr = sprintf('%d min', m); else timestr = sprintf('%d min, %d sec', m, s); end else timestr = sprintf('%d sec', s); end
github
dhirajhr/ECG-based-Biometric-Authentication-master
untitled.m
.m
ECG-based-Biometric-Authentication-master/MATLAB_ECG/untitled.m
14,583
utf_8
1035b4a62875e9877dfb1ab7653f5b47
function varargout = untitled(varargin) % UNTITLED MATLAB code for untitled.fig % UNTITLED, by itself, creates a new UNTITLED or raises the existing % singleton*. % % H = UNTITLED returns the handle to a new UNTITLED or the handle to % the existing singleton*. % % UNTITLED('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in UNTITLED.M with the given input arguments. % % UNTITLED('Property','Value',...) creates a new UNTITLED or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before untitled_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to untitled_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help untitled % Last Modified by GUIDE v2.5 08-Apr-2017 21:17:21 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @untitled_OpeningFcn, ... 'gui_OutputFcn', @untitled_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before untitled is made visible. function untitled_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to untitled (see VARARGIN) % Choose default command line output for untitled handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes untitled wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = untitled_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on selection change in popupmenu2. function popupmenu2_Callback(hObject, eventdata, handles) % hObject handle to popupmenu2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popupmenu2 contents as cell array % contents{get(hObject,'Value')} returns selected item from popupmenu2 %contents = cellstr(get(hObject,'String')); %aaaa=contents{get(hObject,'Value')}; % --- Executes during object creation, after setting all properties. function popupmenu2_CreateFcn(hObject, eventdata, handles) % hObject handle to popupmenu2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) cla reset; aa=load('Person_02.txt'); N=aa(:,1); X=aa(:,2); plot(handles.axes1,N,X); function edit1_Callback(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit1 as text % str2double(get(hObject,'String')) returns contents of edit1 as a double % --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton9. function pushbutton9_Callback(hObject, eventdata, handles) % hObject handle to pushbutton9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) cla reset; ecg=load('Person_02.txt'); N=ecg(:,1); X=ecg(:,2); [qrs_amp_raw,qrs_i_raw,delay,ecg_d, NOISL_buf1, SIGL_buf1, THRS_buf1, locs, ecg_h]=pan_tompkin1(X,500,0); plot(handles.axes1,ecg_h); hold on,scatter(handles.axes1,qrs_i_raw,qrs_amp_raw,'m'); hold on,plot(handles.axes1,locs,NOISL_buf1,'LineWidth',2,'Linestyle','--','color','k'); hold on,plot(handles.axes1,locs,SIGL_buf1,'LineWidth',2,'Linestyle','-.','color','r'); hold on,plot(handles.axes1,locs,THRS_buf1,'LineWidth',2,'Linestyle','-.','color','g'); % --- Executes on button press in pushbutton10. function pushbutton10_Callback(hObject, eventdata, handles) % hObject handle to pushbutton10 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %[N1,X1]=R_Peak(N,X); %plot(handles.axes1,N,X); %plot(handles.axes1,N1,X1,'ro'); %---- %---- % --- Executes on button press in pushbutton11. function pushbutton11_Callback(hObject, eventdata, handles) % hObject handle to pushbutton11 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) cla reset; ecg=load('Person_02.txt'); N=ecg(:,1); X=ecg(:,2); [qrs_amp_raw,qrs_i_raw,delay,ecg_d, NOISL_buf1, SIGL_buf1, THRS_buf1, locs, ecg_h]=pan_tompkin1(X,500,0); plot(handles.axes1,N,ecg_d); disp(handles); function edit2_Callback(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit2 as text % str2double(get(hObject,'String')) returns contents of edit2 as a double % --- Executes during object creation, after setting all properties. function edit2_CreateFcn(hObject, eventdata, handles) % hObject handle to edit2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit3_Callback(hObject, eventdata, handles) % hObject handle to edit3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit3 as text % str2double(get(hObject,'String')) returns contents of edit3 as a double % --- Executes during object creation, after setting all properties. function edit3_CreateFcn(hObject, eventdata, handles) % hObject handle to edit3 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton12. function pushbutton12_Callback(hObject, eventdata, handles) % hObject handle to pushbutton12 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) folder_name = uigetdir('C:\Users\hp1\Desktop'); folder_name=cellstr(folder_name); set(handles.edit2,'string',folder_name); %disp(class(folder_name)); %disp(folder_name); % --- Executes on button press in pushbutton14. function pushbutton14_Callback(hObject, eventdata, handles) % hObject handle to pushbutton14 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) folder_name = uigetdir('C:\Users\hp1\Desktop'); folder_name=cellstr(folder_name); set(handles.edit3,'string',folder_name); % --- Executes on button press in pushbutton15. function pushbutton15_Callback(hObject, eventdata, handles) % hObject handle to pushbutton15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %h=zoom; %disp(h.Enable); %if(h.Enable=='off') % zoom on; %else % zoom off; %end; data = handles.pushbutton15; %if(data.String=='+') zoom on; % data.String='-'; %else % zoom out; % data.String='+'; %end; disp(class(data.String)); % --- Executes on button press in pushbutton16. function pushbutton16_Callback(hObject, eventdata, handles) % hObject handle to pushbutton16 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) zoom out; zoom off; function edit4_Callback(hObject, eventdata, handles) % hObject handle to edit4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit4 as text % str2double(get(hObject,'String')) returns contents of edit4 as a double % --- Executes during object creation, after setting all properties. function edit4_CreateFcn(hObject, eventdata, handles) % hObject handle to edit4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton17. function pushbutton17_Callback(hObject, eventdata, handles) % hObject handle to pushbutton17 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) %disp(handles.edit2); xx=pwd; xx1=strcat(pwd,'\'); train=handles.edit2.String; test=handles.edit3.String; disp(strrep(char(test),xx1,'')); %acc= dwt_verify(strrep(char(test),xx1,''),strrep(char(train),xx1,'')); acc= dwt_verify(char(test),char(train)); disp(strcat('sddssdds',acc)); set(handles.edit4,'String',num2str(acc)); % --- Executes on button press in pushbutton19. function pushbutton19_Callback(hObject, eventdata, handles) % hObject handle to pushbutton19 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) xx=pwd; xx1=strcat(pwd,'\'); train=handles.edit2.String; test=handles.edit3.String; disp(strrep(char(test),xx1,'')); %acc= dwt_verify(strrep(char(test),xx1,''),strrep(char(train),xx1,'')); acc= dwt_verify(char(test),char(train)); set(handles.edit4,'String',num2str(acc)); % --- Executes during object creation, after setting all properties. function pushbutton19_CreateFcn(hObject, eventdata, handles) % hObject handle to pushbutton19 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % --- Executes on button press in pushbutton18. function pushbutton18_Callback(hObject, eventdata, handles) % hObject handle to pushbutton18 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) xx=pwd; xx1=strcat(pwd,'\'); train=handles.edit2.String; test=handles.edit3.String; disp(strrep(char(test),xx1,'')); %acc= dwt_verify(strrep(char(test),xx1,''),strrep(char(train),xx1,'')); N=5; %total number of parfor iterations hbar = parfor_progressbar(N,'Computing...'); %create the progress bar parfor i=1:N, acc{i}= dwt_verify(char(test),char(train)); % computation hbar.iterate(1); % update progress by one iteration end close(hbar); %close progress bar %end %end set(handles.edit4,'string',num2str(acc{N})); % --- Executes when figure1 is resized. function figure1_SizeChangedFcn(hObject, eventdata, handles) % hObject handle to figure1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on key press with focus on pushbutton18 and none of its controls. function pushbutton18_KeyPressFcn(hObject, eventdata, handles) % hObject handle to pushbutton18 (see GCBO) % eventdata structure with the following fields (see MATLAB.UI.CONTROL.UICONTROL) % Key: name of the key that was pressed, in lower case % Character: character interpretation of the key(s) that was pressed % Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed % handles structure with handles and user data (see GUIDATA)
github
dhirajhr/ECG-based-Biometric-Authentication-master
bxb.m
.m
ECG-based-Biometric-Authentication-master/ECGMatlab_Project/Toolbox/wfdb-app-toolbox-0-9-9/mcode/bxb.m
3,461
utf_8
57b3c3892ca3780599004ec45c9df76d
function varargout=bxb(varargin) % % report=bxb(recName,refAnn,testAnn,reportFile,beginTime,stopTime,matchWindow) % % Wrapper to WFDB BXB: % http://www.physionet.org/physiotools/wag/bxb-1.htm % % Creates a report file ("reportFile) using % ANSI/AAMI-standard beat-by-beat annotation comparator. % % Ouput Parameters: % % report (Optional) % Returns a structure containing information on the 'reportFile'. % This can be used to read report File that has been previously % generated by BXB (see Example 2 below), into the workspace. % The structure has the following fields: % report.data -Numerical data matching the Algorithm table % report.textdata -Text data describing the Algorithm table % %Input Parameters: % recName % String specifying the WFDB record file. % % refAnn % String specifying the reference WFDB annotation file. % % testAnn % String specifying the test WFDB annotation file. % % reportFile % String representing the file at which the report will be % written to. % % beginTime (Optional) % String specifying the begin time in WFDB time format. The % WFDB time format is described at % http://www.physionet.org/physiotools/wag/intro.htm#time. % Default starts comparison after 5 minutes. % % stopTime (Optional) % String specifying the stop time in WFDB format (default is end of % record). % % matchWindow (Optional) % 1x1 WFDB Time specifying the match window size (default = 0.15 s). % % % Written by Ikaro Silva, 2013 % Last Modified: May 28, 2014 % Version 1.1 % Since 0.9.0 % % %Example (this will generate a /mitdb/100.qrs file at your directory): % %Compares SQRS detetor with the MITDB ATR annotations % % [refAnn]=rdann('mitdb/100','atr'); % sqrs('mitdb/100'); % [testAnn]=rdann('mitdb/100','qrs'); % report=bxb('mitdb/100','atr','qrs','bxbReport.txt') % % % %Example 2 - Load variables from a report file that has been previously % %generated % report=bxb([],[],[],'bxbReport.txt') % % % See also RDANN, MXM, WFDBTIME %endOfHelp persistent javaWfdbExec if(isempty(javaWfdbExec)) javaWfdbExec=getWfdbClass('bxb'); end %Set default pararamter values inputs={'recName','refAnn','testAnn','reportFile','beginTime','stopTime','matchWindow'}; recName=[]; refAnn=[]; testAnn=[]; reportFile=[]; beginTime=[]; stopTime=[]; matchWindow=[]; for n=1:nargin if(~isempty(varargin{n})) eval([inputs{n} '=varargin{n};']) end end if(~isempty(recName)) %Only execute this if recName is defined, otherwise we assume %that the user just want to load the 'reporFile' variable into the %workspace based on a previously generated 'reportFile' wfdb_argument={'-r',recName,'-a',refAnn,testAnn,'-S',reportFile,'-v'}; if(~isempty(beginTime)) wfdb_argument{end+1}='-f'; wfdb_argument{end+1}=beginTime; end if(~isempty(stopTime)) wfdb_argument{end+1}='-t'; wfdb_argument{end+1}=stopTime; end if(~isempty(matchWindow)) wfdb_argument{end+1}='-w'; wfdb_argument{end+1}=matchWindow; end report=javaWfdbExec.execToStringList(wfdb_argument); end if(nargout>0) varargout{1}=bxbReader(reportFile); end function reportData = bxbReader(fileName) %load file reportData = importdata(fileName); %get rid of unimportant stuff reportData.data(end,:) = []; reportData.textdata(end,:) = []; reportData.textdata(:,end) = [];
github
dhirajhr/ECG-based-Biometric-Authentication-master
surrogate.m
.m
ECG-based-Biometric-Authentication-master/ECGMatlab_Project/Toolbox/wfdb-app-toolbox-0-9-9/mcode/surrogate.m
1,986
utf_8
4dce61f40839e472d48a46aa980d311b
function Y=surrogate(x,M) % % Y=surrogate(x,M) % % Generates M amplitude adjusted phase shuffled surrogate time series from x. % Useufel for testing the underlying assumption that the null hypothesis consists % of linear dynamics with possibly non-linear, monotonically increasing, % measurement function. % % Required Input Parameters: % % x % Nx1 vector of doubles % % M % 1x1 scalar specifying the number of surrogate time series to % generate. % % Required Output Parameters: % % Y % NxM vector of doubles % % % % References: % %[1] Kaplan, Daniel, and Leon Glass. Understanding nonlinear dynamics. Vol. 19. Springer, 1995. % % % Written by Ikaro Silva, 2014 % Last Modified: November 20, 2014 % Version 1.0 % Since 0.9.8 % % % % % See also MSENTROPY, SURROGATE %endOfHelp % 1. Amp transform original data to Gaussian distribution % 2. Phase randomize #1 % 3. Amp transform #2 to original % Auto-correlation function should be similar but not exact! x=x(:); N=length(x); Y=zeros(N,M); for m=1:M %Step 1 y=randn(N,1); y=amplitudeTransform(x,y,N); %Step 2 y=phaseShuffle(y,N); %Step 3 y=amplitudeTransform(y,x,N); Y(:,m)=y; end %%% Helper functions function target=amplitudeTransform(x,target,N) %Steps: %1. Sort the source by increasing amp %2. Sort target as #1 %3. Swap source amp by target amp %4. Sort #3 by increasing time index of #1 X=[[1:N]' x]; X=sortrows(X,2); target=[X(:,1) sort(target)]; target=sortrows(target,1); target=target(:,2); function y=phaseShuffle(x,N) %%Shuffle spectrum X=fft(x); Y=X; mid=floor(N/2)+ mod(N,2); phi=2*pi*rand(mid-1,1); %Generate random phase Y(2:mid)=abs(X(2:mid)).*cos(phi) + j*abs(X(2:mid)).*sin(phi); if(~mod(N,2)) %Even series has Nyquist in the middle+1 because of DC Y(mid+2:end)=conj(flipud(Y(2:mid))); Y(mid+1)=X(mid+1); else %Odd series is fully symetric except for DC Y(mid+1:end)=conj(flipud(Y(2:mid))); end y=real(ifft(Y));
github
dhirajhr/ECG-based-Biometric-Authentication-master
mat2wfdb.m
.m
ECG-based-Biometric-Authentication-master/ECGMatlab_Project/Toolbox/wfdb-app-toolbox-0-9-9/mcode/mat2wfdb.m
10,214
utf_8
ccd1af8befc8050ad893caab1a0463e0
function [varargout]=mat2wfdb(varargin) % % [xbit]=mat2wfdb(X,fname,Fs,bit_res,adu,info,gain,sg_name,baseline,isint) % % Convert data readable in matlab into WFDB Physionet format. % % Input Paramater are: % % X -(required) NxM matrix of M signals with N samples each. The % signals can be of type double.The signals are assumed to be % in physical units already and will be converted to % ADU. % fname -(required) String where the the header (*.hea) and data (*.dat) % files will be saved (one single name for both, with no sufix). % Fs -(Optional) 1x1 sampling frequency in Hz (all signals must have % been sampled at the same frquency). Default is 1 Hz. % bit_res -(Optional) 1xM (or Mx1):scalar determining the bit depth of the conversion for % each signal. % 1x1 : If all the signals should have the same bit depth % Options are: 8, 16, and 32 ( all are signed types). 16 is the default. % adu -(Optional) Cell array of strings describing the physical units (default is 'V'). % If only one string is entered all signals will have the same physical units. % If multiple physical units, the total units entered has to equal M (number of % channels). Units are delimited by '/'. See examples below. % info -(Optional) String that will be added to the comment section of the header file. % gain -(Optional) Scalar, if provided, no automatic scaling will be applied before the % quantitzation of the signal. If a gain is passed, in will be the same one set % on the header file. The signal will be scaled by this gain prior to the quantization % process. Use this options if you want to have a standard gain and quantization % process for all signals in a dataset (the function will not attempt to quantitized % individual waveforms based on their individual range and baseline). %baseline -(Optional) Offset (ADC zero) Mx1 array of integers that represents the amplitude (sample % value) that would be observed if the analog signal present at the ADC inputs had a % level that fell exactly in the middle of the input range of the ADC. % sg_name -(Optional) Cell array of strings describing signal names. % % isint -(Optional) Logical value (default=0). Use this option if you know % the signal is already quantitized, and you want to remove round-off % error by setting the original values to integers prior to fixed % point conversion. % % Ouput Parameters are: % % xbit -(Optional) NxM the quantitized signals that written to file (possible % rescaled if no gain was provided at input). Useful for comparing % and estimating quatitization error with the input double signal X % (see examples below). % % % NOTE: The signals can have different amplitudes, they will all be scaled to % a reference gain, with the scaling factor saved in the *.hea file. % %Written by Ikaro Silva 2010 %Modified by Louis Mayaud 2011 % Version 1.0 % % Since 0.0.1 % See also wrsamp, wfdbdesc % %%%%%%%%%% Example 1 %%%%%%%%%%%% % % display('***This example will write a Ex1.dat and Ex1.hea file to your current directory!') % s=input('Hit "ctrl + c" to quit or "Enter" to continue!'); % % %Generate 3 different signals and convert them to signed 16 bit in WFDB format % clear all;clc;close all % N=1024; % Fs=48000; % tm=[0:1/Fs:(N-1)/Fs]'; % adu='V/mV/V'; % info='Example 1'; % % % %First signal a ramp with 2^16 unique levels and is set to (+-) 2^15 (Volts) % %Thus the header file should have one quant step equal to (2^15-(-2^15))/(2^16) V. % sig1=double(int16(linspace(-2^15,2^15,N)')); % % %Second signal is a sine wave with 2^8 unique levels and set to (+-) 1 (mV) % %Thus the header file should one quant step equal a (1--1)/(2^16) adu step % sig2=double(int8(sin(2*pi*tm*1000).*(2^7)))./(2^7); % % %Third signal is a random binary signal set to to (+-) 1 (V) with DC (to be discarded) % %Thus the header file should have one quant step equal a 1/(2^16) adu step. % sig3=(rand(N,1) > 0.97)*2 -1 + 2^16; % % %Concatenate all signals and convert to WFDB format with default 16 bits (empty brackets) % sig=[sig1 sig2 sig3]; % mat2wfdb(sig,'Ex1',Fs,[],adu,info) % % % %NOTE: If you have WFDB installed you can check the conversion by % % %uncomenting and this section and running (notice that all signals are scaled % % %to unit amplitude during conversion, with the header files keeping the gain info): % % % !rdsamp -r Ex1 > foo % % x=dlmread('foo'); % % subplot(211) % % plot(sig) % % subplot(212) % % plot(x(:,1),x(:,2));hold on;plot(x(:,1),x(:,3),'k');plot(x(:,1),x(:,4),'r') % %%%%%%%% End of Example 1%%%%%%%%% %endOfHelp machine_format='l'; skip=0; %Set default parameters params={'x','fname','Fs','bit_res','adu','info','gain','sg_name','baseline','isint'}; Fs=1; adu=[]; info=[]; isint=0; %Use cell array for baseline and gain in case of empty conditions baseline=[]; gain=[]; sg_name=[]; x=[]; fname=[]; %Convert signal from double to appropiate type bit_res = 16 ; bit_res_suport=[8 16 32]; for i=1:nargin if(~isempty(varargin{i})) eval([params{i} '= varargin{i};']) end end [N,M]=size(x); adu=regexp(adu,'/','split'); if(isempty(gain)) gain=cell(M,1); %Generate empty cells as default elseif(length(gain)==1) gain=repmat(gain,[M 1]); gain=num2cell(gain); else gain=gain; end if(isempty(sg_name)) sg_name=repmat({''},[M 1]); end if(isempty(adu)) adu=repmat({'V'},[M 1]); end if ~isempty(setdiff(bit_res,bit_res_suport)) error(['Bit res should be any of: ' num2str(bit_res_suport)]); end if(isempty(baseline)) baseline=cell(M,1); %Generate empty cells as default elseif(length(baseline)==1) baseline=repmat(baseline,[M 1]); baseline=num2cell(baseline); end %Header string head_str=cell(M+1,1); head_str(1)={[fname ' ' num2str(M) ' ' num2str(Fs) ' ' num2str(N)]}; %Loop through all signals, digitizing them and generating lines in header %file eval(['y=int' num2str(bit_res) '(zeros(N,M));']) %allocate space for m=1:M nameArray = regexp(fname,'/','split'); if ~isempty(nameArray) fname = nameArray{end}; end [tmp_bit1,bit_gain,baseline_tmp,ck_sum]=quant(x(:,m), ... bit_res,gain{m},baseline{m},isint); y(:,m)=tmp_bit1; head_str(m+1)={[fname '.dat ' num2str(bit_res) ' ' num2str(bit_gain) '(' ... num2str(baseline_tmp) ')/' adu{m} ' ' '0 0 0 ' num2str(ck_sum) ' 0 ' sg_name{m}]}; end if(length(y)<1) error(['Converted data is empty. Exiting without saving file...']) end %Write *.dat file fid = fopen([fname '.dat'],'wb',machine_format); if(~fid) error(['Could not create data file for writing: ' fname]) end count=fwrite(fid,y',['int' num2str(bit_res)],skip,machine_format); if(~count) fclose(fid); error(['Could not data write to file: ' fname]) end fprintf(['Generated *.dat file: ' fname '\n']) fclose(fid); %Write *.hea file fid = fopen([fname '.hea'],'w'); for m=1:M+1 if(~fid) error(['Could not create header file for writing: ' fname]) end fprintf(fid,'%s\n',head_str{m}); end if(~isempty(info)) count=fprintf(fid,'#%s',info); end if(nargout==1) varargout(1)={y}; end fprintf(['Generated *.hea file: ' fname '\n']) fclose(fid); %%%End of Main %%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Helper function function [y,adc_gain,baseline,check_sum]=quant(x,bit_res,gain,baseline,isint) %shift so that the signal midrange is at 0 min_x=min(x(~isnan(x))); nan_ind=isnan(x); rg=max(x(~isnan(x)))-min_x; if(isempty(baseline)) baseline=min_x + (rg/2); end x=x-baseline; if(isempty(gain)) %ADC gain (ADC units per physical unit). This value is a floating-point number %that specifies the difference in sample values that would be observed if a step %of one physical unit occurred in the original analog signal. For ECGs, the gain %is usually roughly equal to the R-wave amplitude in a lead that is roughly parallel %to the mean cardiac electrical axis. If the gain is zero or missing, this indicates %that the signal amplitude is uncalibrated; in such cases, a value of 200 (DEFGAIN, %defined in <wfdb/wfdb.h>) ADC units per physical unit may be assumed. %Dynamic range of encoding / Dynamic Range of Data --but leave 1 quant level for NaN adc_gain=(2^(bit_res-1)-1)/(rg/2); y=x.*adc_gain; if(isint) %Use this option if you know the signal is quantitized, and you %want to remove round-off error by setting the original values to %integers prior to fixed point conversion df_db=min(diff(sort(unique(y)))); y=y/df_db; adc_gain=adc_gain/df_db; end else %if gain is alreay passed don't do anything to the signal %the gain will be used in the header file only %Convert the signal to integers before encoding in order minimize round off %error adc_gain=gain; y=x; end %convert to appropiate bit type eval(['y=int' num2str(bit_res) '(y);']) %Shift WFDB NaN int value to a lower value so that they will not be read as NaN's by WFDB WFDBNAN=-32768; iswfdbnan=find(y==WFDBNAN); %-12^15 are NaNs in WFDB if(~isempty(iswfdbnan)) y(iswfdbnan)=WFDBNAN-1; end %Set NaNs to WFDBNAN y(nan_ind)=WFDBNAN; %Calculate the 16-bit signed checksum of all samples in the signal check_sum=sum(y); M=check_sum/(2^15); if(M<0) check_sum=mod(check_sum,-2^15); if(~check_sum && abs(M)<1) check_sum=-2^15; elseif (mod(ceil(M),2)) check_sum=2^15 + check_sum; end else check_sum=mod(check_sum,2^15); if(mod(floor(M),2)) check_sum=-2^15+check_sum; end end %Calculate baseline (ADC units): %The baseline is an integer that specifies the sample %value corresponding to 0 physical units. baseline=baseline.*adc_gain; baseline=-round(baseline); function y=get_names(str,deli) y={}; old=1; ind=regexp(str,deli); ind(end+1)=length(str)+1; for i=1:length(ind) y(end+1)={str(old:ind(i)-1)}; old=ind(i)+1; end
github
dhirajhr/ECG-based-Biometric-Authentication-master
wfdbloadlib.m
.m
ECG-based-Biometric-Authentication-master/ECGMatlab_Project/Toolbox/wfdb-app-toolbox-0-9-9/mcode/wfdbloadlib.m
5,910
utf_8
feb96d305ef53118d12317d29239fc2c
function [varargout]=wfdbloadlib(varargin) % % [isloaded,config]=wfdbloadlib(debugLevel,networkWaitTime) % % Loads the WDFDB libarary if it has not been loaded already into the % MATLAB classpath. And optionally prints configuration environment and debug information % regarding the settings used by the classes in the JAR file. % % Inputs: % % debugLevel % (Optional) 1x1 integer between 0 and 5 represeting the level of debug information to output from % Java class when output configuration information. Level 0 (no debug information), % level =5 is maximum level of information output by the class (logger set to finest). Default is level 0. % % networkWaitTime % (Optional) 1x1 integer representing the longest time in % milliseconds for which the JVM should wait for a data stream from % PhysioNet (default is =1000 , ie one second). If you need to change this time to a % longer value across the entire toolbox, it is better modify to default value in the source % code below and restart MATLAB. % % % Written by Ikaro Silva, 2013 % Last Modified: December 3, 2014 % Since 0.0.1 % % %endOfHelp mlock persistent isloaded wfdb_path wfdb_native_path %%%%% SYSTEM WIDE CONFIGURATION PARAMETERS %%%%%%% %%% Change these values for system wide configuration of the WFDB binaries %If you are using your own custom version of the WFDB binaries, set this to true %NOTE: this parameter is completely ignored if the 'WFDB_COMMAND_PATH' parameter %described above is set (i.e.: the library will used the WFDB commands located % according to the path in 'WFDB_COMMAND_PATH'). %You will need to restart MATLAB/Octave if to sync the changes. %The default is to used commands shipped with the toolbox, this location can be obtained by running the command: %[~,config]=wfdbloadlib; config.WFDB_NATIVE_BIN WFDB_CUSTOMLIB=0; %WFDB_PATH: If empty, will use the default given config.WFDB_PATH %this is where the toolbox searches for data files (*.dat, *.hea etc). %When unistalling the toolbox, you may wish to clear this directory to save space. %See http://www.physionet.org/physiotools/wag/setwfd-1.htm for more details. WFDB_PATH=[]; %WFDBCAL: If empty, will use the default giveng confing.WFDBCAL %The WFDB library require calibration data in order to convert between sample values %(expressed in analog-to-digital converter units, or adus) and physical units. %See http://www.physionet.org/physiotools/wag/wfdbca-5.htm for more details. WFDBCAL=[]; %debugLevel: Ouput JVM information while running commands debugLevel=0; %networkWaitTime: Setting maximum waiting period for fetching data from %PhysioNet servers (default location: http://physionet.org/physiobank). networkWaitTime=1000; %%%% END OF SYSTEM WIDE CONFIGURATION PARAMETERS inputs={'debugLevel','networkWaitTime'}; for n=1:nargin if(~isempty(varargin{n})) eval([inputs{n} '=varargin{n};']) end end inOctave=is_octave; fsep=filesep; if(ispc && inOctave) fsep=['\\']; %Need to escape '\' for regexp in Octave and Windows end if(isempty(isloaded)) jar_path=which('wfdbloadlib'); cut=strfind(jar_path,'wfdbloadlib.m'); wfdb_path=jar_path(1:cut-1); if(~inOctave) ml_jar_version=version('-java'); else %In Octave ml_jar_version=javaMethod('getProperty','java.lang.System','java.version'); ml_jar_version=['Java ' ml_jar_version]; end %Check if path has not been added yet if(~isempty(strfind(ml_jar_version,'Java 1.6'))) wfdb_path=[wfdb_path 'wfdb-app-JVM6-0-9-9.jar']; elseif(~isempty(strfind(ml_jar_version,'Java 1.7'))) wfdb_path=[wfdb_path 'wfdb-app-JVM7-0-9-9.jar']; else error(['Cannot load on unsupported JVM: ' ml_jar_version]) end javaaddpath(wfdb_path) isloaded=1; end outputs={'isloaded','config'}; for n=1:nargout if(n>1) config.MATLAB_VERSION=version; config.inOctave=inOctave; if(inOctave) javaWfdbExec=javaObject('org.physionet.wfdb.Wfdbexec','wfdb-config',WFDB_CUSTOMLIB); javaWfdbExec.setLogLevel(debugLevel); config.WFDB_VERSION=char(javaMethod('execToStringList',javaWfdbExec,{'--version'})); else javaWfdbExec=org.physionet.wfdb.Wfdbexec('wfdb-config',WFDB_CUSTOMLIB); javaWfdbExec.setLogLevel(debugLevel); config.WFDB_VERSION=char(javaWfdbExec.execToStringList('--version')); end env=regexp(char(javaWfdbExec.getEnvironment),',','split'); for e=1:length(env) tmpstr=regexp(env{e},'=','split'); varname=strrep(tmpstr{1},'[',''); varname=strrep(varname,' ',''); varname=strrep(varname,']',''); eval(['config.' varname '=''' tmpstr{2} ''';']) end config.MATLAB_PATH=strrep(which('wfdbloadlib'),'wfdbloadlib.m',''); config.SUPPORT_EMAIL='[email protected]'; wver=regexp(wfdb_path,fsep,'split'); config.WFDB_JAVA_VERSION=wver{end}; config.DEBUG_LEVEL=debugLevel; config.NETWORK_WAIT_TIME=networkWaitTime; config.MATLAB_ARCH=computer('arch'); %Remove empty spaces from arch name del=strfind(config.osName,' '); config.osName(del)=[]; %Define WFDB Environment variables if(isempty(WFDB_PATH)) WFDB_PATH=['. ' 'file:// ' config.MATLAB_PATH 'database http://physionet.org/physiobank/database']; end if(isempty(WFDBCAL)) WFDBCAL=[config.WFDB_JAVA_HOME fsep 'database' fsep 'wfdbcal']; end config.WFDB_PATH=WFDB_PATH; config.WFDBCAL=WFDBCAL; config.WFDB_CUSTOMLIB=WFDB_CUSTOMLIB; end eval(['varargout{n}=' outputs{n} ';']) end %% subfunction that checks if we are in octave function r = is_octave () r = exist ('OCTAVE_VERSION', 'builtin')>0;
github
dhirajhr/ECG-based-Biometric-Authentication-master
woody.m
.m
ECG-based-Biometric-Authentication-master/ECGMatlab_Project/Toolbox/wfdb-app-toolbox-0-9-9/mcode/woody.m
6,574
utf_8
0679ae612c072e1ba908279a60af43e0
function [out]=woody(x,varargin) % % [out]=woody(x,tol,max_it,est_mthd,xcorr_mthd) % % Weighted average using Woody average for a signal % with jitter. Parameters: % % x Signal measurements. Each COLUMN represents % and independent measure of the signal (or channel). % tol Tolerance paremeter to stop average (default is 0.1) % max_it Maximum number of iterations done on the average (default is 100). % est_mthd Estimation method to use. Options are: % 'woody' : classical approach (default) % 'thornton' : implements the Thornton approach that is also useful for different noise sources. % xcorr_mthd Determines what estimation method to use for the estimating the correlaation function using the % XCORR function. Options are: % 'biased' - scales the raw cross-correlation by 1/M. % 'unbiased' - scales the raw correlation by 1/(M-abs(lags)). (Default) % out Final averaged waveform (time aligned). % % % % Written by Ikaro Silva % % Since 0.9.5 % % %%%Example 1 %%%% % t=[0:1/1000:1]; % N=1001; % x=sin(2*pi*t)+sin(4*pi*t)+sin(8*pi*t); % y=exp(0.01*[-1*[500:-1:1] 0 -1*[1:500]]); % s=x.*y; % sig1=0; % sig2=0.1; % M=100; % S=zeros(N,M); % center=501; % TAU=round((rand(1,M)-0.5)*160); % for i=1:M, % tau=TAU(i); % % if(tau<0) % S(:,i)=[s(-1*tau:end)'; zeros(-1*(tau+1),1)]; % else % S(:,i)=[zeros(tau,1);s(1:N-tau)'; ]; % end % if(i<50) % S(:,i)=S(:,i) + randn(N,1).*sig1; % else % S(:,i)=S(:,i) + randn(N,1).*sig2; % end % end % % [wood]=woody(S,[],[],'woody','biased'); % [thor]=woody(S,[],[],'thornton','biased'); % figure; % subplot(211) % plot(s,'b','LineWidth',2);grid on;hold on;plot(S,'r');plot(s,'b','LineWidth',2) % legend('Signal','Measurements') % subplot(212) % plot(s);hold on;plot(mean(S,2),'r');plot(wood,'g');plot(thor,'k') % legend('Signal','Normal Ave','Woody Ave','Thornton Ave');grid on %endOfHelp %Default parameter values tol= 0.1; max_it=100; est_mthd='woody'; xcorr_mthd='unbiased'; thornton_sub=3; %number of subaverages to use in the thornton procedure if(nargin>1) if(~isempty(varargin{1})) tol=varargin{1}; end if(nargin>2) if(~isempty(varargin{2})) max_it=varargin{2}; end if(nargin>3) if(~isempty(varargin{3})) est_mthd=varargin{3}; end if(nargin>4) if(~isempty(varargin{4})) xcorr_mthd=varargin{4}; end end end end end %Call repective averaging technique switch est_mthd case 'woody' out=woody_core(x,tol,max_it,xcorr_mthd); case 'thornton' %Implement procedure from Thornton 2008 [N,M]=size(x); K=floor(M/thornton_sub); %Call woody several times implementing the subaverages for k=1:K sub=thornton_sub*k; ind=round(linspace(1,M,sub+1)); if((length(ind)-2) > (M/2)) %Number of subaverages is equal to or just less than %half the number of trials, move to the final stage %and exit loop [out,est_lags]=woody_core(x,tol,max_it,xcorr_mthd); break end %Get woody average from the subaverages %procedure converges when there is no lag changes y=gen_subave(x,ind); %Generate sub averages y_old=y; err=1; while(err) [trash,est_lags]=woody_core(y,tol,max_it,xcorr_mthd); x=shift_data(x,est_lags,ind,N,M); y=gen_subave(x,ind); %Re-generate sub averages err=sum(abs(y(:)-y_old(:))); y_old=y; end end otherwise error(['Invalid option for est_mthd parameter: ' xcorr_mthd ' valid options are: woody, weighted, and thornton']) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%End of Maing Function%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%Helper Functions%%%%%%%%%%%% function x=shift_data(x,est_lags,ind,N,M) %Shifts individual trials within each subaverage K=length(est_lags); for k=1:K lag=est_lags(k); if(lag) if(k~=K) sel_ind=[ind(k):ind(k+1)-1]; else sel_ind=[ind(k):M]; end pad=length(sel_ind); if(lag>0) x(:,sel_ind)=[zeros(lag-1,pad); x(lag:end,sel_ind)]; %x(:,sel_ind)=[randn(lag-1,pad).*mean(std(x(:,sel_ind))).*0.001; x(lag:end,sel_ind)]; elseif(lag<0) x(:,sel_ind)=[x(1:N+lag,sel_ind); zeros(lag*-1,pad)]; %x(:,sel_ind)=[x(1:N+lag,sel_ind); randn(lag*-1,pad).*mean(std(x(:,sel_ind))).*0.001]; end end end function [out,varargout]=woody_core(x,tol,max_it,xcorr_mthd) [N,M]=size(x); mx=mean(x,2); p=zeros(N,1); conv=1; run=0; sig_x=diag(sqrt(x'*x)); X=xcorr(mx); ref=length(X)/2; if(mod(ref,2)) ref=ceil(ref); else ref=floor(ref); end if(nargout>1) %In this case we output the lag of the trials as well lag_data=zeros(1,M); end while(conv*(run<max_it)) z=zeros(N,1); w=ones(N,1); for i=1:M, y=x(:,i); xy=xcorr(mx,y,xcorr_mthd); [val,ind]=max(xy); if(ind>ref) lag=ref-ind-1; else lag=ref-ind; end if(lag>0) num=w(lag:end)-1; z(1:N-lag+1)=( z(1:N-lag+1).*num + y(lag:end))./w(lag:end); w(lag:end)=w(lag:end)+1; elseif(lag<0) num=w(lag*(-1)+1:end)-1; z(lag*(-1)+1:end)=( z(lag*(-1)+1:end).*num + y(1:N+lag) )./w(lag*(-1)+1:end); w(lag*(-1)+1:end)=w(lag*(-1)+1:end)+1; else z=z.*(w-1)./w + y./w; w=w+1; end if(exist('lag_data','var')) lag_data(i)=lag; end end old_mx=mx; mx=z; p_old=p; p=mx'*x./(sqrt(mx'*mx).*sig_x'); p=sum(p)./M; err=abs(p-p_old); if(err<tol) conv=0; end run=run+1; end out=mx; if(exist('lag_data','var')) varargout(1)={lag_data}; end function [y]=gen_subave(x,ind) [N,M]=size(x); T=length(ind)-1; y=zeros(N,T); %Generate Subaverages for i=1:T-1 y(:,i)=mean(x(:,ind(i):ind(i+1)-1),2); end y(:,end)=mean(x(:,ind(T):end),2);
github
dhirajhr/ECG-based-Biometric-Authentication-master
wfdbRecordViewer.m
.m
ECG-based-Biometric-Authentication-master/ECGMatlab_Project/Toolbox/wfdb-app-toolbox-0-9-9/mcode/wfdbRecordViewer.m
27,253
utf_8
c0504c65c81a11015aa85c985db1c311
function varargout = wfdbRecordViewer(varargin) % WFDBRECORDVIEWER MATLAB code for wfdbRecordViewer.fig % WFDBRECORDVIEWER, by itself, creates a new WFDBRECORDVIEWER or raises the existing % singleton*. % % H = WFDBRECORDVIEWER returns the handle to a new WFDBRECORDVIEWER or the handle to % the existing singleton*. % % WFDBRECORDVIEWER('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in WFDBRECORDVIEWER.M with the given input arguments. % % WFDBRECORDVIEWER('Property','Value',...) creates a new WFDBRECORDVIEWER or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before wfdbRecordViewer_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to wfdbRecordViewer_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help wfdbRecordViewer % Last Modified by GUIDE v2.5 30-Jan-2015 12:05:48 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @wfdbRecordViewer_OpeningFcn, ... 'gui_OutputFcn', @wfdbRecordViewer_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before wfdbRecordViewer is made visible. function wfdbRecordViewer_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to wfdbRecordViewer (see VARARGIN) global current_record records tm tm_step signalDescription % Choose default command line output for wfdbRecordViewer handles.output = hObject; % Update handles structure guidata(hObject, handles); [filename,directoryname] = uigetfile('*.hea','Select signal header file:'); cd(directoryname) tmp=dir('*.hea'); N=length(tmp); records=cell(N,1); current_record=1; for n=1:N fname=tmp(n).name; records(n)={fname(1:end-4)}; if(strcmp(fname,filename)) current_record=n; end end set(handles.RecorListMenu,'String',records) set(handles.RecorListMenu,'Value',current_record) loadRecord(records{current_record}) set(handles.signalList,'String',signalDescription) loadAnnotationList(records{current_record},handles); set(handles.slider1,'Max',tm(end)) set(handles.slider1,'Min',tm(1)) set(handles.slider1,'SliderStep',[1 1]); sliderStep=get(handles.slider1,'SliderStep'); tm_step=(tm(end)-tm(1)).*sliderStep(1); wfdbplot(handles) function varargout = wfdbRecordViewer_OutputFcn(~,~, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function PreviousButton_Callback(hObject, eventdata, handles) global current_record records current_record=current_record - 1; set(handles.RecorListMenu,'Value',current_record); Refresh(hObject, eventdata, handles) function NextButton_Callback(hObject, eventdata, handles) global current_record records current_record=current_record + 1; set(handles.RecorListMenu,'Value',current_record); Refresh(hObject, eventdata, handles) % -------------------------------------------------------------------- function FileMenu_Callback(hObject, eventdata, handles) % hObject handle to FileMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % -------------------------------------------------------------------- function OpenMenuItem_Callback(hObject, eventdata, handles) file = uigetfile('*.fig'); if ~isequal(file, 0) open(file); end % -------------------------------------------------------------------- function PrintMenuItem_Callback(hObject, eventdata, handles) printdlg(handles.figure1) % -------------------------------------------------------------------- function CloseMenuItem_Callback(hObject, eventdata, handles) selection = questdlg(['Close ' get(handles.figure1,'Name') '?'],... ['Close ' get(handles.figure1,'Name') '...'],... 'Yes','No','Yes'); if strcmp(selection,'No') return; end delete(handles.figure1) % --- Executes on selection change in RecorListMenu. function RecorListMenu_Callback(hObject, eventdata, handles) global current_record records current_record=get(handles.RecorListMenu,'Value'); Refresh(hObject, eventdata, handles) % --- Executes during object creation, after setting all properties. function RecorListMenu_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on slider movement. function slider1_Callback(hObject, eventdata, handles) wfdbplot(handles) % --- Executes during object creation, after setting all properties. function slider1_CreateFcn(hObject, eventdata, handles) if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function loadRecord(fname) global tm signal info tm_step signalDescription analysisSignal analysisTime h = waitbar(0,'Loading Data. Please wait...'); try [tm,signal]=rdmat(fname); catch [tm,signal]=rdsamp(fname); end info=wfdbdesc(fname); R=length(info); analysisSignal=[]; analysisTime=[]; signalDescription=cell(R,1); for r=1:R signalDescription(r)={info(r).Description}; end close(h) function loadAnn1(fname,annName) global ann1 h = waitbar(0,'Loading Annotations. Please wait...'); if(strcmp(fname,'none')) ann1=[]; else [ann1,type,subtype,chan,num,comments]=rdann(fname,annName); end close(h) function loadAnn2(fname,annName) global ann2 h = waitbar(0,'Loading Annotations. Please wait...'); if(strcmp(fname,'none')) ann1=[]; else [ann2,type,subtype,chan,num,comments]=rdann(fname,annName); end close(h) function loadAnnotationList(fname,handles) global ann1 ann2 annDiff ann1=[]; ann2=[]; annDiff=[]; tmp=dir([fname '*']); annotations={'none'}; exclude={'dat','hea','edf','mat'}; for i=1:length(tmp) name=tmp(i).name; st=strfind(name,'.'); if(~isempty(st)) tmp_ann=name(st+1:end); enter=1; for k=1:length(exclude) if(strcmp(tmp_ann,exclude{k})) enter=0; end end if(enter) annotations(end+1)={tmp_ann}; end end end set(handles.Ann1Menu,'String',annotations) set(handles.Ann2Menu,'String',annotations) function wfdbplot(handles) global tm signal info tm_step ann1 ann2 annDiff ann1RR analysisSignal analysisTime analysisUnits analysisYAxis axes(handles.axes1); cla; %Normalize each signal and plot them with an offset [N,CH]=size(signal); offset=0.5; %Get time info center=get(handles.slider1,'Value'); maxSlide=get(handles.slider1,'Max'); minSlide=get(handles.slider1,'Min'); if(tm_step == ( tm(end)-tm(1) )) tm_start=tm(1); tm_end=tm(end); elseif(center==maxSlide) tm_end=tm(end); tm_start=tm_end - tm_step; elseif(center==minSlide) tm_start=tm(1); tm_end=tm_start + tm_step; else tm_start=center - tm_step/2; tm_end=center + tm_step/2; end [~,ind_start]=min(abs(tm-tm_start)); [~,ind_end]=min(abs(tm-tm_end)); DC=min(signal(ind_start:ind_end,:),[],1); sig=signal - repmat(DC,[N 1]); SCALE=max(sig(ind_start:ind_end,:),[],1); SCALE(SCALE==0)=1; sig=offset.*sig./repmat(SCALE,[N 1]); OFFSET=offset.*[1:CH]; sig=sig + repmat(OFFSET,[N 1]); for ch=1:CH; plot(tm(ind_start:ind_end),sig(ind_start:ind_end,ch)) hold on ; grid on if(~isempty(ann1)) tmp_ann1=ann1((ann1>ind_start) & (ann1<ind_end)); if(~isempty(tmp_ann1)) if(length(tmp_ann1)<30) msize=8; else msize=5; end plot(tm(tmp_ann1),OFFSET(ch),'go','MarkerSize',msize,'MarkerFaceColor','g') end end if(~isempty(ann2)) tmp_ann2=ann2((ann2>ind_start) & (ann2<ind_end)); if(~isempty(tmp_ann2)) if(length(tmp_ann2)<30) msize=8; else msize=5; end plot(tm(tmp_ann2),OFFSET(ch),'r*','MarkerSize',msize,'MarkerFaceColor','r') end end if(~isempty(info(ch).Description)) text(tm(ind_start),ch*offset+0.85*offset,info(ch).Description,'FontWeight','bold','FontSize',12) end end set(gca,'YTick',[]) set(gca,'YTickLabel',[]) set(gca,'FontSize',10) set(gca,'FontWeight','bold') xlabel('Time (seconds)') xlim([tm(ind_start) tm(ind_end)]) %Plot annotations in analysis window if(~isempty(annDiff) & (get(handles.AnnotationMenu,'Value')==2)) axes(handles.AnalysisAxes); df=annDiff((ann1>ind_start) & (ann1<ind_end)); plot(tm(tmp_ann1),df,'k*-') text(tm(tmp_ann1(1)),max(df),'Ann Diff','FontWeight','bold','FontSize',12) grid on ylabel('Diff (seconds)') xlim([tm(ind_start) tm(ind_end)]) end %Plot custom signal in the analysis window if(~isempty(analysisSignal)) axes(handles.AnalysisAxes); if(isempty(analysisYAxis)) %Standard 2D Plot plot(analysisTime,analysisSignal,'k') grid on; else if(isfield(analysisYAxis,'isImage') && analysisYAxis.isImage) %Plot scaled image imagesc(analysisSignal) else %3D Plot with colormap surf(analysisTime,analysisYAxis.values,analysisSignal,'EdgeColor','none'); axis xy; axis tight; colormap(analysisYAxis.map); view(0,90); end ylim([analysisYAxis.minY analysisYAxis.maxY]) end xlim([tm(ind_start) tm(ind_end)]) if(~isempty(analysisUnits)) ylabel(analysisUnits) end else %Plot RR series in analysis window if(~isempty(ann1RR) & (get(handles.AnnotationMenu,'Value')==3)) Nann=length(ann1); axes(handles.AnalysisAxes); ind=(ann1(1:end)>ind_start) & (ann1(1:end)<ind_end); ind=find(ind==1)+1; if(~isempty(ind) && ind(end)> Nann) ind(end)=[]; end tm_ind=ann1(ind); del_ind=find(tm_ind>N); if(~isempty(del_ind)) ind(ann1(ind)==tm_ind(del_ind))=[]; tm_ind(del_ind)=[]; end if(~isempty(ind) && ind(end)>length(ann1RR)) del_ind=find(ind>length(ann1RR)); ind(del_ind)=[]; tm_ind(del_ind)=[]; end plot(tm(tm_ind),ann1RR(ind),'k*-') text(tm(tm_ind(1)),max(df),'RR Series','FontWeight','bold','FontSize',12) grid on ylabel('Interval (seconds)') if(~isnan(ind_start) && ~isnan(ind_end) && ~(ind_start==ind_end)) xlim([tm(ind_start) tm(ind_end)]) end end end % --- Executes on selection change in TimeScaleSelection. function TimeScaleSelection_Callback(hObject, eventdata, handles) global tm_step tm TM_SC=[tm(end)-tm(1) 120 60 30 15 10 5 1]; index = get(handles.TimeScaleSelection, 'Value'); %Normalize step to time range if(TM_SC(index)>TM_SC(1)) index=1; end stp=TM_SC(index)/TM_SC(1); set(handles.slider1,'SliderStep',[stp stp*10]); tm_step=TM_SC(1).*stp(1); axes(handles.axes1); cla; wfdbplot(handles) % --- Executes during object creation, after setting all properties. function TimeScaleSelection_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in AmplitudeScale. function AmplitudeScale_Callback(hObject, eventdata, handles) wfdbplot(handles) % --- Executes during object creation, after setting all properties. function AmplitudeScale_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in Ann1Menu. function Ann1Menu_Callback(hObject, eventdata, handles) global ann1 records current_record ind = get(handles.Ann1Menu, 'Value'); annStr=get(handles.Ann1Menu, 'String'); loadAnn1(records{current_record},annStr{ind}) wfdbplot(handles) % --- Executes during object creation, after setting all properties. function Ann1Menu_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in Ann2Menu. function Ann2Menu_Callback(hObject, eventdata, handles) global ann2 records current_record ind = get(handles.Ann2Menu, 'Value'); annStr=get(handles.Ann2Menu, 'String'); loadAnn2(records{current_record},annStr{ind}) wfdbplot(handles) % --- Executes during object creation, after setting all properties. function Ann2Menu_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function AnnotationMenu_Callback(hObject, eventdata, handles) global ann1 ann1RR info tm ann2 tips=0; Fs=double(info(1).SamplingFrequency); annStr=get(handles.AnnotationMenu,'String'); index=get(handles.AnnotationMenu,'Value'); switch(annStr{index}) case 'Plot Annotation Differences' h = waitbar(0,'Comparing Annotations. Please wait...'); annDiff=[]; %Compare annotation with ann1menu being the reference N=length(ann1); if(~isempty(ann2)) [A1,A2]=meshgrid(ann1,ann2); annDiff=min(abs(A1-A2))./Fs; end close(h) wfdbplot(handles) case 'Plot RR Series Ann1' h = waitbar(0,'Generating RR Series. Please wait...'); %Compare annotation with ann1menu being the reference ann1RR=diff(ann1)./double(info(1).SamplingFrequency); close(h) wfdbplot(handles) case 'Add annotations to Ann1' %Get closest sample using ginput if(tips) helpdlg('Left click to add multiple annotations. Hit Enter when done.','Adding Annotations'); end axes(handles.axes1); [x,~]= ginput; %Convert to samples ann to ann1 x=round(x*Fs); ann1=sort([ann1;x]); %Refresh annotation plot wfdbplot(handles) case 'Delete annotations from Ann1' %Get closest sample using ginput if(tips) helpdlg('Left click on annotations to remove multiple. Hit Enter when done.','Removing Annotations'); end axes(handles.axes1); [x,~]= ginput; rmN=length(x); rm_ind=zeros(rmN,1); for n=1:rmN [~,tmp_ind]=min(abs(x(n)-tm(ann1))); rm_ind(n)=tmp_ind; end if~(isempty(rm_ind)) ann1(rm_ind)=[]; end %Refresh annotation plot wfdbplot(handles) case 'Delete annotations in a range from Ann1' %Get closest sample using ginput if(tips) helpdlg('Left click on start and end regions. Hit Enter when done.','Removing Annotations'); end axes(handles.axes1); [x,~]= ginput; [~,start_ind]=min(abs(x(end-1)-tm(ann1))); [~,end_ind]=min(abs(x(end)-tm(ann1))); ann1(start_ind:end_ind)=[]; %Refresh annotation plot wfdbplot(handles) case 'Edit annotations in Ann1' %Modify closest sample using ginput if(tips) helpdlg('Left click on waveform will shift closest annotation to the clicked point. Hit Enter when done.','Adding Annotations'); end axes(handles.axes1); [x,~]= ginput; editN=length(x); edit_ind=zeros(editN,1); for n=1:editN [~,tmp_ind]=min(abs(x(n)-tm(ann1))); edit_ind(n)=tmp_ind; end if~(isempty(edit_ind)) ann1(edit_ind)=round(x*Fs); end %Refresh annotation plot wfdbplot(handles) case 'Add annotations in a range from Ann2 to Ann2' global ann2 if(tips) helpdlg('Left click on waveform to select start and end of region to add from Ann2 to Ann1. Hit Enter when done.','Adding Annotations'); end axes(handles.axes1); [x,~]= ginput; [~,start_ind]=min(abs(x(1)-tm(ann2))); [~,end_ind]=min(abs(x(2)-tm(ann2))); ann1=sort([ann1;ann2(start_ind:end_ind)]); %Refresh annotation plot wfdbplot(handles) case 'Save modified annotations of Ann1' global records current_record defaultAnn=get(handles.Ann1Menu,'String'); defaultInd=get(handles.Ann1Menu,'Value'); defName={[defaultAnn{defaultInd} '_x']}; newAnn=inputdlg('Enter new annotation name:','Save Annotation',1,defName); h=waitbar(0,['Saving annotation file: ' records{current_record} '.' newAnn{1}]); wrann(records{current_record},newAnn{1},ann1); close(h) end function AnnotationMenu_CreateFcn(hObject, eventdata, handles) if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function Refresh(hObject, eventdata, handles) global records current_record loadRecord(records{current_record}) loadAnnotationList(records{current_record},handles) Ann1Menu_Callback(hObject, eventdata, handles) Ann2Menu_Callback(hObject, eventdata, handles) %AnalysisMenu_Callback(hObject, eventdata, handles) % --- Executes on selection change in SignalMenu. function SignalMenu_Callback(hObject, eventdata, handles) % hObject handle to SignalMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns SignalMenu contents as cell array % contents{get(hObject,'Value')} returns selected item from SignalMenu global tm signal info analysisSignal analysisTime analysisUnits analysisYAxis contents = cellstr(get(hObject,'String')); ind=get(handles.signalList,'Value'); str= contents{get(hObject,'Value')}; %Get Raw Signal analysisTime=tm; analysisSignal=signal(:,ind); analysisUnits=strsplit(info(ind).Gain,'/'); if(length(analysisUnits)>1) analysisUnits=analysisUnits{2}; else analysisUnits=[]; end Fs=double(info(ind).SamplingFrequency); analysisYAxis=[]; switch str case 'Plot Raw Signal' wfdbplot(handles); case 'Apply General Filter' [analysisSignal]=wfdbFilter(analysisSignal); wfdbplot(handles); case '60/50 Hz Notch Filter' [analysisSignal]=wfdbNotch(analysisSignal,Fs); wfdbplot(handles); case 'Resonator Filter' [analysisSignal]=wfdbResonator(analysisSignal,Fs); wfdbplot(handles); case 'Custom Function' [analysisSignal,analysisTime]=wfdbFunction(analysisSignal,analysisTime,Fs); wfdbplot(handles); case 'Spectogram Analysis' [analysisSignal,analysisTime,analysisYAxis,analysisUnits]=wfdbSpect(analysisSignal,Fs); wfdbplot(handles); case 'Wavelets Analysis' [analysisSignal,analysisYAxis,analysisUnits]=wfdbWavelets(analysisSignal,Fs); wfdbplot(handles); end % --- Executes during object creation, after setting all properties. function SignalMenu_CreateFcn(hObject, eventdata, handles) % hObject handle to SignalMenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in signalList. function signalList_Callback(hObject, eventdata, handles) % hObject handle to signalList (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns signalList contents as cell array % contents{get(hObject,'Value')} returns selected item from signalList % --- Executes during object creation, after setting all properties. function signalList_CreateFcn(hObject, eventdata, handles) % hObject handle to signalList (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function [analysisSignal]=wfdbFilter(analysisSignal) %Set Low-pass default values dlgParam.prompt={'Filter Design Function (should return "a" and "b", for use by FILTFILT ):'}; dlgParam.defaultanswer={'b=fir1(48,[0.1 0.5]);a=1;'}; dlgParam.name='Filter Design Command'; dlgParam.numlines=1; answer=inputdlg(dlgParam.prompt,dlgParam.name,dlgParam.numlines,dlgParam.defaultanswer); h = waitbar(0,'Filtering Data. Please wait...'); try eval([answer{1} ';']); analysisSignal=filtfilt(b,a,analysisSignal); catch errordlg(['Unable to filter data! Error: ' lasterr]) end close(h) function [analysisSignal]=wfdbNotch(analysisSignal,Fs) % References: % *Rangayyan (2002), "Biomedical Signal Analysis", IEEE Press Series in BME % % *Hayes (1999), "Digital Signal Processing", Schaum's Outline %Set Low-pass default values dlgParam.prompt={'Control Paramter (0 < r < 1 ):','Notch Frequency (Hz):'}; dlgParam.defaultanswer={'0.995','60'}; dlgParam.name='Notch Filter Design'; dlgParam.numlines=1; answer=inputdlg(dlgParam.prompt,dlgParam.name,dlgParam.numlines,dlgParam.defaultanswer); h = waitbar(0,'Filtering Data. Please wait...'); r = str2num(answer{1}); % Control parameter. 0 < r < 1. fn= str2num(answer{2}); cW = cos(2*pi*fn/Fs); b=[1 -2*cW 1]; a=[1 -2*r*cW r^2]; try eval([answer{1} ';']); analysisSignal=filtfilt(b,a,analysisSignal); catch errordlg(['Unable to filter data! Error: ' lasterr]) end close(h) function [analysisSignal]=wfdbResonator(analysisSignal,Fs) % References: % *Rangayyan (2002), "Biomedical Signal Analysis", IEEE Press Series in BME % % *Hayes (1999), "Digital Signal Processing", Schaum's Outline %Set Low-pass default values dlgParam.prompt={'Resonating Frequency (Hz):','Q factor:'}; dlgParam.defaultanswer={num2str(Fs/5),'50'}; dlgParam.name='Resonator Filter Design'; dlgParam.numlines=1; answer=inputdlg(dlgParam.prompt,dlgParam.name,dlgParam.numlines,dlgParam.defaultanswer); h = waitbar(0,'Filtering Data. Please wait...'); fn= str2num(answer{1}); K= str2num(answer{2}); %Similar to 'Q1' but more accurate %For details see IEEE SP 2008 (5), pg 113 beta=1+K; f=pi*fn/Fs; numA=tan(pi/4 - f); denA=sin(2*f)+cos(2*f)*numA; A=numA/denA; b=[1 -2*A A.^2]; a=[ (beta + K*(A^2)) -2*A*(beta+K) ((A^2)*beta + K)]; try eval([answer{1} ';']); analysisSignal=filtfilt(b,a,analysisSignal); catch errordlg(['Unable to filter data! Error: ' lasterr]) end close(h) function [analysisSignal,analysisTime]=wfdbFunction(analysisSignal,analysisTime,Fs) dlgParam.prompt={'Custom Function must output variables ''analysisSignal'' and ''analysisTime'''}; dlgParam.defaultanswer={'[analysisSignal,analysisTime]=foo(analysisSignal,analysisTime,Fs)'}; dlgParam.name='Evaluate Command:'; answer=inputdlg(dlgParam.prompt,dlgParam.name,dlgParam.numlines,dlgParam.defaultanswer); h = waitbar(0,'Executing code on signal. Please wait...'); try eval([answer{1} ';']); analysisSignal=filtfilt(b,a,analysisSignal); catch errordlg(['Unable to execute code!! Error: ' lasterr]) end close(h) function [analysisSignal,analysisTime,analysisYAxis,analysisUnits]=wfdbSpect(analysisSignal,Fs) persistent dlgParam if(isempty(dlgParam)) dlgParam.prompt={'window size','overlap size','Min Frequency (Hz)','Max Frequency (Hz)','colormap'}; dlgParam.window=2^10; dlgParam.minY= 0; dlgParam.maxY= floor(Fs/2); dlgParam.noverlap=round(dlgParam.window/2); dlgParam.map='jet'; dlgParam.name='Spectogram Parameters'; dlgParam.numlines=1; end dlgParam.defaultanswer={num2str(dlgParam.window),num2str(dlgParam.noverlap),... num2str(dlgParam.minY),num2str(dlgParam.maxY),dlgParam.map}; answer=inputdlg(dlgParam.prompt,dlgParam.name,dlgParam.numlines,dlgParam.defaultanswer); h = waitbar(0,'Calculating spectogram. Please wait...'); dlgParam.window= str2num(answer{1}); dlgParam.noverlap= str2num(answer{2}); analysisYAxis.minY= str2num(answer{3}); analysisYAxis.maxY= str2num(answer{4}); analysisYAxis.map=answer{5}; dlgParam.minY=analysisYAxis.minY; dlgParam.maxY=analysisYAxis.maxY; dlgParam.map=analysisYAxis.map; [~,F,analysisTime,analysisSignal] = spectrogram(analysisSignal,dlgParam.window,... dlgParam.noverlap,dlgParam.window,Fs,'yaxis'); analysisSignal=10*log10(abs(analysisSignal)); analysisYAxis.values=F; analysisUnits='Frequency (Hz)'; close(h) function [analysisSignal,analysisYAxis,analysisUnits]=wfdbWavelets(analysisSignal,Fs) persistent dlgParam if(isempty(dlgParam)) dlgParam.prompt={'wavelet','scales','colormap','logScale'}; dlgParam.wavelet='coif2'; dlgParam.scales='1:28'; dlgParam.map='jet'; dlgParam.log='false'; dlgParam.name='Wavelet Parameters'; dlgParam.numlines=1; end dlgParam.defaultanswer={num2str(dlgParam.wavelet),num2str(dlgParam.scales),dlgParam.map,dlgParam.log}; answer=inputdlg(dlgParam.prompt,dlgParam.name,dlgParam.numlines,dlgParam.defaultanswer); h = waitbar(0,'Calculating wavelets. Please wait...'); dlgParam.wavelet= answer{1}; dlgParam.scales = str2num(answer{2}); dlgParam.map= answer{3}; dlgParam.log= answer{4}; analysisYAxis.minY= dlgParam.scales(1); analysisYAxis.maxY= dlgParam.scales(end); analysisYAxis.map=dlgParam.map; analysisYAxis.isImage=1; coefs = cwt(analysisSignal,dlgParam.scales,dlgParam.wavelet); analysisSignal = wscalogram('',coefs); if(strcmp(dlgParam.log,'true')) analysisSignal=log(analysisSignal); end analysisYAxis.values=dlgParam.scales; analysisUnits='Scale'; close(h)
github
smaillot/3D_pose_estimation-master
DLT_system.m
.m
3D_pose_estimation-master/DLT_system.m
218
utf_8
680c2d45bf8b0c87f45b63317d5ff0b0
function A = DLT_system(u, x) A = []; for i=1:length(u) A = [A ; DLT_point2vec(u(i,:), x(i,:))]; end end function A = DLT_point2vec(u, x) A = kron(eye(2), [x,1]); A = [A , -u' * [x,1]]; end
github
shenwei1231/caffe-LDLForests-master
classification_demo.m
.m
caffe-LDLForests-master/matlab/demo/classification_demo.m
5,412
utf_8
8f46deabe6cde287c4759f3bc8b7f819
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 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 % % 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 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 you Matlab search PATH 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
xhuang31/AANE_MATLAB-master
Performance.m
.m
AANE_MATLAB-master/Performance.m
3,202
utf_8
ad6f8f3b492868c911c6b76ecf5768ec
function [F1macro,F1micro] = Performance(Xtrain,Xtest,Ytrain,Ytest) %Evaluate the performance of classification for both multi-class and multi-label Classification % [F1macro,F1micro] = Performance(Xtrain,Xtest,Ytrain,Ytest) % % Xtrain is the training data with row denotes instances, column denotes features % Xtest is the test data with row denotes instances, column denotes features % Ytrain is the training labels with row denotes instances % Ytest is the test labels % Copyright 2017, Xiao Huang and Jundong Li. % $Revision: 1.0.0 $ $Date: 2017/10/18 00:00:00 $ %% Multi class Classification if size(Ytrain,2) == 1 && length(unique(Ytrain)) > 2 t = templateSVM('Standardize',true); model = fitcecoc(Xtrain,Ytrain,'Learners',t); pred_label = predict(model,Xtest); [micro, macro] = micro_macro_PR(pred_label,Ytest); F1macro = macro.fscore; F1micro = micro.fscore; else %% For multi-label classification, computer micro and macro rng default % For repeatability NumLabel = size(Ytest,2); macroTP = zeros(NumLabel,1); macroFP = zeros(NumLabel,1); macroFN = zeros(NumLabel,1); macroF = zeros(NumLabel,1); for i = 1:NumLabel model = fitcsvm(Xtrain,Ytrain(:,i),'Standardize',true,'KernelFunction','RBF','KernelScale','auto'); pred_label = predict(model,Xtest); mat = confusionmat(Ytest(:,i), pred_label); if size(mat,1) == 1 macroTP(i) = sum(pred_label); macroFP(i) = 0; macroFN(i) = 0; if macroTP(i) ~= 0 macroF(i) = 1; end else macroTP(i) = mat(2,2); macroFP(i) = mat(1,2); macroFN(i) = mat(2,1); macroF(i) = 2*macroTP(i)/(2*macroTP(i)+macroFP(i)+macroFN(i)); end end F1macro = mean(macroF); F1micro = 2*sum(macroTP)/(2*sum(macroTP)+sum(macroFP)+sum(macroFN)); end end function [micro, macro] = micro_macro_PR(pred_label,orig_label) % computer micro and macro: precision, recall and fscore mat = confusionmat(orig_label, pred_label); len = size(mat,1); macroTP = zeros(len,1); macroFP = zeros(len,1); macroFN = zeros(len,1); macroP = zeros(len,1); macroR = zeros(len,1); macroF = zeros(len,1); for i = 1:len macroTP(i) = mat(i,i); macroFP(i) = sum(mat(:, i))-mat(i,i); macroFN(i) = sum(mat(i,:))-mat(i,i); macroP(i) = macroTP(i)/(macroTP(i)+macroFP(i)); macroR(i) = macroTP(i)/(macroTP(i)+macroFN(i)); macroF(i) = 2*macroP(i)*macroR(i)/(macroP(i)+macroR(i)); end % macroP(isnan(macroP)) = 0; % macroR(isnan(macroR)) = 0; macroF(isnan(macroF)) = 0; % macro.precision = mean(macroP); % macro.recall = mean(macroR); macro.fscore = mean(macroF); micro.precision = sum(macroTP)/(sum(macroTP)+sum(macroFP)); micro.recall = sum(macroTP)/(sum(macroTP)+sum(macroFN)); micro.fscore = 2*micro.precision*micro.recall/(micro.precision+micro.recall); end
github
wincle626/HLS_Legup-master
sobel.m
.m
HLS_Legup-master/legup-4.0/examples/multipump/sobel/sobel.m
926
utf_8
071ab66f3b2a331ededc44016739b25a
% from http://angeljohnsy.blogspot.ca/2011/12/sobel-edge-detection.html function sobel(image, Thresh) if (nargin < 2) Thresh = 100; end A=imread(image); B=rgb2gray(A); C=double(B); for i=1:size(C,1)-2 for j=1:size(C,2)-2 %Sobel mask for x-direction: Gx=((2*C(i+2,j+1)+C(i+2,j)+C(i+2,j+2))-(2*C(i,j+1)+C(i,j)+C(i,j+2))); %Sobel mask for y-direction: Gy=((2*C(i+1,j+2)+C(i,j+2)+C(i+2,j+2))-(2*C(i+1,j)+C(i,j)+C(i+2,j))); %The gradient of the image %keyboard; B(i,j)=sqrt(Gx.^2+Gy.^2); C(i,j)=abs(Gx)+abs(Gy); end end %keyboard %figure,imshow(A); title('Original'); %figure,imshow(B); title('Sobel gradient'); B=max(B,Thresh); B(B==round(Thresh))=0; B=uint8(B); %keyboard figure,imshow(B~=0);title('Edge detected Image'); C=max(C,Thresh); C(C==round(Thresh))=0; C=uint8(C); figure,imshow(C~=0);title('Approx Edge detected Image');
github
wincle626/HLS_Legup-master
dct8x8.m
.m
HLS_Legup-master/legup-4.0/examples/multipump/idct/dct8x8.m
1,576
utf_8
5665ac4c6e35b7683e7a75ef560e7ce9
% from: http://www.mathworks.com/matlabcentral/fileexchange/15494-2-d-dctidct-for-jpeg-compression function O = DCT_8X8(I) cosines = [1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 0.9808 0.8315 0.5556 0.1951 -0.1951 -0.5556 -0.8315 -0.9808 0.9239 0.3827 -0.3827 -0.9239 -0.9239 -0.3827 0.3827 0.9239 0.8315 -0.1951 -0.9808 -0.5556 0.5556 0.9808 0.1951 -0.8315 0.7071 -0.7071 -0.7071 0.7071 0.7071 -0.7071 -0.7071 0.7071 0.5556 -0.9808 0.1951 0.8315 -0.8315 -0.1951 0.9808 -0.5556 0.3827 -0.9239 0.9239 -0.3827 -0.3827 0.9239 -0.9239 0.3827 0.1951 -0.5556 0.8315 -0.9808 0.9808 -0.8315 0.5556 -0.1951]; alpha = [0.1250 0.1768 0.1768 0.1768 0.1768 0.1768 0.1768 0.1768 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500]; O = double(zeros(8,8)); for p = 1 : 8 for q = 1 : 8 s = double(0); for m = 1 : 8 for n = 1 : 8 s = s + (double(I(m,n)) * cosines(p,m) * cosines(q,n)); end end O(p,q) = alpha(p,q) * s; end end return
github
wincle626/HLS_Legup-master
idct8x8.m
.m
HLS_Legup-master/legup-4.0/examples/multipump/idct/idct8x8.m
1,732
utf_8
b81ad096903d006ddfd0dadbbe6d41c2
% from: http://www.mathworks.com/matlabcentral/fileexchange/15494-2-d-dctidct-for-jpeg-compression % a = int32(255*rand(8,8)) % a-int32(idct8x8(dct8x8(a))) % a-int32(idct2(dct2(a))) % correct to within a decimal place % idct2(a)-idct8x8(a)>0.1 function O = IDCT_8X8(I) cosines = [1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 1.0000 0.9808 0.8315 0.5556 0.1951 -0.1951 -0.5556 -0.8315 -0.9808 0.9239 0.3827 -0.3827 -0.9239 -0.9239 -0.3827 0.3827 0.9239 0.8315 -0.1951 -0.9808 -0.5556 0.5556 0.9808 0.1951 -0.8315 0.7071 -0.7071 -0.7071 0.7071 0.7071 -0.7071 -0.7071 0.7071 0.5556 -0.9808 0.1951 0.8315 -0.8315 -0.1951 0.9808 -0.5556 0.3827 -0.9239 0.9239 -0.3827 -0.3827 0.9239 -0.9239 0.3827 0.1951 -0.5556 0.8315 -0.9808 0.9808 -0.8315 0.5556 -0.1951]; alpha = [0.1250 0.1768 0.1768 0.1768 0.1768 0.1768 0.1768 0.1768 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.1768 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500 0.2500]; O = double(zeros(8,8)); for m = 1 : 8 for n = 1 : 8 s = double(0); for p = 1 : 8 for q = 1 : 8 s = s + (alpha(p,q) * double(I(p,q)) * cosines(p,m) * cosines(q,n)); end end O(m,n) = s; end end return
github
swchao/personFrameworkDetectCMU-master
classification_demo.m
.m
personFrameworkDetectCMU-master/3rdparty/caffe/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
mathematical-tours/mathematical-tours.github.io-master
format_ticks.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/cepstrum/format_ticks.m
17,920
utf_8
9451fdec572f520b405113bde2e3fb6c
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% BEGIN HEADER %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Name: format_tick.m % %Usage: [hx,hy] = ... % format_tick(h,tickx,ticky,tickposx,tickposy,rotx,roty,offset,... % varargin); % %Description: Replace or appends XTickLabels and YTickLabels of axis handle % h with input tickx and ticky array % %***NOTE!***: BE SURE TO DELETE ANY PREVIOUS TEXT OBJECTS CREATED BY THIS % FUNCTION BEFORE RUNNING THIS ON THE SAME FIGURE TWICE % %Required Inputs: % h : handle of axis to change tick labels (can use gca) % tickx : cell array of tick labels or string to append to current % labels % (Defaults to appending degree symbols if not input) % %Optional Inputs % ticky : cell array of tick labels or string to append to current % labels (Can use [] or not specify to ignore) % tickposx : Vector of x positions where you want the tick labels % (Can use [] or not specify to ignore) % tickposy : Vector of y positions where you want the tick labels % (Can use [] or not specify to ignore) % rotx : Number of degrees to rotate x tick labels % (Can use [] or not specify to ignore) Default = 0.0 % roty : Number of degrees to rotate y tick labels % (Can use [] or not specify to ignore) Default = 0.0 % offset : Label offsets from axis in fraction of total range % (Can use [] or not specify to ignore) Default = 0.0 % %Optional Inputs:% % Any standard text formatting parameters such as % 'FontSize','FontWeight',etc. % Use the same way you would in a set command after putting % in the required input values. % %Outputs: % hx: handle of text objects created for XTickLabels % hy: handle of text objects created for YTickLabels % %Function Calls: % None % %Required Data Files: % None % % %Example: % ;Example 1: Append Degree Symbols to X-Axis of a Plot % figure; % plot(1:10,1:10); % [hx,hy] = format_ticks(gca); % % ;Example 2: Append Degree Symbolts to X and Y Axes of a Plot % figure; % plot(1:10,1:10); % [hx,hy] = format_ticks(gca,'^{\circ}','^{\circ}'); % % ;Example 2: Append Degree Symbolts to X and Y Axes of a Plot and % ; put a 45 degree tilt on them % figure; % plot(1:10,1:10); % [hx,hy] = format_ticks(gca,'^{\circ}','^{\circ}',[],[],45,45); % % ;Example 3: Make a plot with fractions on the x tick labels % figure % plot(1:10,1:10); % [hx,hy] = format_ticks(gca,{'$1$','$2\frac{1}{2}$','$9\frac{1}{2}$'},... % [],[1,2.5,9.5]); % % ;Example 4: Make a plot with degrees on y tick label and fractions % ; on x % figure % plot(0:10,0:10); % [hx,hy] = format_ticks(gca,... % {'$0$','$2\frac{1}{2}$','$5$','$7\frac{1}{2}$','$10$'},... % '$^{\circ}$',[0,2.5,5,7.5,10],[],0,45,[],... % 'FontSize',16,'FontWeight','Bold'); % %Change Log: % 08/19/2007: Origin Version Created by Alex Hayes % ([email protected]) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% BEGIN FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hx,hy] = ... format_ticks(h,tickx,ticky,tickposx,tickposy,rotx,roty,offset,varargin) %define axis text offset (percentage of total range) if ~exist('offset','var'); offset = 0.02; elseif length(offset) == 0; offset = 0.02; end; %make sure the axis handle input really exists if ~exist('h','var'); h = gca; warning(['Axis handle NOT Input, Defaulting to Current Axes, '... num2str(h)]); elseif length(h) == 0; h = gca; warning(['Axis Handle NOT Input, Defaulting to Current Axes, '... num2str(h)]); elseif ~ishandle(h(1)) warning(['Input (' num2str(h(1)) ') is NOT an axis handle, ' ... 'defaulting to current axis, ' num2str(h)]); h = gca; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%BEGIN: FIRST THE X-AXIS TICK LABELS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %fix the XTickLabels if they have been erased in the past if length(get(h,'XTickLabel'))==0; set(h,'XTickLabel',get(h,'XTick')); end; %set the xtick positions if entered if exist('tickposx','var'); if length(tickposx) > 0; set(h,'XTick',tickposx); end; tickposx = get(h,'XTick'); set(h,'XTickLabel',tickposx); end; %make sure the xtick positions are in the xlimit range if exist('tickposx','var'); if length(tickposx) > 0; lim = get(h,'XLim'); if lim(1) > min(tickposx); lim(1) = min(tickposx); end; if lim(2) < max(tickposx); lim(2) = max(tickposx); end; set(h,'XLim',lim); end; end; %get the tick labels and positions if the user did not input them if ~exist('tickx','var'); tickx = get(h,'XTickLabel'); if ischar(tickx); temp = tickx; tickx = cell(1,size(temp,1)); for j=1:size(temp,1); tickx{j} = strtrim( temp(j,:) ); end; end; append = '^{\circ}'; for j=1:length(tickx); tickx{j} = [tickx{j} append]; end; elseif length(tickx) == 0; tickx = get(h,'XTickLabel'); if ischar(tickx); temp = tickx; tickx = cell(1,size(temp,1)); for j=1:size(temp,1); tickx{j} = strtrim( temp(j,:) ); end; end; append = '^{\circ}'; for j=1:length(tickx); tickx{j} = [tickx{j} append]; end; elseif isstr(tickx); append = tickx; tickx = get(h,'XTickLabel'); if ischar(tickx); temp = tickx; tickx = cell(1,size(temp,1)); for j=1:size(temp,1); tickx{j} = strtrim( temp(j,:) ); end; end; if strcmp(append(1),'$'); for j=1:length(tickx); tickx{j} = ['$' tickx{j} append(2:end)]; end; else; for j=1:length(tickx); tickx{j} = [tickx{j} append]; end; end; elseif ~iscell(tickx ); warning(['Input TICKX variable is not a compatible string ' ... 'or cell array! Returning...']); return; end; %find out if we have to use the LaTex interpreter temp = tickx{1}; if strcmp(temp(1),'$'); latex_on = 1; else; latex_on = 0; end; %erase the current tick label set(h,'XTickLabel',{}); %get the x tick positions if the user did not input them if ~exist('tickposx','var'); tickposx = get(h,'XTick'); elseif length(tickx) == 0; tickposx = get(h,'XTick'); end; %get the y tick positions if the user did not input them if ~exist('tickposy','var'); tickposy = get(h,'YTick'); elseif length(tickposy) == 0; tickposy = get(h,'YTick'); end; %set the new tick positions set(h,'YTick',tickposy); set(h,'XTick',tickposx); %check the lengths of the xtick positions and xtick labels l1 = length(tickx); l2 = length(tickposx); if l1==0; set(h,'XTickLabel',tickx); end; if l1~=l2; disp(['Length of XTick = ' num2str(length(tickposx))]); disp(['Length of XTickLabel = ' num2str(length(tickx))]); if l2 < l1; warning(['Reducing Length of XTickLabel!']); else; warning(['Reducing Length of XTick!']); end; l3 = min([l1,l2]); tickx = tickx{1:l3}; tickposx = tickposx(1:l3); end; %set rotation to 0 if not input if ~exist('rotx','var'); rotx = 0; elseif length(rotx) == 0; rotx = 0; end; %Convert the cell labels to a character string %tickx = char(tickx); tickx = cellstr(tickx); %Make the XTICKS! lim = get(h,'YLim'); if min(tickposy) < lim(1); lim(1) = min(tickposy); end; if max(tickposy) > lim(2); lim(2) = max(tickposy); end; if rotx == 0; if latex_on; hx = text(tickposx,... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposx),1),... tickx,'HorizontalAlignment','center',... 'VerticalAlignment','top','rotation',rotx,'interpreter','LaTex'); else; hx = text(tickposx,... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposx),1),... tickx,'HorizontalAlignment','center',... 'VerticalAlignment','top','rotation',rotx); end; elseif rotx < 0; if latex_on; hx = text(tickposx,... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposx),1),... tickx,'HorizontalAlignment','left','interpreter','LaTex',... 'VerticalAlignment','middlefi','rotation',rotx); else; hx = text(tickposx,... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposx),1),... tickx,'HorizontalAlignment','left',... 'VerticalAlignment','middle','rotation',rotx); end; else; if latex_on; hx = text(tickposx,... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposx),1),... tickx,'HorizontalAlignment','right','interpreter','LaTex',... 'VerticalAlignment','middle','rotation',rotx); else; hx = text(tickposx,... repmat(lim(1)-offset*(lim(2)-lim(2)),length(tickposx),1),... tickx,'HorizontalAlignment','right',... 'VerticalAlignment','middle','rotation',rotx); end; end; %Get and set the text size and weight set(hx,'FontSize',get(h,'FontSize')); set(hx,'FontWeight',get(h,'FontWeight')); %Set the additional parameters if they were input if length(varargin) > 2; command_string = ['set(hx']; for j=1:2:length(varargin); command_string = [command_string ',' ... '''' varargin{j} ''',varargin{' num2str(j+1) '}']; end; command_string = [command_string ');']; eval(command_string); end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%END: FIRST THE X-AXIS TICK LABELS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%BEGIN: NOW THE Y-AXIS TICK LABELS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %only move forward if we are doing anything to the yticks if ~exist('ticky'); hy = -1; elseif length(ticky)==0; hy = -1; else; %fix the YTickLabels if they have been erased in the past if length(get(h,'YTickLabel'))==0; set(h,'YTickLabel',get(h,'YTick')); end; %set the ytick positions if entered if exist('tickposy','var'); if length(tickposy) > 0; set(h,'YTick',tickposy); set(h,'YTickLabel',tickposy); end; end; %make sure the xtick positions are in the xlimit range if exist('tickposy','var'); if length(tickposy) > 0; lim = get(h,'YLim'); if lim(1) > min(tickposy); lim(1) = min(tickposy); end; if lim(2) < max(tickposy); lim(2) = max(tickposy); end; set(h,'YLim',lim); end; end; %get the tick labels and positions if the user did not input them if ~exist('ticky','var'); ticky = get(h,'YTickLabel'); if ischar(ticky); temp = ticky; ticky = cell(1,size(temp,1)); for j=1:size(temp,1); ticky{j} = strtrim( temp(j,:) ); end; end; append = '^{\circ}'; for j=1:length(ticky); ticky{j} = [ticky{j} append]; end; elseif length(ticky) == 0; ticky = get(h,'YTickLabel'); if ischar(ticky); temp = ticky; ticky = cell(1,size(temp,1)); for j=1:size(temp,1); ticky{j} = strtrim( temp(j,:) ); end; end; append = '^{\circ}'; for j=1:length(ticky); ticky{j} = [ticky{j} append]; end; elseif isstr(ticky); append = ticky; ticky = get(h,'YTickLabel'); if ischar(ticky); temp = ticky; ticky = cell(1,size(temp,1)); for j=1:size(temp,1); ticky{j} = strtrim( temp(j,:) ); end; end; if strcmp(append(1),'$'); for j=1:length(ticky); ticky{j} = ['$' ticky{j} append(2:end)]; end; else; for j=1:length(ticky); ticky{j} = [ticky{j} append]; end; end; elseif ~iscell(ticky ); warning(['Input TICKY variable is not a compatible string ' ... 'or cell array! Returning...']); return; end; %find out if we have to use the LaTex interpreter temp = ticky{1}; if strcmp(temp(1),'$'); latex_on = 1; else; latex_on = 0; end; %erase the current tick label set(h,'YTickLabel',{}); %get the x tick positions if the user did not input them if ~exist('tickposy','var'); tickposy = get(h,'YTick'); elseif length(ticky) == 0; tickposy = get(h,'YTick'); end; %get the x tick positions if the user did not input them if ~exist('tickposx','var'); tickposx = get(h,'YTick'); elseif length(tickposx) == 0; tickposx = get(h,'XTick'); end; %set the new tick positions set(h,'YTick',tickposy); % set(h,'XTick',tickposx); %check the lengths of the xtick positions and xtick labels l1 = length(ticky); l2 = length(tickposy); if l1==0; set(h,'YTickLabel',ticky); end; if l1~=l2; disp(['Length of YTick = ' num2str(length(tickposy))]); disp(['Length of YTickLabel = ' num2str(length(ticky))]); if l2 < l1; warning(['Reducing Length of YTickLabel!']); else; warning(['Reducing Length of YTick!']); end; l3 = min([l1,l2]); ticky = ticky{1:l3}; tickposy = tickposy(1:l3); end; %set rotation to 0 if not input if ~exist('roty','var'); roty = 0; elseif length(roty) == 0; roty = 0; end; %Convert the cell labels to a character string %ticky = char(ticky); ticky = cellstr(ticky); %Make the YTICKS! lim = get(h,'XLim'); if min(tickposx) < lim(1); lim(1) = min(tickposx); end; if max(tickposx) > lim(2); lim(2) = max(tickposx); end; if roty == 0; if latex_on; hy = text(... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposy),1),... tickposy,... ticky,'VerticalAlignment','middle',... 'HorizontalAlignment','right','rotation',roty,'interpreter','LaTex'); else; hy = text(... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposy),1),... tickposy,... ticky,'VerticalAlignment','middle',... 'HorizontalAlignment','right','rotation',roty); end; elseif roty < 180; if latex_on; hy = text(... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposy),1),... tickposy,... ticky,'VerticalAlignment','middle',... 'HorizontalAlignment','right','rotation',roty,'interpreter','LaTex'); else; hy = text(... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposy),1),... tickposy,... ticky,'VerticalAlignment','middle',... 'HorizontalAlignment','right','rotation',roty); end; else; if latex_on; hy = text(... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposy),1),... tickposy,... ticky,'VerticalAlignment','middle',... 'HorizontalAlignment','right','rotation',roty,'interpreter','LaTex'); else; hy = text(... repmat(lim(1)-offset*(lim(2)-lim(1)),length(tickposy),1),... tickposy,... ticky,'VerticalAlignment','middle',... 'HorizontalAlignment','right','rotation',roty); end; end; %Get and set the text size and weight set(hy,'FontSize',get(h,'FontSize')); set(hy,'FontWeight',get(h,'FontWeight')); %Set the additional parameters if they were input if length(varargin) > 2; command_string = ['set(hy']; for j=1:2:length(varargin); command_string = [command_string ',' ... '''' varargin{j} ''',varargin{' num2str(j+1) '}']; end; command_string = [command_string ');']; eval(command_string); end; end;
github
mathematical-tours/mathematical-tours.github.io-master
Hungarian.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/newton-fractal/Hungarian.m
9,328
utf_8
51e60bc9f1f362bfdc0b4f6d67c44e80
function [Matching,Cost] = Hungarian(Perf) % % [MATCHING,COST] = Hungarian_New(WEIGHTS) % % A function for finding a minimum edge weight matching given a MxN Edge % weight matrix WEIGHTS using the Hungarian Algorithm. % % An edge weight of Inf indicates that the pair of vertices given by its % position have no adjacent edge. % % MATCHING return a MxN matrix with ones in the place of the matchings and % zeros elsewhere. % % COST returns the cost of the minimum matching % Written by: Alex Melin 30 June 2006 % Initialize Variables Matching = zeros(size(Perf)); % Condense the Performance Matrix by removing any unconnected vertices to % increase the speed of the algorithm % Find the number in each column that are connected num_y = sum(~isinf(Perf),1); % Find the number in each row that are connected num_x = sum(~isinf(Perf),2); % Find the columns(vertices) and rows(vertices) that are isolated x_con = find(num_x~=0); y_con = find(num_y~=0); % Assemble Condensed Performance Matrix P_size = max(length(x_con),length(y_con)); P_cond = zeros(P_size); P_cond(1:length(x_con),1:length(y_con)) = Perf(x_con,y_con); if isempty(P_cond) Cost = 0; return end % Ensure that a perfect matching exists % Calculate a form of the Edge Matrix Edge = P_cond; Edge(P_cond~=Inf) = 0; % Find the deficiency(CNUM) in the Edge Matrix cnum = min_line_cover(Edge); % Project additional vertices and edges so that a perfect matching % exists Pmax = max(max(P_cond(P_cond~=Inf))); P_size = length(P_cond)+cnum; P_cond = ones(P_size)*Pmax; P_cond(1:length(x_con),1:length(y_con)) = Perf(x_con,y_con); %************************************************* % MAIN PROGRAM: CONTROLS WHICH STEP IS EXECUTED %************************************************* exit_flag = 1; stepnum = 1; while exit_flag switch stepnum case 1 [P_cond,stepnum] = step1(P_cond); case 2 [r_cov,c_cov,M,stepnum] = step2(P_cond); case 3 [c_cov,stepnum] = step3(M,P_size); case 4 [M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(P_cond,r_cov,c_cov,M); case 5 [M,r_cov,c_cov,stepnum] = step5(M,Z_r,Z_c,r_cov,c_cov); case 6 [P_cond,stepnum] = step6(P_cond,r_cov,c_cov); case 7 exit_flag = 0; end end % Remove all the virtual satellites and targets and uncondense the % Matching to the size of the original performance matrix. Matching(x_con,y_con) = M(1:length(x_con),1:length(y_con)); Cost = sum(sum(Perf(Matching==1))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % STEP 1: Find the smallest number of zeros in each row % and subtract that minimum from its row %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [P_cond,stepnum] = step1(P_cond) P_size = length(P_cond); % Loop throught each row for ii = 1:P_size rmin = min(P_cond(ii,:)); P_cond(ii,:) = P_cond(ii,:)-rmin; end stepnum = 2; %************************************************************************** % STEP 2: Find a zero in P_cond. If there are no starred zeros in its % column or row start the zero. Repeat for each zero %************************************************************************** function [r_cov,c_cov,M,stepnum] = step2(P_cond) % Define variables P_size = length(P_cond); r_cov = zeros(P_size,1); % A vector that shows if a row is covered c_cov = zeros(P_size,1); % A vector that shows if a column is covered M = zeros(P_size); % A mask that shows if a position is starred or primed for ii = 1:P_size for jj = 1:P_size if P_cond(ii,jj) == 0 && r_cov(ii) == 0 && c_cov(jj) == 0 M(ii,jj) = 1; r_cov(ii) = 1; c_cov(jj) = 1; end end end % Re-initialize the cover vectors r_cov = zeros(P_size,1); % A vector that shows if a row is covered c_cov = zeros(P_size,1); % A vector that shows if a column is covered stepnum = 3; %************************************************************************** % STEP 3: Cover each column with a starred zero. If all the columns are % covered then the matching is maximum %************************************************************************** function [c_cov,stepnum] = step3(M,P_size) c_cov = sum(M,1); if sum(c_cov) == P_size stepnum = 7; else stepnum = 4; end %************************************************************************** % STEP 4: Find a noncovered zero and prime it. If there is no starred % zero in the row containing this primed zero, Go to Step 5. % Otherwise, cover this row and uncover the column containing % the starred zero. Continue in this manner until there are no % uncovered zeros left. Save the smallest uncovered value and % Go to Step 6. %************************************************************************** function [M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(P_cond,r_cov,c_cov,M) P_size = length(P_cond); zflag = 1; while zflag % Find the first uncovered zero row = 0; col = 0; exit_flag = 1; ii = 1; jj = 1; while exit_flag if P_cond(ii,jj) == 0 && r_cov(ii) == 0 && c_cov(jj) == 0 row = ii; col = jj; exit_flag = 0; end jj = jj + 1; if jj > P_size; jj = 1; ii = ii+1; end if ii > P_size; exit_flag = 0; end end % If there are no uncovered zeros go to step 6 if row == 0 stepnum = 6; zflag = 0; Z_r = 0; Z_c = 0; else % Prime the uncovered zero M(row,col) = 2; % If there is a starred zero in that row % Cover the row and uncover the column containing the zero if sum(find(M(row,:)==1)) ~= 0 r_cov(row) = 1; zcol = find(M(row,:)==1); c_cov(zcol) = 0; else stepnum = 5; zflag = 0; Z_r = row; Z_c = col; end end end %************************************************************************** % STEP 5: Construct a series of alternating primed and starred zeros as % follows. Let Z0 represent the uncovered primed zero found in Step 4. % Let Z1 denote the starred zero in the column of Z0 (if any). % Let Z2 denote the primed zero in the row of Z1 (there will always % be one). Continue until the series terminates at a primed zero % that has no starred zero in its column. Unstar each starred % zero of the series, star each primed zero of the series, erase % all primes and uncover every line in the matrix. Return to Step 3. %************************************************************************** function [M,r_cov,c_cov,stepnum] = step5(M,Z_r,Z_c,r_cov,c_cov) zflag = 1; ii = 1; while zflag % Find the index number of the starred zero in the column rindex = find(M(:,Z_c(ii))==1); if rindex > 0 % Save the starred zero ii = ii+1; % Save the row of the starred zero Z_r(ii,1) = rindex; % The column of the starred zero is the same as the column of the % primed zero Z_c(ii,1) = Z_c(ii-1); else zflag = 0; end % Continue if there is a starred zero in the column of the primed zero if zflag == 1; % Find the column of the primed zero in the last starred zeros row cindex = find(M(Z_r(ii),:)==2); ii = ii+1; Z_r(ii,1) = Z_r(ii-1); Z_c(ii,1) = cindex; end end % UNSTAR all the starred zeros in the path and STAR all primed zeros for ii = 1:length(Z_r) if M(Z_r(ii),Z_c(ii)) == 1 M(Z_r(ii),Z_c(ii)) = 0; else M(Z_r(ii),Z_c(ii)) = 1; end end % Clear the covers r_cov = r_cov.*0; c_cov = c_cov.*0; % Remove all the primes M(M==2) = 0; stepnum = 3; % ************************************************************************* % STEP 6: Add the minimum uncovered value to every element of each covered % row, and subtract it from every element of each uncovered column. % Return to Step 4 without altering any stars, primes, or covered lines. %************************************************************************** function [P_cond,stepnum] = step6(P_cond,r_cov,c_cov) a = find(r_cov == 0); b = find(c_cov == 0); minval = min(min(P_cond(a,b))); P_cond(find(r_cov == 1),:) = P_cond(find(r_cov == 1),:) + minval; P_cond(:,find(c_cov == 0)) = P_cond(:,find(c_cov == 0)) - minval; stepnum = 4; function cnum = min_line_cover(Edge) % Step 2 [r_cov,c_cov,M,stepnum] = step2(Edge); % Step 3 [c_cov,stepnum] = step3(M,length(Edge)); % Step 4 [M,r_cov,c_cov,Z_r,Z_c,stepnum] = step4(Edge,r_cov,c_cov,M); % Calculate the deficiency cnum = length(Edge)-sum(r_cov)-sum(c_cov);
github
mathematical-tours/mathematical-tours.github.io-master
glasso_solver.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/graphical-lasso/glasso_solver.m
2,722
utf_8
6796909c4c43ae392d5d83535db957be
% Graphical Lasso function % Author: Xiaohui Chen ([email protected]) % Version: 2012-Feb function [Theta W] = glasso_solver(S, rho, maxIt, tol) % Solve the graphical Lasso % minimize_{Theta > 0} tr(S*Theta) - logdet(Theta) + rho * ||Theta||_1 % Ref: Friedman et al. (2007) Sparse inverse covariance estimation with the % graphical lasso. Biostatistics. % Note: This function needs to call an algorithm that solves the Lasso % problem. Here, we choose to use to the function *lassoShooting* (shooting % algorithm) for this purpose. However, any Lasso algorithm in the % penelized form will work. % % Input: % S -- sample covariance matrix % rho -- regularization parameter % maxIt -- maximum number of iterations % tol -- convergence tolerance level % % Output: % Theta -- inverse covariance matrix estimate % W -- regularized covariance matrix estimate, W = Theta^-1 p = size(S,1); if nargin < 4, tol = 1e-6; end if nargin < 3, maxIt = 1e2; end % Initialization W = S + rho * eye(p); % diagonal of W remains unchanged W_old = W; i = 0; % Graphical Lasso loop while i < maxIt, i = i+1; for j = p:-1:1, jminus = setdiff(1:p,j); [V D] = eig(W(jminus,jminus)); d = diag(D); X = V * diag(sqrt(d)) * V'; % W_11^(1/2) Y = V * diag(1./sqrt(d)) * V' * S(jminus,j); % W_11^(-1/2) * s_12 b = lassoShooting(X, Y, rho, maxIt, tol); W(jminus,j) = W(jminus,jminus) * b; W(j,jminus) = W(jminus,j)'; end % Stop criterion if norm(W-W_old,1) < tol, break; end W_old = W; end if i == maxIt, fprintf('%s\n', 'Maximum number of iteration reached, glasso may not converge.'); end Theta = W^-1; % Shooting algorithm for Lasso (unstandardized version) function b = lassoShooting(X, Y, lambda, maxIt, tol), if nargin < 4, tol = 1e-6; end if nargin < 3, maxIt = 1e2; end % Initialization [n,p] = size(X); if p > n, b = zeros(p,1); % From the null model, if p > n else b = X \ Y; % From the OLS estimate, if p <= n end b_old = b; i = 0; % Precompute X'X and X'Y XTX = X'*X; XTY = X'*Y; % Shooting loop while i < maxIt, i = i+1; for j = 1:p, jminus = setdiff(1:p,j); S0 = XTX(j,jminus)*b(jminus) - XTY(j); % S0 = X(:,j)'*(X(:,jminus)*b(jminus)-Y) if S0 > lambda, b(j) = (lambda-S0) / norm(X(:,j),2)^2; elseif S0 < -lambda, b(j) = -(lambda+S0) / norm(X(:,j),2)^2; else b(j) = 0; end end delta = norm(b-b_old,1); % Norm change during successive iterations if delta < tol, break; end b_old = b; end if i == maxIt, fprintf('%s\n', 'Maximum number of iteration reached, shooting may not converge.'); end
github
mathematical-tours/mathematical-tours.github.io-master
plot_quadtree.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/cart/toolbox-cart/plot_quadtree.m
2,304
utf_8
36dc15aa95e9dab104a6f90ce381d27c
function plot_quadtree(W, f, options) % plot_quadtree - plot an image quadtree % % plot_quadtree(T, f, options); % % f is a background image. % % Copyright (c) 2010 Gabriel Peyre options.null = 0; if nargin<2 f = []; end n = size(f,1); J = length(W); str = 'r'; str_geom = 'b'; hold on; % display image if ~isempty(f) %f = f'; %f = f(end:-1:1,:); %f = fliplr(f); imagesc([0 1],[0 1],f); colormap gray(256); end plot_square([0,0], 1, str); axis square; axis off; axis equal; cx = [.5]; cy = [.5]; v = 1; for j=1:J z = v(:)*0; z(v(:)) = 1:length(v(:)); w = 1/2^j; % width of a square for k=1:length(W{j}) if W{j}(k)==0 plot_cross([cy(z(k)) cx(z(k))], w*2, str); end end % update for the next scale cx1 = zeros(2^j,2^j); cx1(1:2:end,1:2:end) = cx-w/2; cx1(2:2:end,1:2:end) = cx+w/2; cx1(1:2:end,2:2:end) = cx-w/2; cx1(2:2:end,2:2:end) = cx+w/2; cy1 = zeros(2^j,2^j); cy1(1:2:end,1:2:end) = cy-w/2; cy1(2:2:end,1:2:end) = cy-w/2; cy1(1:2:end,2:2:end) = cy+w/2; cy1(2:2:end,2:2:end) = cy+w/2; cx = cx1; cy = cy1; % update for the next scale v1 = zeros(2^j,2^j); v1(1:2:end,1:2:end) = v*4-3; v1(2:2:end,1:2:end) = v*4-2; v1(1:2:end,2:2:end) = v*4-1; v1(2:2:end,2:2:end) = v*4; v = v1; end axis ij %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_cross(pos, w, str) pos = swap_pos(pos); if nargin<3 str = 'r'; end x = [pos(1)-w/2, pos(1)+w/2]; y = [pos(2), pos(2)]; plot(x,y, str); x = [pos(1), pos(1)]; y = [pos(2)-w/2, pos(2)+w/2]; plot(x,y, str); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_square(pos, w, str) % pos = swap_pos(pos); if nargin<3 str = 'r'; end x = [pos(1), pos(1)+w, pos(1)+w, pos(1), pos(1)]; y = [pos(2), pos(2), pos(2)+w, pos(2)+w, pos(2)]; plot(x,y, str); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_square_geometry(theta,pos,w, str) if nargin<4 str = 'b'; end % pos = pos(2:-1:1); x = pos(1)+w/2 + w/2*[cos(theta), -cos(theta)]; y = pos(2)+w/2 + w/2*[sin(theta), -sin(theta)]; plot(x,y, str); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pos1 = swap_pos(pos) pos1 = pos; % pos1 = pos(2:-1:1); %% pos1(1) = 1-pos1(1);
github
mathematical-tours/mathematical-tours.github.io-master
plot_tree.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/cart/toolbox-cart/plot_tree.m
1,658
utf_8
e6be3a012e8a2f5c2eb29c0eecc71e9e
function plot_tree(Tree) % plot_tree - display a tree % % plot_tree(Tree); % % Copyright (c) 2007 Gabriel Peyre J = length(Tree); % branching factor q = length(Tree{2})/length(Tree{1}); % edge edgecolor = 'b'; % leaf leafcolor = 'r.'; leafsize = 20; % node nodecolor = 'b.'; nodesize = 15; delta = [-0.018,-0.045]; textsize = 20; % clf; hold on; for j=1:J t = Tree{j}; hj = 1-(j-1)*1/J; Hj = 1-j*1/J; nj = q^(j-1); % number of nodes xj = linspace(0,1,nj+2); xj(1) = []; xj(end) = []; Xj = linspace(0,1,nj*q+2); Xj(1) = []; Xj(end) = []; for i=1:nj if t(i)==0 % plot two branch for s=1:q plot([xj(i) Xj(q*(i-1)+s)], [hj Hj], edgecolor); end % plot([xj(i) Xj(2*i)], [hj Hj], edgecolor); plot_point(xj(i), hj, nodecolor, nodesize); % plot the choice if 0 h = text( xj(i)+delta(1), hj+delta(2), num2str(t(i)) ); set(h, 'FontSize', textsize); set(h, 'FontWeight', 'bold'); end if j==J plot_point(Xj(2*i-1), Hj, leafcolor, leafsize); plot_point(Xj(2*i), Hj, leafcolor, leafsize); end elseif t(i)==+1 plot_point(xj(i), hj, leafcolor, leafsize); elseif t(i)==-1 % plot_point(xj(i), hj, 'k', leafsize/2); end end end % plot invisible bouding box h = plot([0 1 1 0], [0 0 1 1]); set(h, 'LineStyle', 'none'); hold off; axis tight; axis off; %%% function plot_point(x,y,c,s) h = plot(x, y, c); set(h, 'MarkerSize', s);
github
mathematical-tours/mathematical-tours.github.io-master
patcht.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-param/patcht.m
4,383
utf_8
bdaee35efdd1e4a99596366a2d565917
function patcht(FF,VV,TF,VT,I,Options) %% % This function PATCHT, will show a triangulated mesh like Matlab function % Patch but then with a texture. % % patcht(FF,VV,TF,VT,I,Options); % % inputs, % FF : Face list 3 x N with vertex indices % VV : Vertices 3 x M % TF : Texture list 3 x N with texture vertex indices % VT : Texture Coordinates s 2 x K, range must be [0..1] or real pixel postions % I : The texture-image RGB [O x P x 3] or Grayscale [O x P] % Options : Structure with options for the textured patch such as % EdgeColor, EdgeAlpha see help "Surface Properties :: Functions" % % Options.PSize : Special option, defines the image texturesize for each % individual polygon, a low number gives a more block % like texture, defaults to 64; % % note: % On a normal PC displaying 10,000 faces will take about 6 sec. % % Example, % % % Load Data; % load testdata; % % Show the textured patch % figure, patcht(FF,VV,TF,VT,I); % % Allow Camera Control (with left, right and center mouse button) % mouse3d % % Function is written by D.Kroon University of Twente (July 2010) % FaceColor is a texture Options.FaceColor='texturemap'; % Size of texture image used for every triangle if(isfield(Options,'PSize')) sizep=round(Options.PSize(1)); Options=rmfield(Options,'PSize'); else sizep=64; end % Check input sizes if(size(FF,2)~=size(TF,2)) error('patcht:inputs','Face list must be equal in size to texture-index list'); end if((ndims(I)~=2)&&(ndims(I)~=3)) error('patcht:inputs','No valid Input texture image'); end % Detect if grayscale or color image switch(size(I,3)) case 1 iscolor=false; case 3 iscolor=true; otherwise error('patcht:inputs','No valid Input texture image'); end if(max(VT(:))<2) % Remap texture coordinates to image coordinates VT2(:,1)=(size(I,1)-1)*(VT(:,1))+1; VT2(:,2)=(size(I,2)-1)*(VT(:,2))+1; else VT2=VT; end % Calculate the texture interpolation values [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep); % Split texture-image in r,g,b to allow fast 1D index Ir=I(:,:,1); if(iscolor), Ig=I(:,:,2); Ib=I(:,:,3); end % The Patch used for every triangle (rgb) Jr=zeros([(sizep+1) (sizep+1) 1],class(I)); if(iscolor) Jg=zeros([(sizep+1) (sizep+1) 1],class(I)); Jb=zeros([(sizep+1) (sizep+1) 1],class(I)); end hold on; % Loop through all triangles of the mesh for i=1:size(FF,1) % Get current triangle vertices and current texture-vertices V=VV(FF(i,:),:); Vt=VT2(TF(i,:),:); % Define the triangle as a surface x=[V(1,1) V(2,1); V(3,1) V(3,1)]; y=[V(1,2) V(2,2); V(3,2) V(3,2)]; z=[V(1,3) V(2,3); V(3,3) V(3,3)]; % Define the texture coordinates of the surface tx=[Vt(1,1) Vt(2,1) Vt(3,1) Vt(3,1)]; ty=[Vt(1,2) Vt(2,2) Vt(3,2) Vt(3,2)] ; xy=[tx(1) ty(1); tx(2) ty(2); tx(3) ty(3); tx(3) ty(3)]; % Calculate texture interpolation coordinates pos(:,1)=xy(1,1)*lambda1+xy(2,1)*lambda2+xy(3,1)*lambda3; pos(:,2)=xy(1,2)*lambda1+xy(2,2)*lambda2+xy(3,2)*lambda3; pos=round(pos); pos=max(pos,1); pos(:,1)=min(pos(:,1),size(I,1)); pos(:,2)=min(pos(:,2),size(I,2)); posind=(pos(:,1)-1)+(pos(:,2)-1)*size(I,1)+1; % Map texture to surface image Jr(jind)=Ir(posind); J(:,:,1)=Jr; if(iscolor) Jg(jind)=Ig(posind); Jb(jind)=Ib(posind); J(:,:,2)=Jg; J(:,:,3)=Jb; end % Show the surface surface(x,y,z,J,Options); end hold off; function [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep) % Define a triangle in the upperpart of an square, because only that % part is used by the surface function % x1=sizep; y1=sizep; x2=sizep; y2=0; x3=0 ;y3=0; x1=sizep; y1=sizep; x2=sizep; y2=0; x3=0 ;y3=sizep; % Calculate the bary centric coordinates (instead of creating a 2D image % with the interpolation values, we map them directly to an 1D vector) detT = (x1-x3)*(y2-y3) - (x2-x3)*(y1-y3); [x,y]=ndgrid(0:sizep,0:sizep); x=x(:); y=y(:); lambda1=((y2-y3).*(x-x3)+(x3-x2).*(y-y3))/detT; lambda2=((y3-y1).*(x-x3)+(x1-x3).*(y-y3))/detT; lambda3=1-lambda1-lambda2; % Make from 2D (surface)image indices 1D image indices [jx jy]=ndgrid(sizep-(0:sizep)+1,sizep-(0:sizep)+1); jind=(jx(:)-1)+(jy(:)-1)*(sizep+1)+1;
github
mathematical-tours/mathematical-tours.github.io-master
compute_boundary.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-param/compute_boundary.m
2,537
utf_8
1722359a4efff29fd344fc6e14eddba5
function boundary=compute_boundary(face, options) % compute_boundary - compute the vertices on the boundary of a 3D mesh % % boundary=compute_boundary(face); % % Copyright (c) 2007 Gabriel Peyre if size(face,1)<size(face,2) face=face'; end %% compute edges (i,j) that are adjacent to only 1 face A = compute_edge_face_ring(face); [i,j,v] = find(A); i = i(v==-1); j = j(v==-1); %% build the boundary by traversing the edges boundary = i(1); i(1) = []; j(1) = []; while not(isempty(i)) b = boundary(end); I = find(i==b); if isempty(I) I = find(j==b); if isempty(I) warning('Problem with boundary'); break; end boundary(end+1) = i(I); else boundary(end+1) = j(I); end i(I) = []; j(I) = []; end return; %% OLD CODE %% nvert=max(max(face)); nface=size(face,1); % count number of faces adjacent to a vertex A=sparse(nvert,nvert); for i=1:nface if verb progressbar(i,nface); end f=face(i,:); A(f(1),f(2))=A(f(1),f(2))+1; A(f(1),f(3))=A(f(1),f(3))+1; A(f(3),f(2))=A(f(3),f(2))+1; end A=A+A'; for i=1:nvert u=find(A(i,:)==1); if ~isempty(u) boundary=[i u(1)]; break; end end s=boundary(2); i=2; while(i<=nvert) u=find(A(s,:)==1); if length(u)~=2 warning('problem in boundary'); end if u(1)==boundary(i-1) s=u(2); else s=u(1); end if s~=boundary(1) boundary=[boundary s]; else break; end i=i+1; end if i>nvert warning('problem in boundary'); end %%% OLD %%% function v = compute_boundary_old(faces) nvert = max(face(:)); ring = compute_vertex_ring( face ); % compute boundary v = -1; for i=1:nvert % first find a starting vertex f = ring{i}; if f(end)<0 v = i; break; end end if v<0 error('No boundary found.'); end boundary = [v]; prev = -1; while true f = ring{v}; if f(end)>=0 error('Problem in boundary'); end if f(1)~=prev prev = v; v = f(1); else prev = v; v = f(end-1); end if ~isempty( find(boundary==v) ) % we have reach the begining of the boundary if v~=boundary(1) warning('Begining and end of boundary doesn''t match.'); else break; end end boundary = [boundary,v]; end
github
mathematical-tours/mathematical-tours.github.io-master
check_face_vertex.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-param/check_face_vertex.m
671
utf_8
21c65f119991c973909eedd356838dad
function [vertex,face] = check_face_vertex(vertex,face, options) % check_face_vertex - check that vertices and faces have the correct size % % [vertex,face] = check_face_vertex(vertex,face); % % Copyright (c) 2007 Gabriel Peyre vertex = check_size(vertex,2,4); face = check_size(face,3,4); %%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = check_size(a,vmin,vmax) if isempty(a) return; end if size(a,1)>size(a,2) a = a'; end if size(a,1)<3 && size(a,2)==3 a = a'; end if size(a,1)<=3 && size(a,2)>=3 && sum(abs(a(:,3)))==0 % for flat triangles % a = a'; end if size(a,1)<vmin || size(a,1)>vmax error('face or vertex is not of correct size'); end
github
mathematical-tours/mathematical-tours.github.io-master
patcht.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-param/patcht/patcht.m
4,465
utf_8
aff599d5c7bab679b7b543addd97579b
function patcht(FF,VV,TF,VT,I,Options) % This function PATCHT, will show a triangulated mesh like Matlab function % Patch but then with a texture. % % patcht(FF,VV,TF,VT,I,Options); % % inputs, % FF : Face list 3 x N with vertex indices % VV : Vertices 3 x M % TF : Texture list 3 x N with texture vertex indices % VT : Texture Coordinates s 2 x K, range must be [0..1] or real pixel postions % I : The texture-image RGB [O x P x 3] or Grayscale [O x P] % Options : Structure with options for the textured patch such as % EdgeColor, EdgeAlpha see help "Surface Properties :: Functions" % % Options.PSize : Special option, defines the image texturesize for each % individual polygon, a low number gives a more block % like texture, defaults to 64; % % note: % On a normal PC displaying 10,000 faces will take about 6 sec. % % Example, % % % Load Data; % load testdata; % % Show the textured patch % figure, patcht(FF,VV,TF,VT,I); % % Allow Camera Control (with left, right and center mouse button) % mouse3d % % Function is written by D.Kroon University of Twente (July 2010) % FaceColor is a texture Options.FaceColor='texturemap'; % Size of texture image used for every triangle if(isfield(Options,'PSize')) sizep=round(Options.PSize(1)); Options=rmfield(Options,'PSize'); else sizep=64; end % Check input sizes if(size(FF,2)~=size(TF,2)) error('patcht:inputs','Face list must be equal in size to texture-index list'); end if((ndims(I)~=2)&&(ndims(I)~=3)) error('patcht:inputs','No valid Input texture image'); end % Detect if grayscale or color image switch(size(I,3)) case 1 iscolor=false; case 3 iscolor=true; otherwise error('patcht:inputs','No valid Input texture image'); end if(max(VT(:))<2) % Remap texture coordinates to image coordinates VT2(:,1)=(size(I,1)-1)*(VT(:,1))+1; VT2(:,2)=(size(I,2)-1)*(VT(:,2))+1; else VT2=VT; end % Calculate the texture interpolation values [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep); % Split texture-image in r,g,b to allow fast 1D index Ir=I(:,:,1); if(iscolor), Ig=I(:,:,2); Ib=I(:,:,3); end % The Patch used for every triangle (rgb) Jr=zeros([(sizep+1) (sizep+1) 1],class(I)); if(iscolor) Jg=zeros([(sizep+1) (sizep+1) 1],class(I)); Jb=zeros([(sizep+1) (sizep+1) 1],class(I)); end hold on; % Loop through all triangles of the mesh for i=1:size(FF,1) % Get current triangle vertices and current texture-vertices V=VV(FF(i,:),:); Vt=VT2(TF(i,:),:); % Define the triangle as a surface x=[V(1,1) V(2,1); V(3,1) V(3,1)]; y=[V(1,2) V(2,2); V(3,2) V(3,2)]; z=[V(1,3) V(2,3); V(3,3) V(3,3)]; % Define the texture coordinates of the surface tx=[Vt(1,1) Vt(2,1) Vt(3,1) Vt(3,1)]; ty=[Vt(1,2) Vt(2,2) Vt(3,2) Vt(3,2)] ; xy=[tx(1) ty(1); tx(2) ty(2); tx(3) ty(3); tx(3) ty(3)]; % Calculate texture interpolation coordinates pos(:,1)=xy(1,1)*lambda1+xy(2,1)*lambda2+xy(3,1)*lambda3; pos(:,2)=xy(1,2)*lambda1+xy(2,2)*lambda2+xy(3,2)*lambda3; pos=round(pos); pos=max(pos,1); pos(:,1)=min(pos(:,1),size(I,1)); pos(:,2)=min(pos(:,2),size(I,2)); posind=(pos(:,1)-1)+(pos(:,2)-1)*size(I,1)+1; % Map texture to surface image Jr(jind)=Ir(posind); J(:,:,1)=Jr; if(iscolor) Jg(jind)=Ig(posind); Jb(jind)=Ib(posind); J(:,:,2)=Jg; J(:,:,3)=Jb; end % Show the surface surface(x,y,z,J,Options) end hold off; function [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep) % Define a triangle in the upperpart of an square, because only that % part is used by the surface function x1=sizep; y1=sizep; x2=sizep; y2=0; x3=0 ;y3=0; % Calculate the bary centric coordinates (instead of creating a 2D image % with the interpolation values, we map them directly to an 1D vector) detT = (x1-x3)*(y2-y3) - (x2-x3)*(y1-y3); [x,y]=ndgrid(0:sizep,0:sizep); x=x(:); y=y(:); lambda1=((y2-y3).*(x-x3)+(x3-x2).*(y-y3))/detT; lambda2=((y3-y1).*(x-x3)+(x1-x3).*(y-y3))/detT; lambda3=1-lambda1-lambda2; % Make from 2D (surface)image indices 1D image indices [jx jy]=ndgrid(sizep-(0:sizep)+1,sizep-(0:sizep)+1); jind=(jx(:)-1)+(jy(:)-1)*(sizep+1)+1;
github
mathematical-tours/mathematical-tours.github.io-master
mouse3d.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-param/patcht/mouse3d.m
11,755
utf_8
21e012d7de63f0c8898540286a7e366c
function mouse3d(varargin) % This function MOUSE3D enables mouse camera control on an certain figure % axes. % % Enable mouse control with mouse3d(axis-handle) or just mouse3d % % % MouseButtons % Left : Rotate % Right : Zoom % Center : Pan % Keys % 'r' : Change mouse rotation from inplane to outplane % 'i' : Go back to initial view % % Example, % [X,Y,Z] = peaks(30); % surf(X,Y,Z) % colormap hsv % % Enable mouse control % mouse3d % % Function is written by D.Kroon University of Twente (July 2010) if(nargin<1) handle=gca; else handle=varargin{1}; if(ishandle(handle)) if(~strcmpi(get(handle,'Type'),'axes')) error('mouse3d:input','no valid axis handle'); end else error('mouse3d:input','no valid axis handle'); end end handles.figure1=get(handle,'Parent'); handles.axes1=handle; mouse3d_OpeningFcn(gcf, handles, varargin); % --- Executes just before mouse3d is made visible. function mouse3d_OpeningFcn(hObject, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to mouse3d (see VARARGIN) % Choose default command line output for mouse3d handles.output = hObject; % UIWAIT makes mouse3d wait for user response (see UIRESUME) % uiwait(handles.figure1); data.mouse_position_pressed=[0 0]; data.mouse_position=[0 0]; data.mouse_position_last=[0 0]; data.mouse_pressed=false; data.mouse_button=''; data.firsttime=true; data.mouse_rotate=true; data=loadmousepointershapes(data); data.handles=handles; data.trans=[0 0 0]; data.Mview=[1 0 0 0;0 1 0 0; 0 0 1 0; 0 0 0 1]; setMyData(data); set(data.handles.axes1,'ButtonDownFcn',@axes1_ButtonDownFcn); set(data.handles.figure1,'WindowButtonMotionFcn',@figure1_WindowButtonMotionFcn); set(data.handles.figure1,'WindowButtonUpFcn',@figure1_WindowButtonUpFcn); set(data.handles.figure1,'KeyPressFcn',@figure1_KeyPressFcn); function setViewMatrix() data=getMyData; if(isempty(data)), return, end Mview=data.Mview; UpVector=Mview(1,1:3); Camtar=[0 0 0]; XYZ=Mview(2,1:3); Forward=Mview(3,1:3); UpVector=cross(cross(UpVector,Forward),Forward); trans2=Mview(1:3,1:3)\data.trans(:); Camtar=Camtar-Mview(1:3,4)'+trans2(1:3)'*data.scale; XYZ=(XYZ-Mview(1:3,4)'+trans2(1:3)')*data.scale; set(data.handles.axes1,'CameraUpVector', UpVector); set(data.handles.axes1,'CameraPosition', XYZ+data.center); set(data.handles.axes1,'CameraTarget', Camtar+data.center); drawnow; function setWindow() data=getMyData; if(isempty(data)), return, end c=get(data.handles.axes1,'Children'); jx=0; jy=0; jz=0; if(~isempty(c)) pmin=zeros(length(c),3); pmax=zeros(length(c),3); for i=1:length(c) c2=get(c(i)); if(isfield(c2,'XData')), xd=c2.XData(:); xd(isnan(xd))=[]; jx=jx+1; pmin(jx,1)= min(xd); pmax(jx,1)= max(xd); end if(isfield(c2,'YData')), yd=c2.YData(:); yd(isnan(yd))=[]; jy=jy+1; pmin(jy,2)= min(yd); pmax(jy,2)= max(yd); end if(isfield(c2,'ZData')), zd=c2.ZData(:); zd(isnan(zd))=[]; jz=jz+1; pmin(jz,3)= min(zd); pmax(jz,3)= max(zd); end end jx(jx==0)=1; jy(jy==0)=1; jz(jz==0)=1; pmin=[min(pmin(1:jx,1)) min(pmin(1:jy,2)) min(pmin(1:jz,3))]; pmax=[max(pmax(1:jx,1)) max(pmax(1:jy,2)) max(pmax(1:jz,3))]; data.center=(pmax+pmin)/2; data.scale=max(pmax-pmin)/2; else data.center=[0 0 0]; data.scale=1; end setMyData(data); axis([-1 1 -1 1 -1 1]*data.scale+[data.center(1) data.center(1) data.center(2) data.center(2) data.center(3) data.center(3)]); drawnow set(data.handles.axes1,'CameraPositionMode','manual'); set(data.handles.axes1,'CameraUpVectorMode','manual'); set(data.handles.axes1,'CameraTargetMode','manual'); set(data.handles.axes1,'CameraViewAngleMode','manual'); set(data.handles.axes1,'PlotBoxAspectRatioMode','manual'); set(data.handles.axes1,'DataAspectRatioMode','manual'); set(data.handles.axes1,'CameraViewAngle',100); set(get(data.handles.axes1,'Children'),'ButtonDownFcn',@axes1_ButtonDownFcn); set(data.handles.axes1,'ButtonDownFcn',@axes1_ButtonDownFcn); setViewMatrix() function figure1_WindowButtonMotionFcn(hObject, eventdata) cursor_position_in_axes(); data=getMyData(); if(isempty(data)), return, end if(data.firsttime) data.firsttime=false; setMyData(data); setWindow(); end if(data.mouse_pressed) t1=(data.mouse_position_last(1)-data.mouse_position(1)); t2=(data.mouse_position_last(2)-data.mouse_position(2)); switch(data.mouse_button) case 'rotate1' R=RotationMatrix([t1 0 t2]); data.Mview=R*data.Mview; setMyData(data); setViewMatrix() case 'rotate2' R=RotationMatrix([0 0.5*(t1+t2) 0]); data.Mview=R*data.Mview; setMyData(data); setViewMatrix() case 'pan' data.trans=data.trans+[-t2/100 0 -t1/100]; setMyData(data); setViewMatrix() case 'zoom' z=1-t2/100; R=ResizeMatrix([z z z]); data.Mview=R*data.Mview; setMyData(data); setViewMatrix() otherwise end end function R=RotationMatrix(r) % Determine the rotation matrix (View matrix) for rotation angles xyz ... Rx=[1 0 0 0; 0 cosd(r(1)) -sind(r(1)) 0; 0 sind(r(1)) cosd(r(1)) 0; 0 0 0 1]; Ry=[cosd(r(2)) 0 sind(r(2)) 0; 0 1 0 0; -sind(r(2)) 0 cosd(r(2)) 0; 0 0 0 1]; Rz=[cosd(r(3)) -sind(r(3)) 0 0; sind(r(3)) cosd(r(3)) 0 0; 0 0 1 0; 0 0 0 1]; R=Rx*Ry*Rz; function M=ResizeMatrix(s) M=[1/s(1) 0 0 0; 0 1/s(2) 0 0; 0 0 1/s(3) 0; 0 0 0 1]; function axes1_ButtonDownFcn(hObject, eventdata) data=getMyData(); if(isempty(data)), return, end handles=data.handles; data.mouse_pressed=true; data.mouse_button=get(handles.figure1,'SelectionType'); data.mouse_position_pressed=data.mouse_position; if(strcmp(data.mouse_button,'normal')) if(data.mouse_rotate) data.mouse_button='rotate1'; set_mouse_shape('rotate1',data); else data.mouse_button='rotate2'; set_mouse_shape('rotate2',data); end end if(strcmp(data.mouse_button,'open')) end if(strcmp(data.mouse_button,'extend')) data.mouse_button='pan'; set_mouse_shape('pan',data); end if(strcmp(data.mouse_button,'alt')) data.mouse_button='zoom'; set_mouse_shape('zoom',data); end setMyData(data); function data=loadmousepointershapes(data) I=[0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0; 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0; 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0; 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 1 0 0 0 1 1 1 1 0 0 0 0 0 0; 0 1 1 1 1 1 0 1 0 0 1 1 1 1 1 1; 1 1 1 1 0 0 0 1 0 0 0 0 0 0 1 1; 1 1 1 1 0 0 0 1 0 0 0 0 0 1 1 1; 1 0 0 0 0 0 0 0 1 0 1 0 0 0 1 1; 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1; 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0; 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0]; I(I==0)=NaN; data.icon_mouse_rotate1=I; I=[1 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0; 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 0; 1 1 1 1 1 1 0 0 0 0 0 1 1 1 0 0; 1 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0; 1 0 0 1 1 0 0 0 0 0 0 0 0 1 0 0; 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0; 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1; 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 1; 0 0 1 0 0 0 0 0 0 0 0 1 1 0 0 1; 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1; 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 1]; I(I==0)=NaN; data.icon_mouse_rotate2=I; I=[0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0; 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0; 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0; 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0; 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0; 1 0 0 1 1 1 1 1 0 0 1 0 0 0 0 0; 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0; 1 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0; 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0; 0 0 1 0 0 0 0 1 1 1 1 0 0 0 0 0; 0 0 0 1 1 1 1 0 0 1 1 1 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1]; I(I==0)=NaN; data.icon_mouse_zoom=I; I=[0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0; 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0; 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0; 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 1 1 0 0 0 1 0 0 0 1 1 0 0 0; 0 1 1 0 0 0 0 1 0 0 0 0 1 1 0 0; 1 0 0 1 1 1 1 1 1 1 1 1 0 0 1 0; 0 1 1 0 0 0 0 1 0 0 0 0 1 1 0 0; 0 0 1 1 0 0 0 1 0 0 0 1 1 0 0 0; 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 0 0 0 1 0 1 0 1 0 0 0 0 0 0; 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0; 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0; 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]; I(I==0)=NaN; data.icon_mouse_pan=I; function set_mouse_shape(type,data) switch(type) case 'rotate1' set(gcf,'Pointer','custom','PointerShapeCData',data.icon_mouse_rotate1,'PointerShapeHotSpot',round(size(data.icon_mouse_rotate1)/2)) set(data.handles.figure1,'Pointer','custom'); case 'rotate2' set(gcf,'Pointer','custom','PointerShapeCData',data.icon_mouse_rotate2,'PointerShapeHotSpot',round(size(data.icon_mouse_rotate2)/2)) set(data.handles.figure1,'Pointer','custom'); case 'select_distance' set(data.handles.figure1,'Pointer','crosshair') case 'select_landmark' set(data.handles.figure1,'Pointer','crosshair') case 'select_roi' set(data.handles.figure1,'Pointer','crosshair') case 'normal' set(data.handles.figure1,'Pointer','arrow') case 'alt' set(data.handles.figure1,'Pointer','arrow') case 'open' set(data.handles.figure1,'Pointer','arrow') case 'zoom' set(gcf,'Pointer','custom','PointerShapeCData',data.icon_mouse_zoom,'PointerShapeHotSpot',round(size(data.icon_mouse_zoom)/2)) set(data.handles.figure1,'Pointer','custom'); case 'pan' set(gcf,'Pointer','custom','PointerShapeCData',data.icon_mouse_pan,'PointerShapeHotSpot',round(size(data.icon_mouse_pan)/2)) set(data.handles.figure1,'Pointer','custom'); otherwise set(data.handles.figure1,'Pointer',type); end % --- Executes on mouse press over figure background, over a disabled or % --- inactive control, or over an axes background. function figure1_WindowButtonUpFcn(hObject, eventdata) data=getMyData(); if(isempty(data)), return, end if(data.mouse_pressed) data.mouse_pressed=false; setMyData(data); end set_mouse_shape('arrow',data) function cursor_position_in_axes() data=getMyData(); if(isempty(data)), return, end; data.mouse_position_last=data.mouse_position; p = get(0, 'PointerLocation'); data.mouse_position=[p(1, 1) p(1, 2)]; setMyData(data); function setMyData(data) % Store data struct in figure setappdata(gcf,'data3d',data); function data=getMyData() % Get data struct stored in figure data=getappdata(gcf,'data3d'); % --- Executes on key press with focus on figure1 and none of its controls. function figure1_KeyPressFcn(hObject, eventdata) data=getappdata(gcf,'data3d'); switch(eventdata.Character) case 'i' data.trans=[0 0 0]; data.Mview=[1 0 0 0;0 1 0 0; 0 0 1 0; 0 0 0 1]; setMyData(data); setViewMatrix(); case 'r' data.mouse_rotate=~data.mouse_rotate; setMyData(data) otherwise end
github
mathematical-tours/mathematical-tours.github.io-master
load_signal.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/fourier-signal/load_signal.m
12,338
utf_8
b70e4cb57d6b467ae9c90d4b3310a81f
function y = load_signal(name, n, options) % load_signal - load a 1D signal % % y = load_signal(name, n, options); % % name is a string that can be : % 'regular' (options.alpha gives regularity) % 'step', 'rand', % 'gaussiannoise' (options.sigma gives width of filtering in pixels), % [natural signals] % 'tiger', 'bell', 'bird' % [WAVELAB signals] % 'HeaviSine', 'Bumps', 'Blocks', % 'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine', % 'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp', % 'MishMash', 'WernerSorrows' (Heisenberg), % 'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth), % 'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor' % 'sineoneoverx','Cusp2','SmoothCusp','Gaussian' % 'Piece-Polynomial' (Piece-Wise 3rd degree polynomial) if nargin<2 n = 1024; end options.null = 0; if isfield(options, 'alpha') alpha = options.alpha; else alpha = 2; end options.rep = ''; switch lower(name) case 'regular' y = gen_signal(n,alpha); case 'step' y = linspace(0,1,n)>0.5; case 'stepregular' y = linspace(0,1,n)>0.5; y=y(:); a = gen_signal(n,2); a = a(:); a = rescale(a,-0.1,0.1); y = y+a; case 'gaussiannoise' % filtered gaussian noise y = randn(n,1); if isfield(options, 'sigma') sigma = options.sigma; % variance in number of pixels else sigma = 20; end m = min(n, 6*round(sigma/2)+1); h = compute_gaussian_filter(m,sigma/(4*n),n); options.bound = 'per'; y = perform_convolution(y,h, options); case 'rand' if isfield(options, 'p1') p1 = options.p1; else c = 10; p1 = 1:c; p1 = p1/sum(p1); end p1 = p1(:); c = length(p1); if isfield(options, 'p2') p2 = options.p2; else if isfield(options, 'evol') evol = options.evol; else evol = 0; end p2 = p1(:) + evol*(rand(c,1)-0.5); p2 = max(p2,0); p2 = p2/sum(p2); end y = zeros(n,1); for i=1:n a = (i-1)/(n-1); p = a*p1+(1-a)*p2; p = p/sum(p); y(i) = rand_discr(p, 1); end case 'bird' [y,fs] = load_sound([name '.wav'], n, options); case 'tiger' [y,fs] = load_sound([name '.au'], n, options); case 'bell' [y,fs] = load_sound([name '.wav'], n, options); otherwise y = MakeSignal(name,n); end y = y(:); function y = gen_signal(n,alpha) % gen_signal - generate a 1D C^\alpha signal of length n. % % y = gen_signal(n,alpha); % % The signal is scaled in [0,1]. % % Copyright (c) 2003 Gabriel Peyr? if nargin<2 alpha = 2; end y = randn(n,1); fy = fft(y); fy = fftshift(fy); % filter with |omega|^{-\alpha} h = (-n/2+1):(n/2); h = (abs(h)+1).^(-alpha-0.5); fy = fy.*h'; fy = fftshift(fy); y = real( ifft(fy) ); y = (y-min(y))/(max(y)-min(y)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sig = MakeSignal(Name,n) % MakeSignal -- Make artificial signal % Usage % sig = MakeSignal(Name,n) % Inputs % Name string: 'HeaviSine', 'Bumps', 'Blocks', % 'Doppler', 'Ramp', 'Cusp', 'Sing', 'HiSine', % 'LoSine', 'LinChirp', 'TwoChirp', 'QuadChirp', % 'MishMash', 'WernerSorrows' (Heisenberg), % 'Leopold' (Kronecker), 'Piece-Regular' (Piece-Wise Smooth), % 'Riemann','HypChirps','LinChirps', 'Chirps', 'Gabor' % 'sineoneoverx','Cusp2','SmoothCusp','Gaussian' % 'Piece-Polynomial' (Piece-Wise 3rd degree polynomial) % n desired signal length % Outputs % sig 1-d signal % % References % Various articles of D.L. Donoho and I.M. Johnstone % if nargin > 1, t = (1:n) ./n; end Name = lower(Name); if strcmp(Name,'heavisine'), sig = 4.*sin(4*pi.*t); sig = sig - sign(t - .3) - sign(.72 - t); elseif strcmp(Name,'bumps'), pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81]; hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2]; wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005]; sig = zeros(size(t)); for j =1:length(pos) sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4; end elseif strcmp(Name,'blocks'), pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81]; hgt = [4 (-5) 3 (-4) 5 (-4.2) 2.1 4.3 (-3.1) 2.1 (-4.2)]; sig = zeros(size(t)); for j=1:length(pos) sig = sig + (1 + sign(t-pos(j))).*(hgt(j)/2) ; end elseif strcmp(Name,'doppler'), sig = sqrt(t.*(1-t)).*sin((2*pi*1.05) ./(t+.05)); elseif strcmp(Name,'ramp'), sig = t - (t >= .37); elseif strcmp(Name,'cusp'), sig = sqrt(abs(t - .37)); elseif strcmp(Name,'sing'), k = floor(n * .37); sig = 1 ./abs(t - (k+.5)/n); elseif strcmp(Name,'hisine'), sig = sin( pi * (n * .6902) .* t); elseif strcmp(Name,'losine'), sig = sin( pi * (n * .3333) .* t); elseif strcmp(Name,'linchirp'), sig = sin(pi .* t .* ((n .* .500) .* t)); elseif strcmp(Name,'twochirp'), sig = sin(pi .* t .* (n .* t)) + sin((pi/3) .* t .* (n .* t)); elseif strcmp(Name,'quadchirp'), sig = sin( (pi/3) .* t .* (n .* t.^2)); elseif strcmp(Name,'mishmash'), % QuadChirp + LinChirp + HiSine sig = sin( (pi/3) .* t .* (n .* t.^2)) ; sig = sig + sin( pi * (n * .6902) .* t); sig = sig + sin(pi .* t .* (n .* .125 .* t)); elseif strcmp(Name,'wernersorrows'), sig = sin( pi .* t .* (n/2 .* t.^2)) ; sig = sig + sin( pi * (n * .6902) .* t); sig = sig + sin(pi .* t .* (n .* t)); pos = [ .1 .13 .15 .23 .25 .40 .44 .65 .76 .78 .81]; hgt = [ 4 5 3 4 5 4.2 2.1 4.3 3.1 5.1 4.2]; wth = [.005 .005 .006 .01 .01 .03 .01 .01 .005 .008 .005]; for j =1:length(pos) sig = sig + hgt(j)./( 1 + abs((t - pos(j))./wth(j))).^4; end elseif strcmp(Name,'leopold'), sig = (t == floor(.37 * n)/n); % Kronecker elseif strcmp(Name,'riemann'), sqn = round(sqrt(n)); sig = t .* 0; % Riemann's Non-differentiable Function sig((1:sqn).^2) = 1. ./ (1:sqn); sig = real(ifft(sig)); elseif strcmp(Name,'hypchirps'), % Hyperbolic Chirps of Mallat's book alpha = 15*n*pi/1024; beta = 5*n*pi/1024; t = (1.001:1:n+.001)./n; f1 = zeros(1,n); f2 = zeros(1,n); f1 = sin(alpha./(.8-t)).*(0.1<t).*(t<0.68); f2 = sin(beta./(.8-t)).*(0.1<t).*(t<0.75); M = round(0.65*n); P = floor(M/4); enveloppe = ones(1,M); % the rising cutoff function enveloppe(1:P) = (1+sin(-pi/2+((1:P)-ones(1,P))./(P-1)*pi))/2; enveloppe(M-P+1:M) = reverse(enveloppe(1:P)); env = zeros(1,n); env(ceil(n/10):M+ceil(n/10)-1) = enveloppe(1:M); sig = (f1+f2).*env; elseif strcmp(Name,'linchirps'), % Linear Chirps of Mallat's book b = 100*n*pi/1024; a = 250*n*pi/1024; t = (1:n)./n; A1 = sqrt((t-1/n).*(1-t)); sig = A1.*(cos((a*(t).^2)) + cos((b*t+a*(t).^2))); elseif strcmp(Name,'chirps'), % Mixture of Chirps of Mallat's book t = (1:n)./n.*10.*pi; f1 = cos(t.^2*n/1024); a = 30*n/1024; t = (1:n)./n.*pi; f2 = cos(a.*(t.^3)); f2 = reverse(f2); ix = (-n:n)./n.*20; g = exp(-ix.^2*4*n/1024); i1 = (n/2+1:n/2+n); i2 = (n/8+1:n/8+n); j = (1:n)/n; f3 = g(i1).*cos(50.*pi.*j*n/1024); f4 = g(i2).*cos(350.*pi.*j*n/1024); sig = f1+f2+f3+f4; enveloppe = ones(1,n); % the rising cutoff function enveloppe(1:n/8) = (1+sin(-pi/2+((1:n/8)-ones(1,n/8))./(n/8-1)*pi))/2; enveloppe(7*n/8+1:n) = reverse(enveloppe(1:n/8)); sig = sig.*enveloppe; elseif strcmp(Name,'gabor'), % two modulated Gabor functions in % Mallat's book N = 512; t = (-N:N)*5/N; j = (1:N)./N; g = exp(-t.^2*20); i1 = (2*N/4+1:2*N/4+N); i2 = (N/4+1:N/4+N); sig1 = 3*g(i1).*exp(i*N/16.*pi.*j); sig2 = 3*g(i2).*exp(i*N/4.*pi.*j); sig = sig1+sig2; elseif strcmp(Name,'sineoneoverx'), % sin(1/x) in Mallat's book N = 1024; a = (-N+1:N); a(N) = 1/100; a = a./(N-1); sig = sin(1.5./(i)); sig = sig(513:1536); elseif strcmp(Name,'cusp2'), N = 64; a = (1:N)./N; x = (1-sqrt(a)) + a/2 -.5; M = 8*N; sig = zeros(1,M); sig(M-1.5.*N+1:M-.5*N) = x; sig(M-2.5*N+2:M-1.5.*N+1) = reverse(x); sig(3*N+1:3*N + N) = .5*ones(1,N); elseif strcmp(Name,'smoothcusp'), sig = MakeSignal('Cusp2'); N = 64; M = 8*N; t = (1:M)/M; sigma = 0.01; g = exp(-.5.*(abs(t-.5)./sigma).^2)./sigma./sqrt(2*pi); g = fftshift(g); sig2 = iconv(g',sig)'/M; elseif strcmp(Name,'piece-regular'), sig1=-15*MakeSignal('Bumps',n); t = (1:fix(n/12)) ./fix(n/12); sig2=-exp(4*t); t = (1:fix(n/7)) ./fix(n/7); sig5=exp(4*t)-exp(4); t = (1:fix(n/3)) ./fix(n/3); sigma=6/40; sig6=-70*exp(-((t-1/2).*(t-1/2))/(2*sigma^2)); sig(1:fix(n/7))= sig6(1:fix(n/7)); sig((fix(n/7)+1):fix(n/5))=0.5*sig6((fix(n/7)+1):fix(n/5)); sig((fix(n/5)+1):fix(n/3))=sig6((fix(n/5)+1):fix(n/3)); sig((fix(n/3)+1):fix(n/2))=sig1((fix(n/3)+1):fix(n/2)); sig((fix(n/2)+1):(fix(n/2)+fix(n/12)))=sig2; sig((fix(n/2)+2*fix(n/12)):-1:(fix(n/2)+fix(n/12)+1))=sig2; sig(fix(n/2)+2*fix(n/12)+fix(n/20)+1:(fix(n/2)+2*fix(n/12)+3*fix(n/20)))=... -ones(1,fix(n/2)+2*fix(n/12)+3*fix(n/20)-fix(n/2)-2*fix(n/12)-fix(n/20))*25; k=fix(n/2)+2*fix(n/12)+3*fix(n/20); sig((k+1):(k+fix(n/7)))=sig5; diff=n-5*fix(n/5); sig(5*fix(n/5)+1:n)=sig(diff:-1:1); % zero-mean bias=sum(sig)/n; sig=bias-sig; elseif strcmp(Name,'piece-polynomial'), t = (1:fix(n/5)) ./fix(n/5); sig1=20*(t.^3+t.^2+4); sig3=40*(2.*t.^3+t) + 100; sig2=10.*t.^3 + 45; sig4=16*t.^2+8.*t+16; sig5=20*(t+4); sig6(1:fix(n/10))=ones(1,fix(n/10)); sig6=sig6*20; sig(1:fix(n/5))=sig1; sig(2*fix(n/5):-1:(fix(n/5)+1))=sig2; sig((2*fix(n/5)+1):3*fix(n/5))=sig3; sig((3*fix(n/5)+1):4*fix(n/5))=sig4; sig((4*fix(n/5)+1):5*fix(n/5))=sig5(fix(n/5):-1:1); diff=n-5*fix(n/5); sig(5*fix(n/5)+1:n)=sig(diff:-1:1); %sig((fix(n/20)+1):(fix(n/20)+fix(n/10)))=-ones(1,fix(n/10))*20; sig((fix(n/20)+1):(fix(n/20)+fix(n/10)))=ones(1,fix(n/10))*10; sig((n-fix(n/10)+1):(n+fix(n/20)-fix(n/10)))=ones(1,fix(n/20))*150; % zero-mean bias=sum(sig)/n; sig=sig-bias; elseif strcmp(Name,'gaussian'), sig=GWN(n,beta); g=zeros(1,n); lim=alpha*n; mult=pi/(2*alpha*n); g(1:lim)=(cos(mult*(1:lim))).^2; g((n/2+1):n)=g((n/2):-1:1); g = rnshift(g,n/2); g=g/norm(g); sig=iconv(g,sig); else disp(sprintf('MakeSignal: I don*t recognize <<%s>>',Name)) disp('Allowable Names are:') disp('HeaviSine'), disp('Bumps'), disp('Blocks'), disp('Doppler'), disp('Ramp'), disp('Cusp'), disp('Crease'), disp('Sing'), disp('HiSine'), disp('LoSine'), disp('LinChirp'), disp('TwoChirp'), disp('QuadChirp'), disp('MishMash'), disp('WernerSorrows'), disp('Leopold'), disp('Sing'), disp('HiSine'), disp('LoSine'), disp('LinChirp'), disp('TwoChirp'), disp('QuadChirp'), disp('MishMash'), disp('WernerSorrows'), disp('Leopold'), disp('Riemann'), disp('HypChirps'), disp('LinChirps'), disp('Chirps'), disp('sineoneoverx'), disp('Cusp2'), disp('SmoothCusp'), disp('Gabor'), disp('Piece-Regular'); disp('Piece-Polynomial'); disp('Gaussian'); end % % Originally made by David L. Donoho. % Function has been enhanced. % % Part of WaveLab Version 802 % Built Sunday, October 3, 1999 8:52:27 AM % This is Copyrighted Material % For Copying permissions see COPYING.m % Comments? e-mail [email protected] %
github
mathematical-tours/mathematical-tours.github.io-master
GameOfLife.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/cellular/GameOfLife.m
3,374
utf_8
a30e18a0dce03b6f6d490e96282b1f1f
function GameOfLife % This is a simple simulation of Conway Game of life GoL % it is good for understanding Cellular Automata (CA) concept % GoL Rules: % 1. Survival: an alive cell live if it has 2 or 3 alive neighbors % 2. Birth: a dead cell will be alive if it has 3 alive neighbors % 3. Deaths: % Lonless: alive cell dies if it has 0 or 1 alive neighbors % Overcrowding: alive cell dies if it has 4 or more alive neighbors % Any questions related to CA are welcome % By: Ibraheem Al-Dhamari clc; %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Initialization %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % size= 500x500 % different random initial values %A= rand(500,500); %A= ones(500,500); % periodic configuration %A= zeros(500,500); % A(100,200)=1; % A(100,201)=1; % A(100,202)=1; % initial from image A=imread('CA02.JPG'); % convert to binary--> % states={0,1} A=im2bw(A); % visualize the initial states disp('the binary image') imshow(A); % pause % boundary type: 0= reflection % 1= doublication % 2= null, zeros % this step enlarge A with 4 virtual vectors A=Bnd(A,0); [d1,d2]=size(A); % disp('the extended binary image') % whos A imshow(A); pause B=A; t=0; stp=false; % to stop when if no new configrations %B is the CA in time t %A is the CA in time t+1 %t is the number of generations %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Play ^_^ %%%%%%%%%%%%%%%%%%%%%%%%%%%%% while ~stp & (t<10) % repeat for 10 generations % for each cell in the CA for i=2:d1-1 for j=2:d2-1 % apply Game of life rule A(i,j)=GOL(A,B,i,j) ; end end % visualize what happened disp('the CA image') imshow(A); drawnow; % pause % save B if A==B stp=true; % no more new states end B=A; t=t+1 end %========================================== % Game of Life Rules %========================================== function s=GOL (A,B,i,j) % game of life rule sm=0; % count number of alive neighbors sm=sm+ B(i-1,j-1)+B(i-1,j)+B(i-1,j+1); sm=sm+ B(i,j-1)+ B(i,j+1); sm=sm+ B(i+1,j-1)+B(i+1,j)+B(i+1,j+1); % compute the new state of the current cell s=B(i,j); if B(i,j)==1 if (sm>1)&&(sm<4) s=1; else s=0 ; end else if sm==3 s=1; end end %========================================== % Boundary Type %========================================== function bA= Bnd(A,k) % add new four vectors based on boundary type [d1, d2]=size(A); d1=d1+2; d2=d2+2; X=ones(d1,d2); X=im2bw(X); X(2:d1-1,2:d2-1)=A; imshow(X); whos A X if k==0 % Reflection X( 1 , 2:d2-1)=A(end , :); X( d1 , 2:d2-1)=A( 1 , :); X( 2:d1-1 , 1 )=A(: , end); X( 2:d1-1 , d2 )=A(: , 1 ); X(1,1) =A(end,end); X(1,end) =A(end,1); X(end,1) =A(1,end); X(end,end)=A(1,1); elseif k==1 % Double X( 1 , 2:d2-1)=A( 1 , :); X( d1 , 2:d2-1)=A(end , :); X( 2:d1-1 , 1 )=A(: , 1 ); X( 2:d1-1 , d2 )=A(: , end); X(1,1) =A(end,1); X(1,end) =A(end,end); X(end,1) =A(1,1); X(end,end)=A(1,end); else % k==2 % zeros X( 1 ,:)=0; X( end ,:)=0; X(: , 1 )=0; X(: , end )=0; end bA=X;
github
mathematical-tours/mathematical-tours.github.io-master
load_gear.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/gears-non-circ/load_gear.m
4,615
utf_8
aed61f3cb53895649282de68959df88e
function x = load_gear(name, n, center, tooth, smoothing) % load_gear - create default gears % % x = load_gear(name, n, center, tooth, smoothing); % % n is the number of points used for the discretization. % center is the coordinate of the center of rotation (detaul is [0 0]) % tooth gives the parameters for the tooth extrusion. % % Copyright (c) 2010 Gabriel Peyre theta = (0:n-1)'/n*2*pi; if nargin<3 center = [0 0]; end if nargin<4 tooth.transition =.2; tooth.nbr = 30; tooth.height = .05; end if nargin<5 smoothing=0; end switch name case 'ellipse-focal' % ellipse, focal bmin = 1; epsilon = .5; x = bmin*(1-epsilon^2)./( 1-epsilon*cos(theta) ); case 'ellipse-centered' % ellipse, centered bmin = 1; bmax = 3; x = bmin*bmax./sqrt( (bmin*cos(theta)).^2 + (bmax*sin(theta)).^2 ); case {'random' 'random-strong'} if strcmp(name, 'random') bmin = 1; bmax = 1.5; p = 6; else bmin = 1; bmax = 4; p = 10; end x = zeros(n,1); x(1:p) = exp(2i*rand(p,1)); x = real(ifft(x)); x = (x-min(x))/(max(x)-min(x)); x = x*(bmax-bmin)+bmin; case 'petal' x = sin(4*theta)+1.5; case 'petal-8' x = sin(8*theta).^2+2; case 'circle' x = theta*0+1; case 'cardioid' x = 1.2+cos(theta); case 'engrenage-16' eta = 16; x = 10+ abs(cos(theta*eta)).^.2 .* sign(cos(theta*eta)); case 'discont' x = .5*theta/2*pi + 1; case 'discont-2' x = mod(theta/(2*pi),.5)*3 + 1; case 'square' a = genpolygon_regular(4,n); case 'triangle' a = genpolygon_regular(3,n); case 'hexagon' a = genpolygon_regular(6,n); end %% add tooths if not(exist('a')) %% convert to rectangular a = gear2cart(x); end a(:,1) = a(:,1) + center(1); a(:,2) = a(:,2) + center(2); if smoothing>0 niter = round(n * smoothing); a = smooth(a,niter); end if tooth.nbr>0 q = n*10; % number of point for the profile curve t = mod((0:q-1)'/q, 1/tooth.nbr)*tooth.nbr; e = (tooth_profile(t, tooth.transition)) * 2 * tooth.height; % normal asmooth = smooth(a,.02); u = compute_normal(asmooth); s = compute_curvabs(a); e1 = interp1( linspace(0,1,q+1), [e;e(1)], s ); % offset a = a + u .* repmat(e1, [1 2]); end x = cart2gear(a); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = smooth(a,s) n = size(a,1); t = (-n/2:n/2-1)'; h = exp( -(t.^2)/(2*s^2) ); h = h/sum(h); % recenter the filter for fft use h1 = fftshift(h); filter = @(u)real(ifft(fft(h1).*fft(u))); a(:,1) = filter(a(:,1)); a(:,2) = filter(a(:,2)); return; if nargin<2 niter = 1; end for i=1:niter a = (a + a([2:end 1],:) + a([end 1:end-1],:) )/3; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = compute_curvabs(a) u = a([2:end 1],:) - a([end 1:end-1],:); s = sqrt(sum(u.^2,2)); s = [0;cumsum(s)]; s = s/s(end); s = s(1:end-1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function u = compute_normal(a) u = a([2:end 1],:) - a([end 1:end-1],:); u = u ./ repmat( sqrt(sum(u.^2,2)), [1 2] ); u = [-u(:,2) u(:,1)]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function e = tooth_profile(t, a) d = 1/2-a; e = double(t<d) + double(t>=d & t<a+d).*(d+a-t)/(a) + ... double(t>=1-a).*(t-(1-a))/(a); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = normal_extrude(a) n = a-a(:,[2:end 1]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = genpolygon_regular(p,n) theta = linspace(0,2*pi,p+1)'; theta(end) = []; A = [cos(theta), sin(theta)]; a = genpolygon(A,n); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = genpolygon(A,n) p = size(A,1); a = []; for i=1:p j = mod(i,p)+1; if i<p k = floor(n/p); else k = n - (p-1)*floor(n/p); end t = (0:k-1)'/k; a(end+1:end+k,:) = (1-t)*A(i,:) + t*A(j,:); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function x = cart2gear(a) n = size(a,1); [theta,r] = cart2pol(a(:,1), a(:,2)); theta = theta - theta(1); theta(theta<0) = theta(theta<0) + 2*pi; theta(end+1) = 2*pi; r(end+1) = r(1); theta0 = (0:n-1)'/n*2*pi; x = interp1(theta,r,theta0); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = gear2cart(x) n = length(x); theta = (0:n-1)'/n*2*pi; a = [x.*cos(theta), x.*sin(theta)];
github
mathematical-tours/mathematical-tours.github.io-master
hilbert.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/hilbert-curve/hilbert.m
416
utf_8
be622fc6b0e538e3287a391980e5091d
function [x,y] = hilbert(n) %HILBERT Hilbert curve. % % [x,y]=hilbert(n) gives the vector coordinates of points % in n-th order Hilbert curve of area 1. % % Example: plot of 5-th order curve % % [x,y]=hilbert(5);line(x,y) % % Copyright (c) by Federico Forte % Date: 2000/10/06 if n<=0 x=0; y=0; else [xo,yo]=hilbert(n-1); x=.5*[-.5+yo -.5+xo .5+xo .5-yo]; y=.5*[-.5+xo .5+yo .5+yo -.5-xo]; end
github
mathematical-tours/mathematical-tours.github.io-master
plot_tensor_field.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/tensor-diffusion/plot_tensor_field.m
5,736
utf_8
08ad2346cf316598da10c6b1d5c367d3
function h = plot_tensor_field(H, M, options) % plot_tensor_field - display a tensor field % % h = plot_tensor_field(H, M, options); % % options.sub controls sub-sampling % options.color controls color % % Copyright (c) 2006 Gabriel Peyre if nargin<3 options.null = 0; end if not( isstruct(options) ) sub = options; clear options; options.sub = sub; end % sub = getoptions(options, 'sub', 1); sub = getoptions(options, 'sub', round(size(H,1)/30) ); color = getoptions(options, 'color', 'r'); if nargin<2 M = []; end if not(isempty(M)) && size(M,3)==1 M = repmat(M, [1 1 3]); % ensure B&W image end if size(H,3)==3 && size(H,4)==1 H = cat(3, H(:,:,1), H(:,:,3), H(:,:,3), H(:,:,2) ); H = reshape(H, size(H,1), size(H,2), 2, 2); if 0 % flip the main eigen-axes [e1,e2,l1,l2] = perform_tensor_decomp(H); H = perform_tensor_recomp(e2,e1,l1,l2); end h = plot_tensor_field(H, M, sub); return; end % swap X and Y axis %%% TODO a = H(:,:,2,2); H(:,:,2,2) = H(:,:,1,1); H(:,:,1,1) = a; hold on; if ~isempty(M) imagesc(rescale(M)); drawnow; end h = fn_tensordisplay(H(:,:,1,1),H(:,:,1,2), H(:,:,2,2), 'sub', sub, 'color', color); axis image; axis off; colormap jet(256); % hold off; function h = fn_tensordisplay(varargin) % function h = fn_tensordisplay([X,Y,]Txx,Txy,Tyy[,'sigma',sigma][,'sub',sub][,color][,patch options...]]) % function h = fn_tensordisplay([X,Y,]e[,'sigma',sigma][,'sub',sub][,color][,patch options...]]) % X,Y,Txx,Txy,Tyy if isstruct(varargin{1}) || isstruct(varargin{3}) if isstruct(varargin{1}), nextarg=1; else nextarg=3; end e = varargin{nextarg}; Txx = e.ytyt; Txy = -e.ytyx; Tyy = e.yxyx; if nextarg==1 [nj ni] = size(Txx); [X Y] = meshgrid(1:ni,1:nj); else [X Y] = deal(varargin{1:2}); end nextarg = nextarg+1; else [nj ni] = size(varargin{3}); if nargin<5 || ischar(varargin{4}) || ischar(varargin{5}) || any(size(varargin{5})~=[nj ni]) [X Y] = meshgrid(1:ni,1:nj); nextarg = 1; else [X Y] = deal(varargin{1:2}); nextarg = 3; end [Txx Txy Tyy] = deal(varargin{nextarg:nextarg+2}); nextarg = nextarg+3; end if any(size(X)==1), [X Y] = meshgrid(X,Y); end [nj,ni] = size(X); if any(size(Y)~=[nj ni]) || ... any(size(Txx)~=[nj ni]) || any(size(Txy)~=[nj ni]) || any(size(Tyy)~=[nj ni]) error('Matrices must be same size') end % sigma, sub, color color = 'r'; while nextarg<=nargin flag = varargin{nextarg}; nextarg=nextarg+1; if ~ischar(flag), color = flag; continue, end switch lower(flag) case 'sigma' sigma = varargin{nextarg}; nextarg = nextarg+1; switch length(sigma) case 1 sigmax = sigma; sigmay = sigma; case 2 sigmax = sigma(1); sigmay = sigma(2); otherwise error('sigma definition should entail two values'); end h = fspecial('gaussian',[ceil(2*sigmay) 1],sigmay)*fspecial('gaussian',[1 ceil(2*sigmax)],sigmax); Txx = imfilter(Txx,h,'replicate'); Txy = imfilter(Txy,h,'replicate'); Tyy = imfilter(Tyy,h,'replicate'); case 'sub' sub = varargin{nextarg}; nextarg = nextarg+1; switch length(sub) case 1 [x y] = meshgrid(1:sub:ni,1:sub:nj); sub = y+nj*(x-1); case 2 [x y] = meshgrid(1:sub(1):ni,1:sub(2):nj); sub = y+nj*(x-1); end X = X(sub); Y = Y(sub); Txx = Txx(sub); Txy = Txy(sub); Tyy = Tyy(sub); [nj ni] = size(sub); case 'color' color = varargin{nextarg}; nextarg = nextarg+1; otherwise break end end % options options = {varargin{nextarg:end}}; npoints = 50; theta = (0:npoints-1)*(2*pi/npoints); circle = [cos(theta) ; sin(theta)]; Tensor = cat(3,Txx,Txy,Txy,Tyy); % jdisplay x idisplay x tensor Tensor = reshape(Tensor,2*nj*ni,2); % (display x 1tensor) x 2tensor Ellipse = Tensor * circle; % (display x uv) x npoints Ellipse = reshape(Ellipse,nj*ni,2,npoints); % display x uv x npoints XX = repmat(X(:),1,npoints); % display x npoints YY = repmat(Y(:),1,npoints); % display x npoints U = reshape(Ellipse(:,1,:),nj*ni,npoints); % display x npoints V = reshape(Ellipse(:,2,:),nj*ni,npoints); % display x npoints umax = max(U')'; vmax = max(V')'; umax(umax==0)=1; vmax(vmax==0)=1; if ni==1, dx=1; else dx = X(1,2)-X(1,1); end if nj==1, dy=1; else dy = Y(2,1)-Y(1,1); end fact = min(dx./umax,dy./vmax)*.35; fact = repmat(fact,1,npoints); U = XX + fact.*U; V = YY + fact.*V; %----------- MM = mmax(Txx+Tyy); mm = mmin(Txx+Tyy); [S1, S2] = size(U); Colormap = zeros(S2, S1, 3); Map = colormap(jet(256)); for k =1:npoints Colormap(k,:,1) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 1); Colormap(k,:,2) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 2); Colormap(k,:,3) = Map(floor(255*(Txx(:)+Tyy(:)-mm)/(MM-mm)) + 1, 3); end %----------- h = fill(U',V',color,'EdgeColor',color,options{:}); %h = fill(U',V',Colormap,'EdgeColor', 'interp'); axis ij; if nargout==0, clear h, end function a=mmax(a) a = max(a(:)); function a=mmin(a) a = min(a(:));
github
mathematical-tours/mathematical-tours.github.io-master
inpolyhedron.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/wave-heat-3d/inpolyhedron.m
22,756
utf_8
16738ef64a83b8c37c57511248fb93cf
function IN = inpolyhedron(varargin) %INPOLYHEDRON Tests if points are inside a 3D triangulated (faces/vertices) surface % BY CONVENTION, SURFACE NORMALS SHOULD POINT OUT from the object. (see % FLIPNORMALS option below for details) % % IN = INPOLYHEDRON(FV,QPTS) tests if the query points (QPTS) are inside the % patch/surface/polyhedron defined by FV (a structure with fields 'vertices' and % 'faces'). QPTS is an N-by-3 set of XYZ coordinates. IN is an N-by-1 logical % vector which will be TRUE for each query point inside the surface. % % INPOLYHEDRON(FACES,VERTICES,...) takes faces/vertices separately, rather than in % an FV structure. % % IN = INPOLYHEDRON(..., X, Y, Z) voxelises a mask of 3D gridded query points % rather than an N-by-3 array of points. X, Y, and Z coordinates of the grid % supplied in XVEC, YVEC, and ZVEC respectively. IN will return as a 3D logical % volume with SIZE(IN) = [LENGTH(YVEC) LENGTH(XVEC) LENGTH(ZVEC)], equivalent to % syntax used by MESHGRID. INPOLYHEDRON handles this input faster and with a lower % memory footprint than using MESHGRID to make full X, Y, Z query points matrices. % % INPOLYHEDRON(...,'PropertyName',VALUE,'PropertyName',VALUE,...) tests query % points using the following optional property values: % % TOL - Tolerance on the tests for "inside" the surface. You can think of % tol as the distance a point may possibly lie above/below the surface, and still % be perceived as on the surface. Due to numerical rounding nothing can ever be % done exactly here. Defaults to ZERO. Note that in the current implementation TOL % only affects points lying above/below a surface triangle (in the Z-direction). % Points coincident with a vertex in the XY plane are considered INside the surface. % More formal rules can be implemented with input/feedback from users. % % GRIDSIZE - Internally, INPOLYHEDRON uses a divide-and-conquer algorithm to % split all faces into a chessboard-like grid of GRIDSIZE-by-GRIDSIZE regions. % Performance will be a tradeoff between a small GRIDSIZE (few iterations, more % data per iteration) and a large GRIDSIZE (many iterations of small data % calculations). The sweet-spot has been experimentally determined (on a win64 % system) to be correlated with the number of faces/vertices. You can overwrite % this automatically computed choice by specifying a GRIDSIZE parameter. % % FACENORMALS - By default, the normals to the FACE triangles are computed as the % cross-product of the first two triangle edges. You may optionally specify face % normals here if they have been pre-computed. % % FLIPNORMALS - (Defaults FALSE). To match a wider convention, triangle % face normals are presumed to point OUT from the object's surface. If % your surface normals are defined pointing IN, then you should set the % FLIPNORMALS option to TRUE to use the reverse of this convention. % % Example: % tmpvol = zeros(20,20,20); % Empty voxel volume % tmpvol(5:15,8:12,8:12) = 1; % Turn some voxels on % tmpvol(8:12,5:15,8:12) = 1; % tmpvol(8:12,8:12,5:15) = 1; % fv = isosurface(tmpvol, 0.99); % Create the patch object % fv.faces = fliplr(fv.faces); % Ensure normals point OUT % % Test SCATTERED query points % pts = rand(200,3)*12 + 4; % Make some query points % in = inpolyhedron(fv, pts); % Test which are inside the patch % figure, hold on, view(3) % Display the result % patch(fv,'FaceColor','g','FaceAlpha',0.2) % plot3(pts(in,1),pts(in,2),pts(in,3),'bo','MarkerFaceColor','b') % plot3(pts(~in,1),pts(~in,2),pts(~in,3),'ro'), axis image % % Test STRUCTURED GRID of query points % gridLocs = 3:2.1:19; % [x,y,z] = meshgrid(gridLocs,gridLocs,gridLocs); % in = inpolyhedron(fv, gridLocs,gridLocs,gridLocs); % figure, hold on, view(3) % Display the result % patch(fv,'FaceColor','g','FaceAlpha',0.2) % plot3(x(in), y(in), z(in),'bo','MarkerFaceColor','b') % plot3(x(~in),y(~in),z(~in),'ro'), axis image % % See also: UNIFYMESHNORMALS (on the <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=43013">file exchange</a>) % TODO-list % - Optmise overall memory footprint. (need examples with MEM errors) % - Implement an "ignore these" step to speed up calculations for: % * Query points outside the convex hull of the faces/vertices input % - Get a better/best gridSize calculation. User feedback? % - Detect cases where X-rays or Y-rays would be better than Z-rays? % % Author: Sven Holcombe % - 10 Jun 2012: Version 1.0 % - 28 Aug 2012: Version 1.1 - Speedup using accumarray % - 07 Nov 2012: Version 2.0 - BEHAVIOUR CHANGE % Query points coincident with a VERTEX are now IN an XY triangle % - 18 Aug 2013: Version 2.1 - Gridded query point handling with low memory footprint. % - 10 Sep 2013: Version 3.0 - BEHAVIOUR CHANGE % NEW CONVENTION ADOPTED to expect face normals pointing IN % Vertically oriented faces are now ignored. Speeds up % computation and fixes bug where presence of vertical faces % produced NaN distance from a query pt to facet, making all % query points under facet erroneously NOT IN polyhedron. % - 25 Sep 2013: Version 3.1 - Dropped nested unique call which was made % mostly redundant via v2.1 gridded point handling. Also % refreshed grid size selection via optimisation. % - 25 Feb 2014: Version 3.2 - Fixed indeterminate behaviour for query % points *exactly* in line with an "overhanging" vertex. %% % FACETS is an unpacked arrangement of faces/vertices. It is [3-by-3-by-N], % with 3 1-by-3 XYZ coordinates of N faces. [facets, qPts, options] = parseInputs(varargin{:}); numFaces = size(facets,3); if ~options.griddedInput % SCATTERED QUERY POINTS numQPoints = size(qPts,1); else % STRUCTURED QUERY POINTS numQPoints = prod(cellfun(@numel,qPts(1:2))); end % Precompute 3d normals to all facets (triangles). Do this via the cross % product of the first edge vector with the second. Normalise the result. allEdgeVecs = facets([2 3 1],:,:) - facets(:,:,:); if isempty(options.facenormals) allFacetNormals = bsxfun(@times, allEdgeVecs(1,[2 3 1],:), allEdgeVecs(2,[3 1 2],:)) - ... bsxfun(@times, allEdgeVecs(2,[2 3 1],:), allEdgeVecs(1,[3 1 2],:)); allFacetNormals = bsxfun(@rdivide, allFacetNormals, sqrt(sum(allFacetNormals.^2,2))); else allFacetNormals = permute(options.facenormals,[3 2 1]); end if options.flipnormals allFacetNormals = -allFacetNormals; end % We use a Z-ray intersection so we don't even need to consider facets that % are purely vertically oriented (have zero Z-component). isFacetUseful = allFacetNormals(:,3,:) ~= 0; %% Setup grid referencing system % Function speed can be thought of as a function of grid size. A small number of grid % squares means iterating over fewer regions (good) but with more faces/qPts to % consider each time (bad). For any given mesh/queryPt configuration, there will be a % sweet spot that minimises computation time. There will also be a constraint from % memory available - low grid sizes means considering many queryPt/faces at once, % which will require a larger memory footprint. Here we will let the user specify % gridsize directly, or we will estimate the optimum size based on prior testing. if ~isempty(options.gridsize) gridSize = options.gridsize; else % Coefficients (with 95% confidence bounds): p00 = -47; p10 = 12.83; p01 = 20.89; p20 = 0.7578; p11 = -6.511; p02 = -2.586; p30 = -0.1802; p21 = 0.2085; p12 = 0.7521; p03 = 0.09984; p40 = 0.005815; p31 = 0.007775; p22 = -0.02129; p13 = -0.02309; GSfit = @(x,y)p00 + p10*x + p01*y + p20*x^2 + p11*x*y + p02*y^2 + p30*x^3 + p21*x^2*y + p12*x*y^2 + p03*y^3 + p40*x^4 + p31*x^3*y + p22*x^2*y^2 + p13*x*y^3; gridSize = min(150 ,max(1, ceil(GSfit(log(numQPoints),log(numFaces))))); if isnan(gridSize), gridSize = 1; end end %% Find candidate qPts -> triangles pairs % We have a large set of query points. For each query point, find potential % triangles that would be pierced by vertical rays through the qPt. First, % a simple filter by XY bounding box % Calculate the bounding box of each facet minFacetCoords = permute(min(facets(:,1:2,:),[],1),[3 2 1]); maxFacetCoords = permute(max(facets(:,1:2,:),[],1),[3 2 1]); % Set rescale values to rescale all vertices between 0(-eps) and 1(+eps) scalingOffsetsXY = min(minFacetCoords,[],1) - eps; scalingRangeXY = max(maxFacetCoords,[],1) - scalingOffsetsXY + 2*eps; % Based on scaled min/max facet coords, get the [lowX lowY highX highY] "grid" index % of all faces lowToHighGridIdxs = floor(bsxfun(@rdivide, ... bsxfun(@minus, ... % Use min/max coordinates of each facet (+/- the tolerance) [minFacetCoords-options.tol maxFacetCoords+options.tol],... [scalingOffsetsXY scalingOffsetsXY]),... [scalingRangeXY scalingRangeXY]) * gridSize) + 1; % Build a grid of cells. In each cell, place the facet indices that encroach into % that grid region. Similarly, each query point will be assigned to a grid region. % Note that query points will be assigned only one grid region, facets can cover many % regions. Furthermore, we will add a tolerance to facet region assignment to ensure % a query point will be compared to facets even if it falls only on the edge of a % facet's bounding box, rather than inside it. cells = cell(gridSize); [unqLHgrids,~,facetInds] = unique(lowToHighGridIdxs,'rows'); tmpInds = accumarray(facetInds(isFacetUseful),find(isFacetUseful),[size(unqLHgrids,1),1],@(x){x}); for xi = 1:gridSize xyMinMask = xi >= unqLHgrids(:,1) & xi <= unqLHgrids(:,3); for yi = 1:gridSize cells{yi,xi} = cat(1,tmpInds{xyMinMask & yi >= unqLHgrids(:,2) & yi <= unqLHgrids(:,4)}); % The above line (with accumarray) is faster with equiv results than: % % cells{yi,xi} = find(ismember(facetInds, xyInds)); end end % With large number of facets, memory may be important: clear lowToHightGridIdxs LHgrids facetInds tmpInds xyMinMask minFacetCoords maxFacetCoords %% Compute edge unit vectors and dot products % Precompute the 2d unit vectors making up each facet's edges in the XY plane. allEdgeUVecs = bsxfun(@rdivide, allEdgeVecs(:,1:2,:), sqrt(sum(allEdgeVecs(:,1:2,:).^2,2))); % Precompute the inner product between edgeA.edgeC, edgeB.edgeA, edgeC.edgeB allEdgeEdgeDotPs = sum(allEdgeUVecs .* -allEdgeUVecs([3 1 2],:,:),2) - 1e-9; %% Gather XY query locations % Since query points are most likely given as a (3D) grid of query locations, we only % need to consider the unique XY locations when asking which facets a vertical ray % through an XY location would pierce. if ~options.griddedInput % SCATTERED QUERY POINTS qPtsXY = @(varargin)qPts(:,1:2); qPtsXYZViaUnqIndice = @(ind)qPts(ind,:); outPxIndsViaUnqIndiceMask = @(ind,mask)ind(mask); outputSize = [size(qPts,1),1]; reshapeINfcn = @(INMASK)INMASK; minFacetDistanceFcn = @minFacetToQptDistance; else % STRUCTURED QUERY POINTS [xmat,ymat] = meshgrid(qPts{1:2}); qPtsXY = [xmat(:) ymat(:)]; % A standard set of Z locations will be shifted around by different % unqQpts XY coordinates. zCoords = qPts{3}(:) * [0 0 1]; qPtsXYZViaUnqIndice = @(ind)bsxfun(@plus, zCoords, [qPtsXY(ind,:) 0]); % From a given indice and mask, we will turn on/off the IN points under % that indice based on the mask. The easiest calculation is to setup % the IN matrix as a numZpts-by-numUnqPts mask. At the end, we must % unpack/reshape this 2D mask to a full 3D logical mask numZpts = size(zCoords,1); baseZinds = 1:numZpts; outPxIndsViaUnqIndiceMask = @(ind,mask)(ind-1)*numZpts + baseZinds(mask); outputSize = [numZpts, size(qPtsXY,1)]; reshapeINfcn = @(INMASK)reshape(INMASK', cellfun(@numel, qPts([2 1 3]))); minFacetDistanceFcn = @minFacetToQptsDistance; end % Start with every query point NOT inside the polyhedron. We will % iteratively find those query points that ARE inside. IN = false(outputSize); % Determine with grids each query point falls into. qPtGridXY = floor(bsxfun(@rdivide, bsxfun(@minus, qPtsXY(:,:), scalingOffsetsXY),... scalingRangeXY) * gridSize) + 1; [unqQgridXY,~,qPtGridInds] = unique(qPtGridXY,'rows'); % We need only consider grid indices within those already set up ptsToConsidMask = ~any(qPtGridXY<1 | qPtGridXY>gridSize, 2); if ~any(ptsToConsidMask) IN = reshapeINfcn(IN); return; end % Build the reference list cellQptContents = accumarray(qPtGridInds(ptsToConsidMask),find(ptsToConsidMask), [],@(x){x}); gridsToCheck = unqQgridXY(~any(unqQgridXY<1 | unqQgridXY>gridSize, 2),:); cellQptContents(cellfun('isempty',cellQptContents)) = []; gridIndsToCheck = sub2ind(size(cells), gridsToCheck(:,2), gridsToCheck(:,1)); % For ease of multiplication, reshape qPt XY coords to [1-by-2-by-1-by-N] qPtsXY = permute(qPtsXY(:,:),[4 2 3 1]); % There will be some grid indices with query points but without facets. emptyMask = cellfun('isempty',cells(gridIndsToCheck))'; for i = find(~emptyMask) % We get all the facet coordinates (ie, triangle vertices) of triangles % that intrude into this grid location. The size is [3-by-2-by-N], for % the [3vertices-by-XY-by-Ntriangles] allFacetInds = cells{gridIndsToCheck(i)}; candVerts = facets(:,1:2,allFacetInds); % We need the XY coordinates of query points falling into this grid. allqPtInds = cellQptContents{i}; queryPtsXY = qPtsXY(:,:,:,allqPtInds); % Get unit vectors pointing from each triangle vertex to my query point(s) vert2ptVecs = bsxfun(@minus, queryPtsXY, candVerts); vert2ptUVecs = bsxfun(@rdivide, vert2ptVecs, sqrt(sum(vert2ptVecs.^2,2))); % Get unit vectors pointing around each triangle (along edge A, edge B, edge C) edgeUVecs = allEdgeUVecs(:,:,allFacetInds); % Get the inner product between edgeA.edgeC, edgeB.edgeA, edgeC.edgeB edgeEdgeDotPs = allEdgeEdgeDotPs(:,:,allFacetInds); % Get inner products between each edge unit vec and the UVs from qPt to vertex edgeQPntDotPs = sum(bsxfun(@times, edgeUVecs, vert2ptUVecs),2); qPntEdgeDotPs = sum(bsxfun(@times,vert2ptUVecs, -edgeUVecs([3 1 2],:,:)),2); % If both inner products 2 edges to the query point are greater than the inner % product between the two edges themselves, the query point is between the V % shape made by the two edges. If this is true for all 3 edge pair, the query % point is inside the triangle. resultIN = all(bsxfun(@gt, edgeQPntDotPs, edgeEdgeDotPs) & bsxfun(@gt, qPntEdgeDotPs, edgeEdgeDotPs),1); resultONVERTEX = any(any(isnan(vert2ptUVecs),2),1); result = resultIN | resultONVERTEX; qPtHitsTriangles = any(result,3); % If NONE of the query points pierce ANY triangles, we can skip forward if ~any(qPtHitsTriangles), continue, end % In the next step, we'll need to know the indices of ALL the query points at % each of the distinct XY coordinates. Let's get their indices into "qPts" as a % cell of length M, where M is the number of unique XY points we had found. for ptNo = find(qPtHitsTriangles(:))' % Which facets does it pierce? piercedFacetInds = allFacetInds(result(1,1,:,ptNo)); % Get the 1-by-3-by-N set of triangle normals that this qPt pierces piercedTriNorms = allFacetNormals(:,:,piercedFacetInds); % Pick the first vertex as the "origin" of a plane through the facet. Get the % vectors from each query point to each facet origin facetToQptVectors = bsxfun(@minus, ... qPtsXYZViaUnqIndice(allqPtInds(ptNo)),... facets(1,:,piercedFacetInds)); % Calculate how far you need to go up/down to pierce the facet's plane. % Positive direction means "inside" the facet, negative direction means % outside. facetToQptDists = bsxfun(@rdivide, ... sum(bsxfun(@times,piercedTriNorms,facetToQptVectors),2), ... abs(piercedTriNorms(:,3,:))); % Since it's possible for two triangles sharing the same vertex to % be the same distance away, I want to sum up all the distances of % triangles that are closest to the query point. Simple case: The % closest triangle is unique Edge case: The closest triangle is one % of many the same distance and direction away. Tricky case: The % closes triangle has another triangle the equivalent distance % but facing the opposite direction IN( outPxIndsViaUnqIndiceMask(allqPtInds(ptNo), ... minFacetDistanceFcn(facetToQptDists)<options.tol... )) = true; end end % If they provided X,Y,Z vectors of query points, our output is currently a % 2D mask and must be reshaped to [LEN(Y) LEN(X) LEN(Z)]. IN = reshapeINfcn(IN); %% Called subfunctions % vertices = [ % 0.9046 0.1355 -0.0900 % 0.8999 0.3836 -0.0914 % 1.0572 0.2964 -0.0907 % 0.8735 0.1423 -0.1166 % 0.8685 0.4027 -0.1180 % 1.0337 0.3112 -0.1173 % 0.9358 0.1287 -0.0634 % 0.9313 0.3644 -0.0647 % 1.0808 0.2816 -0.0641 % ]; % faces = [ % 1 2 5 % 1 5 4 % 2 3 6 % 2 6 5 % 3 1 4 % 3 4 6 % 6 4 5 % 2 1 8 % 8 1 7 % 3 2 9 % 9 2 8 % 1 3 7 % 7 3 9 % 7 9 8 % ]; % point = [vertices(3,1),vertices(3,2),1.5]; function closestTriDistance = minFacetToQptDistance(facetToQptDists) % FacetToQptDists is a 1pt-by-1-by-Nfacets array of how far you need to go % up/down to pierce each facet's plane. If the Qpt was directly over an % "overhang" vertex, then two facets with opposite orientation will be % equally distant from the Qpt, with one distance positive and one % negative. In such cases, it is impossible for the Qpt to actually be % "inside" this pair of facets, so their distance is updated to Inf. [~,minInd] = min(abs(facetToQptDists),[],3); while any( abs(facetToQptDists + facetToQptDists(minInd)) < 1e-15 ) % Since the above comparison is made every time, but the below variable % setting is done only in the rare case that a query point coincides % with an overhang vertex, it is more efficient to re-compute the % equality when it's true, rather than store the result every time. facetToQptDists( abs(facetToQptDists) - abs(facetToQptDists(minInd)) < 1e-15) = inf; if ~any(isfinite(facetToQptDists)) break; end [~,minInd] = min(abs(facetToQptDists),[],3); end closestTriDistance = facetToQptDists(minInd); function closestTriDistance = minFacetToQptsDistance(facetToQptDists) % As above, but facetToQptDists is an Mpts-by-1-by-Nfacets array. % The multi-point version is a little more tricky. While below is quite a % bit slower when the while loop is entered, it is very rarely entered and % very fast to make just the initial comparison. [minVals,minInds] = min(abs(facetToQptDists),[],3); while any(... any(abs(bsxfun(@plus,minVals,facetToQptDists))<1e-15,3) & ... any(abs(bsxfun(@minus,minVals,facetToQptDists))<1e-15,3)) maskP = abs(bsxfun(@plus,minVals,facetToQptDists))<1e-15; maskN = abs(bsxfun(@minus,minVals,facetToQptDists))<1e-15; mustAlterMask = any(maskP,3) & any(maskN,3); for i = find(mustAlterMask)' facetToQptDists(i,:,maskP(i,:,:) | maskN(i,:,:)) = inf; end [newMv,newMinInds] = min(abs(facetToQptDists(mustAlterMask,:,:)),[],3); minInds(mustAlterMask) = newMinInds(:); minVals(mustAlterMask) = newMv(:); end % Below is a tiny speedup on basically a sub2ind call. closestTriDistance = facetToQptDists((minInds-1)*size(facetToQptDists,1) + (1:size(facetToQptDists,1))'); %% Input handling subfunctions function [facets, qPts, options] = parseInputs(varargin) % Gather FACES and VERTICES if isstruct(varargin{1}) % inpolyhedron(FVstruct, ...) if ~all(isfield(varargin{1},{'vertices','faces'})) error( 'Structure FV must have "faces" and "vertices" fields' ); end faces = varargin{1}.faces; vertices = varargin{1}.vertices; varargin(1) = []; % Chomp off the faces/vertices else % inpolyhedron(FACES, VERTICES, ...) faces = varargin{1}; vertices = varargin{2}; varargin(1:2) = []; % Chomp off the faces/vertices end % Unpack the faces/vertices into [3-by-3-by-N] facets. It's better to % perform this now and have FACETS only in memory in the main program, % rather than FACETS, FACES and VERTICES facets = vertices'; facets = permute(reshape(facets(:,faces'), 3, 3, []),[2 1 3]); % Extract query points if length(varargin)<2 || ischar(varargin{2}) % inpolyhedron(F, V, [x(:) y(:) z(:)], ...) qPts = varargin{1}; varargin(1) = []; % Chomp off the query points else % inpolyhedron(F, V, xVec, yVec, zVec, ...) qPts = varargin(1:3); % Chomp off the query points and tell the world that it's gridded input. varargin(1:3) = []; varargin = [varargin {'griddedInput',true}]; end % Extract configurable options options = parseOptions(varargin{:}); % Check if face normals are unified if options.testNormals options.normalsAreUnified = checkNormalUnification(faces); end function options = parseOptions(varargin) IP = inputParser; IP.addParamValue('gridsize',[], @(x)isscalar(x) && isnumeric(x)) IP.addParamValue('tol', 0, @(x)isscalar(x) && isnumeric(x)) IP.addParamValue('tol_ang', 1e-5, @(x)isscalar(x) && isnumeric(x)) IP.addParamValue('facenormals',[]); IP.addParamValue('flipnormals',false); IP.addParamValue('griddedInput',false); IP.addParamValue('testNormals',false); IP.parse(varargin{:}); options = IP.Results;
github
mathematical-tours/mathematical-tours.github.io-master
load_image.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/wass-barycenters/toolbox/load_image.m
19,798
utf_8
df61d87c209e587d6199fa36bbe979bf
function M = load_image(type, n, options) % load_image - load benchmark images. % % M = load_image(name, n, options); % % name can be: % Synthetic images: % 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line', % 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle', % 'parabola', 'sin', 'phantom', 'circ_oscil', % 'fnoise' (1/f^alpha noise). % Natural images: % 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own. % % Copyright (c) 2004 Gabriel Peyre if nargin<2 n = 512; end options.null = 0; if iscell(type) for i=1:length(type) M{i} = load_image(type{i},n,options); end return; end type = lower(type); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % parameters for geometric objects eta = getoptions(options, 'eta', .1); gamma = getoptions(options, 'gamma', 1/sqrt(2)); radius = getoptions(options, 'radius', 10); center = getoptions(options, 'center', [0 0]); center1 = getoptions(options, 'center1', [0 0]); w = getoptions(options, 'tube_width', 0.06); nb_points = getoptions(options, 'nb_points', 9); scaling = getoptions(options, 'scaling', 1); theta = getoptions(options, 'theta', 30 * 2*pi/360); eccentricity = getoptions(options, 'eccentricity', 1.3); sigma = getoptions(options, 'sigma', 0); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for the line, can be vertical / horizontal / diagonal / any if strcmp(type, 'line_vertical') eta = 0.5; % translation gamma = 0; % slope elseif strcmp(type, 'line_horizontal') eta = 0.5; % translation gamma = Inf; % slope elseif strcmp(type, 'line_diagonal') eta = 0; % translation gamma = 1; % slope end if strcmp(type(1:min(12,end)), 'square-tube-') k = str2double(type(13:end)); c1 = [.22 .5]; c2 = [1-c1(1) .5]; eta = 1.5; r1 = [c1 c1] + .21*[-1 -eta 1 eta]; r2 = [c2 c2] + .21*[-1 -eta 1 eta]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) ); if mod(k,2)==0 sel = n/2-k/2+1:n/2+k/2; else sel = n/2-(k-1)/2:n/2+(k-1)/2; end M( round(.25*n:.75*n), sel ) = 1; return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch lower(type) case 'constant' M = ones(n); case 'ramp' x = linspace(0,1,n); [Y,M] = meshgrid(x,x); case 'bump' s = getoptions(options, 'bump_size', .5); c = getoptions(options, 'center', [0 0]); if length(s)==1 s = [s s]; end x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); X = (X-c(1))/s(1); Y = (Y-c(2))/s(2); M = exp( -(X.^2+Y.^2)/2 ); case 'periodic' x = linspace(-pi,pi,n)/1.1; [Y,X] = meshgrid(x,x); f = getoptions(options, 'freq', 6); M = (1+cos(f*X)).*(1+cos(f*Y)); case {'letter-x' 'letter-v' 'letter-z' 'letter-y'} M = create_letter(type(8), radius, n); case 'l' r1 = [.1 .1 .3 .9]; r2 = [.1 .1 .9 .4]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) ); case 'ellipse' c1 = [0.15 0.5]; c2 = [0.85 0.5]; x = linspace(0,1,n); [Y,X] = meshgrid(x,x); d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2); M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) ); case 'ellipse-thin' options.eccentricity = 1.06; M = load_image('ellipse', n, options); case 'ellipse-fat' options.eccentricity = 1.3; M = load_image('ellipse', n, options); case 'square-tube' c1 = [.25 .5]; c2 = [.75 .5]; r1 = [c1 c1] + .18*[-1 -1 1 1]; r2 = [c2 c2] + .18*[-1 -1 1 1]; r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) ); case 'square-tube-1' options.tube_width = 0.03; M = load_image('square-tube', n, options); case 'square-tube-2' options.tube_width = 0.06; M = load_image('square-tube', n, options); case 'square-tube-3' options.im = 0.09; M = load_image('square-tube', n, options); case 'polygon' theta = sort( rand(nb_points,1)*2*pi ); radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93); points = [cos(theta) sin(theta)] .* repmat(radius, 1,2); points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:); M = draw_polygons(zeros(n),0.8,{points'}); [x,y] = ind2sub(size(M),find(M)); p = 100; m = length(x); lambda = linspace(0,1,p); X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]); Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]); I = round(X) + (round(Y)-1)*n; M = zeros(n); M(I) = 1; case 'polygon-8' options.nb_points = 8; M = load_image('polygon', n, options); case 'polygon-10' options.nb_points = 8; M = load_image('polygon', n, options); case 'polygon-12' options.nb_points = 8; M = load_image('polygon', n, options); case 'pacman' options.radius = 0.45; options.center = [.5 .5]; M = load_image('disk', n, options); x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); T =atan2(Y,X); M = M .* (1-(abs(T-pi/2)<theta/2)); case 'square-hole' options.radius = 0.45; M = load_image('disk', n, options); options.scaling = 0.5; M = M - load_image('polygon-10', n, options); case 'grid-circles' if isempty(n) n = 256; end f = getoptions(options, 'frequency', 30); eta = getoptions(options, 'width', .3); x = linspace(-n/2,n/2,n) - round(n*0.03); y = linspace(0,n,n); [Y,X] = meshgrid(y,x); R = sqrt(X.^2+Y.^2); theta = 0.05*pi/2; X1 = cos(theta)*X+sin(theta)*Y; Y1 = -sin(theta)*X+cos(theta)*Y; A1 = abs(cos(2*pi*R/f))<eta; A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta ); M = A1; M(X1>0) = A2(X1>0); case 'chessboard1' x = -1:2/(n-1):1; [Y,X] = meshgrid(x,x); M = (2*(Y>=0)-1).*(2*(X>=0)-1); case 'chessboard' width = getoptions(options, 'width', round(n/16) ); [Y,X] = meshgrid(0:n-1,0:n-1); M = mod( floor(X/width)+floor(Y/width), 2 ) == 0; case 'square' if ~isfield( options, 'radius' ) radius = 0.6; end x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); M = max( abs(X),abs(Y) )<radius; case 'squareregular' M = rescale(load_image('square',n,options)); if not(isfield(options, 'alpha')) options.alpha = 3; end S = load_image('fnoise',n,options); M = M + rescale(S,-0.3,0.3); case 'regular1' options.alpha = 1; M = load_image('fnoise',n,options); case 'regular2' options.alpha = 2; M = load_image('fnoise',n,options); case 'regular3' options.alpha = 3; M = load_image('fnoise',n,options); case 'sparsecurves' options.alpha = 3; M = load_image('fnoise',n,options); M = rescale(M); ncurves = 3; M = cos(2*pi*ncurves); case 'geometrical' J = getoptions(options, 'Jgeometrical', 4); sgeom = 100*n/256; options.bound = 'per'; A = ones(n); for j=0:J-1 B = A; for k=1:2^j I = find(B==k); U = perform_blurring(randn(n),sgeom,options); s = median(U(I)); I1 = find( (B==k) & (U>s) ); I2 = find( (B==k) & (U<=s) ); A(I1) = 2*k-1; A(I2) = 2*k; end end M = A; case 'lic-texture' disp('Computing random tensor field.'); options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256); T = compute_tensor_field_random(n,options); Flow = perform_tensor_decomp(T); % extract eigenfield. options.isoriented = 0; % no orientation in streamlines % initial texture lic_width = getoptions(options, 'lic_width', 0); M0 = perform_blurring(randn(n),lic_width); M0 = perform_histogram_equalization( M0, 'linear'); options.histogram = 'linear'; options.dt = 0.4; options.M0 = M0; options.verb = 1; options.flow_correction = 1; options.niter_lic = 3; w = 30; M = perform_lic(Flow, w, options); case 'square_texture' M = load_image('square',n); M = rescale(M); % make a texture patch x = linspace(0,1,n); [Y,X] = meshgrid(x,x); theta = pi/3; x = cos(theta)*X + sin(theta)*Y; c = [0.3,0.4]; r = 0.2; I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 ); eta = 3/n; lambda = 0.3; M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta ); case 'tv-image' M = rand(n); tau = compute_total_variation(M); options.niter = 400; [M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options); M = perform_histogram_equalization(M,'linear'); case 'oscillatory_texture' x = linspace(0,1,n); [Y,X] = meshgrid(x,x); theta = pi/3; x = cos(theta)*X + sin(theta)*Y; c = [0.3,0.4]; r = 0.2; I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 ); eta = 3/n; lambda = 0.3; M = sin( x * 2*pi / eta ); case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'} x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); if gamma~=Inf M = (X-eta) - gamma*Y < 0; else M = (Y-eta) < 0; end case 'line-windowed' x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); eta = .3; gamma = getoptions(options, 'gamma', pi/10); parabola = getoptions(options, 'parabola', 0); M = (X-eta) - gamma*Y - parabola*Y.^2 < 0; f = sin( pi*x ).^2; M = M .* ( f'*f ); case 'grating' x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); theta = getoptions(options, 'theta', .2); freq = getoptions(options, 'freq', .2); X = cos(theta)*X + sin(theta)*Y; M = sin(2*pi*X/freq); case 'disk' if ~isfield( options, 'radius' ) radius = 0.35; end if ~isfield( options, 'center' ) center = [0.5, 0.5]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; case 'twodisks' M = zeros(n); options.center = [.25 .25]; M = load_image('disk', n, options); options.center = [.75 .75]; M = M + load_image('disk', n, options); case 'diskregular' M = rescale(load_image('disk',n,options)); if not(isfield(options, 'alpha')) options.alpha = 3; end S = load_image('fnoise',n,options); M = M + rescale(S,-0.3,0.3); case 'quarterdisk' if ~isfield( options, 'radius' ) radius = 0.95; end if ~isfield( options, 'center' ) center = -[0.1, 0.1]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; case 'fading_contour' if ~isfield( options, 'radius' ) radius = 0.95; end if ~isfield( options, 'center' ) center = -[0.1, 0.1]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; theta = 2/pi*atan2(Y,X); h = 0.5; M = exp(-(1-theta).^2/h^2).*M; case '3contours' radius = 1.3; center = [-1, 1]; radius1 = 0.8; center1 = [0, 0]; x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2; M = f1 + 0.5*f2.*(1-f1); case 'line_circle' gamma = 1/sqrt(2); x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); M1 = double( X>gamma*Y+0.25 ); M2 = X.^2 + Y.^2 < 0.6^2; M = 20 + max(0.5*M1,M2) * 216; case 'fnoise' % generate an image M whose Fourier spectrum amplitude is % |M^(omega)| = 1/f^{omega} alpha = getoptions(options, 'alpha', 1); M = gen_noisy_image(n,alpha); case 'gaussiannoise' % generate an image of filtered noise with gaussian sigma = getoptions(options, 'sigma', 10); M = randn(n); m = 51; h = compute_gaussian_filter([m m],sigma/(4*n),[n n]); M = perform_convolution(M,h); return; case {'bwhorizontal','bwvertical','bwcircle'} [Y,X] = meshgrid(0:n-1,0:n-1); if strcmp(type, 'bwhorizontal') d = X; elseif strcmp(type, 'bwvertical') d = Y; elseif strcmp(type, 'bwcircle') d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 ); end if isfield(options, 'stripe_width') stripe_width = options.stripe_width; else stripe_width = 5; end if isfield(options, 'black_prop') black_prop = options.black_prop; else black_prop = 0.5; end M = double( mod( d/(2*stripe_width),1 )>=black_prop ); case 'parabola' % curvature c = getoptions(c, 'c', .1); % angle theta = getoptions(options, 'theta', pi/sqrt(2)); x = -0.5:1/(n-1):0.5; [Y,X] = meshgrid(x,x); Xs = X*cos(theta) + Y*sin(theta); Y =-X*sin(theta) + Y*cos(theta); X = Xs; M = Y>c*X.^2; case 'sin' [Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1); M = Y >= 0.6*cos(pi*X); M = double(M); case 'circ_oscil' x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); R = sqrt(X.^2+Y.^2); M = cos(R.^3*50); case 'phantom' M = phantom(n); case 'periodic_bumps' nbr_periods = getoptions(options, 'nbr_periods', 8); theta = getoptions(options, 'theta', 1/sqrt(2)); skew = getoptions(options, 'skew', 1/sqrt(2) ); A = [cos(theta), -sin(theta); sin(theta), cos(theta)]; B = [1 skew; 0 1]; T = B*A; x = (0:n-1)*2*pi*nbr_periods/(n-1); [Y,X] = meshgrid(x,x); pos = [X(:)'; Y(:)']; pos = T*pos; X = reshape(pos(1,:), n,n); Y = reshape(pos(2,:), n,n); M = cos(X).*sin(Y); case 'noise' sigma = getoptions(options, 'sigma', 1); M = randn(n) * sigma; case 'disk-corner' x = linspace(0,1,n); [Y,X] = meshgrid(x,x); rho = .3; eta = .1; M1 = rho*X+eta<Y; c = [0 .2]; r = .85; d = (X-c(1)).^2 + (Y-c(2)).^2; M2 = d<r^2; M = M1.*M2; otherwise ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'}; for i=1:length(ext) name = [type '.' ext{i}]; if( exist(name) ) M = imread( name ); M = double(M); if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2 M = image_resize(M,n,n); end if strcmp(type, 'peppers-bw') M(:,1) = M(:,2); M(1,:) = M(2,:); end if sigma>0 M = perform_blurring(M,sigma); end return; end end error( ['Image ' type ' does not exists.'] ); end M = double(M); if sigma>0 M = perform_blurring(M,sigma); end M = rescale(M); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = create_letter(a, r, n) c = 0.2; p1 = [c;c]; p2 = [c; 1-c]; p3 = [1-c; 1-c]; p4 = [1-c; c]; p4 = [1-c; c]; pc = [0.5;0.5]; pu = [0.5; c]; switch a case 'x' point_list = { [p1 p3] [p2 p4] }; case 'z' point_list = { [p2 p3 p1 p4] }; case 'v' point_list = { [p2 pu p3] }; case 'y' point_list = { [p2 pc pu] [pc p3] }; end % fit image for i=1:length(point_list) a = point_list{i}(2:-1:1,:); a(1,:) = 1-a(1,:); point_list{i} = round( a*(n-1)+1 ); end M = draw_polygons(zeros(n),r,point_list); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sk = draw_polygons(mask,r,point_list) sk = mask*0; for i=1:length(point_list) pl = point_list{i}; for k=2:length(pl) sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sk = draw_line(sk,x1,y1,x2,y2,r) n = size(sk,1); [Y,X] = meshgrid(1:n,1:n); q = 100; t = linspace(0,1,q); x = x1*t+x2*(1-t); y = y1*t+y2*(1-t); if r==0 x = round( x ); y = round( y ); sk( x+(y-1)*n ) = 1; else for k=1:q I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 ); sk(I) = 1; end end function M = gen_noisy_image(n,alpha) % gen_noisy_image - generate a noisy cloud-like image. % % M = gen_noisy_image(n,alpha); % % generate an image M whose Fourier spectrum amplitude is % |M^(omega)| = 1/f^{omega} % % Copyright (c) 2004 Gabriel Peyre if nargin<1 n = 128; end if nargin<2 alpha = 1.5; end if mod(n(1),2)==0 x = -n/2:n/2-1; else x = -(n-1)/2:(n-1)/2; end [Y,X] = meshgrid(x,x); d = sqrt(X.^2 + Y.^2) + 0.1; f = rand(n)*2*pi; M = (d.^(-alpha)) .* exp(f*1i); % M = real(ifft2(fftshift(M))); M = ifftshift(M); M = real( ifft2(M) ); function y = gen_signal_2d(n,alpha) % gen_signal_2d - generate a 2D C^\alpha signal of length n x n. % gen_signal_2d(n,alpha) generate a 2D signal C^alpha. % % The signal is scale in [0,1]. % % Copyright (c) 2003 Gabriel Peyre % new new method [Y,X] = meshgrid(0:n-1, 0:n-1); A = X+Y+1; B = X-Y+n+1; a = gen_signal(2*n+1, alpha); b = gen_signal(2*n+1, alpha); y = a(A).*b(B); % M = a(1:n)*b(1:n)'; return; % new method h = (-n/2+1):(n/2); h(n/2)=1; [X,Y] = meshgrid(h,h); h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2); h = h .* exp( 2i*pi*rand(n,n) ); h = fftshift(h); y = real( ifft2(h) ); m1 = min(min(y)); m2 = max(max(y)); y = (y-m1)/(m2-m1); return; %% old code y = rand(n,n); y = y - mean(mean(y)); for i=1:alpha y = cumsum(cumsum(y)')'; y = y - mean(mean(y)); end m1 = min(min(y)); m2 = max(max(y)); y = (y-m1)/(m2-m1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = draw_rectangle(r,n) x = linspace(0,1,n); [Y,X] = meshgrid(x,x); M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
github
mathematical-tours/mathematical-tours.github.io-master
imageplot.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/wass-barycenters/toolbox/imageplot.m
2,996
utf_8
bb6359ff3ad5e82264a744d41ba24582
function h1 = imageplot(M,str, a,b,c) % imageplot - diplay an image and a title % % Example of usages: % imageplot(M); % imageplot(M,title); % imageplot(M,title,1,2,1); % to make subplot(1,2,1); % % imageplot(M,options); % % If you want to display several images: % imageplot({M1 M2}, {'title1', 'title2'}); % % Copyright (c) 2007 Gabriel Peyre if nargin<2 str = []; end options.null = 0; if isstruct(str) options = str; str = ''; end nbdims = nb_dims(M); if iscell(M) q = length(M); if nargin<5 c = 1; end if nargin<4 a = ceil(q/4); end if nargin<3 b = ceil(q/a); end if (c-1+q)>(a*b) warning('a and c parameters not large enough'); a = ceil((c-1+q)/4); b = ceil((c-1+q)/a); end for i=1:q if iscell(str) str1 = str{i}; else str1 = str; end h{i} = imageplot(M{i},str1, a,b,c-1+i); end global axlist; if not(isempty(axlist)) linkaxes(axlist, 'xy'); end if nargout>0 if exist('h') h1 = h; else h1 = []; end end return; end if nargin==5 global axlist; global imageplot_size; if c==1 || isempty(imageplot_size) || imageplot_size~=size(M,1) clear axlist; global axlist; axlist = []; imageplot_size = size(M,1); end axlist(end+1) = subplot(a,b,c); end if nbdims==1 h = plot(M); axis tight; elseif size(M,3)<=3 % gray-scale or color image if size(M,3)==2 M = cat(3,M, zeros(size(M,1),size(M,2))); end if not(isreal(M)) if size(M,3)==1 % turn into color matrix M = cat(3, real(M), imag(M), zeros(size(M,1),size(M,2))); else warning('Complex data'); M = real(M); end end if size(M,3)==1 colormap gray(256); else colormap jet(256); end h = imagesc(rescale(M)); axis image; axis off; else if not(isfield(options, 'center') ) options.center = .5; % here a value in [0,1] end if not(isfield(options, 'sigma')) options.sigma = .08; % control the width of the non-transparent region end a = compute_alpha_map('gaussian', options); % you can plot(a) to see the alphamap % volumetric image h = vol3d('cdata',rescale(M),'texture','2D'); view(3); axis tight; % daspect([1 1 .4]) colormap bone(256); % alphamap('rampup'); % alphamap(.06 .* alphamap); vol3d(h); end if not(isempty(str)) title(str); end if nargout>0 if exist('h') h1 = h; else h1 = []; end end if nargin==5 && c==a*b linkaxes(axlist, 'xy'); end function d = nb_dims(x) % nb_dims - debugged version of ndims. % % d = nb_dims(x); % % Copyright (c) 2004 Gabriel Peyre if isempty(x) d = 0; return; end d = ndims(x); if d==2 && (size(x,1)==1 || size(x,2)==1) d = 1; end
github
mathematical-tours/mathematical-tours.github.io-master
check_face_vertex.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/silouhette/check_face_vertex.m
671
utf_8
21c65f119991c973909eedd356838dad
function [vertex,face] = check_face_vertex(vertex,face, options) % check_face_vertex - check that vertices and faces have the correct size % % [vertex,face] = check_face_vertex(vertex,face); % % Copyright (c) 2007 Gabriel Peyre vertex = check_size(vertex,2,4); face = check_size(face,3,4); %%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = check_size(a,vmin,vmax) if isempty(a) return; end if size(a,1)>size(a,2) a = a'; end if size(a,1)<3 && size(a,2)==3 a = a'; end if size(a,1)<=3 && size(a,2)>=3 && sum(abs(a(:,3)))==0 % for flat triangles % a = a'; end if size(a,1)<vmin || size(a,1)>vmax error('face or vertex is not of correct size'); end
github
mathematical-tours/mathematical-tours.github.io-master
load_image.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/toolbox/load_image.m
19,798
utf_8
df61d87c209e587d6199fa36bbe979bf
function M = load_image(type, n, options) % load_image - load benchmark images. % % M = load_image(name, n, options); % % name can be: % Synthetic images: % 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line', % 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle', % 'parabola', 'sin', 'phantom', 'circ_oscil', % 'fnoise' (1/f^alpha noise). % Natural images: % 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own. % % Copyright (c) 2004 Gabriel Peyre if nargin<2 n = 512; end options.null = 0; if iscell(type) for i=1:length(type) M{i} = load_image(type{i},n,options); end return; end type = lower(type); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % parameters for geometric objects eta = getoptions(options, 'eta', .1); gamma = getoptions(options, 'gamma', 1/sqrt(2)); radius = getoptions(options, 'radius', 10); center = getoptions(options, 'center', [0 0]); center1 = getoptions(options, 'center1', [0 0]); w = getoptions(options, 'tube_width', 0.06); nb_points = getoptions(options, 'nb_points', 9); scaling = getoptions(options, 'scaling', 1); theta = getoptions(options, 'theta', 30 * 2*pi/360); eccentricity = getoptions(options, 'eccentricity', 1.3); sigma = getoptions(options, 'sigma', 0); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for the line, can be vertical / horizontal / diagonal / any if strcmp(type, 'line_vertical') eta = 0.5; % translation gamma = 0; % slope elseif strcmp(type, 'line_horizontal') eta = 0.5; % translation gamma = Inf; % slope elseif strcmp(type, 'line_diagonal') eta = 0; % translation gamma = 1; % slope end if strcmp(type(1:min(12,end)), 'square-tube-') k = str2double(type(13:end)); c1 = [.22 .5]; c2 = [1-c1(1) .5]; eta = 1.5; r1 = [c1 c1] + .21*[-1 -eta 1 eta]; r2 = [c2 c2] + .21*[-1 -eta 1 eta]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) ); if mod(k,2)==0 sel = n/2-k/2+1:n/2+k/2; else sel = n/2-(k-1)/2:n/2+(k-1)/2; end M( round(.25*n:.75*n), sel ) = 1; return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch lower(type) case 'constant' M = ones(n); case 'ramp' x = linspace(0,1,n); [Y,M] = meshgrid(x,x); case 'bump' s = getoptions(options, 'bump_size', .5); c = getoptions(options, 'center', [0 0]); if length(s)==1 s = [s s]; end x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); X = (X-c(1))/s(1); Y = (Y-c(2))/s(2); M = exp( -(X.^2+Y.^2)/2 ); case 'periodic' x = linspace(-pi,pi,n)/1.1; [Y,X] = meshgrid(x,x); f = getoptions(options, 'freq', 6); M = (1+cos(f*X)).*(1+cos(f*Y)); case {'letter-x' 'letter-v' 'letter-z' 'letter-y'} M = create_letter(type(8), radius, n); case 'l' r1 = [.1 .1 .3 .9]; r2 = [.1 .1 .9 .4]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) ); case 'ellipse' c1 = [0.15 0.5]; c2 = [0.85 0.5]; x = linspace(0,1,n); [Y,X] = meshgrid(x,x); d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2); M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) ); case 'ellipse-thin' options.eccentricity = 1.06; M = load_image('ellipse', n, options); case 'ellipse-fat' options.eccentricity = 1.3; M = load_image('ellipse', n, options); case 'square-tube' c1 = [.25 .5]; c2 = [.75 .5]; r1 = [c1 c1] + .18*[-1 -1 1 1]; r2 = [c2 c2] + .18*[-1 -1 1 1]; r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) ); case 'square-tube-1' options.tube_width = 0.03; M = load_image('square-tube', n, options); case 'square-tube-2' options.tube_width = 0.06; M = load_image('square-tube', n, options); case 'square-tube-3' options.im = 0.09; M = load_image('square-tube', n, options); case 'polygon' theta = sort( rand(nb_points,1)*2*pi ); radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93); points = [cos(theta) sin(theta)] .* repmat(radius, 1,2); points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:); M = draw_polygons(zeros(n),0.8,{points'}); [x,y] = ind2sub(size(M),find(M)); p = 100; m = length(x); lambda = linspace(0,1,p); X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]); Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]); I = round(X) + (round(Y)-1)*n; M = zeros(n); M(I) = 1; case 'polygon-8' options.nb_points = 8; M = load_image('polygon', n, options); case 'polygon-10' options.nb_points = 8; M = load_image('polygon', n, options); case 'polygon-12' options.nb_points = 8; M = load_image('polygon', n, options); case 'pacman' options.radius = 0.45; options.center = [.5 .5]; M = load_image('disk', n, options); x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); T =atan2(Y,X); M = M .* (1-(abs(T-pi/2)<theta/2)); case 'square-hole' options.radius = 0.45; M = load_image('disk', n, options); options.scaling = 0.5; M = M - load_image('polygon-10', n, options); case 'grid-circles' if isempty(n) n = 256; end f = getoptions(options, 'frequency', 30); eta = getoptions(options, 'width', .3); x = linspace(-n/2,n/2,n) - round(n*0.03); y = linspace(0,n,n); [Y,X] = meshgrid(y,x); R = sqrt(X.^2+Y.^2); theta = 0.05*pi/2; X1 = cos(theta)*X+sin(theta)*Y; Y1 = -sin(theta)*X+cos(theta)*Y; A1 = abs(cos(2*pi*R/f))<eta; A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta ); M = A1; M(X1>0) = A2(X1>0); case 'chessboard1' x = -1:2/(n-1):1; [Y,X] = meshgrid(x,x); M = (2*(Y>=0)-1).*(2*(X>=0)-1); case 'chessboard' width = getoptions(options, 'width', round(n/16) ); [Y,X] = meshgrid(0:n-1,0:n-1); M = mod( floor(X/width)+floor(Y/width), 2 ) == 0; case 'square' if ~isfield( options, 'radius' ) radius = 0.6; end x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); M = max( abs(X),abs(Y) )<radius; case 'squareregular' M = rescale(load_image('square',n,options)); if not(isfield(options, 'alpha')) options.alpha = 3; end S = load_image('fnoise',n,options); M = M + rescale(S,-0.3,0.3); case 'regular1' options.alpha = 1; M = load_image('fnoise',n,options); case 'regular2' options.alpha = 2; M = load_image('fnoise',n,options); case 'regular3' options.alpha = 3; M = load_image('fnoise',n,options); case 'sparsecurves' options.alpha = 3; M = load_image('fnoise',n,options); M = rescale(M); ncurves = 3; M = cos(2*pi*ncurves); case 'geometrical' J = getoptions(options, 'Jgeometrical', 4); sgeom = 100*n/256; options.bound = 'per'; A = ones(n); for j=0:J-1 B = A; for k=1:2^j I = find(B==k); U = perform_blurring(randn(n),sgeom,options); s = median(U(I)); I1 = find( (B==k) & (U>s) ); I2 = find( (B==k) & (U<=s) ); A(I1) = 2*k-1; A(I2) = 2*k; end end M = A; case 'lic-texture' disp('Computing random tensor field.'); options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256); T = compute_tensor_field_random(n,options); Flow = perform_tensor_decomp(T); % extract eigenfield. options.isoriented = 0; % no orientation in streamlines % initial texture lic_width = getoptions(options, 'lic_width', 0); M0 = perform_blurring(randn(n),lic_width); M0 = perform_histogram_equalization( M0, 'linear'); options.histogram = 'linear'; options.dt = 0.4; options.M0 = M0; options.verb = 1; options.flow_correction = 1; options.niter_lic = 3; w = 30; M = perform_lic(Flow, w, options); case 'square_texture' M = load_image('square',n); M = rescale(M); % make a texture patch x = linspace(0,1,n); [Y,X] = meshgrid(x,x); theta = pi/3; x = cos(theta)*X + sin(theta)*Y; c = [0.3,0.4]; r = 0.2; I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 ); eta = 3/n; lambda = 0.3; M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta ); case 'tv-image' M = rand(n); tau = compute_total_variation(M); options.niter = 400; [M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options); M = perform_histogram_equalization(M,'linear'); case 'oscillatory_texture' x = linspace(0,1,n); [Y,X] = meshgrid(x,x); theta = pi/3; x = cos(theta)*X + sin(theta)*Y; c = [0.3,0.4]; r = 0.2; I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 ); eta = 3/n; lambda = 0.3; M = sin( x * 2*pi / eta ); case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'} x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); if gamma~=Inf M = (X-eta) - gamma*Y < 0; else M = (Y-eta) < 0; end case 'line-windowed' x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); eta = .3; gamma = getoptions(options, 'gamma', pi/10); parabola = getoptions(options, 'parabola', 0); M = (X-eta) - gamma*Y - parabola*Y.^2 < 0; f = sin( pi*x ).^2; M = M .* ( f'*f ); case 'grating' x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); theta = getoptions(options, 'theta', .2); freq = getoptions(options, 'freq', .2); X = cos(theta)*X + sin(theta)*Y; M = sin(2*pi*X/freq); case 'disk' if ~isfield( options, 'radius' ) radius = 0.35; end if ~isfield( options, 'center' ) center = [0.5, 0.5]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; case 'twodisks' M = zeros(n); options.center = [.25 .25]; M = load_image('disk', n, options); options.center = [.75 .75]; M = M + load_image('disk', n, options); case 'diskregular' M = rescale(load_image('disk',n,options)); if not(isfield(options, 'alpha')) options.alpha = 3; end S = load_image('fnoise',n,options); M = M + rescale(S,-0.3,0.3); case 'quarterdisk' if ~isfield( options, 'radius' ) radius = 0.95; end if ~isfield( options, 'center' ) center = -[0.1, 0.1]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; case 'fading_contour' if ~isfield( options, 'radius' ) radius = 0.95; end if ~isfield( options, 'center' ) center = -[0.1, 0.1]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; theta = 2/pi*atan2(Y,X); h = 0.5; M = exp(-(1-theta).^2/h^2).*M; case '3contours' radius = 1.3; center = [-1, 1]; radius1 = 0.8; center1 = [0, 0]; x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2; M = f1 + 0.5*f2.*(1-f1); case 'line_circle' gamma = 1/sqrt(2); x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); M1 = double( X>gamma*Y+0.25 ); M2 = X.^2 + Y.^2 < 0.6^2; M = 20 + max(0.5*M1,M2) * 216; case 'fnoise' % generate an image M whose Fourier spectrum amplitude is % |M^(omega)| = 1/f^{omega} alpha = getoptions(options, 'alpha', 1); M = gen_noisy_image(n,alpha); case 'gaussiannoise' % generate an image of filtered noise with gaussian sigma = getoptions(options, 'sigma', 10); M = randn(n); m = 51; h = compute_gaussian_filter([m m],sigma/(4*n),[n n]); M = perform_convolution(M,h); return; case {'bwhorizontal','bwvertical','bwcircle'} [Y,X] = meshgrid(0:n-1,0:n-1); if strcmp(type, 'bwhorizontal') d = X; elseif strcmp(type, 'bwvertical') d = Y; elseif strcmp(type, 'bwcircle') d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 ); end if isfield(options, 'stripe_width') stripe_width = options.stripe_width; else stripe_width = 5; end if isfield(options, 'black_prop') black_prop = options.black_prop; else black_prop = 0.5; end M = double( mod( d/(2*stripe_width),1 )>=black_prop ); case 'parabola' % curvature c = getoptions(c, 'c', .1); % angle theta = getoptions(options, 'theta', pi/sqrt(2)); x = -0.5:1/(n-1):0.5; [Y,X] = meshgrid(x,x); Xs = X*cos(theta) + Y*sin(theta); Y =-X*sin(theta) + Y*cos(theta); X = Xs; M = Y>c*X.^2; case 'sin' [Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1); M = Y >= 0.6*cos(pi*X); M = double(M); case 'circ_oscil' x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); R = sqrt(X.^2+Y.^2); M = cos(R.^3*50); case 'phantom' M = phantom(n); case 'periodic_bumps' nbr_periods = getoptions(options, 'nbr_periods', 8); theta = getoptions(options, 'theta', 1/sqrt(2)); skew = getoptions(options, 'skew', 1/sqrt(2) ); A = [cos(theta), -sin(theta); sin(theta), cos(theta)]; B = [1 skew; 0 1]; T = B*A; x = (0:n-1)*2*pi*nbr_periods/(n-1); [Y,X] = meshgrid(x,x); pos = [X(:)'; Y(:)']; pos = T*pos; X = reshape(pos(1,:), n,n); Y = reshape(pos(2,:), n,n); M = cos(X).*sin(Y); case 'noise' sigma = getoptions(options, 'sigma', 1); M = randn(n) * sigma; case 'disk-corner' x = linspace(0,1,n); [Y,X] = meshgrid(x,x); rho = .3; eta = .1; M1 = rho*X+eta<Y; c = [0 .2]; r = .85; d = (X-c(1)).^2 + (Y-c(2)).^2; M2 = d<r^2; M = M1.*M2; otherwise ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'}; for i=1:length(ext) name = [type '.' ext{i}]; if( exist(name) ) M = imread( name ); M = double(M); if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2 M = image_resize(M,n,n); end if strcmp(type, 'peppers-bw') M(:,1) = M(:,2); M(1,:) = M(2,:); end if sigma>0 M = perform_blurring(M,sigma); end return; end end error( ['Image ' type ' does not exists.'] ); end M = double(M); if sigma>0 M = perform_blurring(M,sigma); end M = rescale(M); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = create_letter(a, r, n) c = 0.2; p1 = [c;c]; p2 = [c; 1-c]; p3 = [1-c; 1-c]; p4 = [1-c; c]; p4 = [1-c; c]; pc = [0.5;0.5]; pu = [0.5; c]; switch a case 'x' point_list = { [p1 p3] [p2 p4] }; case 'z' point_list = { [p2 p3 p1 p4] }; case 'v' point_list = { [p2 pu p3] }; case 'y' point_list = { [p2 pc pu] [pc p3] }; end % fit image for i=1:length(point_list) a = point_list{i}(2:-1:1,:); a(1,:) = 1-a(1,:); point_list{i} = round( a*(n-1)+1 ); end M = draw_polygons(zeros(n),r,point_list); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sk = draw_polygons(mask,r,point_list) sk = mask*0; for i=1:length(point_list) pl = point_list{i}; for k=2:length(pl) sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sk = draw_line(sk,x1,y1,x2,y2,r) n = size(sk,1); [Y,X] = meshgrid(1:n,1:n); q = 100; t = linspace(0,1,q); x = x1*t+x2*(1-t); y = y1*t+y2*(1-t); if r==0 x = round( x ); y = round( y ); sk( x+(y-1)*n ) = 1; else for k=1:q I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 ); sk(I) = 1; end end function M = gen_noisy_image(n,alpha) % gen_noisy_image - generate a noisy cloud-like image. % % M = gen_noisy_image(n,alpha); % % generate an image M whose Fourier spectrum amplitude is % |M^(omega)| = 1/f^{omega} % % Copyright (c) 2004 Gabriel Peyre if nargin<1 n = 128; end if nargin<2 alpha = 1.5; end if mod(n(1),2)==0 x = -n/2:n/2-1; else x = -(n-1)/2:(n-1)/2; end [Y,X] = meshgrid(x,x); d = sqrt(X.^2 + Y.^2) + 0.1; f = rand(n)*2*pi; M = (d.^(-alpha)) .* exp(f*1i); % M = real(ifft2(fftshift(M))); M = ifftshift(M); M = real( ifft2(M) ); function y = gen_signal_2d(n,alpha) % gen_signal_2d - generate a 2D C^\alpha signal of length n x n. % gen_signal_2d(n,alpha) generate a 2D signal C^alpha. % % The signal is scale in [0,1]. % % Copyright (c) 2003 Gabriel Peyre % new new method [Y,X] = meshgrid(0:n-1, 0:n-1); A = X+Y+1; B = X-Y+n+1; a = gen_signal(2*n+1, alpha); b = gen_signal(2*n+1, alpha); y = a(A).*b(B); % M = a(1:n)*b(1:n)'; return; % new method h = (-n/2+1):(n/2); h(n/2)=1; [X,Y] = meshgrid(h,h); h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2); h = h .* exp( 2i*pi*rand(n,n) ); h = fftshift(h); y = real( ifft2(h) ); m1 = min(min(y)); m2 = max(max(y)); y = (y-m1)/(m2-m1); return; %% old code y = rand(n,n); y = y - mean(mean(y)); for i=1:alpha y = cumsum(cumsum(y)')'; y = y - mean(mean(y)); end m1 = min(min(y)); m2 = max(max(y)); y = (y-m1)/(m2-m1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = draw_rectangle(r,n) x = linspace(0,1,n); [Y,X] = meshgrid(x,x); M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
github
mathematical-tours/mathematical-tours.github.io-master
check_face_vertex.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/toolbox/check_face_vertex.m
669
utf_8
c940a837f5afef7c3a7f7aed3aff9f7a
function [vertex,face] = check_face_vertex(vertex,face, options) % check_face_vertex - check that vertices and faces have the correct size % % [vertex,face] = check_face_vertex(vertex,face); % % Copyright (c) 2007 Gabriel Peyre vertex = check_size(vertex,2,4); face = check_size(face,3,4); %%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = check_size(a,vmin,vmax) if isempty(a) return; end if size(a,1)>size(a,2) a = a'; end if size(a,1)<3 && size(a,2)==3 a = a'; end if size(a,1)<=3 && size(a,2)>=3 && sum(abs(a(:,3)))==0 % for flat triangles a = a'; end if size(a,1)<vmin || size(a,1)>vmax error('face or vertex is not of correct size'); end
github
mathematical-tours/mathematical-tours.github.io-master
imageplot.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/toolbox/imageplot.m
2,996
utf_8
bb6359ff3ad5e82264a744d41ba24582
function h1 = imageplot(M,str, a,b,c) % imageplot - diplay an image and a title % % Example of usages: % imageplot(M); % imageplot(M,title); % imageplot(M,title,1,2,1); % to make subplot(1,2,1); % % imageplot(M,options); % % If you want to display several images: % imageplot({M1 M2}, {'title1', 'title2'}); % % Copyright (c) 2007 Gabriel Peyre if nargin<2 str = []; end options.null = 0; if isstruct(str) options = str; str = ''; end nbdims = nb_dims(M); if iscell(M) q = length(M); if nargin<5 c = 1; end if nargin<4 a = ceil(q/4); end if nargin<3 b = ceil(q/a); end if (c-1+q)>(a*b) warning('a and c parameters not large enough'); a = ceil((c-1+q)/4); b = ceil((c-1+q)/a); end for i=1:q if iscell(str) str1 = str{i}; else str1 = str; end h{i} = imageplot(M{i},str1, a,b,c-1+i); end global axlist; if not(isempty(axlist)) linkaxes(axlist, 'xy'); end if nargout>0 if exist('h') h1 = h; else h1 = []; end end return; end if nargin==5 global axlist; global imageplot_size; if c==1 || isempty(imageplot_size) || imageplot_size~=size(M,1) clear axlist; global axlist; axlist = []; imageplot_size = size(M,1); end axlist(end+1) = subplot(a,b,c); end if nbdims==1 h = plot(M); axis tight; elseif size(M,3)<=3 % gray-scale or color image if size(M,3)==2 M = cat(3,M, zeros(size(M,1),size(M,2))); end if not(isreal(M)) if size(M,3)==1 % turn into color matrix M = cat(3, real(M), imag(M), zeros(size(M,1),size(M,2))); else warning('Complex data'); M = real(M); end end if size(M,3)==1 colormap gray(256); else colormap jet(256); end h = imagesc(rescale(M)); axis image; axis off; else if not(isfield(options, 'center') ) options.center = .5; % here a value in [0,1] end if not(isfield(options, 'sigma')) options.sigma = .08; % control the width of the non-transparent region end a = compute_alpha_map('gaussian', options); % you can plot(a) to see the alphamap % volumetric image h = vol3d('cdata',rescale(M),'texture','2D'); view(3); axis tight; % daspect([1 1 .4]) colormap bone(256); % alphamap('rampup'); % alphamap(.06 .* alphamap); vol3d(h); end if not(isempty(str)) title(str); end if nargout>0 if exist('h') h1 = h; else h1 = []; end end if nargin==5 && c==a*b linkaxes(axlist, 'xy'); end function d = nb_dims(x) % nb_dims - debugged version of ndims. % % d = nb_dims(x); % % Copyright (c) 2004 Gabriel Peyre if isempty(x) d = 0; return; end d = ndims(x); if d==2 && (size(x,1)==1 || size(x,2)==1) d = 1; end
github
mathematical-tours/mathematical-tours.github.io-master
plot_mesh.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/toolbox/plot_mesh.m
11,184
utf_8
0dcb199b54eb7b66240316a0359d9127
function h = plot_mesh(vertex,face,options) % plot_mesh - plot a 3D mesh. % % plot_mesh(vertex,face, options); % % 'options' is a structure that may contains: % - 'normal' : a (nvertx x 3) array specifying the normals at each vertex. % - 'edge_color' : a float specifying the color of the edges. % - 'face_color' : a float specifying the color of the faces. % - 'face_vertex_color' : a color per vertex or face. % - 'vertex' % - 'texture' : a 2-D image to be mapped on the surface % - 'texture_coords' : a (nvertx x 2) array specifying the texture % coordinates in [0,1] of the vertices in the texture. % - 'tmesh' : set it to 1 if this corresponds to a volumetric tet mesh. % % See also: mesh_previewer. % % Copyright (c) 2004 Gabriel Peyr? if nargin<2 error('Not enough arguments.'); end options.null = 0; name = getoptions(options, 'name', ''); normal = getoptions(options, 'normal', []); face_color = getoptions(options, 'face_color', [.7 .7 .7]); edge_color = getoptions(options, 'edge_color', [0 0 0]); normal_scaling = getoptions(options, 'normal_scaling', .8); sanity_check = getoptions(options, 'sanity_check', 1); view_param = getoptions(options, 'view_param', []); texture = getoptions(options, 'texture', []); texture_coords = getoptions(options, 'texture_coords', []); tmesh = getoptions(options, 'tmesh', 0); if size(vertex,1)==2 % 2D triangulation % vertex = cat(1,vertex, zeros(1,size(vertex,2))); plot_graph(triangulation2adjacency(face),vertex); return; end % can flip to accept data in correct ordering %[vertex,face] = check_face_vertex(vertex,face); if size(face,1)==4 && tmesh==1 %%%% tet mesh %%%% % normal to the plane <x,w><=a w = getoptions(options, 'cutting_plane', [0.2 0 1]'); w = w(:)/sqrt(sum(w.^2)); t = sum(vertex.*repmat(w,[1 size(vertex,2)])); a = getoptions(options, 'cutting_offs', median(t(:)) ); b = getoptions(options, 'cutting_interactive', 0); plot_points = getoptions(options, 'plot_points', 0); while true; % in/out I = ( t<=a ); % trim e = sum(I(face)); J = find(e==4); facetrim = face(:,J); % convert to triangular mesh hold on; if not(isempty(facetrim)) face1 = tet2tri(facetrim, vertex, 1); % options.method = 'slow'; face1 = perform_faces_reorientation(vertex,face1, options); h{1} = plot_mesh(vertex,face1, options); end view(3); % camlight; shading faceted; if plot_points K = find(e==0); K = face(:,K); K = unique(K(:)); h{2} = plot3(vertex(1,K), vertex(2,K), vertex(3,K), 'k.'); end hold off; if b==0 break; end [x,y,b] = ginput(1); if b==1 a = a+.03; elseif b==3 a = a-.03; else break; end end return; end vertex = vertex'; face = face'; if strcmp(name, 'bunny') || strcmp(name, 'pieta') % vertex = -vertex; end if strcmp(name, 'armadillo') vertex(:,3) = -vertex(:,3); end if sanity_check && ( (size(face,2)~=3 && size(face,2)~=4) || (size(vertex,2)~=3 && size(vertex,2)~=2)) error('face or vertex does not have correct format.'); end % if ~isfield(options, 'face_vertex_color') || isempty(options.face_vertex_color) % options.face_vertex_color = zeros(size(vertex,1),1); % end face_vertex_color = getoptions(options, 'face_vertex_color', []); if not(isempty(texture)) %%% textured mesh %%% if isempty(texture_coords) error('You need to provide texture_coord.'); end if size(texture_coords,2)~=2 texture_coords = texture_coords'; end opts.EdgeColor = 'none'; patcht(face,vertex,face,texture_coords,texture',opts); if size(texture,3)==1 colormap gray(256); else colormap jet(256); end set_view(name, view_param); axis off; axis equal; % camlight; % problem with pithon notebook shading faceted; return; end shading_type = 'interp'; if isempty(face_vertex_color) h = patch('vertices',vertex,'faces',face,'facecolor', face_color(:)','edgecolor',edge_color(:)'); else nverts = size(vertex,1); % vertex_color = rand(nverts,1); if size(face_vertex_color,1)==size(vertex,1) shading_type = 'interp'; else shading_type = 'flat'; end h = patch('vertices',vertex,'faces',face,'FaceVertexCData',face_vertex_color, 'FaceColor',shading_type); end colormap gray(256); lighting phong; % camlight infinite; camproj('perspective'); axis square; axis off; if ~isempty(normal) %%% plot the normals %%% n = size(vertex,1); subsample_normal = getoptions(options, 'subsample_normal', min(4000/n,1) ); sel = randperm(n); sel = sel(1:floor(end*subsample_normal)); hold on; quiver3(vertex(sel,1),vertex(sel,2),vertex(sel,3),normal(1,sel)',normal(2,sel)',normal(3,sel)',normal_scaling); hold off; end % camlight; set_view(name, view_param); shading(shading_type); % camlight; %% BUG WITH PYTHON %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function set_view(name, view_param) switch lower(name) case 'hammerheadtriang' view(150,-45); case 'horse' view(134,-61); case 'skull' view(21.5,-12); case 'mushroom' view(160,-75); case 'bunny' % view(0,-55); view(0,90); case 'david_head' view(-100,10); case 'screwdriver' view(-10,25); case 'pieta' view(15,31); case 'mannequin' view(25,15); view(27,6); case 'david-low' view(40,3); case 'david-head' view(-150,5); case 'brain' view(30,40); case 'pelvis' view(5,-15); case 'fandisk' view(36,-34); case 'earth' view(125,35); case 'camel' view(-123,-5); camroll(-90); case 'beetle' view(-117,-5); camroll(-90); zoom(.85); case 'cat' view(-60,15); case 'nefertiti' view(-20,65); end if not(isempty(view_param)) view(view_param(1),view_param(2)); end axis tight; axis equal; if strcmp(name, 'david50kf') || strcmp(name, 'hand') zoom(.85); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function patcht(FF,VV,TF,VT,I,Options) % This function PATCHT, will show a triangulated mesh like Matlab function % Patch but then with a texture. % % patcht(FF,VV,TF,VT,I,Options); % % inputs, % FF : Face list 3 x N with vertex indices % VV : Vertices 3 x M % TF : Texture list 3 x N with texture vertex indices % VT : Texture Coordinates s 2 x K, range must be [0..1] or real pixel postions % I : The texture-image RGB [O x P x 3] or Grayscale [O x P] % Options : Structure with options for the textured patch such as % EdgeColor, EdgeAlpha see help "Surface Properties :: Functions" % % Options.PSize : Special option, defines the image texturesize for each % individual polygon, a low number gives a more block % like texture, defaults to 64; % % note: % On a normal PC displaying 10,000 faces will take about 6 sec. % % Example, % % % Load Data; % load testdata; % % Show the textured patch % figure, patcht(FF,VV,TF,VT,I); % % Allow Camera Control (with left, right and center mouse button) % mouse3d % % Function is written by D.Kroon University of Twente (July 2010) % FaceColor is a texture Options.FaceColor='texturemap'; % Size of texture image used for every triangle if(isfield(Options,'PSize')) sizep=round(Options.PSize(1)); Options=rmfield(Options,'PSize'); else sizep=64; end % Check input sizes if(size(FF,2)~=size(TF,2)) error('patcht:inputs','Face list must be equal in size to texture-index list'); end if((ndims(I)~=2)&&(ndims(I)~=3)) error('patcht:inputs','No valid Input texture image'); end % Detect if grayscale or color image switch(size(I,3)) case 1 iscolor=false; case 3 iscolor=true; otherwise error('patcht:inputs','No valid Input texture image'); end if(max(VT(:))<2) % Remap texture coordinates to image coordinates VT2(:,1)=(size(I,1)-1)*(VT(:,1))+1; VT2(:,2)=(size(I,2)-1)*(VT(:,2))+1; else VT2=VT; end % Calculate the texture interpolation values [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep); % Split texture-image in r,g,b to allow fast 1D index Ir=I(:,:,1); if(iscolor), Ig=I(:,:,2); Ib=I(:,:,3); end % The Patch used for every triangle (rgb) Jr=zeros([(sizep+1) (sizep+1) 1],class(I)); if(iscolor) Jg=zeros([(sizep+1) (sizep+1) 1],class(I)); Jb=zeros([(sizep+1) (sizep+1) 1],class(I)); end hold on; % Loop through all triangles of the mesh for i=1:size(FF,1) % Get current triangle vertices and current texture-vertices V=VV(FF(i,:),:); Vt=VT2(TF(i,:),:); % Define the triangle as a surface x=[V(1,1) V(2,1); V(3,1) V(3,1)]; y=[V(1,2) V(2,2); V(3,2) V(3,2)]; z=[V(1,3) V(2,3); V(3,3) V(3,3)]; % Define the texture coordinates of the surface tx=[Vt(1,1) Vt(2,1) Vt(3,1) Vt(3,1)]; ty=[Vt(1,2) Vt(2,2) Vt(3,2) Vt(3,2)] ; xy=[tx(1) ty(1); tx(2) ty(2); tx(3) ty(3); tx(3) ty(3)]; % Calculate texture interpolation coordinates pos(:,1)=xy(1,1)*lambda1+xy(2,1)*lambda2+xy(3,1)*lambda3; pos(:,2)=xy(1,2)*lambda1+xy(2,2)*lambda2+xy(3,2)*lambda3; pos=round(pos); pos=max(pos,1); pos(:,1)=min(pos(:,1),size(I,1)); pos(:,2)=min(pos(:,2),size(I,2)); posind=(pos(:,1)-1)+(pos(:,2)-1)*size(I,1)+1; % Map texture to surface image Jr(jind)=Ir(posind); J(:,:,1)=Jr; if(iscolor) Jg(jind)=Ig(posind); Jb(jind)=Ib(posind); J(:,:,2)=Jg; J(:,:,3)=Jb; end % Show the surface surface(x,y,z,J,Options); end hold off; function [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep) % Define a triangle in the upperpart of an square, because only that % part is used by the surface function x1=sizep; y1=sizep; x2=sizep; y2=0; x3=0 ;y3=0; % Calculate the bary centric coordinates (instead of creating a 2D image % with the interpolation values, we map them directly to an 1D vector) detT = (x1-x3)*(y2-y3) - (x2-x3)*(y1-y3); [x,y]=ndgrid(0:sizep,0:sizep); x=x(:); y=y(:); lambda1=((y2-y3).*(x-x3)+(x3-x2).*(y-y3))/detT; lambda2=((y3-y1).*(x-x3)+(x1-x3).*(y-y3))/detT; lambda3=1-lambda1-lambda2; % Make from 2D (surface)image indices 1D image indices [jx jy]=ndgrid(sizep-(0:sizep)+1,sizep-(0:sizep)+1); jind=(jx(:)-1)+(jy(:)-1)*(sizep+1)+1;
github
mathematical-tours/mathematical-tours.github.io-master
distinguishable_colors.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/toolbox/distinguishable_colors.m
5,753
utf_8
57960cf5d13cead2f1e291d1288bccb2
function colors = distinguishable_colors(n_colors,bg,func) % DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct % % When plotting a set of lines, you may want to distinguish them by color. % By default, Matlab chooses a small set of colors and cycles among them, % and so if you have more than a few lines there will be confusion about % which line is which. To fix this problem, one would want to be able to % pick a much larger set of distinct colors, where the number of colors % equals or exceeds the number of lines you want to plot. Because our % ability to distinguish among colors has limits, one should choose these % colors to be "maximally perceptually distinguishable." % % This function generates a set of colors which are distinguishable % by reference to the "Lab" color space, which more closely matches % human color perception than RGB. Given an initial large list of possible % colors, it iteratively chooses the entry in the list that is farthest (in % Lab space) from all previously-chosen entries. While this "greedy" % algorithm does not yield a global maximum, it is simple and efficient. % Moreover, the sequence of colors is consistent no matter how many you % request, which facilitates the users' ability to learn the color order % and avoids major changes in the appearance of plots when adding or % removing lines. % % Syntax: % colors = distinguishable_colors(n_colors) % Specify the number of colors you want as a scalar, n_colors. This will % generate an n_colors-by-3 matrix, each row representing an RGB % color triple. If you don't precisely know how many you will need in % advance, there is no harm (other than execution time) in specifying % slightly more than you think you will need. % % colors = distinguishable_colors(n_colors,bg) % This syntax allows you to specify the background color, to make sure that % your colors are also distinguishable from the background. Default value % is white. bg may be specified as an RGB triple or as one of the standard % "ColorSpec" strings. You can even specify multiple colors: % bg = {'w','k'} % or % bg = [1 1 1; 0 0 0] % will only produce colors that are distinguishable from both white and % black. % % colors = distinguishable_colors(n_colors,bg,rgb2labfunc) % By default, distinguishable_colors uses the image processing toolbox's % color conversion functions makecform and applycform. Alternatively, you % can supply your own color conversion function. % % Example: % c = distinguishable_colors(25); % figure % image(reshape(c,[1 size(c)])) % % Example using the file exchange's 'colorspace': % func = @(x) colorspace('RGB->Lab',x); % c = distinguishable_colors(25,'w',func); % Copyright 2010-2011 by Timothy E. Holy % Parse the inputs if (nargin < 2) bg = [1 1 1]; % default white background else if iscell(bg) % User specified a list of colors as a cell aray bgc = bg; for i = 1:length(bgc) bgc{i} = parsecolor(bgc{i}); end bg = cat(1,bgc{:}); else % User specified a numeric array of colors (n-by-3) bg = parsecolor(bg); end end % Generate a sizable number of RGB triples. This represents our space of % possible choices. By starting in RGB space, we ensure that all of the % colors can be generated by the monitor. n_grid = 30; % number of grid divisions along each axis in RGB space x = linspace(0,1,n_grid); [R,G,B] = ndgrid(x,x,x); rgb = [R(:) G(:) B(:)]; if (n_colors > size(rgb,1)/3) error('You can''t readily distinguish that many colors'); end % Convert to Lab color space, which more closely represents human % perception if (nargin > 2) lab = func(rgb); bglab = func(bg); else C = makecform('srgb2lab'); lab = applycform(rgb,C); bglab = applycform(bg,C); end % If the user specified multiple background colors, compute distances % from the candidate colors to the background colors mindist2 = inf(size(rgb,1),1); for i = 1:size(bglab,1)-1 dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color end % Iteratively pick the color that maximizes the distance to the nearest % already-picked color colors = zeros(n_colors,3); lastlab = bglab(end,:); % initialize by making the "previous" color equal to background for i = 1:n_colors dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color [~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors colors(i,:) = rgb(index,:); % save for output lastlab = lab(index,:); % prepare for next iteration end end function c = parsecolor(s) if ischar(s) c = colorstr2rgb(s); elseif isnumeric(s) && size(s,2) == 3 c = s; else error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.'); end end function c = colorstr2rgb(c) % Convert a color string to an RGB value. % This is cribbed from Matlab's whitebg function. % Why don't they make this a stand-alone function? rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0]; cspec = 'rgbwcmyk'; k = find(cspec==c(1)); if isempty(k) error('MATLAB:InvalidColorString','Unknown color string.'); end if k~=3 || length(c)==1, c = rgbspec(k,:); elseif length(c)>2, if strcmpi(c(1:3),'bla') c = [0 0 0]; elseif strcmpi(c(1:3),'blu') c = [0 0 1]; else error('MATLAB:UnknownColorString', 'Unknown color string.'); end end end
github
mathematical-tours/mathematical-tours.github.io-master
perform_haar_transf.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/toolbox/perform_haar_transf.m
3,170
utf_8
14b7d7fd610eca05949ef196c55d7b83
function f = perform_haar_transf(f, Jmin, dir, options) % perform_haar_transf - peform fast Haar transform % % y = perform_haar_transf(x, Jmin, dir); % % Implement a Haar wavelets. % Works in any dimension. % % Copyright (c) 2008 Gabriel Peyre n = size(f,1); Jmax = log2(n)-1; if dir==1 %%% FORWARD %%% for j=Jmax:-1:Jmin sel = 1:2^(j+1); a = subselect(f,sel); for d=1:nb_dims(f) Coarse = ( subselectdim(a,1:2:size(a,d),d) + subselectdim(a,2:2:size(a,d),d) )/sqrt(2); Detail = ( subselectdim(a,1:2:size(a,d),d) - subselectdim(a,2:2:size(a,d),d) )/sqrt(2); a = cat(d, Coarse, Detail ); end f = subassign(f,sel,a); end else %%% BACKWARD %%% for j=Jmin:Jmax sel = 1:2^(j+1); a = subselect(f,sel); for d=1:nb_dims(f) Detail = subselectdim(a,2^j+1:2^(j+1),d); Coarse = subselectdim(a,1:2^j,d); a = subassigndim(a, 1:2:2^(j+1), ( Coarse + Detail )/sqrt(2),d ); a = subassigndim(a, 2:2:2^(j+1), ( Coarse - Detail )/sqrt(2),d ); end f = subassign(f,sel,a); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subselect(f,sel) switch nb_dims(f) case 1 f = f(sel); case 2 f = f(sel,sel); case 3 f = f(sel,sel,sel); case 4 f = f(sel,sel,sel,sel); case 5 f = f(sel,sel,sel,sel,sel); case 6 f = f(sel,sel,sel,sel,sel,sel); case 7 f = f(sel,sel,sel,sel,sel,sel,sel); case 8 f = f(sel,sel,sel,sel,sel,sel,sel,sel); otherwise error('Not implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subselectdim(f,sel,d) switch d case 1 f = f(sel,:,:,:,:,:,:,:); case 2 f = f(:,sel,:,:,:,:,:,:); case 3 f = f(:,:,sel,:,:,:,:,:); case 4 f = f(:,:,:,sel,:,:,:,:); case 5 f = f(:,:,:,:,sel,:,:,:); case 6 f = f(:,:,:,:,:,sel,:,:); case 7 f = f(:,:,:,:,:,:,sel,:); case 8 f = f(:,:,:,:,:,:,:,sel); otherwise error('Not implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subassign(f,sel,g) switch nb_dims(f) case 1 f(sel) = g; case 2 f(sel,sel) = g; case 3 f(sel,sel,sel) = g; case 4 f(sel,sel,sel,sel) = g; case 5 f(sel,sel,sel,sel,sel) = g; case 6 f(sel,sel,sel,sel,sel,sel) = g; case 7 f(sel,sel,sel,sel,sel,sel,sel) = g; case 8 f(sel,sel,sel,sel,sel,sel,sel,sel) = g; otherwise error('Not implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subassigndim(f,sel,g,d) switch d case 1 f(sel,:,:,:,:,:,:,:) = g; case 2 f(:,sel,:,:,:,:,:,:) = g; case 3 f(:,:,sel,:,:,:,:,:) = g; case 4 f(:,:,:,sel,:,:,:,:) = g; case 5 f(:,:,:,:,sel,:,:,:) = g; case 6 f(:,:,:,:,:,sel,:,:) = g; case 7 f(:,:,:,:,:,:,sel,:) = g; case 8 f(:,:,:,:,:,:,:,sel) = g; otherwise error('Not implemented'); end
github
mathematical-tours/mathematical-tours.github.io-master
load_image.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/wasserstein-flows/toolbox/load_image.m
19,798
utf_8
df61d87c209e587d6199fa36bbe979bf
function M = load_image(type, n, options) % load_image - load benchmark images. % % M = load_image(name, n, options); % % name can be: % Synthetic images: % 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line', % 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle', % 'parabola', 'sin', 'phantom', 'circ_oscil', % 'fnoise' (1/f^alpha noise). % Natural images: % 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own. % % Copyright (c) 2004 Gabriel Peyre if nargin<2 n = 512; end options.null = 0; if iscell(type) for i=1:length(type) M{i} = load_image(type{i},n,options); end return; end type = lower(type); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % parameters for geometric objects eta = getoptions(options, 'eta', .1); gamma = getoptions(options, 'gamma', 1/sqrt(2)); radius = getoptions(options, 'radius', 10); center = getoptions(options, 'center', [0 0]); center1 = getoptions(options, 'center1', [0 0]); w = getoptions(options, 'tube_width', 0.06); nb_points = getoptions(options, 'nb_points', 9); scaling = getoptions(options, 'scaling', 1); theta = getoptions(options, 'theta', 30 * 2*pi/360); eccentricity = getoptions(options, 'eccentricity', 1.3); sigma = getoptions(options, 'sigma', 0); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for the line, can be vertical / horizontal / diagonal / any if strcmp(type, 'line_vertical') eta = 0.5; % translation gamma = 0; % slope elseif strcmp(type, 'line_horizontal') eta = 0.5; % translation gamma = Inf; % slope elseif strcmp(type, 'line_diagonal') eta = 0; % translation gamma = 1; % slope end if strcmp(type(1:min(12,end)), 'square-tube-') k = str2double(type(13:end)); c1 = [.22 .5]; c2 = [1-c1(1) .5]; eta = 1.5; r1 = [c1 c1] + .21*[-1 -eta 1 eta]; r2 = [c2 c2] + .21*[-1 -eta 1 eta]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) ); if mod(k,2)==0 sel = n/2-k/2+1:n/2+k/2; else sel = n/2-(k-1)/2:n/2+(k-1)/2; end M( round(.25*n:.75*n), sel ) = 1; return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch lower(type) case 'constant' M = ones(n); case 'ramp' x = linspace(0,1,n); [Y,M] = meshgrid(x,x); case 'bump' s = getoptions(options, 'bump_size', .5); c = getoptions(options, 'center', [0 0]); if length(s)==1 s = [s s]; end x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); X = (X-c(1))/s(1); Y = (Y-c(2))/s(2); M = exp( -(X.^2+Y.^2)/2 ); case 'periodic' x = linspace(-pi,pi,n)/1.1; [Y,X] = meshgrid(x,x); f = getoptions(options, 'freq', 6); M = (1+cos(f*X)).*(1+cos(f*Y)); case {'letter-x' 'letter-v' 'letter-z' 'letter-y'} M = create_letter(type(8), radius, n); case 'l' r1 = [.1 .1 .3 .9]; r2 = [.1 .1 .9 .4]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) ); case 'ellipse' c1 = [0.15 0.5]; c2 = [0.85 0.5]; x = linspace(0,1,n); [Y,X] = meshgrid(x,x); d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2); M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) ); case 'ellipse-thin' options.eccentricity = 1.06; M = load_image('ellipse', n, options); case 'ellipse-fat' options.eccentricity = 1.3; M = load_image('ellipse', n, options); case 'square-tube' c1 = [.25 .5]; c2 = [.75 .5]; r1 = [c1 c1] + .18*[-1 -1 1 1]; r2 = [c2 c2] + .18*[-1 -1 1 1]; r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) ); case 'square-tube-1' options.tube_width = 0.03; M = load_image('square-tube', n, options); case 'square-tube-2' options.tube_width = 0.06; M = load_image('square-tube', n, options); case 'square-tube-3' options.im = 0.09; M = load_image('square-tube', n, options); case 'polygon' theta = sort( rand(nb_points,1)*2*pi ); radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93); points = [cos(theta) sin(theta)] .* repmat(radius, 1,2); points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:); M = draw_polygons(zeros(n),0.8,{points'}); [x,y] = ind2sub(size(M),find(M)); p = 100; m = length(x); lambda = linspace(0,1,p); X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]); Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]); I = round(X) + (round(Y)-1)*n; M = zeros(n); M(I) = 1; case 'polygon-8' options.nb_points = 8; M = load_image('polygon', n, options); case 'polygon-10' options.nb_points = 8; M = load_image('polygon', n, options); case 'polygon-12' options.nb_points = 8; M = load_image('polygon', n, options); case 'pacman' options.radius = 0.45; options.center = [.5 .5]; M = load_image('disk', n, options); x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); T =atan2(Y,X); M = M .* (1-(abs(T-pi/2)<theta/2)); case 'square-hole' options.radius = 0.45; M = load_image('disk', n, options); options.scaling = 0.5; M = M - load_image('polygon-10', n, options); case 'grid-circles' if isempty(n) n = 256; end f = getoptions(options, 'frequency', 30); eta = getoptions(options, 'width', .3); x = linspace(-n/2,n/2,n) - round(n*0.03); y = linspace(0,n,n); [Y,X] = meshgrid(y,x); R = sqrt(X.^2+Y.^2); theta = 0.05*pi/2; X1 = cos(theta)*X+sin(theta)*Y; Y1 = -sin(theta)*X+cos(theta)*Y; A1 = abs(cos(2*pi*R/f))<eta; A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta ); M = A1; M(X1>0) = A2(X1>0); case 'chessboard1' x = -1:2/(n-1):1; [Y,X] = meshgrid(x,x); M = (2*(Y>=0)-1).*(2*(X>=0)-1); case 'chessboard' width = getoptions(options, 'width', round(n/16) ); [Y,X] = meshgrid(0:n-1,0:n-1); M = mod( floor(X/width)+floor(Y/width), 2 ) == 0; case 'square' if ~isfield( options, 'radius' ) radius = 0.6; end x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); M = max( abs(X),abs(Y) )<radius; case 'squareregular' M = rescale(load_image('square',n,options)); if not(isfield(options, 'alpha')) options.alpha = 3; end S = load_image('fnoise',n,options); M = M + rescale(S,-0.3,0.3); case 'regular1' options.alpha = 1; M = load_image('fnoise',n,options); case 'regular2' options.alpha = 2; M = load_image('fnoise',n,options); case 'regular3' options.alpha = 3; M = load_image('fnoise',n,options); case 'sparsecurves' options.alpha = 3; M = load_image('fnoise',n,options); M = rescale(M); ncurves = 3; M = cos(2*pi*ncurves); case 'geometrical' J = getoptions(options, 'Jgeometrical', 4); sgeom = 100*n/256; options.bound = 'per'; A = ones(n); for j=0:J-1 B = A; for k=1:2^j I = find(B==k); U = perform_blurring(randn(n),sgeom,options); s = median(U(I)); I1 = find( (B==k) & (U>s) ); I2 = find( (B==k) & (U<=s) ); A(I1) = 2*k-1; A(I2) = 2*k; end end M = A; case 'lic-texture' disp('Computing random tensor field.'); options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256); T = compute_tensor_field_random(n,options); Flow = perform_tensor_decomp(T); % extract eigenfield. options.isoriented = 0; % no orientation in streamlines % initial texture lic_width = getoptions(options, 'lic_width', 0); M0 = perform_blurring(randn(n),lic_width); M0 = perform_histogram_equalization( M0, 'linear'); options.histogram = 'linear'; options.dt = 0.4; options.M0 = M0; options.verb = 1; options.flow_correction = 1; options.niter_lic = 3; w = 30; M = perform_lic(Flow, w, options); case 'square_texture' M = load_image('square',n); M = rescale(M); % make a texture patch x = linspace(0,1,n); [Y,X] = meshgrid(x,x); theta = pi/3; x = cos(theta)*X + sin(theta)*Y; c = [0.3,0.4]; r = 0.2; I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 ); eta = 3/n; lambda = 0.3; M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta ); case 'tv-image' M = rand(n); tau = compute_total_variation(M); options.niter = 400; [M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options); M = perform_histogram_equalization(M,'linear'); case 'oscillatory_texture' x = linspace(0,1,n); [Y,X] = meshgrid(x,x); theta = pi/3; x = cos(theta)*X + sin(theta)*Y; c = [0.3,0.4]; r = 0.2; I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 ); eta = 3/n; lambda = 0.3; M = sin( x * 2*pi / eta ); case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'} x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); if gamma~=Inf M = (X-eta) - gamma*Y < 0; else M = (Y-eta) < 0; end case 'line-windowed' x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); eta = .3; gamma = getoptions(options, 'gamma', pi/10); parabola = getoptions(options, 'parabola', 0); M = (X-eta) - gamma*Y - parabola*Y.^2 < 0; f = sin( pi*x ).^2; M = M .* ( f'*f ); case 'grating' x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); theta = getoptions(options, 'theta', .2); freq = getoptions(options, 'freq', .2); X = cos(theta)*X + sin(theta)*Y; M = sin(2*pi*X/freq); case 'disk' if ~isfield( options, 'radius' ) radius = 0.35; end if ~isfield( options, 'center' ) center = [0.5, 0.5]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; case 'twodisks' M = zeros(n); options.center = [.25 .25]; M = load_image('disk', n, options); options.center = [.75 .75]; M = M + load_image('disk', n, options); case 'diskregular' M = rescale(load_image('disk',n,options)); if not(isfield(options, 'alpha')) options.alpha = 3; end S = load_image('fnoise',n,options); M = M + rescale(S,-0.3,0.3); case 'quarterdisk' if ~isfield( options, 'radius' ) radius = 0.95; end if ~isfield( options, 'center' ) center = -[0.1, 0.1]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; case 'fading_contour' if ~isfield( options, 'radius' ) radius = 0.95; end if ~isfield( options, 'center' ) center = -[0.1, 0.1]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; theta = 2/pi*atan2(Y,X); h = 0.5; M = exp(-(1-theta).^2/h^2).*M; case '3contours' radius = 1.3; center = [-1, 1]; radius1 = 0.8; center1 = [0, 0]; x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2; M = f1 + 0.5*f2.*(1-f1); case 'line_circle' gamma = 1/sqrt(2); x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); M1 = double( X>gamma*Y+0.25 ); M2 = X.^2 + Y.^2 < 0.6^2; M = 20 + max(0.5*M1,M2) * 216; case 'fnoise' % generate an image M whose Fourier spectrum amplitude is % |M^(omega)| = 1/f^{omega} alpha = getoptions(options, 'alpha', 1); M = gen_noisy_image(n,alpha); case 'gaussiannoise' % generate an image of filtered noise with gaussian sigma = getoptions(options, 'sigma', 10); M = randn(n); m = 51; h = compute_gaussian_filter([m m],sigma/(4*n),[n n]); M = perform_convolution(M,h); return; case {'bwhorizontal','bwvertical','bwcircle'} [Y,X] = meshgrid(0:n-1,0:n-1); if strcmp(type, 'bwhorizontal') d = X; elseif strcmp(type, 'bwvertical') d = Y; elseif strcmp(type, 'bwcircle') d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 ); end if isfield(options, 'stripe_width') stripe_width = options.stripe_width; else stripe_width = 5; end if isfield(options, 'black_prop') black_prop = options.black_prop; else black_prop = 0.5; end M = double( mod( d/(2*stripe_width),1 )>=black_prop ); case 'parabola' % curvature c = getoptions(c, 'c', .1); % angle theta = getoptions(options, 'theta', pi/sqrt(2)); x = -0.5:1/(n-1):0.5; [Y,X] = meshgrid(x,x); Xs = X*cos(theta) + Y*sin(theta); Y =-X*sin(theta) + Y*cos(theta); X = Xs; M = Y>c*X.^2; case 'sin' [Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1); M = Y >= 0.6*cos(pi*X); M = double(M); case 'circ_oscil' x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); R = sqrt(X.^2+Y.^2); M = cos(R.^3*50); case 'phantom' M = phantom(n); case 'periodic_bumps' nbr_periods = getoptions(options, 'nbr_periods', 8); theta = getoptions(options, 'theta', 1/sqrt(2)); skew = getoptions(options, 'skew', 1/sqrt(2) ); A = [cos(theta), -sin(theta); sin(theta), cos(theta)]; B = [1 skew; 0 1]; T = B*A; x = (0:n-1)*2*pi*nbr_periods/(n-1); [Y,X] = meshgrid(x,x); pos = [X(:)'; Y(:)']; pos = T*pos; X = reshape(pos(1,:), n,n); Y = reshape(pos(2,:), n,n); M = cos(X).*sin(Y); case 'noise' sigma = getoptions(options, 'sigma', 1); M = randn(n) * sigma; case 'disk-corner' x = linspace(0,1,n); [Y,X] = meshgrid(x,x); rho = .3; eta = .1; M1 = rho*X+eta<Y; c = [0 .2]; r = .85; d = (X-c(1)).^2 + (Y-c(2)).^2; M2 = d<r^2; M = M1.*M2; otherwise ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'}; for i=1:length(ext) name = [type '.' ext{i}]; if( exist(name) ) M = imread( name ); M = double(M); if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2 M = image_resize(M,n,n); end if strcmp(type, 'peppers-bw') M(:,1) = M(:,2); M(1,:) = M(2,:); end if sigma>0 M = perform_blurring(M,sigma); end return; end end error( ['Image ' type ' does not exists.'] ); end M = double(M); if sigma>0 M = perform_blurring(M,sigma); end M = rescale(M); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = create_letter(a, r, n) c = 0.2; p1 = [c;c]; p2 = [c; 1-c]; p3 = [1-c; 1-c]; p4 = [1-c; c]; p4 = [1-c; c]; pc = [0.5;0.5]; pu = [0.5; c]; switch a case 'x' point_list = { [p1 p3] [p2 p4] }; case 'z' point_list = { [p2 p3 p1 p4] }; case 'v' point_list = { [p2 pu p3] }; case 'y' point_list = { [p2 pc pu] [pc p3] }; end % fit image for i=1:length(point_list) a = point_list{i}(2:-1:1,:); a(1,:) = 1-a(1,:); point_list{i} = round( a*(n-1)+1 ); end M = draw_polygons(zeros(n),r,point_list); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sk = draw_polygons(mask,r,point_list) sk = mask*0; for i=1:length(point_list) pl = point_list{i}; for k=2:length(pl) sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sk = draw_line(sk,x1,y1,x2,y2,r) n = size(sk,1); [Y,X] = meshgrid(1:n,1:n); q = 100; t = linspace(0,1,q); x = x1*t+x2*(1-t); y = y1*t+y2*(1-t); if r==0 x = round( x ); y = round( y ); sk( x+(y-1)*n ) = 1; else for k=1:q I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 ); sk(I) = 1; end end function M = gen_noisy_image(n,alpha) % gen_noisy_image - generate a noisy cloud-like image. % % M = gen_noisy_image(n,alpha); % % generate an image M whose Fourier spectrum amplitude is % |M^(omega)| = 1/f^{omega} % % Copyright (c) 2004 Gabriel Peyre if nargin<1 n = 128; end if nargin<2 alpha = 1.5; end if mod(n(1),2)==0 x = -n/2:n/2-1; else x = -(n-1)/2:(n-1)/2; end [Y,X] = meshgrid(x,x); d = sqrt(X.^2 + Y.^2) + 0.1; f = rand(n)*2*pi; M = (d.^(-alpha)) .* exp(f*1i); % M = real(ifft2(fftshift(M))); M = ifftshift(M); M = real( ifft2(M) ); function y = gen_signal_2d(n,alpha) % gen_signal_2d - generate a 2D C^\alpha signal of length n x n. % gen_signal_2d(n,alpha) generate a 2D signal C^alpha. % % The signal is scale in [0,1]. % % Copyright (c) 2003 Gabriel Peyre % new new method [Y,X] = meshgrid(0:n-1, 0:n-1); A = X+Y+1; B = X-Y+n+1; a = gen_signal(2*n+1, alpha); b = gen_signal(2*n+1, alpha); y = a(A).*b(B); % M = a(1:n)*b(1:n)'; return; % new method h = (-n/2+1):(n/2); h(n/2)=1; [X,Y] = meshgrid(h,h); h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2); h = h .* exp( 2i*pi*rand(n,n) ); h = fftshift(h); y = real( ifft2(h) ); m1 = min(min(y)); m2 = max(max(y)); y = (y-m1)/(m2-m1); return; %% old code y = rand(n,n); y = y - mean(mean(y)); for i=1:alpha y = cumsum(cumsum(y)')'; y = y - mean(mean(y)); end m1 = min(min(y)); m2 = max(max(y)); y = (y-m1)/(m2-m1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = draw_rectangle(r,n) x = linspace(0,1,n); [Y,X] = meshgrid(x,x); M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
github
mathematical-tours/mathematical-tours.github.io-master
inpolyhedron.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/level-sets/inpolyhedron.m
22,756
utf_8
16738ef64a83b8c37c57511248fb93cf
function IN = inpolyhedron(varargin) %INPOLYHEDRON Tests if points are inside a 3D triangulated (faces/vertices) surface % BY CONVENTION, SURFACE NORMALS SHOULD POINT OUT from the object. (see % FLIPNORMALS option below for details) % % IN = INPOLYHEDRON(FV,QPTS) tests if the query points (QPTS) are inside the % patch/surface/polyhedron defined by FV (a structure with fields 'vertices' and % 'faces'). QPTS is an N-by-3 set of XYZ coordinates. IN is an N-by-1 logical % vector which will be TRUE for each query point inside the surface. % % INPOLYHEDRON(FACES,VERTICES,...) takes faces/vertices separately, rather than in % an FV structure. % % IN = INPOLYHEDRON(..., X, Y, Z) voxelises a mask of 3D gridded query points % rather than an N-by-3 array of points. X, Y, and Z coordinates of the grid % supplied in XVEC, YVEC, and ZVEC respectively. IN will return as a 3D logical % volume with SIZE(IN) = [LENGTH(YVEC) LENGTH(XVEC) LENGTH(ZVEC)], equivalent to % syntax used by MESHGRID. INPOLYHEDRON handles this input faster and with a lower % memory footprint than using MESHGRID to make full X, Y, Z query points matrices. % % INPOLYHEDRON(...,'PropertyName',VALUE,'PropertyName',VALUE,...) tests query % points using the following optional property values: % % TOL - Tolerance on the tests for "inside" the surface. You can think of % tol as the distance a point may possibly lie above/below the surface, and still % be perceived as on the surface. Due to numerical rounding nothing can ever be % done exactly here. Defaults to ZERO. Note that in the current implementation TOL % only affects points lying above/below a surface triangle (in the Z-direction). % Points coincident with a vertex in the XY plane are considered INside the surface. % More formal rules can be implemented with input/feedback from users. % % GRIDSIZE - Internally, INPOLYHEDRON uses a divide-and-conquer algorithm to % split all faces into a chessboard-like grid of GRIDSIZE-by-GRIDSIZE regions. % Performance will be a tradeoff between a small GRIDSIZE (few iterations, more % data per iteration) and a large GRIDSIZE (many iterations of small data % calculations). The sweet-spot has been experimentally determined (on a win64 % system) to be correlated with the number of faces/vertices. You can overwrite % this automatically computed choice by specifying a GRIDSIZE parameter. % % FACENORMALS - By default, the normals to the FACE triangles are computed as the % cross-product of the first two triangle edges. You may optionally specify face % normals here if they have been pre-computed. % % FLIPNORMALS - (Defaults FALSE). To match a wider convention, triangle % face normals are presumed to point OUT from the object's surface. If % your surface normals are defined pointing IN, then you should set the % FLIPNORMALS option to TRUE to use the reverse of this convention. % % Example: % tmpvol = zeros(20,20,20); % Empty voxel volume % tmpvol(5:15,8:12,8:12) = 1; % Turn some voxels on % tmpvol(8:12,5:15,8:12) = 1; % tmpvol(8:12,8:12,5:15) = 1; % fv = isosurface(tmpvol, 0.99); % Create the patch object % fv.faces = fliplr(fv.faces); % Ensure normals point OUT % % Test SCATTERED query points % pts = rand(200,3)*12 + 4; % Make some query points % in = inpolyhedron(fv, pts); % Test which are inside the patch % figure, hold on, view(3) % Display the result % patch(fv,'FaceColor','g','FaceAlpha',0.2) % plot3(pts(in,1),pts(in,2),pts(in,3),'bo','MarkerFaceColor','b') % plot3(pts(~in,1),pts(~in,2),pts(~in,3),'ro'), axis image % % Test STRUCTURED GRID of query points % gridLocs = 3:2.1:19; % [x,y,z] = meshgrid(gridLocs,gridLocs,gridLocs); % in = inpolyhedron(fv, gridLocs,gridLocs,gridLocs); % figure, hold on, view(3) % Display the result % patch(fv,'FaceColor','g','FaceAlpha',0.2) % plot3(x(in), y(in), z(in),'bo','MarkerFaceColor','b') % plot3(x(~in),y(~in),z(~in),'ro'), axis image % % See also: UNIFYMESHNORMALS (on the <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=43013">file exchange</a>) % TODO-list % - Optmise overall memory footprint. (need examples with MEM errors) % - Implement an "ignore these" step to speed up calculations for: % * Query points outside the convex hull of the faces/vertices input % - Get a better/best gridSize calculation. User feedback? % - Detect cases where X-rays or Y-rays would be better than Z-rays? % % Author: Sven Holcombe % - 10 Jun 2012: Version 1.0 % - 28 Aug 2012: Version 1.1 - Speedup using accumarray % - 07 Nov 2012: Version 2.0 - BEHAVIOUR CHANGE % Query points coincident with a VERTEX are now IN an XY triangle % - 18 Aug 2013: Version 2.1 - Gridded query point handling with low memory footprint. % - 10 Sep 2013: Version 3.0 - BEHAVIOUR CHANGE % NEW CONVENTION ADOPTED to expect face normals pointing IN % Vertically oriented faces are now ignored. Speeds up % computation and fixes bug where presence of vertical faces % produced NaN distance from a query pt to facet, making all % query points under facet erroneously NOT IN polyhedron. % - 25 Sep 2013: Version 3.1 - Dropped nested unique call which was made % mostly redundant via v2.1 gridded point handling. Also % refreshed grid size selection via optimisation. % - 25 Feb 2014: Version 3.2 - Fixed indeterminate behaviour for query % points *exactly* in line with an "overhanging" vertex. %% % FACETS is an unpacked arrangement of faces/vertices. It is [3-by-3-by-N], % with 3 1-by-3 XYZ coordinates of N faces. [facets, qPts, options] = parseInputs(varargin{:}); numFaces = size(facets,3); if ~options.griddedInput % SCATTERED QUERY POINTS numQPoints = size(qPts,1); else % STRUCTURED QUERY POINTS numQPoints = prod(cellfun(@numel,qPts(1:2))); end % Precompute 3d normals to all facets (triangles). Do this via the cross % product of the first edge vector with the second. Normalise the result. allEdgeVecs = facets([2 3 1],:,:) - facets(:,:,:); if isempty(options.facenormals) allFacetNormals = bsxfun(@times, allEdgeVecs(1,[2 3 1],:), allEdgeVecs(2,[3 1 2],:)) - ... bsxfun(@times, allEdgeVecs(2,[2 3 1],:), allEdgeVecs(1,[3 1 2],:)); allFacetNormals = bsxfun(@rdivide, allFacetNormals, sqrt(sum(allFacetNormals.^2,2))); else allFacetNormals = permute(options.facenormals,[3 2 1]); end if options.flipnormals allFacetNormals = -allFacetNormals; end % We use a Z-ray intersection so we don't even need to consider facets that % are purely vertically oriented (have zero Z-component). isFacetUseful = allFacetNormals(:,3,:) ~= 0; %% Setup grid referencing system % Function speed can be thought of as a function of grid size. A small number of grid % squares means iterating over fewer regions (good) but with more faces/qPts to % consider each time (bad). For any given mesh/queryPt configuration, there will be a % sweet spot that minimises computation time. There will also be a constraint from % memory available - low grid sizes means considering many queryPt/faces at once, % which will require a larger memory footprint. Here we will let the user specify % gridsize directly, or we will estimate the optimum size based on prior testing. if ~isempty(options.gridsize) gridSize = options.gridsize; else % Coefficients (with 95% confidence bounds): p00 = -47; p10 = 12.83; p01 = 20.89; p20 = 0.7578; p11 = -6.511; p02 = -2.586; p30 = -0.1802; p21 = 0.2085; p12 = 0.7521; p03 = 0.09984; p40 = 0.005815; p31 = 0.007775; p22 = -0.02129; p13 = -0.02309; GSfit = @(x,y)p00 + p10*x + p01*y + p20*x^2 + p11*x*y + p02*y^2 + p30*x^3 + p21*x^2*y + p12*x*y^2 + p03*y^3 + p40*x^4 + p31*x^3*y + p22*x^2*y^2 + p13*x*y^3; gridSize = min(150 ,max(1, ceil(GSfit(log(numQPoints),log(numFaces))))); if isnan(gridSize), gridSize = 1; end end %% Find candidate qPts -> triangles pairs % We have a large set of query points. For each query point, find potential % triangles that would be pierced by vertical rays through the qPt. First, % a simple filter by XY bounding box % Calculate the bounding box of each facet minFacetCoords = permute(min(facets(:,1:2,:),[],1),[3 2 1]); maxFacetCoords = permute(max(facets(:,1:2,:),[],1),[3 2 1]); % Set rescale values to rescale all vertices between 0(-eps) and 1(+eps) scalingOffsetsXY = min(minFacetCoords,[],1) - eps; scalingRangeXY = max(maxFacetCoords,[],1) - scalingOffsetsXY + 2*eps; % Based on scaled min/max facet coords, get the [lowX lowY highX highY] "grid" index % of all faces lowToHighGridIdxs = floor(bsxfun(@rdivide, ... bsxfun(@minus, ... % Use min/max coordinates of each facet (+/- the tolerance) [minFacetCoords-options.tol maxFacetCoords+options.tol],... [scalingOffsetsXY scalingOffsetsXY]),... [scalingRangeXY scalingRangeXY]) * gridSize) + 1; % Build a grid of cells. In each cell, place the facet indices that encroach into % that grid region. Similarly, each query point will be assigned to a grid region. % Note that query points will be assigned only one grid region, facets can cover many % regions. Furthermore, we will add a tolerance to facet region assignment to ensure % a query point will be compared to facets even if it falls only on the edge of a % facet's bounding box, rather than inside it. cells = cell(gridSize); [unqLHgrids,~,facetInds] = unique(lowToHighGridIdxs,'rows'); tmpInds = accumarray(facetInds(isFacetUseful),find(isFacetUseful),[size(unqLHgrids,1),1],@(x){x}); for xi = 1:gridSize xyMinMask = xi >= unqLHgrids(:,1) & xi <= unqLHgrids(:,3); for yi = 1:gridSize cells{yi,xi} = cat(1,tmpInds{xyMinMask & yi >= unqLHgrids(:,2) & yi <= unqLHgrids(:,4)}); % The above line (with accumarray) is faster with equiv results than: % % cells{yi,xi} = find(ismember(facetInds, xyInds)); end end % With large number of facets, memory may be important: clear lowToHightGridIdxs LHgrids facetInds tmpInds xyMinMask minFacetCoords maxFacetCoords %% Compute edge unit vectors and dot products % Precompute the 2d unit vectors making up each facet's edges in the XY plane. allEdgeUVecs = bsxfun(@rdivide, allEdgeVecs(:,1:2,:), sqrt(sum(allEdgeVecs(:,1:2,:).^2,2))); % Precompute the inner product between edgeA.edgeC, edgeB.edgeA, edgeC.edgeB allEdgeEdgeDotPs = sum(allEdgeUVecs .* -allEdgeUVecs([3 1 2],:,:),2) - 1e-9; %% Gather XY query locations % Since query points are most likely given as a (3D) grid of query locations, we only % need to consider the unique XY locations when asking which facets a vertical ray % through an XY location would pierce. if ~options.griddedInput % SCATTERED QUERY POINTS qPtsXY = @(varargin)qPts(:,1:2); qPtsXYZViaUnqIndice = @(ind)qPts(ind,:); outPxIndsViaUnqIndiceMask = @(ind,mask)ind(mask); outputSize = [size(qPts,1),1]; reshapeINfcn = @(INMASK)INMASK; minFacetDistanceFcn = @minFacetToQptDistance; else % STRUCTURED QUERY POINTS [xmat,ymat] = meshgrid(qPts{1:2}); qPtsXY = [xmat(:) ymat(:)]; % A standard set of Z locations will be shifted around by different % unqQpts XY coordinates. zCoords = qPts{3}(:) * [0 0 1]; qPtsXYZViaUnqIndice = @(ind)bsxfun(@plus, zCoords, [qPtsXY(ind,:) 0]); % From a given indice and mask, we will turn on/off the IN points under % that indice based on the mask. The easiest calculation is to setup % the IN matrix as a numZpts-by-numUnqPts mask. At the end, we must % unpack/reshape this 2D mask to a full 3D logical mask numZpts = size(zCoords,1); baseZinds = 1:numZpts; outPxIndsViaUnqIndiceMask = @(ind,mask)(ind-1)*numZpts + baseZinds(mask); outputSize = [numZpts, size(qPtsXY,1)]; reshapeINfcn = @(INMASK)reshape(INMASK', cellfun(@numel, qPts([2 1 3]))); minFacetDistanceFcn = @minFacetToQptsDistance; end % Start with every query point NOT inside the polyhedron. We will % iteratively find those query points that ARE inside. IN = false(outputSize); % Determine with grids each query point falls into. qPtGridXY = floor(bsxfun(@rdivide, bsxfun(@minus, qPtsXY(:,:), scalingOffsetsXY),... scalingRangeXY) * gridSize) + 1; [unqQgridXY,~,qPtGridInds] = unique(qPtGridXY,'rows'); % We need only consider grid indices within those already set up ptsToConsidMask = ~any(qPtGridXY<1 | qPtGridXY>gridSize, 2); if ~any(ptsToConsidMask) IN = reshapeINfcn(IN); return; end % Build the reference list cellQptContents = accumarray(qPtGridInds(ptsToConsidMask),find(ptsToConsidMask), [],@(x){x}); gridsToCheck = unqQgridXY(~any(unqQgridXY<1 | unqQgridXY>gridSize, 2),:); cellQptContents(cellfun('isempty',cellQptContents)) = []; gridIndsToCheck = sub2ind(size(cells), gridsToCheck(:,2), gridsToCheck(:,1)); % For ease of multiplication, reshape qPt XY coords to [1-by-2-by-1-by-N] qPtsXY = permute(qPtsXY(:,:),[4 2 3 1]); % There will be some grid indices with query points but without facets. emptyMask = cellfun('isempty',cells(gridIndsToCheck))'; for i = find(~emptyMask) % We get all the facet coordinates (ie, triangle vertices) of triangles % that intrude into this grid location. The size is [3-by-2-by-N], for % the [3vertices-by-XY-by-Ntriangles] allFacetInds = cells{gridIndsToCheck(i)}; candVerts = facets(:,1:2,allFacetInds); % We need the XY coordinates of query points falling into this grid. allqPtInds = cellQptContents{i}; queryPtsXY = qPtsXY(:,:,:,allqPtInds); % Get unit vectors pointing from each triangle vertex to my query point(s) vert2ptVecs = bsxfun(@minus, queryPtsXY, candVerts); vert2ptUVecs = bsxfun(@rdivide, vert2ptVecs, sqrt(sum(vert2ptVecs.^2,2))); % Get unit vectors pointing around each triangle (along edge A, edge B, edge C) edgeUVecs = allEdgeUVecs(:,:,allFacetInds); % Get the inner product between edgeA.edgeC, edgeB.edgeA, edgeC.edgeB edgeEdgeDotPs = allEdgeEdgeDotPs(:,:,allFacetInds); % Get inner products between each edge unit vec and the UVs from qPt to vertex edgeQPntDotPs = sum(bsxfun(@times, edgeUVecs, vert2ptUVecs),2); qPntEdgeDotPs = sum(bsxfun(@times,vert2ptUVecs, -edgeUVecs([3 1 2],:,:)),2); % If both inner products 2 edges to the query point are greater than the inner % product between the two edges themselves, the query point is between the V % shape made by the two edges. If this is true for all 3 edge pair, the query % point is inside the triangle. resultIN = all(bsxfun(@gt, edgeQPntDotPs, edgeEdgeDotPs) & bsxfun(@gt, qPntEdgeDotPs, edgeEdgeDotPs),1); resultONVERTEX = any(any(isnan(vert2ptUVecs),2),1); result = resultIN | resultONVERTEX; qPtHitsTriangles = any(result,3); % If NONE of the query points pierce ANY triangles, we can skip forward if ~any(qPtHitsTriangles), continue, end % In the next step, we'll need to know the indices of ALL the query points at % each of the distinct XY coordinates. Let's get their indices into "qPts" as a % cell of length M, where M is the number of unique XY points we had found. for ptNo = find(qPtHitsTriangles(:))' % Which facets does it pierce? piercedFacetInds = allFacetInds(result(1,1,:,ptNo)); % Get the 1-by-3-by-N set of triangle normals that this qPt pierces piercedTriNorms = allFacetNormals(:,:,piercedFacetInds); % Pick the first vertex as the "origin" of a plane through the facet. Get the % vectors from each query point to each facet origin facetToQptVectors = bsxfun(@minus, ... qPtsXYZViaUnqIndice(allqPtInds(ptNo)),... facets(1,:,piercedFacetInds)); % Calculate how far you need to go up/down to pierce the facet's plane. % Positive direction means "inside" the facet, negative direction means % outside. facetToQptDists = bsxfun(@rdivide, ... sum(bsxfun(@times,piercedTriNorms,facetToQptVectors),2), ... abs(piercedTriNorms(:,3,:))); % Since it's possible for two triangles sharing the same vertex to % be the same distance away, I want to sum up all the distances of % triangles that are closest to the query point. Simple case: The % closest triangle is unique Edge case: The closest triangle is one % of many the same distance and direction away. Tricky case: The % closes triangle has another triangle the equivalent distance % but facing the opposite direction IN( outPxIndsViaUnqIndiceMask(allqPtInds(ptNo), ... minFacetDistanceFcn(facetToQptDists)<options.tol... )) = true; end end % If they provided X,Y,Z vectors of query points, our output is currently a % 2D mask and must be reshaped to [LEN(Y) LEN(X) LEN(Z)]. IN = reshapeINfcn(IN); %% Called subfunctions % vertices = [ % 0.9046 0.1355 -0.0900 % 0.8999 0.3836 -0.0914 % 1.0572 0.2964 -0.0907 % 0.8735 0.1423 -0.1166 % 0.8685 0.4027 -0.1180 % 1.0337 0.3112 -0.1173 % 0.9358 0.1287 -0.0634 % 0.9313 0.3644 -0.0647 % 1.0808 0.2816 -0.0641 % ]; % faces = [ % 1 2 5 % 1 5 4 % 2 3 6 % 2 6 5 % 3 1 4 % 3 4 6 % 6 4 5 % 2 1 8 % 8 1 7 % 3 2 9 % 9 2 8 % 1 3 7 % 7 3 9 % 7 9 8 % ]; % point = [vertices(3,1),vertices(3,2),1.5]; function closestTriDistance = minFacetToQptDistance(facetToQptDists) % FacetToQptDists is a 1pt-by-1-by-Nfacets array of how far you need to go % up/down to pierce each facet's plane. If the Qpt was directly over an % "overhang" vertex, then two facets with opposite orientation will be % equally distant from the Qpt, with one distance positive and one % negative. In such cases, it is impossible for the Qpt to actually be % "inside" this pair of facets, so their distance is updated to Inf. [~,minInd] = min(abs(facetToQptDists),[],3); while any( abs(facetToQptDists + facetToQptDists(minInd)) < 1e-15 ) % Since the above comparison is made every time, but the below variable % setting is done only in the rare case that a query point coincides % with an overhang vertex, it is more efficient to re-compute the % equality when it's true, rather than store the result every time. facetToQptDists( abs(facetToQptDists) - abs(facetToQptDists(minInd)) < 1e-15) = inf; if ~any(isfinite(facetToQptDists)) break; end [~,minInd] = min(abs(facetToQptDists),[],3); end closestTriDistance = facetToQptDists(minInd); function closestTriDistance = minFacetToQptsDistance(facetToQptDists) % As above, but facetToQptDists is an Mpts-by-1-by-Nfacets array. % The multi-point version is a little more tricky. While below is quite a % bit slower when the while loop is entered, it is very rarely entered and % very fast to make just the initial comparison. [minVals,minInds] = min(abs(facetToQptDists),[],3); while any(... any(abs(bsxfun(@plus,minVals,facetToQptDists))<1e-15,3) & ... any(abs(bsxfun(@minus,minVals,facetToQptDists))<1e-15,3)) maskP = abs(bsxfun(@plus,minVals,facetToQptDists))<1e-15; maskN = abs(bsxfun(@minus,minVals,facetToQptDists))<1e-15; mustAlterMask = any(maskP,3) & any(maskN,3); for i = find(mustAlterMask)' facetToQptDists(i,:,maskP(i,:,:) | maskN(i,:,:)) = inf; end [newMv,newMinInds] = min(abs(facetToQptDists(mustAlterMask,:,:)),[],3); minInds(mustAlterMask) = newMinInds(:); minVals(mustAlterMask) = newMv(:); end % Below is a tiny speedup on basically a sub2ind call. closestTriDistance = facetToQptDists((minInds-1)*size(facetToQptDists,1) + (1:size(facetToQptDists,1))'); %% Input handling subfunctions function [facets, qPts, options] = parseInputs(varargin) % Gather FACES and VERTICES if isstruct(varargin{1}) % inpolyhedron(FVstruct, ...) if ~all(isfield(varargin{1},{'vertices','faces'})) error( 'Structure FV must have "faces" and "vertices" fields' ); end faces = varargin{1}.faces; vertices = varargin{1}.vertices; varargin(1) = []; % Chomp off the faces/vertices else % inpolyhedron(FACES, VERTICES, ...) faces = varargin{1}; vertices = varargin{2}; varargin(1:2) = []; % Chomp off the faces/vertices end % Unpack the faces/vertices into [3-by-3-by-N] facets. It's better to % perform this now and have FACETS only in memory in the main program, % rather than FACETS, FACES and VERTICES facets = vertices'; facets = permute(reshape(facets(:,faces'), 3, 3, []),[2 1 3]); % Extract query points if length(varargin)<2 || ischar(varargin{2}) % inpolyhedron(F, V, [x(:) y(:) z(:)], ...) qPts = varargin{1}; varargin(1) = []; % Chomp off the query points else % inpolyhedron(F, V, xVec, yVec, zVec, ...) qPts = varargin(1:3); % Chomp off the query points and tell the world that it's gridded input. varargin(1:3) = []; varargin = [varargin {'griddedInput',true}]; end % Extract configurable options options = parseOptions(varargin{:}); % Check if face normals are unified if options.testNormals options.normalsAreUnified = checkNormalUnification(faces); end function options = parseOptions(varargin) IP = inputParser; IP.addParamValue('gridsize',[], @(x)isscalar(x) && isnumeric(x)) IP.addParamValue('tol', 0, @(x)isscalar(x) && isnumeric(x)) IP.addParamValue('tol_ang', 1e-5, @(x)isscalar(x) && isnumeric(x)) IP.addParamValue('facenormals',[]); IP.addParamValue('flipnormals',false); IP.addParamValue('griddedInput',false); IP.addParamValue('testNormals',false); IP.parse(varargin{:}); options = IP.Results;
github
mathematical-tours/mathematical-tours.github.io-master
knnsearch.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/quantized-rendering/knnsearch.m
4,137
utf_8
40fbf8d0695309e13ce021d477c579c3
function [idx,D]=knnsearch(varargin) % KNNSEARCH Linear k-nearest neighbor (KNN) search % IDX = knnsearch(Q,R,K) searches the reference data set R (n x d array % representing n points in a d-dimensional space) to find the k-nearest % neighbors of each query point represented by eahc row of Q (m x d array). % The results are stored in the (m x K) index array, IDX. % % IDX = knnsearch(Q,R) takes the default value K=1. % % IDX = knnsearch(Q) or IDX = knnsearch(Q,[],K) does the search for R = Q. % % Rationality % Linear KNN search is the simplest appraoch of KNN. The search is based on % calculation of all distances. Therefore, it is normally believed only % suitable for small data sets. However, other advanced approaches, such as % kd-tree and delaunary become inefficient when d is large comparing to the % number of data points. On the other hand, the linear search in MATLAB is % relatively insensitive to d due to the vectorization. In this code, the % efficiency of linear search is further improved by using the JIT % aceeleration of MATLAB. Numerical example shows that its performance is % comparable with kd-tree algorithm in mex. % % See also, kdtree, nnsearch, delaunary, dsearch % By Yi Cao at Cranfield University on 25 March 2008 % Example 1: small data sets %{ R=randn(100,2); Q=randn(3,2); idx=knnsearch(Q,R); plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'ro',R(idx,1),R(idx,2),'gx'); %} % Example 2: ten nearest points to [0 0] %{ R=rand(100,2); Q=[0 0]; K=10; idx=knnsearch(Q,R,10); r=max(sqrt(sum(R(idx,:).^2,2))); theta=0:0.01:pi/2; x=r*cos(theta); y=r*sin(theta); plot(R(:,1),R(:,2),'b.',Q(:,1),Q(:,2),'co',R(idx,1),R(idx,2),'gx',x,y,'r-','linewidth',2); %} % Example 3: cputime comparion with delaunay+dsearch I, a few to look up %{ R=randn(10000,4); Q=randn(500,4); t0=cputime; idx=knnsearch(Q,R); t1=cputime; T=delaunayn(R); idx1=dsearchn(R,T,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Example 4: cputime comparion with delaunay+dsearch II, lots to look up %{ Q=randn(10000,4); R=randn(500,4); t0=cputime; idx=knnsearch(Q,R); t1=cputime; T=delaunayn(R); idx1=dsearchn(R,T,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Example 5: cputime comparion with kd-tree by Steven Michael (mex file) % <a href="http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=7030&objectType=file">kd-tree by Steven Michael</a> %{ Q=randn(10000,10); R=randn(500,10); t0=cputime; idx=knnsearch(Q,R); t1=cputime; tree=kdtree(R); idx1=kdtree_closestpoint(tree,Q); t2=cputime; fprintf('Are both indices the same? %d\n',isequal(idx,idx1)); fprintf('CPU time for knnsearch = %g\n',t1-t0); fprintf('CPU time for delaunay = %g\n',t2-t1); %} % Check inputs [Q,R,K,fident] = parseinputs(varargin{:}); % Check outputs error(nargoutchk(0,2,nargout)); % C2 = sum(C.*C,2)'; [N,M] = size(Q); L=size(R,1); idx = zeros(N,K); D = idx; if K==1 % Loop for each query point for k=1:N d=zeros(L,1); for t=1:M d=d+(R(:,t)-Q(k,t)).^2; end if fident d(k)=inf; end [D(k),idx(k)]=min(d); end else for k=1:N d=zeros(L,1); for t=1:M d=d+(R(:,t)-Q(k,t)).^2; end if fident d(k)=inf; end [s,t]=sort(d); idx(k,:)=t(1:K); D(k,:)=s(1:K); end end if nargout>1 D=sqrt(D); end function [Q,R,K,fident] = parseinputs(varargin) % Check input and output error(nargchk(1,3,nargin)); Q=varargin{1}; if nargin<2 R=Q; fident = true; else fident = false; R=varargin{2}; end if isempty(R) fident = true; R=Q; end if ~fident fident = isequal(Q,R); end if nargin<3 K=1; else K=varargin{3}; end
github
mathematical-tours/mathematical-tours.github.io-master
lorenz.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/lorentz/lorenz.m
1,363
utf_8
9da3a6e8b70b72c64b10f262bb879ade
function [x,y,z,T] = lorenz(rho, sigma, beta, initV, T, eps) % LORENZ Function generates the lorenz attractor of the prescribed values % of parameters rho, sigma, beta % % [X,Y,Z] = LORENZ(RHO,SIGMA,BETA,INITV,T,EPS) % X, Y, Z - output vectors of the strange attactor trajectories % RHO - Rayleigh number % SIGMA - Prandtl number % BETA - parameter % INITV - initial point % T - time interval % EPS - ode solver precision % % Example. % [X Y Z] = lorenz(28, 10, 8/3); % plot3(X,Y,Z); if nargin<3 error('MATLAB:lorenz:NotEnoughInputs','Not enough input arguments.'); end if nargin<4 eps = 0.000001; T = [0 25]; initV = [0 1 1.05]; end options = odeset('RelTol',eps,'AbsTol',[eps eps eps/10]); [T,X] = ode45(@(T,X) F(T, X, sigma, rho, beta), T, initV, options); plot3(X(:,1),X(:,2),X(:,3)); axis equal; grid; title('Lorenz attractor'); xlabel('X'); ylabel('Y'); zlabel('Z'); x = X(:,1); y = X(:,2); z = X(:,3); return end function dx = F(T, X, sigma, rho, beta) % Evaluates the right hand side of the Lorenz system % x' = sigma*(y-x) % y' = x*(rho - z) - y % z' = x*y - beta*z % typical values: rho = 28; sigma = 10; beta = 8/3; dx = zeros(3,1); dx(1) = sigma*(X(2) - X(1)); dx(2) = X(1)*(rho - X(3)) - X(2); dx(3) = X(1)*X(2) - beta*X(3); return end
github
mathematical-tours/mathematical-tours.github.io-master
demoUI.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/bilateral-filtering/bilateral-toolbox/demoUI.m
11,896
utf_8
66455746f1799fcc484ea751ad4eda26
function varargout = demoUI(varargin) % DEMOUI MATLAB code for demoUI.fig % DEMOUI, by itself, creates a new DEMOUI or raises the existing % singleton*. % % H = DEMOUI returns the handle to a new DEMOUI or the handle to % the existing singleton*. % % DEMOUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in DEMOUI.M with the given input arguments. % % DEMOUI('Property','Value',...) creates a new DEMOUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before demoUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to demoUI_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help demoUI % Last Modified by GUIDE v2.5 05-Jul-2016 17:35:13 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @demoUI_OpeningFcn, ... 'gui_OutputFcn', @demoUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before demoUI is made visible. function demoUI_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to demoUI (see VARARGIN) % Choose default command line output for demoUI handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes demoUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = demoUI_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function imagepath_Callback(hObject, eventdata, handles) % hObject handle to imagepath (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of imagepath as text % str2double(get(hObject,'String')) returns contents of imagepath as a double % --- Executes during object creation, after setting all properties. function imagepath_CreateFcn(hObject, eventdata, handles) % hObject handle to imagepath (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in browseButton. function browseButton_Callback(hObject, eventdata, handles) % hObject handle to browseButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) CallbackFcns browse; % --- Executes on button press in loadButton. function loadButton_Callback(hObject, eventdata, handles) % hObject handle to loadButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) CallbackFcns load; % --- Executes on button press in filterButton. function filterButton_Callback(hObject, eventdata, handles) % hObject handle to filterButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) CallbackFcns filter; % --- Executes on button press in pushbutton4. function pushbutton4_Callback(hObject, eventdata, handles) % hObject handle to pushbutton4 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on slider movement. function sliderS_Callback(hObject, eventdata, handles) % hObject handle to sliderS (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider CallbackFcns sigmas_slider; % --- Executes during object creation, after setting all properties. function sliderS_CreateFcn(hObject, eventdata, handles) % hObject handle to sliderS (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function sliderR_Callback(hObject, eventdata, handles) % hObject handle to sliderR (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider CallbackFcns sigmar_slider; % --- Executes during object creation, after setting all properties. function sliderR_CreateFcn(hObject, eventdata, handles) % hObject handle to sliderR (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on selection change in listbox1. function listbox1_Callback(hObject, eventdata, handles) % hObject handle to listbox1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array % contents{get(hObject,'Value')} returns selected item from listbox1 % --- Executes during object creation, after setting all properties. function listbox1_CreateFcn(hObject, eventdata, handles) % hObject handle to listbox1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: listbox controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function editS_Callback(hObject, eventdata, handles) % hObject handle to editS (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of editS as text % str2double(get(hObject,'String')) returns contents of editS as a double CallbackFcns sigmas_edit; % --- Executes during object creation, after setting all properties. function editS_CreateFcn(hObject, eventdata, handles) % hObject handle to editS (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function editR_Callback(hObject, eventdata, handles) % hObject handle to editR (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of editR as text % str2double(get(hObject,'String')) returns contents of editR as a double CallbackFcns sigmar_edit; % --- Executes during object creation, after setting all properties. function editR_CreateFcn(hObject, eventdata, handles) % hObject handle to editR (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in saveButton. function saveButton_Callback(hObject, eventdata, handles) % hObject handle to saveButton (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) CallbackFcns save; % --- Executes on slider movement. function sliderEps_Callback(hObject, eventdata, handles) % hObject handle to sliderEps (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider CallbackFcns eps_slider; % --- Executes during object creation, after setting all properties. function sliderEps_CreateFcn(hObject, eventdata, handles) % hObject handle to sliderEps (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function editEps_Callback(hObject, eventdata, handles) % hObject handle to editEps (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of editEps as text % str2double(get(hObject,'String')) returns contents of editEps as a double CallbackFcns eps_edit; % --- Executes during object creation, after setting all properties. function editEps_CreateFcn(hObject, eventdata, handles) % hObject handle to editEps (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end
github
mathematical-tours/mathematical-tours.github.io-master
CallbackFcns.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/bilateral-filtering/bilateral-toolbox/CallbackFcns.m
3,734
utf_8
bb2767d88ebb2ec18d4b4dd2088ee8d5
function CallbackFcns (action) switch (action) case 'sigmas_slider' sigmas = get(gcbo, 'Value'); sigmas = round(sigmas) + 1; updatesigmas(sigmas); case 'sigmar_slider' sigmar = get(gcbo, 'Value'); sigmar = (round(sigmar*10))/10 + 5; updatesigmar(sigmar); case 'sigmas_edit' sigmas = eval(get(gcbo, 'String')); updatesigmas(sigmas); case 'sigmar_edit' sigmar = eval(get(gcbo, 'String')); updatesigmar(sigmar); case 'eps_slider' eps = get(gcbo, 'Value'); eps = (round(eps) + 1)*0.001; update_eps(eps); case 'eps_edit' eps = eval(get(gcbo, 'String')); update_eps(eps); case 'browse' [filename, user_canceled] = imgetfile; if (~user_canceled) imagepath_Handle = findobj(gcbf,'Tag','imagepath'); set(imagepath_Handle,'String',filename); end case 'load' imagepath_Handle = findobj(gcbf,'Tag','imagepath'); mread = imread(get(imagepath_Handle,'String')); axes(findobj(gcbf,'Tag','input')); cla; hold on; imshow(mread); axis('image', 'off'); minput = double(mread); set(gcbf,'UserData',minput); case 'filter' minput = get(gcbf,'UserData'); editS_Handle = findobj(gcbf,'Tag','editS'); sigmas = eval(get(editS_Handle,'String')); editR_Handle = findobj(gcbf,'Tag','editR'); sigmar = eval(get(editR_Handle,'String')); editEps_Handle = findobj(gcbf,'Tag','editEps'); eps = eval(get(editEps_Handle,'String')); % [moutput,params] = shiftableBF(minput,sigmas,sigmar); [moutput,N] = GPA(minput, sigmar, sigmas, eps, 'Gauss'); axes(findobj(gcbf,'Tag','output')); cla; hold on; imshow(uint8(moutput)); axis('image', 'off'); rkernel_Handle = findobj(gcbf,'Tag','rkernelplot'); axes(rkernel_Handle); cla; set(rkernel_Handle,'Color','White'); set(rkernel_Handle,'AmbientLightColor','White'); set(rkernel_Handle,'XColor','Black'); set(rkernel_Handle,'YColor','Black'); box on; sigmar2 = sigmar^2; L = -127; U =128; t = L : 0.01 : U; tauList = [-50,0,50]; %center for i=1:length(tauList) tau=tauList(i); g = exp(-0.5*(t-tau).^2/sigmar2); % Gauss-polynomial nu = 0.5*(1/sigmar2); gapprox = zeros(size(t)); for k = 0 : N gapprox = gapprox + (1/factorial(k)) * (1/sigmar2)^k ... *(tau*t).^k; end gapprox = gapprox.*exp(-nu*t.^2).* exp(-nu*tau^2); %g3 = (1 - nu*((t-tau).^2/N)).^N; % display hold on, plot(t,g, 'r','LineWidth',3); hold on, plot(t,gapprox,'k','LineWidth',2); axis('tight'), grid('on'), hleg=legend('Target Gaussian', 'Gaussian-Polynomial'); set(hleg,'fontsize',8); end case 'save' imsave(findobj(gcbf,'Tag','output')); end function updatesigmas (sigmas) sliderS_Handle = findobj(gcbf,'Tag','sliderS'); set(sliderS_Handle,'Value',sigmas-1); editS_Handle = findobj(gcbf,'Tag','editS'); set(editS_Handle,'String',sigmas); function updatesigmar (sigmar) sliderR_Handle = findobj(gcbf,'Tag','sliderR'); set(sliderR_Handle,'Value',sigmar-5); editR_Handle = findobj(gcbf,'Tag','editR'); set(editR_Handle,'String',sigmar); function update_eps (eps) sliderEps_Handle = findobj(gcbf,'Tag','sliderEps'); set(sliderEps_Handle,'Value',eps*1000-1); editEps_Handle = findobj(gcbf,'Tag','editEps'); set(editEps_Handle,'String',eps);
github
mathematical-tours/mathematical-tours.github.io-master
perform_ar_synthesis.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/motion-clouds/perform_ar_synthesis.m
2,236
utf_8
b3c984def5c7d189f8756566ad7b839a
function F = perform_ar_synthesis(H, options) % perform_ar_synthesis - perform motion cloud synthesis % % F = perform_ar_synthesis(H, options); % % Copyright (c) 2013 Gabriel Peyre n = size(H,1); synth2d = @(h)real(ifft2(fft2(randn(n,n)).*h)); extend = @(f)[f f(:,1); f(1,:) f(1)]; % movement scale = getoptions(options, 'scale', 1); rotation = getoptions(options, 'rotation', 0); translation = getoptions(options, 'translation', [0 0]); center = getoptions(options, 'center', [n/2 n/2]); sigmat = getoptions(options, 'sigmat', 40); p = getoptions(options, 'nbframes', 64); pdisp = getoptions(options, 'nbframes_disp', 2*p); % a = fit_ar2(sigmat); x = 1:n; [Y,X] = meshgrid(x,x); % moved grid X1 = center(1) + scale*( (X-center(1))*cos(rotation) - (Y-center(2))*sin(rotation) ) + translation(1); Y1 = center(2) + scale*( (X-center(1))*sin(rotation) + (Y-center(2))*cos(rotation) ) + translation(2); X1 = mod(X1-1,n)+1; Y1 = mod(Y1-1,n)+1; % apply movement move = @(f)interp2(1:n+1,1:n+1,extend(f),Y1,X1); % Stop button clf; % Axes ax = axes(... 'Units','Normalized',... 'OuterPosition', [0 0.2 1 0.8]); f0 = zeros(n); f1 = zeros(n); Contrast = 50; s = 0; F = []; EarlyStop = 0; i = 0; randn('state', 123); global run; run = 1; while run i = i+1; % rotate the noise W = synth2d(H); X1 = center(1) + ( (X-center(1))*cos(rotation*(i-1)) - (Y-center(2))*sin(rotation*(i-1)) ); Y1 = center(2) + ( (X-center(1))*sin(rotation*(i-1)) + (Y-center(2))*cos(rotation*(i-1)) ); X1 = mod(X1-1,n)+1; Y1 = mod(Y1-1,n)+1; W = interp2(1:n+1,1:n+1,extend(W),Y1,X1); % f = W + a(1)*f0 + a(2)*f1; f1 = f0; f0 = f; s = max(s,std(f(:))); % scale f0 = move(f0); f1 = move(f1); % display image( 127 + Contrast*f/s ); colormap gray(256); axis image; axis off; if i==p uicontrol(... 'Style','pushbutton', 'String', 'Stop',... 'Units','Normalized', 'Position', [0.4 0.1 0.2 0.1],... 'Callback', @MyCallback); end if i>=p set(ax, 'ButtonDownFcn', 'get(ax, ''CurrentPoint'')'); end drawnow; % save if i<p F(:,:,end+1) = f; end end end function MyCallback(a,b,c) global run; run = 0; end
github
mathematical-tours/mathematical-tours.github.io-master
movie_display.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/motion-clouds/toolbox/movie_display.m
766
utf_8
72007c865584bc804987e7f24d64ce47
function movie_display(f) % movie_display - display a 3-D array as a movie. % % movie_display(f); % % Copyright (c) 2012 Gabriel Peyre s = 2.5; normalize = @(x)rescale( clamp( (x-mean(x(:)))/std(x(:)), -s,s) ); A = normalize(f)*256; clf; % stpo button uicontrol(... 'Style','pushbutton', 'String', 'Stop',... 'Units','Normalized', 'Position', [0.4 0.1 0.2 0.1],... 'Callback', @MyCallback); % Axes ax = axes(... 'Units','Normalized',... 'OuterPosition', [0 0.2 1 0.8]); k = 0; global run; run = 1; while run k = mod(k,size(A,3))+1; image(A(:,:,k)); axis image; axis off; colormap gray(256); drawnow; set(ax, 'ButtonDownFcn', 'get(ax, ''CurrentPoint'')'); end end function MyCallback(a,b,c) global run; run = 0; end
github
mathematical-tours/mathematical-tours.github.io-master
demo_stepwise.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/dbscan/demo_stepwise.m
4,650
utf_8
9f483f576b60f8e3bc193aae38407161
function demo_stepwise() %twospirals % data=twospirals(200,360,50,1.5,15); data = twospirals(600, 360*1.3, 30, 50); global it; global rep; it = 0; addpath('../toolbox/'); rep = MkResRep(); % generate mixtures k0 = 20; z0 = (.1+.1i) + .8*( rand(k0,1) + 1i*rand(k0,1) ); % mean/scale/anisotrop/orientation p = 30; % #sample per cluster gauss = @(m,s,a,t)m + s*exp(2i*t)*( randn(p,1) + 1i*randn(p,1)*a ); X = []; a = .5; s = .04; for k=1:k0 X = [X; gauss(rand+rand*1i,s,a,rand)]; end n = length(X); clf; plot(X, '.'); axis equal; axis([0,1,0,1]); box on; set(gca, 'XTick', [], 'YTick', []); data = (2*[real(X), imag(X)]-1)*6; % data=corners(500); s=zeros(size(data,1),1); clf; for i=1:size(data,1) hold on s(i)=scatter(data(i,1),data(i,2),'filled','markerfacecolor',[0.8,0.8,0.8]); end axis equal; % axis([0 1 0 1]); axis([-1 1 -1 1]*8); axis off; drawnow %% %using euclidean distance distmat=zeros(size(data,1),size(data,1)); for i=1:size(data,1) for j=i:size(data,1) distmat(i,j)=sqrt((data(i,1:2)-data(j,1:2))*(data(i,1:2)-data(j,1:2))'); end end for i=1:size(data,1) for j=i:size(data,1) distmat(j,i)=distmat(i,j); end end % k_dist=zeros(size(data,1),1); % figure % for k=3:5 % for i=1:size(data,1) % tmp=sort(distmat(:,i),'ascend'); % k_dist(i)=tmp(k); % end % hold on % plot(1:size(data,1),k_dist); % end %% Eps=0.5; MinPts=4; DBSCAN_STEPWISE(s,distmat,Eps,MinPts); end function Clust = DBSCAN_STEPWISE(s,DistMat,Eps,MinPts) %A step-wise illustration of DBSCAN on 2D data %A simple DBSCAN implementation of the original paper: %"A Density-Based Algorithm for Discovering Clusters in Large Spatial %Databases with Noise" -- Martin Ester et.al. %Since no spatial access method is implemented, the run time complexity %will be N^2 rather than N*logN %************************************************************************** %Input: DistMat, Eps, MinPts %DistMat: A N*N distance matrix, the (i,j) element contains the distance %from point-i to point-j. %Eps: A scalar value for Epsilon-neighborhood threshold. %MinPts: A scalar value for minimum points in Eps-neighborhood that holds %the core-point condition. %************************************************************************** %Output: Clust %Clust: A N*1 vector describes the cluster membership for each point. 0 is %reserved for NOISE. %************************************************************************** %Written by Tianxiao Jiang, [email protected] %Nov-4-2015 %************************************************************************** %Initialize Cluster membership as -1, which means UNCLASSIFIED Clust=zeros(size(DistMat,1),1)-1; ClusterId=1; ClusterColor=rand(1,3); %randomly choose the visiting order VisitSequence=randperm(length(Clust)); for i=1:length(Clust) % For each point, check if it is not visited yet (unclassified) pt=VisitSequence(i); if Clust(pt)==-1 %Iteratively expand the cluster through density-reachability [Clust,isnoise]=ExpandCluster(s,DistMat,pt,ClusterId,Eps,MinPts,Clust,ClusterColor); if ~isnoise ClusterId=ClusterId+1; ClusterColor=rand(1,3); end end end end function [Clust,isnoise]=ExpandCluster(s,DistMat,pt,ClusterId,Eps,MinPts,Clust,ClusterColor) global it; %region query seeds=find(DistMat(:,pt)<=Eps); if length(seeds)<MinPts Clust(pt)=0; % 0 reserved for noise set(s(pt),'Marker','*'); pause(0.01) isnoise=true; return else Clust(seeds)=ClusterId; set(s(seeds),'MarkerFaceColor',ClusterColor); pause(0.01) %delete the core point seeds=setxor(seeds,pt); while ~isempty(seeds) currentP=seeds(1); %region query result=find(DistMat(:,currentP)<=Eps); if length(result)>=MinPts for i=1:length(result) resultP=result(i); if Clust(resultP)==-1||Clust(resultP)==0 % unclassified or noise set(s(resultP),'MarkerFaceColor',ClusterColor); global it; global rep; it = it+1; if mod(it,4)==0 saveas(gcf, [rep 'anim-' znum2str(it,3) '.png']); end if Clust(resultP)==-1 %unclassified seeds=[seeds(:);resultP]; end Clust(resultP)=ClusterId; end end end seeds=setxor(seeds,currentP); end isnoise=false; return end end
github
mathematical-tours/mathematical-tours.github.io-master
DBSCAN.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/dbscan/DBSCAN.m
2,588
utf_8
232558b4366cd2668ad0f85e2185b21f
function Clust = DBSCAN(DistMat,Eps,MinPts) %A simple DBSCAN implementation of the original paper: %"A Density-Based Algorithm for Discovering Clusters in Large Spatial %Databases with Noise" -- Martin Ester et.al. %Since no spatial access method is implemented, the run time complexity %will be N^2 rather than N*logN %************************************************************************** %Input: DistMat, Eps, MinPts %DistMat: A N*N distance matrix, the (i,j) element contains the distance %from point-i to point-j. %Eps: A scalar value for Epsilon-neighborhood threshold. %MinPts: A scalar value for minimum points in Eps-neighborhood that holds %the core-point condition. %************************************************************************** %Output: Clust %Clust: A N*1 vector describes the cluster membership for each point. 0 is %reserved for NOISE. %************************************************************************** %Written by Tianxiao Jiang, [email protected] %Nov-4-2015 %************************************************************************** %Initialize Cluster membership as -1, which means UNCLASSIFIED Clust=zeros(size(DistMat,1),1)-1; ClusterId=1; %randomly choose the visiting order VisitSequence=randperm(length(Clust)); for i=1:length(Clust) % For each point, check if it is not visited yet (unclassified) pt=VisitSequence(i); if Clust(pt)==-1 %Iteratively expand the cluster through density-reachability [Clust,isnoise]=ExpandCluster(DistMat,pt,ClusterId,Eps,MinPts,Clust); if ~isnoise ClusterId=ClusterId+1; end end end end function [Clust,isnoise]=ExpandCluster(DistMat,pt,ClusterId,Eps,MinPts,Clust) %region query seeds=find(DistMat(:,pt)<=Eps); if length(seeds)<MinPts Clust(pt)=0; % 0 reserved for noise isnoise=true; return else Clust(seeds)=ClusterId; %delete the core point seeds=setxor(seeds,pt); while ~isempty(seeds) currentP=seeds(1); %region query result=find(DistMat(:,currentP)<=Eps); if length(result)>=MinPts for i=1:length(result) resultP=result(i); if Clust(resultP)==-1||Clust(resultP)==0 % unclassified or noise if Clust(resultP)==-1 %unclassified seeds=[seeds(:);resultP]; end Clust(resultP)=ClusterId; end end end seeds=setxor(seeds,currentP); end isnoise=false; return end end
github
mathematical-tours/mathematical-tours.github.io-master
load_image.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/total-variation/toolbox/load_image.m
20,275
utf_8
c700b54853577ab37402e27e4ca061b8
function M = load_image(type, n, options) % load_image - load benchmark images. % % M = load_image(name, n, options); % % name can be: % Synthetic images: % 'chessboard1', 'chessboard', 'square', 'squareregular', 'disk', 'diskregular', 'quaterdisk', '3contours', 'line', % 'line_vertical', 'line_horizontal', 'line_diagonal', 'line_circle', % 'parabola', 'sin', 'phantom', 'circ_oscil', % 'fnoise' (1/f^alpha noise). % Natural images: % 'boat', 'lena', 'goldhill', 'mandrill', 'maurice', 'polygons_blurred', or your own. % % Copyright (c) 2004 Gabriel Peyre if nargin<2 n = 512; end options.null = 0; if iscell(type) for i=1:length(type) M{i} = load_image(type{i},n,options); end return; end type = lower(type); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % parameters for geometric objects eta = getoptions(options, 'eta', .1); gamma = getoptions(options, 'gamma', 1/sqrt(2)); radius = getoptions(options, 'radius', 10); center = getoptions(options, 'center', [0 0]); center1 = getoptions(options, 'center1', [0 0]); w = getoptions(options, 'tube_width', 0.06); nb_points = getoptions(options, 'nb_points', 9); scaling = getoptions(options, 'scaling', 1); theta = getoptions(options, 'theta', 30 * 2*pi/360); eccentricity = getoptions(options, 'eccentricity', 1.3); sigma = getoptions(options, 'sigma', 0); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for the line, can be vertical / horizontal / diagonal / any if strcmp(type, 'line_vertical') eta = 0.5; % translation gamma = 0; % slope elseif strcmp(type, 'line_horizontal') eta = 0.5; % translation gamma = Inf; % slope elseif strcmp(type, 'line_diagonal') eta = 0; % translation gamma = 1; % slope end if strcmp(type(1:min(12,end)), 'square-tube-') k = str2double(type(13:end)); c1 = [.22 .5]; c2 = [1-c1(1) .5]; eta = 1.5; r1 = [c1 c1] + .21*[-1 -eta 1 eta]; r2 = [c2 c2] + .21*[-1 -eta 1 eta]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) ); if mod(k,2)==0 sel = n/2-k/2+1:n/2+k/2; else sel = n/2-(k-1)/2:n/2+(k-1)/2; end M( round(.25*n:.75*n), sel ) = 1; return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch lower(type) case 'constant' M = ones(n); case 'ramp' x = linspace(0,1,n); [Y,M] = meshgrid(x,x); case 'bump' s = getoptions(options, 'bump_size', .5); c = getoptions(options, 'center', [0 0]); if length(s)==1 s = [s s]; end x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); X = (X-c(1))/s(1); Y = (Y-c(2))/s(2); M = exp( -(X.^2+Y.^2)/2 ); case 'periodic' x = linspace(-pi,pi,n)/1.1; [Y,X] = meshgrid(x,x); f = getoptions(options, 'freq', 6); M = (1+cos(f*X)).*(1+cos(f*Y)); case {'letter-x' 'letter-v' 'letter-z' 'letter-y'} M = create_letter(type(8), radius, n); case 'l' r1 = [.1 .1 .3 .9]; r2 = [.1 .1 .9 .4]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) ); case 'ellipse' c1 = [0.15 0.5]; c2 = [0.85 0.5]; x = linspace(0,1,n); [Y,X] = meshgrid(x,x); d = sqrt((X-c1(1)).^2 + (Y-c1(2)).^2) + sqrt((X-c2(1)).^2 + (Y-c2(2)).^2); M = double( d<=eccentricity*sqrt( sum((c1-c2).^2) ) ); case 'ellipse-thin' options.eccentricity = 1.06; M = load_image('ellipse', n, options); case 'ellipse-fat' options.eccentricity = 1.3; M = load_image('ellipse', n, options); case 'square-tube' c1 = [.25 .5]; c2 = [.75 .5]; r1 = [c1 c1] + .18*[-1 -1 1 1]; r2 = [c2 c2] + .18*[-1 -1 1 1]; r3 = [c1(1)-w c1(2)-w c2(1)+w c2(2)+w]; M = double( draw_rectangle(r1,n) | draw_rectangle(r2,n) | draw_rectangle(r3,n) ); case 'square-tube-1' options.tube_width = 0.03; M = load_image('square-tube', n, options); case 'square-tube-2' options.tube_width = 0.06; M = load_image('square-tube', n, options); case 'square-tube-3' options.im = 0.09; M = load_image('square-tube', n, options); case 'polygon' theta = sort( rand(nb_points,1)*2*pi ); radius = scaling*rescale(rand(nb_points,1), 0.1, 0.93); points = [cos(theta) sin(theta)] .* repmat(radius, 1,2); points = (points+1)/2*(n-1)+1; points(end+1,:) = points(1,:); M = draw_polygons(zeros(n),0.8,{points'}); [x,y] = ind2sub(size(M),find(M)); p = 100; m = length(x); lambda = linspace(0,1,p); X = n/2 + repmat(x-n/2, [1 p]) .* repmat(lambda, [m 1]); Y = n/2 + repmat(y-n/2, [1 p]) .* repmat(lambda, [m 1]); I = round(X) + (round(Y)-1)*n; M = zeros(n); M(I) = 1; case 'polygon-8' options.nb_points = 8; M = load_image('polygon', n, options); case 'polygon-10' options.nb_points = 8; M = load_image('polygon', n, options); case 'polygon-12' options.nb_points = 8; M = load_image('polygon', n, options); case 'pacman' options.radius = 0.45; options.center = [.5 .5]; M = load_image('disk', n, options); x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); T =atan2(Y,X); M = M .* (1-(abs(T-pi/2)<theta/2)); case 'square-hole' options.radius = 0.45; M = load_image('disk', n, options); options.scaling = 0.5; M = M - load_image('polygon-10', n, options); case 'grid-circles' if isempty(n) n = 256; end f = getoptions(options, 'frequency', 30); eta = getoptions(options, 'width', .3); x = linspace(-n/2,n/2,n) - round(n*0.03); y = linspace(0,n,n); [Y,X] = meshgrid(y,x); R = sqrt(X.^2+Y.^2); theta = 0.05*pi/2; X1 = cos(theta)*X+sin(theta)*Y; Y1 = -sin(theta)*X+cos(theta)*Y; A1 = abs(cos(2*pi*R/f))<eta; A2 = max( abs(cos(2*pi*X1/f))<eta, abs(cos(2*pi*Y1/f))<eta ); M = A1; M(X1>0) = A2(X1>0); case 'chessboard1' x = -1:2/(n-1):1; [Y,X] = meshgrid(x,x); M = (2*(Y>=0)-1).*(2*(X>=0)-1); case 'chessboard' width = getoptions(options, 'width', round(n/16) ); [Y,X] = meshgrid(0:n-1,0:n-1); M = mod( floor(X/width)+floor(Y/width), 2 ) == 0; case 'square' if ~isfield( options, 'radius' ) radius = 0.6; end x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); M = max( abs(X),abs(Y) )<radius; case 'squareregular' M = rescale(load_image('square',n,options)); if not(isfield(options, 'alpha')) options.alpha = 3; end S = load_image('fnoise',n,options); M = M + rescale(S,-0.3,0.3); case 'regular1' options.alpha = 1; M = load_image('fnoise',n,options); case 'regular2' options.alpha = 2; M = load_image('fnoise',n,options); case 'regular3' options.alpha = 3; M = load_image('fnoise',n,options); case 'sparsecurves' options.alpha = 3; M = load_image('fnoise',n,options); M = rescale(M); ncurves = 3; M = cos(2*pi*ncurves); case 'geometrical' J = getoptions(options, 'Jgeometrical', 4); sgeom = 100*n/256; options.bound = 'per'; A = ones(n); for j=0:J-1 B = A; for k=1:2^j I = find(B==k); U = perform_blurring(randn(n),sgeom,options); s = median(U(I)); I1 = find( (B==k) & (U>s) ); I2 = find( (B==k) & (U<=s) ); A(I1) = 2*k-1; A(I2) = 2*k; end end M = A; case 'lic-texture' disp('Computing random tensor field.'); options.sigma_tensor = getoptions(options, 'lic_regularity', 50*n/256); T = compute_tensor_field_random(n,options); Flow = perform_tensor_decomp(T); % extract eigenfield. options.isoriented = 0; % no orientation in streamlines % initial texture lic_width = getoptions(options, 'lic_width', 0); M0 = perform_blurring(randn(n),lic_width); M0 = perform_histogram_equalization( M0, 'linear'); options.histogram = 'linear'; options.dt = 0.4; options.M0 = M0; options.verb = 1; options.flow_correction = 1; options.niter_lic = 3; w = 30; M = perform_lic(Flow, w, options); case 'square_texture' M = load_image('square',n); M = rescale(M); % make a texture patch x = linspace(0,1,n); [Y,X] = meshgrid(x,x); theta = pi/3; x = cos(theta)*X + sin(theta)*Y; c = [0.3,0.4]; r = 0.2; I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 ); eta = 3/n; lambda = 0.3; M(I) = M(I) + lambda * sin( x(I) * 2*pi / eta ); case 'tv-image' M = rand(n); tau = compute_total_variation(M); options.niter = 400; [M,err_tv,err_l2] = perform_tv_projection(M,tau/1000,options); M = perform_histogram_equalization(M,'linear'); case 'oscillatory_texture' x = linspace(0,1,n); [Y,X] = meshgrid(x,x); theta = pi/3; x = cos(theta)*X + sin(theta)*Y; c = [0.3,0.4]; r = 0.2; I = find( (X-c(1)).^2 + (Y-c(2)).^2 < r^2 ); eta = 3/n; lambda = 0.3; M = sin( x * 2*pi / eta ); case {'line', 'line_vertical', 'line_horizontal', 'line_diagonal'} x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); if gamma~=Inf M = (X-eta) - gamma*Y < 0; else M = (Y-eta) < 0; end case 'line-windowed' x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); eta = .3; gamma = getoptions(options, 'gamma', pi/10); parabola = getoptions(options, 'parabola', 0); M = (X-eta) - gamma*Y - parabola*Y.^2 < 0; f = sin( pi*x ).^2; M = M .* ( f'*f ); case 'grating' x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); theta = getoptions(options, 'theta', .2); freq = getoptions(options, 'freq', .2); X = cos(theta)*X + sin(theta)*Y; M = sin(2*pi*X/freq); case 'disk' if ~isfield( options, 'radius' ) radius = 0.35; end if ~isfield( options, 'center' ) center = [0.5, 0.5]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; case 'twodisks' M = zeros(n); options.center = [.25 .25]; M = load_image('disk', n, options); options.center = [.75 .75]; M = M + load_image('disk', n, options); case 'diskregular' M = rescale(load_image('disk',n,options)); if not(isfield(options, 'alpha')) options.alpha = 3; end S = load_image('fnoise',n,options); M = M + rescale(S,-0.3,0.3); case 'quarterdisk' if ~isfield( options, 'radius' ) radius = 0.95; end if ~isfield( options, 'center' ) center = -[0.1, 0.1]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; case 'fading_contour' if ~isfield( options, 'radius' ) radius = 0.95; end if ~isfield( options, 'center' ) center = -[0.1, 0.1]; % center of the circle end x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); M = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; theta = 2/pi*atan2(Y,X); h = 0.5; M = exp(-(1-theta).^2/h^2).*M; case '3contours' radius = 1.3; center = [-1, 1]; radius1 = 0.8; center1 = [0, 0]; x = 0:1/(n-1):1; [Y,X] = meshgrid(x,x); f1 = (X-center(1)).^2 + (Y-center(2)).^2 < radius^2; f2 = (X-center1(1)).^2 + (Y-center1(2)).^2 < radius1^2; M = f1 + 0.5*f2.*(1-f1); case 'line_circle' gamma = 1/sqrt(2); x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); M1 = double( X>gamma*Y+0.25 ); M2 = X.^2 + Y.^2 < 0.6^2; M = 20 + max(0.5*M1,M2) * 216; case 'fnoise' % generate an image M whose Fourier spectrum amplitude is % |M^(omega)| = 1/f^{omega} alpha = getoptions(options, 'alpha', 1); M = gen_noisy_image(n,alpha); case 'gaussiannoise' % generate an image of filtered noise with gaussian sigma = getoptions(options, 'sigma', 10); M = randn(n); m = 51; h = compute_gaussian_filter([m m],sigma/(4*n),[n n]); M = perform_convolution(M,h); return; case {'bwhorizontal','bwvertical','bwcircle'} [Y,X] = meshgrid(0:n-1,0:n-1); if strcmp(type, 'bwhorizontal') d = X; elseif strcmp(type, 'bwvertical') d = Y; elseif strcmp(type, 'bwcircle') d = sqrt( (X-(n-1)/2).^2 + (Y-(n-1)/2).^2 ); end if isfield(options, 'stripe_width') stripe_width = options.stripe_width; else stripe_width = 5; end if isfield(options, 'black_prop') black_prop = options.black_prop; else black_prop = 0.5; end M = double( mod( d/(2*stripe_width),1 )>=black_prop ); case 'parabola' % curvature c = getoptions(c, 'c', .1); % angle theta = getoptions(options, 'theta', pi/sqrt(2)); x = -0.5:1/(n-1):0.5; [Y,X] = meshgrid(x,x); Xs = X*cos(theta) + Y*sin(theta); Y =-X*sin(theta) + Y*cos(theta); X = Xs; M = Y>c*X.^2; case 'sin' [Y,X] = meshgrid(-1:2/(n-1):1, -1:2/(n-1):1); M = Y >= 0.6*cos(pi*X); M = double(M); case 'circ_oscil' x = linspace(-1,1,n); [Y,X] = meshgrid(x,x); R = sqrt(X.^2+Y.^2); M = cos(R.^3*50); case 'phantom' M = phantom(n); case 'periodic_bumps' nbr_periods = getoptions(options, 'nbr_periods', 8); theta = getoptions(options, 'theta', 1/sqrt(2)); skew = getoptions(options, 'skew', 1/sqrt(2) ); A = [cos(theta), -sin(theta); sin(theta), cos(theta)]; B = [1 skew; 0 1]; T = B*A; x = (0:n-1)*2*pi*nbr_periods/(n-1); [Y,X] = meshgrid(x,x); pos = [X(:)'; Y(:)']; pos = T*pos; X = reshape(pos(1,:), n,n); Y = reshape(pos(2,:), n,n); M = cos(X).*sin(Y); case 'noise' sigma = getoptions(options, 'sigma', 1); M = randn(n) * sigma; case 'disk-corner' x = linspace(0,1,n); [Y,X] = meshgrid(x,x); rho = .3; eta = .1; M1 = rho*X+eta<Y; c = [0 .2]; r = .85; d = (X-c(1)).^2 + (Y-c(2)).^2; M2 = d<r^2; M = M1.*M2; otherwise ext = {'gif', 'png', 'jpg', 'bmp', 'tiff', 'pgm', 'ppm'}; for i=1:length(ext) name = [type '.' ext{i}]; if( exist(name) ) M = imread( name ); M = double(M); if not(isempty(n)) && (n~=size(M, 1) || n~=size(M, 2)) && nargin>=2 M = image_resize(M,n,n); end if strcmp(type, 'peppers-bw') M(:,1) = M(:,2); M(1,:) = M(2,:); end if sigma>0 M = perform_blurring(M,sigma); end return; end end error( ['Image ' type ' does not exists.'] ); end M = double(M); if sigma>0 M = perform_blurring(M,sigma); end M = rescale(M); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = create_letter(a, r, n) c = 0.2; p1 = [c;c]; p2 = [c; 1-c]; p3 = [1-c; 1-c]; p4 = [1-c; c]; p4 = [1-c; c]; pc = [0.5;0.5]; pu = [0.5; c]; switch a case 'x' point_list = { [p1 p3] [p2 p4] }; case 'z' point_list = { [p2 p3 p1 p4] }; case 'v' point_list = { [p2 pu p3] }; case 'y' point_list = { [p2 pc pu] [pc p3] }; end % fit image for i=1:length(point_list) a = point_list{i}(2:-1:1,:); a(1,:) = 1-a(1,:); point_list{i} = round( a*(n-1)+1 ); end M = draw_polygons(zeros(n),r,point_list); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sk = draw_polygons(mask,r,point_list) sk = mask*0; for i=1:length(point_list) pl = point_list{i}; for k=2:length(pl) sk = draw_line(sk,pl(1,k-1),pl(2,k-1),pl(1,k),pl(2,k),r); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sk = draw_line(sk,x1,y1,x2,y2,r) n = size(sk,1); [Y,X] = meshgrid(1:n,1:n); q = 100; t = linspace(0,1,q); x = x1*t+x2*(1-t); y = y1*t+y2*(1-t); if r==0 x = round( x ); y = round( y ); sk( x+(y-1)*n ) = 1; else for k=1:q I = find((X-x(k)).^2 + (Y-y(k)).^2 <= r^2 ); sk(I) = 1; end end function M = gen_noisy_image(n,alpha) % gen_noisy_image - generate a noisy cloud-like image. % % M = gen_noisy_image(n,alpha); % % generate an image M whose Fourier spectrum amplitude is % |M^(omega)| = 1/f^{omega} % % Copyright (c) 2004 Gabriel Peyr? if nargin<1 n = 128; end if nargin<2 alpha = 1.5; end if mod(n(1),2)==0 x = -n/2:n/2-1; else x = -(n-1)/2:(n-1)/2; end [Y,X] = meshgrid(x,x); d = sqrt(X.^2 + Y.^2) + 0.1; f = rand(n)*2*pi; M = (d.^(-alpha)) .* exp(f*1i); % M = real(ifft2(fftshift(M))); M = ifftshift(M); M = real( ifft2(M) ); function y = gen_signal_2d(n,alpha) % gen_signal_2d - generate a 2D C^\alpha signal of length n x n. % gen_signal_2d(n,alpha) generate a 2D signal C^alpha. % % The signal is scale in [0,1]. % % Copyright (c) 2003 Gabriel Peyr? % new new method [Y,X] = meshgrid(0:n-1, 0:n-1); A = X+Y+1; B = X-Y+n+1; a = gen_signal(2*n+1, alpha); b = gen_signal(2*n+1, alpha); y = a(A).*b(B); % M = a(1:n)*b(1:n)'; return; % new method h = (-n/2+1):(n/2); h(n/2)=1; [X,Y] = meshgrid(h,h); h = sqrt(X.^2+Y.^2+1).^(-alpha-1/2); h = h .* exp( 2i*pi*rand(n,n) ); h = fftshift(h); y = real( ifft2(h) ); m1 = min(min(y)); m2 = max(max(y)); y = (y-m1)/(m2-m1); return; %% old code y = rand(n,n); y = y - mean(mean(y)); for i=1:alpha y = cumsum(cumsum(y)')'; y = y - mean(mean(y)); end m1 = min(min(y)); m2 = max(max(y)); y = (y-m1)/(m2-m1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = draw_rectangle(r,n) x = linspace(0,1,n); [Y,X] = meshgrid(x,x); M = double( (X>=r(1)) & (X<=r(3)) & (Y>=r(2)) & (Y<=r(4)) ) ;
github
mathematical-tours/mathematical-tours.github.io-master
resize_img.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/total-variation/toolbox/resize_img.m
4,491
utf_8
08e13146c462c4c031869291d64de7a5
function resize_img(imnames, Voxdim, BB, ismask) % resize_img -- resample images to have specified voxel dims and BBox % resize_img(imnames, voxdim, bb, ismask) % % Output images will be prefixed with 'r', and will have voxel dimensions % equal to voxdim. Use NaNs to determine voxdims from transformation matrix % of input image(s). % If bb == nan(2,3), bounding box will include entire original image % Origin will move appropriately. Use world_bb to compute bounding box from % a different image. % % Pass ismask=true to re-round binary mask values (avoid % growing/shrinking masks due to linear interp) % % See also voxdim, world_bb % Based on John Ashburner's reorient.m % http://www.sph.umich.edu/~nichols/JohnsGems.html#Gem7 % http://www.sph.umich.edu/~nichols/JohnsGems5.html#Gem2 % Adapted by Ged Ridgway -- email bugs to [email protected] % This version doesn't check spm_flip_analyze_images -- the handedness of % the output image and matrix should match those of the input. % Check spm version: if exist('spm_select','file') % should be true for spm5 spm5 = 1; elseif exist('spm_get','file') % should be true for spm2 spm5 = 0; else error('Can''t find spm_get or spm_select; please add SPM to path') end spm_defaults; % prompt for missing arguments if ( ~exist('imnames','var') || isempty(char(imnames)) ) if spm5 imnames = spm_select(inf, 'image', 'Choose images to resize'); else imnames = spm_get(inf, 'img', 'Choose images to resize'); end end % check if inter fig already open, don't close later if so... Fint = spm_figure('FindWin', 'Interactive'); Fnew = []; if ( ~exist('Voxdim', 'var') || isempty(Voxdim) ) Fnew = spm_figure('GetWin', 'Interactive'); Voxdim = spm_input('Vox Dims (NaN for "as input")? ',... '+1', 'e', '[nan nan nan]', 3); end if ( ~exist('BB', 'var') || isempty(BB) ) Fnew = spm_figure('GetWin', 'Interactive'); BB = spm_input('Bound Box (NaN => original)? ',... '+1', 'e', '[nan nan nan; nan nan nan]', [2 3]); end if ~exist('ismask', 'var') ismask = false; end if isempty(ismask) ismask = false; end % reslice images one-by-one vols = spm_vol(imnames); for V=vols' % (copy to allow defaulting of NaNs differently for each volume) voxdim = Voxdim; bb = BB; % default voxdim to current volume's voxdim, (from mat parameters) if any(isnan(voxdim)) vprm = spm_imatrix(V.mat); vvoxdim = vprm(7:9); voxdim(isnan(voxdim)) = vvoxdim(isnan(voxdim)); end voxdim = voxdim(:)'; mn = bb(1,:); mx = bb(2,:); % default BB to current volume's if any(isnan(bb(:))) vbb = world_bb(V); vmn = vbb(1,:); vmx = vbb(2,:); mn(isnan(mn)) = vmn(isnan(mn)); mx(isnan(mx)) = vmx(isnan(mx)); end % voxel [1 1 1] of output should map to BB mn % (the combination of matrices below first maps [1 1 1] to [0 0 0]) mat = spm_matrix([mn 0 0 0 voxdim])*spm_matrix([-1 -1 -1]); % voxel-coords of BB mx gives number of voxels required % (round up if more than a tenth of a voxel over) imgdim = ceil(mat \ [mx 1]' - 0.1)'; % output image VO = V; [pth,nam,ext] = fileparts(V.fname); VO.fname = fullfile(pth,['r' nam ext]); VO.dim(1:3) = imgdim(1:3); VO.mat = mat; VO = spm_create_vol(VO); spm_progress_bar('Init',imgdim(3),'reslicing...','planes completed'); for i = 1:imgdim(3) M = inv(spm_matrix([0 0 -i])*inv(VO.mat)*V.mat); img = spm_slice_vol(V, M, imgdim(1:2), 1); % (linear interp) if ismask img = round(img); end spm_write_plane(VO, img, i); spm_progress_bar('Set', i) end spm_progress_bar('Clear'); end % call spm_close_vol if spm2 if ~spm5 spm_close_vol(VO); end if (isempty(Fint) && ~isempty(Fnew)) % interactive figure was opened by this script, so close it again. close(Fnew); end disp('Done.') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bb = world_bb(V) % world-bb -- get bounding box in world (mm) coordinates d = V.dim(1:3); % corners in voxel-space c = [ 1 1 1 1 1 1 d(3) 1 1 d(2) 1 1 1 d(2) d(3) 1 d(1) 1 1 1 d(1) 1 d(3) 1 d(1) d(2) 1 1 d(1) d(2) d(3) 1 ]'; % corners in world-space tc = V.mat(1:3,1:4)*c; % bounding box (world) min and max mn = min(tc,[],2)'; mx = max(tc,[],2)'; bb = [mn; mx];
github
mathematical-tours/mathematical-tours.github.io-master
perform_wavortho_transf.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/orthobases/perform_wavortho_transf.m
2,736
utf_8
362bed43d951f6bdefb520003047e2ea
function f = perform_wavortho_transf(f,Jmin,dir,options) % perform_wavortho_transf - compute orthogonal wavelet transform % % fw = perform_wavortho_transf(f,Jmin,dir,options); % % You can give the filter in options.h. % % Works in arbitrary dimension. % % Copyright (c) 2009 Gabriel Peyre options.null = 0; h = getoptions(options,'h', compute_wavelet_filter('Daubechies',4) ); g = [0 h(length(h):-1:2)] .* (-1).^(1:length(h)); n = size(f,1); Jmax = log2(n)-1; if dir==1 %%% FORWARD %%% for j=Jmax:-1:Jmin sel = 1:2^(j+1); a = subselect(f,sel); for d=1:nb_dims(f) a = cat(d, subsampling(cconvol(a,h,d),d), subsampling(cconvol(a,g,d),d) ); end f = subassign(f,sel,a); end else %%% FORWARD %%% for j=Jmin:Jmax sel = 1:2^(j+1); a = subselect(f,sel); for d=1:nb_dims(f) w = subselectdim(a,2^j+1:2^(j+1),d); a = subselectdim(a,1:2^j,d); a = cconvol(upsampling(a,d),reverse(h),d) + cconvol(upsampling(w,d),reverse(g),d); end f = subassign(f,sel,a); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subselect(f,sel) switch nb_dims(f) case 1 f = f(sel); case 2 f = f(sel,sel); case 3 f = f(sel,sel,sel); case 4 f = f(sel,sel,sel,sel); case 5 f = f(sel,sel,sel,sel,sel); case 6 f = f(sel,sel,sel,sel,sel,sel); case 7 f = f(sel,sel,sel,sel,sel,sel,sel); case 8 f = f(sel,sel,sel,sel,sel,sel,sel,sel); otherwise error('Not implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subselectdim(f,sel,d) switch d case 1 f = f(sel,:,:,:,:,:,:,:); case 2 f = f(:,sel,:,:,:,:,:,:); case 3 f = f(:,:,sel,:,:,:,:,:); case 4 f = f(:,:,:,sel,:,:,:,:); case 5 f = f(:,:,:,:,sel,:,:,:); case 6 f = f(:,:,:,:,:,sel,:,:); case 7 f = f(:,:,:,:,:,:,sel,:); case 8 f = f(:,:,:,:,:,:,:,sel); otherwise error('Not implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subassign(f,sel,g) switch nb_dims(f) case 1 f(sel) = g; case 2 f(sel,sel) = g; case 3 f(sel,sel,sel) = g; case 4 f(sel,sel,sel,sel) = g; case 5 f(sel,sel,sel,sel,sel) = g; case 6 f(sel,sel,sel,sel,sel,sel) = g; case 7 f(sel,sel,sel,sel,sel,sel,sel) = g; case 8 f(sel,sel,sel,sel,sel,sel,sel,sel) = g; otherwise error('Not implemented'); end
github
mathematical-tours/mathematical-tours.github.io-master
nbECGM.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/displ-interp-2d/toolbox-lsap/nbECGM.m
737
utf_8
12c013e9e8fa1ded80b1fdb944a77e4f
% ----------------------------------------------------------- % file: nbECGM.m % ----------------------------------------------------------- % authors: Sebastien Bougleux (UNICAEN) and Luc Brun (ENSICAEN) % institution: Normandie Univ, CNRS - ENSICAEN - UNICAEN, GREYC UMR 6072 % ----------------------------------------------------------- % This file is part of LSAPE. % LSAPE is free software: you can redistribute it and/or modify % it under the terms of the CeCILL-C License. See README file % for more details. % ----------------------------------------------------------- function nb = nbECGM(nbU,nbV) nb = 0; for p=0:min(nbU,nbV) nb = nb + factorial(p) * nchoosek(nbU,p) * nchoosek(nbV,p); end end
github
mathematical-tours/mathematical-tours.github.io-master
showDecoratedTiles.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/penrose/showDecoratedTiles.m
2,810
utf_8
335ec04536c1ee3229b4817c7b9de25a
function showDecoratedTiles(T) %showDecoratedTiles Show Penrose rhombus tiles with connecting arcs. % % showDecoratedTiles(T) displays the Penrose rhombus tiles constructed % from the triangles in the input table, T. Each triangle is decorated % with arcs so that the arcs connect smoothly from triangle to % triangle, resulting in an interesting geometric pattern overlaid on % the Penrose tiles. % % EXAMPLE % Decompose a B triangle 4 times and display the resulting rhombus % tiles. % % t = bTriangle([],-1,1); % for k = 1:4 % t = decomposeTriangles(t); % end % showDecoratedTiles(t) % Copyright 2018 The MathWorks, Inc. showTiles(T); [arc1,arc2] = triangleCurves(T); arc_color = [255 255 191]/255; line(real(arc1),imag(arc1),... 'LineWidth',0.5,... 'Color',arc_color); line(real(arc2),imag(arc2),... 'LineWidth',3,... 'Color',arc_color); axis equal function [arc1,arc2] = triangleCurves(T) arc1 = []; arc2 = []; for k = 1:height(T) t_k = T(k,:); switch t_k.Type case 'A' [arc1_k,arc2_k] = arcsA(t_k.Apex,t_k.Left,t_k.Right); case 'Ap' [arc1_k,arc2_k] = arcsAp(t_k.Apex,t_k.Left,t_k.Right); case 'B' [arc1_k,arc2_k] = arcsB(t_k.Apex,t_k.Left,t_k.Right); case 'Bp' [arc1_k,arc2_k] = arcsBp(t_k.Apex,t_k.Left,t_k.Right); end arc1 = [arc1 arc1_k NaN]; arc2 = [arc2 arc2_k NaN]; end function [arc1,arc2] = arcsA(P1,P2,P3) ray = P1 - P2; theta1 = angle(ray); theta2 = theta1 - deg2rad(72); theta = linspace(theta1,theta2,10); arc1 = P2 + 0.25 * abs(ray) * exp(1i * theta); ray = P1 - P3; theta1 = angle(ray); theta2 = theta1 + deg2rad(72); theta = linspace(theta1,theta2,10); arc2 = P3 + 0.25 * abs(ray) * exp(1i * theta); function [arc1,arc2] = arcsAp(P1,P2,P3) ray = P1 - P2; theta1 = angle(ray); theta2 = theta1 - deg2rad(72); theta = linspace(theta1,theta2,10); arc2 = P2 + 0.25 * abs(ray) * exp(1i * theta); ray = P1 - P3; theta1 = angle(ray); theta2 = theta1 + deg2rad(72); theta = linspace(theta1,theta2,10); arc1 = P3 + 0.25 * abs(ray) * exp(1i * theta); function [arc1,arc2] = arcsB(P1,P2,P3) ray = P1 - P2; theta1 = angle(ray); theta2 = theta1 - deg2rad(36); theta = linspace(theta1,theta2,10); arc2 = P2 + 0.75 * abs(ray) * exp(1i * theta); ray = P1 - P3; theta1 = angle(ray); theta2 = theta1 + deg2rad(36); theta = linspace(theta1,theta2,10); arc1 = P3 + 0.25 * abs(ray) * exp(1i * theta); function [arc1,arc2] = arcsBp(P1,P2,P3) ray = P1 - P2; theta1 = angle(ray); theta2 = theta1 - deg2rad(36); theta = linspace(theta1,theta2,10); arc1 = P2 + 0.25 * abs(ray) * exp(1i * theta); ray = P1 - P3; theta1 = angle(ray); theta2 = theta1 + deg2rad(36); theta = linspace(theta1,theta2,10); arc2 = P3 + 0.75 * abs(ray) * exp(1i * theta);
github
mathematical-tours/mathematical-tours.github.io-master
isoscelesTriangle.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/penrose/isoscelesTriangle.m
1,580
utf_8
fb942b8fbc4f919cb973dd5524fac1be
function [apex,left,right] = isoscelesTriangle(apex,left,right,theta) %isoscelesTriangle Isosceles triangle. % [apex,left,right] = isoscelesTriangle(apex,left,right,theta) returns % the three vertices of an isosceles triangle given any two vertices and % the apex angle (in degrees). Triangle vertices are represented as % points in the complex plane. Specify the unknown input vertex as []. % % If none of the input vertices is empty, then they are returned % unmodified. % % EXAMPLE % Compute the isosceles triangle with apex at (0,1), left base vertex at % (0,0), and an apex angle of 36 degrees. % % [apex,left,right] = isoscelesTriangle(1i,0,[],36) % v = [apex left right apex]; % plot(real(v),imag(v),'LineWidth',2) % axis equal % Copyright 2018 The MathWorks, Inc. if isempty(apex) base_to_side_ratio = sqrt(2 - 2*cos(deg2rad(theta))); base = right - left; apex = left + (abs(base)/base_to_side_ratio) * exp(1i * (angle(base) + deg2rad((180-theta)/2))); apex = scrub(apex); elseif isempty(left) right_side = right - apex; left = apex + abs(right_side) * exp(1i * (angle(right_side) - deg2rad(theta))); left = scrub(left); elseif isempty(right) left_side = left - apex; right = apex + abs(left_side) * exp(1i * (angle(left_side) + deg2rad(theta))); right = scrub(right); end function z = scrub(z) % z = scrub(z) removes unsightly real or imaginary part. if abs(real(z)) < 10*eps(abs(imag(z))) z = imag(z)*1i; end if abs(imag(z)) < 10*eps(abs(real(z))) z = real(z); end
github
mathematical-tours/mathematical-tours.github.io-master
showLabeledTriangles.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/penrose/showLabeledTriangles.m
2,695
utf_8
8d390c710fc92875de69726b2d36e2ea
function showLabeledTriangles(T) %showLabeledTriangles Show triangles with type and side labels. % % showLabeledTriangles(T) shows the outline of each triangle contained % in the input table. Each row of the input table has the form % returned by aTriangle, apTriangle, bTriangle, or bpTriangle. Each % displayed triangled is labeled according to type: A, A', B, or B'. % Each triangle side is marked with a symbol that helps indicate a % correct or incorrect tiling. % % EXAMPLE % % Show how a B triangle is decomposed into three triangles (of type A, % B, and B') according to Penrose tiling rules. % % t = bTriangle([],-1,1); % t1 = decomposeTriangles(t); % showLabeledTriangles(t1) % Copyright 2018 The MathWorks, Inc. showTriangles(T); vertices = [T.Left T.Apex T.Right]; centroids = mean(vertices,2); cx = real(centroids); cy = imag(centroids); labels = cellstr(T.Type); labels = strrep(labels,'Ap','A'''); labels = strrep(labels,'Bp','B'''); hold on text(cx,cy,labels,... 'HorizontalAlignment','center',... 'VerticalAlignment','middle',... 'FontWeight','bold',... 'FontSize',14); labelSides(T(T.Type == "A",:),... 0.5,{'LineStyle','none','Marker','o','Color','k','MarkerSize',15},... 0.5,{'LineStyle','none','Marker','s','Color','k','MarkerSize',12},... 0.6,{'LineStyle','none','Marker','*','Color','k','MarkerSize',14}); labelSides(T(T.Type == "Ap",:),... 0.5,{'LineStyle','none','Marker','s','Color','k','MarkerSize',12},... 0.5,{'LineStyle','none','Marker','o','Color','k','MarkerSize',15},... 0.4,{'LineStyle','none','Marker','*','Color','k','MarkerSize',14}); labelSides(T(T.Type == "B",:),... 0.5,{'LineStyle','none','Marker','s','Color','k','MarkerSize',12},... 0.5,{'LineStyle','none','Marker','o','Color','k','MarkerSize',15},... 0.6,{'LineStyle','none','Marker','p','Color','k','MarkerSize',16}); labelSides(T(T.Type == "Bp",:),... 0.5,{'LineStyle','none','Marker','o','Color','k','MarkerSize',15},... 0.5,{'LineStyle','none','Marker','s','Color','k','MarkerSize',12},... 0.4,{'LineStyle','none','Marker','p','Color','k','MarkerSize',16}); hold off function labelSides(T,alpha_left,line_params_left,alpha_right,line_params_right,alpha_base,line_params_base) side1_label_point = T.Apex + alpha_left*(T.Left - T.Apex); plot(real(side1_label_point),imag(side1_label_point),line_params_left{:}); side2_label_point = T.Apex + alpha_right*(T.Right - T.Apex); plot(real(side2_label_point),imag(side2_label_point),line_params_right{:}); base_label_point = T.Left + alpha_base*(T.Right - T.Left); plot(real(base_label_point),imag(base_label_point),line_params_base{:});
github
mathematical-tours/mathematical-tours.github.io-master
solveTSP.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/tsp/solveTSP.m
3,663
utf_8
20479919ca2129026113b1c9c3f48ee5
function varargout = solveTSP( cities, display, maxIteration, order) % cities = solveTSP( cities, maxItt, display) % % cities - An Nx2 matrix containing cartesian coordinates of the "cities" % beeing visited. The initial trail is assumed from the first city to the % scond and so on... % % display - bolean flag decide if to display the progress of the program (slows the running time). % default = false; % % maxIteration - maximum iterations for the program % default = 10,000 % % % [cities ind] = solveTSP( cities, display) returns the aranged cities and % an index vector of the visiting order % % [cities ind totalDist] = solveTSP( cities, display) % totalDist is the route total distance % % demo1: % cities = solveTSP( rand(100,2), true ); % % demo2: % t = (0:999)' /1000; % cities = [ t.^2.*cos( t*30 ) t.^2.*sin( t*30 ) ]; % [ans ind] = sort( rand(1000,1) ); % [cities ind] = solveTSP( cities(ind,:), true ); if nargin < 2 display = false; end if nargin<3 %maxIteration = 1e5; maxIteration = 1000; end siz = size(cities); if siz(2) ~= 2 error( 'The program is expecting cities to be an Nx2 matix of cartesian coordinates' ); end N = siz(1); if nargin<4 order = (1:N)'; % initial cities visit order end if display hFig = gcf; % figure; hAx = gca; updateRate = ceil( N/50 ); end itt = 1; maxItt = min(20*N,maxIteration); noChange = 0; while itt < maxItt && noChange < N dist = calcDistVec( cities(order,:),1 ); % travel distance between the cities %% ----------- Displaying current route ----------------------- if display && ~mod(itt,updateRate) && ishandle( hFig ) hold(hAx,'off'); plot( hAx, cities( order,1),cities( order,2),'r.' ); hold( hAx,'on'); plot( hAx, cities( order,1),cities( order,2) ); str = {[ 'iteration: ' num2str( itt ) ] ; [ 'total route: ' num2str( sum( dist) ) ] }; title( hAx,str ); pause(0.02) end flip = mod( itt-1, N-3 )+2 ; untie = dist(1:end-flip) + dist(flip+1:end); % the distance saved by untying a loop shufledDist = calcDistVec( cities( order,:),flip ); connect = shufledDist(1:end-1) + shufledDist( 2:end); % the distance payed by connecting the loop (after flip) benifit = connect - untie; % "what's the distance benifit from this loop fliping %% --------------- Finding the optimal flips (most benficial) ---------------- localMin = imerode(benifit,ones(2*flip+1,1) ); minimasInd = find( localMin == benifit); reqFlips = minimasInd( benifit(minimasInd) < -eps ); %% -------- fliping all loops found worth fliping -------------------- prevOrd = order; for n=1:numel( reqFlips ) order( reqFlips(n) : reqFlips(n)+flip-1 ) = order( reqFlips(n) +flip-1: -1 :reqFlips(n) ); end %% ------- counting how many iterations there was no improvement if isequal( order,prevOrd ) noChange = noChange + 1; else noChange = 0; end itt = itt+1; end % while itt < maxItt && noChange < N output = {cities( order,:), order, sum( dist)}; varargout = output(1:nargout); function dist = calcDistVec( cord,offset ) % dist = calcDistVec( cord,offset ) % offset is the number of cities to calculate the distence between % the distance for the first city is allway 0 dist = zeros( size(cord,1)-offset+1,1 ); temp = cord( 1:end-offset,:) - cord( offset+1:end,:); dist(2:end) = sqrt( sum(temp.^2,2) );
github
mathematical-tours/mathematical-tours.github.io-master
tsp_ga.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/tsp/tsp_ga.m
9,855
utf_8
d7af84e7693bc9af24e3d4164fd89ae6
%TSP_GA Traveling Salesman Problem (TSP) Genetic Algorithm (GA) % Finds a (near) optimal solution to the TSP by setting up a GA to search % for the shortest route (least distance for the salesman to travel to % each city exactly once and return to the starting city) % % Summary: % 1. A single salesman travels to each of the cities and completes the % route by returning to the city he started from % 2. Each city is visited by the salesman exactly once % % Input: % USERCONFIG (structure) with zero or more of the following fields: % - XY (float) is an Nx2 matrix of city locations, where N is the number of cities % - DMAT (float) is an NxN matrix of point to point distances/costs % - POPSIZE (scalar integer) is the size of the population (should be divisible by 4) % - NUMITER (scalar integer) is the number of desired iterations for the algorithm to run % - SHOWPROG (scalar logical) shows the GA progress if true % - SHOWRESULT (scalar logical) shows the GA results if true % - SHOWWAITBAR (scalar logical) shows a waitbar if true % % Input Notes: % 1. Rather than passing in a structure containing these fields, any/all of % these inputs can be passed in as parameter/value pairs in any order instead. % 2. Field/parameter names are case insensitive but must match exactly otherwise. % % Output: % RESULTSTRUCT (structure) with the following fields: % (in addition to a record of the algorithm configuration) % - OPTROUTE (integer array) is the best route found by the algorithm % - MINDIST (scalar float) is the cost of the best route % % Usage: % tsp_ga % -or- % tsp_ga(userConfig) % -or- % resultStruct = tsp_ga; % -or- % resultStruct = tsp_ga(userConfig); % -or- % [...] = tsp_ga('Param1',Value1,'Param2',Value2, ...); % % Example: % % Let the function create an example problem to solve % tsp_ga; % % Example: % % Request the output structure from the solver % resultStruct = tsp_ga; % % Example: % % Pass a random set of user-defined XY points to the solver % userConfig = struct('xy',10*rand(50,2)); % resultStruct = tsp_ga(userConfig); % % Example: % % Pass a more interesting set of XY points to the solver % n = 100; % phi = (sqrt(5)-1)/2; % theta = 2*pi*phi*(0:n-1); % rho = (1:n).^phi; % [x,y] = pol2cart(theta(:),rho(:)); % xy = 10*([x y]-min([x;y]))/(max([x;y])-min([x;y])); % userConfig = struct('xy',xy); % resultStruct = tsp_ga(userConfig); % % Example: % % Pass a random set of 3D (XYZ) points to the solver % xyz = 10*rand(50,3); % userConfig = struct('xy',xyz); % resultStruct = tsp_ga(userConfig); % % Example: % % Change the defaults for GA population size and number of iterations % userConfig = struct('popSize',200,'numIter',1e4); % resultStruct = tsp_ga(userConfig); % % Example: % % Turn off the plots but show a waitbar % userConfig = struct('showProg',false,'showResult',false,'showWaitbar',true); % resultStruct = tsp_ga(userConfig); % % See also: mtsp_ga, tsp_nn, tspo_ga, tspof_ga, tspofs_ga, distmat % % Author: Joseph Kirk % Email: [email protected] % Release: 3.0 % Release Date: 05/01/2014 function varargout = tsp_ga(varargin) % Initialize default configuration defaultConfig.xy = 10*rand(50,2); defaultConfig.dmat = []; defaultConfig.popSize = 100; defaultConfig.numIter = 1e4; defaultConfig.showProg = true; defaultConfig.showResult = true; defaultConfig.showWaitbar = false; % Interpret user configuration inputs if ~nargin userConfig = struct(); elseif isstruct(varargin{1}) userConfig = varargin{1}; else try userConfig = struct(varargin{:}); catch error('Expected inputs are either a structure or parameter/value pairs'); end end % Override default configuration with user inputs configStruct = get_config(defaultConfig,userConfig); % Extract configuration xy = configStruct.xy; dmat = configStruct.dmat; popSize = configStruct.popSize; numIter = configStruct.numIter; showProg = configStruct.showProg; showResult = configStruct.showResult; showWaitbar = configStruct.showWaitbar; if isempty(dmat) nPoints = size(xy,1); a = meshgrid(1:nPoints); dmat = reshape(sqrt(sum((xy(a,:)-xy(a',:)).^2,2)),nPoints,nPoints); end % Verify Inputs [N,dims] = size(xy); [nr,nc] = size(dmat); if N ~= nr || N ~= nc error('Invalid XY or DMAT inputs!') end n = N; % Sanity Checks popSize = 4*ceil(popSize/4); numIter = max(1,round(real(numIter(1)))); showProg = logical(showProg(1)); showResult = logical(showResult(1)); showWaitbar = logical(showWaitbar(1)); % Initialize the Population pop = zeros(popSize,n); pop(1,:) = (1:n); for k = 2:popSize pop(k,:) = randperm(n); end % Run the GA globalMin = Inf; totalDist = zeros(1,popSize); distHistory = zeros(1,numIter); tmpPop = zeros(4,n); newPop = zeros(popSize,n); if showProg figure('Name','TSP_GA | Current Best Solution','Numbertitle','off'); hAx = gca; end if showWaitbar hWait = waitbar(0,'Searching for near-optimal solution ...'); end for iter = 1:numIter % Evaluate Each Population Member (Calculate Total Distance) for p = 1:popSize d = dmat(pop(p,n),pop(p,1)); % Closed Path for k = 2:n d = d + dmat(pop(p,k-1),pop(p,k)); end totalDist(p) = d; end % Find the Best Route in the Population [minDist,index] = min(totalDist); distHistory(iter) = minDist; if minDist < globalMin globalMin = minDist; optRoute = pop(index,:); if showProg % Plot the Best Route rte = optRoute([1:n 1]); if dims > 2, plot3(hAx,xy(rte,1),xy(rte,2),xy(rte,3),'r.-'); else plot(hAx,xy(rte,1),xy(rte,2),'r.-'); end title(hAx,sprintf('Total Distance = %1.4f, Iteration = %d',minDist,iter)); drawnow; end end % Genetic Algorithm Operators randomOrder = randperm(popSize); for p = 4:4:popSize rtes = pop(randomOrder(p-3:p),:); dists = totalDist(randomOrder(p-3:p)); [ignore,idx] = min(dists); %#ok bestOf4Route = rtes(idx,:); routeInsertionPoints = sort(ceil(n*rand(1,2))); I = routeInsertionPoints(1); J = routeInsertionPoints(2); for k = 1:4 % Mutate the Best to get Three New Routes tmpPop(k,:) = bestOf4Route; switch k case 2 % Flip tmpPop(k,I:J) = tmpPop(k,J:-1:I); case 3 % Swap tmpPop(k,[I J]) = tmpPop(k,[J I]); case 4 % Slide tmpPop(k,I:J) = tmpPop(k,[I+1:J I]); otherwise % Do Nothing end end newPop(p-3:p,:) = tmpPop; end pop = newPop; % Update the waitbar if showWaitbar && ~mod(iter,ceil(numIter/325)) waitbar(iter/numIter,hWait); end end if showWaitbar close(hWait); end if showResult % Plots the GA Results figure('Name','TSP_GA | Results','Numbertitle','off'); subplot(2,2,1); pclr = ~get(0,'DefaultAxesColor'); if dims > 2, plot3(xy(:,1),xy(:,2),xy(:,3),'.','Color',pclr); else plot(xy(:,1),xy(:,2),'.','Color',pclr); end title('City Locations'); subplot(2,2,2); imagesc(dmat(optRoute,optRoute)); title('Distance Matrix'); subplot(2,2,3); rte = optRoute([1:n 1]); if dims > 2, plot3(xy(rte,1),xy(rte,2),xy(rte,3),'r.-'); else plot(xy(rte,1),xy(rte,2),'r.-'); end title(sprintf('Total Distance = %1.4f',minDist)); subplot(2,2,4); plot(distHistory,'b','LineWidth',2); title('Best Solution History'); set(gca,'XLim',[0 numIter+1],'YLim',[0 1.1*max([1 distHistory])]); end % Return Output if nargout resultStruct = struct( ... 'xy', xy, ... 'dmat', dmat, ... 'popSize', popSize, ... 'numIter', numIter, ... 'showProg', showProg, ... 'showResult', showResult, ... 'showWaitbar', showWaitbar, ... 'optRoute', optRoute, ... 'minDist', minDist); varargout = {resultStruct}; end end % Subfunction to override the default configuration with user inputs function config = get_config(defaultConfig,userConfig) % Initialize the configuration structure as the default config = defaultConfig; % Extract the field names of the default configuration structure defaultFields = fieldnames(defaultConfig); % Extract the field names of the user configuration structure userFields = fieldnames(userConfig); nUserFields = length(userFields); % Override any default configuration fields with user values for i = 1:nUserFields userField = userFields{i}; isField = strcmpi(defaultFields,userField); if nnz(isField) == 1 thisField = defaultFields{isField}; config.(thisField) = userConfig.(userField); end end end
github
mathematical-tours/mathematical-tours.github.io-master
nbECGM.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/tsp/toolbox-lsap/nbECGM.m
737
utf_8
12c013e9e8fa1ded80b1fdb944a77e4f
% ----------------------------------------------------------- % file: nbECGM.m % ----------------------------------------------------------- % authors: Sebastien Bougleux (UNICAEN) and Luc Brun (ENSICAEN) % institution: Normandie Univ, CNRS - ENSICAEN - UNICAEN, GREYC UMR 6072 % ----------------------------------------------------------- % This file is part of LSAPE. % LSAPE is free software: you can redistribute it and/or modify % it under the terms of the CeCILL-C License. See README file % for more details. % ----------------------------------------------------------- function nb = nbECGM(nbU,nbV) nb = 0; for p=0:min(nbU,nbV) nb = nb + factorial(p) * nchoosek(nbU,p) * nchoosek(nbV,p); end end
github
mathematical-tours/mathematical-tours.github.io-master
synth.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/texture-synthesis/synth.m
7,300
utf_8
63e55eb25b6cd0ff71909e7414adf4fb
function [Image, Mapping] = synth(rawSample, winsize, newRows, newCols, outpath) % Non-parametric Texture Synthesis using Efros & Leung's algorithm % Author: Alex Rubinsteyn (alex.rubinsteyn at gmail) % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA % 02110-1301 USA % Inputs: % 'filename': the image file containing the sample image (the texture to grow) % 'winsize': the edge length of the window to match at each iteration (the window is (winsize x winsize) ) % (newRows, newCols): the size of the output image % Outputs: % 'Image': the output image (the synthesized texture) % 'time': the amount of time it took to perform the synthesis MaxErrThreshold = 0.1; % rawSample = im2double(imread(filename)); rawSample = im2double(rawSample); sample = rawSample; [rows, cols, channels] = size(sample); windowlessSize = [(rows - winsize + 1) (cols - winsize + 1)]; halfWindow = (winsize - 1) / 2; npixels = newRows * newCols; Image = zeros(newRows, newCols, 3); Mapping = zeros(newRows, newCols,3); red_patches = im2col(sample(:, :, 1), [winsize winsize], 'sliding'); green_patches = im2col(sample(:, :, 2), [winsize winsize], 'sliding'); blue_patches = im2col(sample(:, :, 3), [winsize winsize], 'sliding'); %initialize new texture with a random 3x3 patch from the sample randRow = ceil(rand() * (rows - 2)); randCol = ceil(rand() * (cols - 2)); seedSize = 3; seedRows = ceil(newRows/2):ceil(newRows/2)+seedSize-1; seedCols = ceil(newCols/2):ceil(newCols/2)+seedSize-1; M = sample(randRow:randRow+seedSize-1, randCol:randCol+seedSize-1, :); if 0 k = length(seedRows); I = randperm(k*k); for i=1:3 m = M(:,:,i); m = reshape(m(I), size(m)); M(:,:,i) = m; end end Image(seedRows, seedCols, :) = M; Mapping(seedRows, seedCols,1) = (randRow:randRow+seedSize-1)' * ones(1,length(seedCols)); Mapping(seedRows, seedCols,2) = ones(length(seedCols),1) * (randCol:randCol+seedSize-1); nfilled = seedSize * seedSize; filled = repmat(false, [newRows newCols]); filled(seedRows, seedCols) = repmat(true, [3 3]); gaussMask = fspecial('gaussian',winsize, winsize/6.4); nskipped = 0; while nfilled < npixels progress = false; [pixelRows, pixelCols] = GetUnfilledNeighbors(filled, winsize); for i = 1:length(pixelRows) pixelRow = pixelRows(i); pixelCol = pixelCols(i); rowRange = pixelRow-halfWindow:pixelRow+halfWindow; colRange = pixelCol - halfWindow:pixelCol + halfWindow; deadRows = rowRange < 1 | rowRange > newRows; deadCols = colRange < 1 | colRange > newCols; if sum(deadRows) + sum(deadCols) > 0 safeRows = rowRange(~deadRows); safeCols = colRange(~deadCols); template = zeros(winsize, winsize, 3); template(~deadRows, ~deadCols, :) = Image(safeRows, safeCols, :); validMask = repmat(false, [winsize winsize]); validMask(~deadRows, ~deadCols) = filled(safeRows, safeCols); else template = Image(rowRange, colRange, :); validMask = filled(rowRange, colRange); end [bestMatches, SSD] = FindMatches(template, validMask, gaussMask, red_patches, green_patches, blue_patches); matchIdx = RandomPick(bestMatches); matchError = SSD(matchIdx); if matchError < MaxErrThreshold [matchRow, matchCol] = ind2sub(windowlessSize, matchIdx); %match coords are at corner of window and need to be offset matchRow = matchRow + halfWindow; matchCol = matchCol + halfWindow; Mapping(pixelRow, pixelCol,1) = matchRow; Mapping(pixelRow, pixelCol,2) = matchCol; Image(pixelRow, pixelCol, :) = sample(matchRow, matchCol, :); filled(pixelRow, pixelCol) = true; nfilled = nfilled + 1; progress = true; else nskipped = nskipped + 1; end end progressbar(nfilled,npixels); if not(exist('k')) k=1; end I = Image + (1-filled); J = Mapping/max(rows, cols) + (1-filled); clf; subplot(1,2,1); image(I); axis image; axis off; subplot(1,2,2); image(J); axis image; axis off; drawnow; imwrite(rescale(I), [outpath 'anim-' znum2str(k,3) '.png' ]); imwrite(rescale(J), [outpath 'map-' znum2str(k,3) '.png' ]); k = k+1; % disp(sprintf('Pixels filled: %d / %d', nfilled, npixels)); % % figure; % subplot(2,1,1); % imshow(filled); % subplot(2,1,2); % imshow(Image); if ~progress MaxErrThreshold = MaxErrThreshold * 1.1; disp(sprintf('Incrementing error tolerance to %d', MaxErrThreshold)); end end %% Get pixels at edge of synthesized texture function [pixelRows, pixelCols] = GetUnfilledNeighbors(filled, winsize) border = bwmorph(filled,'dilate')-filled; [pixelRows, pixelCols] = find(border); len = length(pixelRows); %randomly permute candidate pixels randIdx = randperm(len); pixelRows = pixelRows(randIdx); pixelCols = pixelCols(randIdx); %sort by number of neighbors filledSums = colfilt(filled, [winsize winsize], 'sliding', @sum); numFilledNeighbors = filledSums( sub2ind(size(filled), pixelRows, pixelCols) ); [sorted, sortIndex] = sort(numFilledNeighbors, 1, 'descend'); pixelRows = pixelRows(sortIndex); pixelCols = pixelCols(sortIndex); %% Pick a random pixel from valid patches function idx = RandomPick(matches) indices = find(matches); idx = indices(ceil(rand() * length(indices))); %% Find candidate patches that match template function [pixelList, SSD] = FindMatches (template, validMask, gaussMask, red_patches, green_patches, blue_patches) ErrThreshold = 0.3; [pixels_per_patch, npatches] = size(red_patches); totalWeight = sum(sum(gaussMask(validMask))); mask = (gaussMask .* validMask) / totalWeight; mask_vec = mask(:)'; red = reshape(template(:, :, 1), [pixels_per_patch 1]); green = reshape(template(:, :, 2), [pixels_per_patch 1]); blue = reshape(template(:, :, 3), [pixels_per_patch 1]); red_templates = repmat(red, [1 npatches]); green_templates = repmat(green, [1 npatches]); blue_templates = repmat(blue, [1 npatches]); red_dist = mask_vec * (red_templates - red_patches).^2; green_dist = mask_vec * (green_templates - green_patches).^2 ; blue_dist = mask_vec * (blue_templates - blue_patches).^2; SSD = (red_dist + green_dist + blue_dist); pixelList = SSD <= min(SSD) * (1+ErrThreshold);
github
mathematical-tours/mathematical-tours.github.io-master
spharm.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/spherical-harmonics/spharm.m
3,033
utf_8
eab2f35cc9c57041cd97499a220f93a0
% This function generates the Spherical Harmonics basis functions of degree % L and order M. % % SYNTAX: [Ymn,THETA,PHI,X,Y,Z]=spharm4(L,M,RES,PLOT_FLAG); % % INPUTS: % % L - Spherical harmonic degree, [1x1] % M - Spherical harmonic order, [1x1] % RES - Vector of # of points to use [#Theta x #Phi points],[1x2] or [2x1] % PLOT_FLAG - Binary flag to generates a figure of the spherical harmonic surfaces (DEFAULT=1) % % % OUTPUTS: % % Ymn - Spherical harmonics coordinates, [RES(1) x RES(2)] % THETA - Circumferential coordinates, [RES(1) x RES(2)] % PHI - Latitudinal coordinates, [RES(1) x RES(2)] % X,Y,Z - Cartesian coordinates of magnitude, squared, spherical harmonic surface points, [RES(1) x RES(2)] % % % NOTE: It is very important to keep the various usages of THETA and PHI % straight. For this function THETA is the Azimuthal/Longitude/Circumferential % coordinate and is defined on the interval [0,2*pi], whereas PHI is the % Altitude/Latitude/Elevation and is defined on the interval [0,pi]. Also note that % the conversion to cartesian coordinates requires that PHI be offset by pi/2 so % that the conversion is on the interval [-pi/2,pi/2]. % % DBE 2005/09/30 function [Ymn,THETA,PHI,Xm,Ym,Zm]=spharm4(L,M,RES,PLOT_FLAG); % Define constants (REQUIRED THAT L(DEGREE)>=M(ORDER)) if nargin==0 L=3; % DEGREE M=2; % ORDER RES=[55 55]; end if nargin<3 RES=[25 25]; PLOT_FLAG=1; end if nargin<4 PLOT_FLAG=1; end if L<M, error('The ORDER (M) must be less than or eqaul to the DEGREE(L).'); end THETA=linspace(0,2*pi,RES(1)); % Azimuthal/Longitude/Circumferential PHI =linspace(0, pi,RES(2)); % Altitude /Latitude /Elevation [THETA,PHI]=meshgrid(THETA,PHI); Lmn=legendre(L,cos(PHI)); if L~=0 Lmn=squeeze(Lmn(M+1,:,:)); end a1=((2*L+1)/(4*pi)); a2=factorial(L-M)/factorial(L+M); C=sqrt(a1*a2); Ymn=C*Lmn.*exp(i*M*THETA); [Xm,Ym,Zm]=sph2cart(THETA,PHI-pi/2,abs(Ymn).^2); [Xr,Yr,Zr]=sph2cart(THETA,PHI-pi/2,real(Ymn).^2); [Xi,Yi,Zi]=sph2cart(THETA,PHI-pi/2,imag(Ymn).^2); % [Xp,Yp,Zp]=sph2cart(THETA,PHI-pi/2,angle(Ymn).^2); if PLOT_FLAG f=figure; axis off; hold on; axes('position',[0.0500 0 0.2666 1]); surf(Xm,Ym,Zm); axis equal off; %rot3d; light; lighting phong; camzoom(1.3); axes('position',[0.3666 0 0.2666 1]); surf(Xr,Yr,Zr); axis equal off; %rot3d; light; lighting phong; camzoom(1.3); axes('position',[0.6833 0 0.2666 1]); surf(Xi,Yi,Zi); axis equal off; %rot3d; light; lighting phong; camzoom(1.3); axes('position',[0 0.9 1 0.1]); axis off; t(1)=text(0.50,0.25,'Spherical Harmonics','HorizontalAlignment','Center'); axes('position',[0 0 1 0.1]); axis off; t(2)=text(0.20,0.25,['|Y^',num2str(M),'_',num2str(L),'|^2'],'HorizontalAlignment','Center'); t(3)=text(0.50,0.25,['Real(Y^',num2str(M),'_',num2str(L),')^2'],'HorizontalAlignment','Center'); t(4)=text(0.80,0.25,['Imag(Y^',num2str(M),'_',num2str(L),')^2'],'HorizontalAlignment','Center'); setfig(gcf,10,5,12); end return
github
mathematical-tours/mathematical-tours.github.io-master
check_face_vertex.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/spherical-harmonics/toolbox/check_face_vertex.m
669
utf_8
c940a837f5afef7c3a7f7aed3aff9f7a
function [vertex,face] = check_face_vertex(vertex,face, options) % check_face_vertex - check that vertices and faces have the correct size % % [vertex,face] = check_face_vertex(vertex,face); % % Copyright (c) 2007 Gabriel Peyre vertex = check_size(vertex,2,4); face = check_size(face,3,4); %%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = check_size(a,vmin,vmax) if isempty(a) return; end if size(a,1)>size(a,2) a = a'; end if size(a,1)<3 && size(a,2)==3 a = a'; end if size(a,1)<=3 && size(a,2)>=3 && sum(abs(a(:,3)))==0 % for flat triangles a = a'; end if size(a,1)<vmin || size(a,1)>vmax error('face or vertex is not of correct size'); end
github
mathematical-tours/mathematical-tours.github.io-master
perform_bfgs.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/perceptron/perform_bfgs.m
58,067
utf_8
91b03f91b3bec570bfdda2f700810657
function [f, R, info] = perform_bfgs(Grad, f, options) % perform_bfgs - wrapper to HANSO code % % [f, R, info] = perform_bfgs(Grad, f, options); % % Grad should return (value, gradient) % f is an initialization % options.niter is the number of iterations. % options.bfgs_memory is the memory for the hessian bookeeping. % R is filled using options.report which takes as input (f,val). % % Copyright (c) 2011 Gabriel Peyre n = length(f); pars.nvar = n; pars.fgname = @(f,pars)Grad(f); options.x0 = f; options.nvec = getoptions(options, 'bfgs_memory', 20); % BFGS memory options.maxit = getoptions(options, 'niter', 1000); options.prtlevel = 0; options.normtol = eps; options.tol = eps; options.verb = 1; % options.report = @(x,val)struct('E', val, 'timing', cputime()-t); [f, R, energy, d, H, iter, info] = bfgs(pars,options); % % if (info == 7) % disp(['Not satisfying Wolf conditions!']) % end function [x, R, f, d, H, iter, info, X, G, w, fevalrec, xrec, Hrec] = bfgs(pars, options) %BFGS The BFGS quasi-Newton minimization algorithm, Version 2.0, 2010 % Basic call:[x, R, f, d] = bfgs(pars) % Full call: [x, R, f, d, H, iter, info, X, G, w, fevalrec, xrec, Hrec] = bfgs(pars,options) % Input parameters % pars is a required struct, with two required fields % pars.nvar: the number of variables % pars.fgname: string giving the name of function (in single quotes) % that returns the function and its gradient at a given input x, % with call [f,g] = fgtest(x,pars) if pars.fgname is 'fgtest'. % Any data required to compute the function and gradient may be % encoded in other fields of pars. % options is an optional struct, with no required fields % options.x0: each column is a starting vector of variables % (default: empty) % options.nstart: number of starting vectors, generated randomly % if needed to augment those specified in options.x0 % (default: 10 if options.x0 is not specified) % options.maxit: max number of iterations % (default 1000) (applies to each starting vector) % options.nvec: 0 for full BFGS matrix update, otherwise specifies % number of vectors to save and use in the limited memory updates % (default: 0 if pars.nvar <= 100, otherwise 10) % options.H0: % for full BFGS: initial inverse Hessian approximation % (must be positive definite, but this is not checked) % for limited memory BFGS: same, but applied every iteration % (must be sparse in this case) % (default: identity matrix, sparse in limited memory case) % options.scale: % for full BFGS: 1 to scale H0 at first iteration, 0 otherwise % for limited memory BFGS: 1 to scale H0 every time, 0 otherwise % (default: 1) % options.ngrad: number of gradients willing to save and use in % solving QP to check optimality tolerance on smallest vector in % their convex hull; see also next two options % (default: min(100, 2*pars.nvar, pars.nvar + 10) % (1 is recommended if and only if f is known to be smooth) % options.normtol: termination tolerance on d: smallest vector in % convex hull of up to options.ngrad gradients % (default: 1e-6) % options.evaldist: the gradients used in the termination test % qualify only if they are evaluated at points approximately % within distance options.evaldist of x % (default: 1e-4) % options.fvalquit: quit if f drops below this value % (default: -inf) % options.xnormquit: quit if norm(x) exceeds this value % (default: inf) % options.cpumax: quit if cpu time in secs exceeds this % (default: inf) (applies to total running time) % options.strongwolfe: 0 for weak Wolfe line search (default) % 1 for strong Wolfe line search % (strong Wolfe line search is not recommended for use with % BFGS; it is very complicated and bad if f is nonsmooth; % however, it can be useful to simulate an exact line search) % options.wolfe1: first Wolfe line search parameter % (ensuring sufficient decrease in function value, default: 0) % (should be > 0 in theory, but 0 is fine in practice) % options.wolfe2: second Wolfe line search parameter % (ensuring algebraic increase (weak) or absolute decrease (strong) % in projected gradient, default: 0.5) % (important in theory and practice that this is not 0 or 1, % except that it can be set to 0 if an exact line search is to be % simulated, using options.strongwolfe = 1) % options.quitLSfail: 1 if quit when line search fails, 0 otherwise % (default: 1, except if options.strongwolfe = 1 and % options.wolfe2 = 0, simulating exact line search) % (0 is potentially useful if f is not numerically continuous) % options.prtlevel: one of 0 (no printing), 1 (minimal), 2 (verbose) % (default: 1) % % Output parameters: % all return information on the runs for each starting vector % x: the final iterates % f: the final function values % d: the final smallest vectors in the convex hull of the saved gradients % at termination (the final gradient if options.ngrad == 1) % H: final BFGS inverse Hessian approximation matrices % (full BFGS update only, symmetrized so they are exactly symmetric) % (nan if limited memory updates were used) % iter: number of iterations % info: reason for termination: % 0: tolerance on smallest vector in convex hull of saved gradients met % 1: max number of iterations reached % 2: f reached target value % 3: norm(x) exceeded limit % 4: cpu time exceeded limit % 5: f is inf or nan at initial point % 6: direction not a descent direction due to rounding error % 7: line search bracketed minimizer but Wolfe conditions not satisfied % 8: line search did not bracket minimizer: f may be unbounded below % X: iterates where saved gradients were evaluated (see below) % G: saved gradients used for computation of smallest vector in convex hull % of gradients at points near final x % w: weights giving the smallest vector in the convex hull of the saved % gradients % fevalrec: record of all function values evaluated in all line searches, % including the final accepted values (nans if options.strongwolfe = 1) % xrec: record of all x iterates % Hrec: record of all H iterates % (not symmetrized, may not be symmetric because of rounding error) % Note: if there is more than one starting vector, then: % f, iter, info are vectors of length options.nstart % x, d are matrices of size pars.nvar by options.nstart % H, X, G, w, xrec, Hrec are cell arrays of length options.nstart, and % fevalrec is a cell array of cell arrays % Thus, for example, d(:,i) = G{i}*w{i}, for i = 1,...,options.nstart % % BFGS is normally used for optimizing smooth, not necessarily convex, % functions, for which the convergence rate is generically superlinear. % But it also works very well for functions that are nonsmooth at their % minimizers, typically with a linear convergence rate and a final % inverse Hessian approximation that is very ill conditioned, as long % as a weak Wolfe line search is used. This version of BFGS will work % well both for smooth and nonsmooth functions and has a stopping % criterion that applies for both cases, described above. % See A.S. Lewis and M.L. Overton, Nonsmooth Optimization via BFGS, 2008. % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso" or "bfgs". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % parameter defaults if nargin == 0 error('bfgs: "pars" is a required input parameter') end if nargin == 1 options = []; end options = setdefaults(pars, options); % set most default options options = setx0(pars, options); % augment options.x0 randomly x0 = options.x0; nstart = size(x0,2); cpufinish = cputime + options.cpumax; fvalquit = options.fvalquit; xnormquit = options.xnormquit; prtlevel = options.prtlevel; % set other options options = setdefaultsbfgs(pars, options); for run = 1:nstart if prtlevel > 0 & nstart > 1 fprintf('bfgs: starting point %d\n', run) end options.cpumax = cpufinish - cputime; % time left if nargout > 10 [x(:,run), R, f(run), d(:,run), HH, iter(run), info(run), X{run}, G{run}, w{run}, ... fevalrec{run}, xrec{run}, Hrec{run}] = bfgs1run(x0(:,run), pars, options); elseif nargout > 7 % avoid computing fevalrec, xrec, Hrec which are expensive as they grow inside the main loop [x(:,run), R, f(run), d(:,run), HH, iter(run), info(run), X{run}, G{run}, w{run}] = bfgs1run(x0(:,run), pars, options); else % avoid computing unnecessary cell arrays [x(:,run), R, f(run), d(:,run), HH, iter(run), info(run)] = bfgs1run(x0(:,run), pars, options); end % make exactly symmetric (too expensive to do inside optimization loop} H{run} = (HH + HH')/2; if cputime > cpufinish | f < fvalquit | norm(x) > xnormquit break end end if nstart == 1 % no point returning cell arrays of length 1 H = H{1}; if nargout > 10 fevalrec = fevalrec{1}; xrec = xrec{1}; Hrec = Hrec{1}; % don't symmetrize end if nargout > 7 X = X{1}; G = G{1}; w = w{1}; end end function [x, R, f, d, H, iter, info, X, G, w, fevalrec, xrec, Hrec] = bfgs1run(x0, pars, options) % Version 2.0, 2010 % make a single run of BFGS from one starting point % intended to be called by bfgs.m % outputs: % x: final iterate % f: final function value % d: final smallest vector in convex hull of saved gradients % H: final inverse Hessian approximation % iter: number of iterations % info: reason for termination % 0: tolerance on smallest vector in convex hull of saved gradients met % 1: max number of iterations reached % 2: f reached target value % 3: norm(x) exceeded limit % 4: cpu time exceeded limit % 5: f or g is inf or nan at initial point % 6: direction not a descent direction (because of rounding) % 7: line search bracketed minimizer but Wolfe conditions not satisfied % 8: line search did not bracket minimizer: f may be unbounded below % X: iterates where saved gradients were evaluated % G: gradients evaluated at these points % w: weights defining convex combination d = G*w % fevalrec: record of all function evaluations in the line searches % xrec: record of x iterates % Hrec: record of H iterates % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso" or "bfgs". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% n = pars.nvar; fgname = pars.fgname; normtol = options.normtol; fvalquit = options.fvalquit; xnormquit = options.xnormquit; cpufinish = cputime + options.cpumax; maxit = options.maxit; nvec = options.nvec; prtlevel = options.prtlevel; strongwolfe = options.strongwolfe; wolfe1 = options.wolfe1; wolfe2 = options.wolfe2; quitLSfail = options.quitLSfail; ngrad = options.ngrad; evaldist = options.evaldist; verb = getoptions(options, 'verb', 1); report = getoptions(options, 'report', @(x,v)v); H0 = options.H0; H = H0; % sparse for limited memory BFGS scale = options.scale; x = x0; if isstr(fgname) [f,g] = feval(fgname, x, pars); else [f,g] = fgname(x, pars); end d = g; G = g; X = x; nG = 1; w = 1; dnorm = norm(g); if nvec > 0 % limited memory BFGS S = []; Y = []; end iter = 0; if nargout > 9 % so outputs defined if quit immediately fevalrec{1} = nan; % cell array xrec = nan*ones(n,1); % not cell array Hrec{1} = nan; % cell array end if isnaninf(f) % better not to generate an error return if prtlevel > 0 fprintf('bfgs: f is infinite or nan at initial iterate\n') end info = 5; return elseif isnaninf(g) if prtlevel > 0 fprintf('bfgs: gradient is infinite or nan at initial iterate\n') end info = 5; return elseif dnorm < normtol if prtlevel > 0 fprintf('bfgs: tolerance on gradient satisfied at initial iterate\n') end info = 0; return elseif f < fvalquit if prtlevel > 0 fprintf('bfgs: below target objective at initial iterate\n') end info = 2; return elseif norm(x) > xnormquit if prtlevel > 0 keyboard fprintf('bfgs: norm(x) exceeds specified limit at initial iterate\n') end info = 3; return end clear R; for iter = 1:maxit if verb progressbar(iter,maxit); end R(iter) = report(x,f); if nvec == 0 % full BFGS p = -H*g; else % limited memory BFGS p = -hgprod(H, g, S, Y); % not H0, as in previous version end gtp = g'*p; if gtp >= 0 | isnan(gtp) % in rare cases, H could contain nans if prtlevel > 0 fprintf('bfgs: not descent direction, quit at iteration %d, f = %g, dnorm = %5.1e\n',... iter, f, dnorm) end info = 6; return end gprev = g; % for BFGS update if strongwolfe % strong Wolfe line search is not recommended % except to simulate an exact line search % function values are not returned, so set fevalrecline to nan fevalrecline = nan; [alpha, x, f, g, fail] = ... linesch_sw(x, f, g, p, pars, wolfe1, wolfe2, fvalquit, prtlevel); if wolfe2 == 0 % exact line search: increase alpha slightly to get % to other side of any discontinuity in nonsmooth case increase = 1e-8*(1 + alpha); % positive if alpha = 0 x = x + increase*p; if prtlevel > 1 fprintf(' exact line sch simulation: slightly increasing step from %g to %g\n', alpha, alpha + increase) end [f,g] = feval(pars.fgname, x, pars); end else % weak Wolfe line search is the default [alpha, x, f, g, fail, notused, notused2, fevalrecline] = ... linesch_ww(x, f, g, p, pars, wolfe1, wolfe2, fvalquit, prtlevel); end % for the optimality check: % discard the saved gradients iff the new point x is not sufficiently % close to the previous point and replace them by new gradient if alpha*norm(p) > evaldist nG = 1; G = g; X = x; % otherwise add new gradient to set of saved gradients, % discarding oldest if already have ngrad saved gradients elseif nG < ngrad nG = nG + 1; G = [g G]; X = [x X]; else % nG = ngrad G = [g G(:,1:ngrad-1)]; X = [x X(:,1:ngrad-1)]; end % optimality check: compute smallest vector in convex hull of qualifying % gradients: reduces to norm of latest gradient if ngrad == 1, and the % set must always have at least one gradient: could gain efficiency % here by updating previous QP solution if nG > 1 [w,d] = qpspecial(G); % Anders Skajaa code for this special QP else w = 1; d = g; end dnorm = norm(d); if nargout > 9 xrec(:,iter) = x; fevalrec{iter} = fevalrecline; % function vals computed in line search Hrec{iter} = H; end if prtlevel > 1 nfeval = length(fevalrecline); fprintf('bfgs: iter %d: nfevals = %d, step = %5.1e, f = %g, nG = %d, dnorm = %5.1e\n', ... iter, nfeval, alpha, f, nG, dnorm) end if f < fvalquit % this is checked inside the line search if prtlevel > 0 fprintf('bfgs: reached target objective, quit at iteration %d \n', iter) end info = 2; return elseif norm(x) > xnormquit % this is not checked inside the line search if prtlevel > 0 fprintf('bfgs: norm(x) exceeds specified limit, quit at iteration %d \n', iter) end info = 3; return end if fail == 1 % line search failed (Wolfe conditions not both satisfied) if ~quitLSfail if prtlevel > 1 fprintf('bfgs: continue although line search failed\n') end else % quit since line search failed if prtlevel > 0 fprintf('bfgs: quit at iteration %d, f = %g, dnorm = %5.1e\n', iter, f, dnorm) end info = 7; return end elseif fail == -1 % function apparently unbounded below if prtlevel > 0 fprintf('bfgs: f may be unbounded below, quit at iteration %d, f = %g\n', iter, f) end info = 8; return end if dnorm <= normtol if prtlevel > 0 if nG == 1 fprintf('bfgs: gradient norm below tolerance, quit at iteration %d, f = %g\n', iter, f') else fprintf('bfgs: norm of smallest vector in convex hull of gradients below tolerance, quit at iteration %d, f = %g\n', iter, f') end end info = 0; return end if cputime > cpufinish if prtlevel > 0 fprintf('bfgs: cpu time limit exceeded, quit at iteration %d\n', iter) end info = 4; return end s = alpha*p; y = g - gprev; sty = s'*y; % successful line search ensures this is positive if nvec == 0 % perform rank two BFGS update to the inverse Hessian H if sty > 0 if iter == 1 & scale % for full BFGS, Nocedal and Wright recommend scaling I before % the first update only H = (sty/(y'*y))*H; end % for formula, see Nocedal and Wright's book rho = 1/sty; rhoHyst = rho*(H*y)*s'; % M = I - rho*s*y'; H = H - rhoHyst' - rhoHyst + rho*s*(y'*rhoHyst) + rho*s*s'; % H = M*H*M' + rho*s*s'; else % should not happen unless line search fails, and in that case should normally have quit if prtlevel > 1 fprintf('bfgs: sty <= 0, skipping BFGS update at iteration %d \n', iter) end end else % save s and y vectors for limited memory update s = alpha*p; y = g - gprev; if iter <= nvec S = [S s]; Y = [Y y]; else % could be more efficient here by avoiding moving the columns S = [S(:,2:nvec) s]; Y = [Y(:,2:nvec) y]; end if scale H = ((s'*y)/(y'*y))*H0; % recommended by Nocedal-Wright end end end % for loop if prtlevel > 0 fprintf('bfgs: %d iterations reached, f = %g, dnorm = %5.1e\n', maxit, f, dnorm) end info = 1; % quit since max iterations reached function [xbundle, gbundle] = getbundle(x, g, samprad, N, pars); % get bundle of N-1 gradients at points near x, in addition to g, % which is gradient at x and goes in first column % intended to be called by gradsampfixed % % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso" or "gradsamp". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% m = length(x); xbundle(:,1) = x; gbundle(:,1) = g; for k = 2:N % note the 2 xpert = x + samprad*(rand(m,1) - 0.5); % uniform distribution [f,grad] = feval(pars.fgname, xpert, pars); count = 0; while isnaninf(f) | isnaninf(grad) % in particular, disallow infinite function values xpert = (x + xpert)/2; % contract back until feasible [f,grad] = feval(pars.fgname, xpert, pars); count = count + 1; if count > 100 % should never happen, but just in case error('too many contractions needed to find finite f and grad values') end end; % discard function values xbundle(:,k) = xpert; gbundle(:,k) = grad; end function options = setdefaults(pars,options) % call: options = setdefaults(pars,options) % check that fields of pars and options are set correctly and % set basic default values for options that are common to various % optimization methods, including bfgs and gradsamp % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso" or "bfgs". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 2 options = []; end if ~isfield(pars, 'nvar') error('setdefaults: input "pars" must have a field "nvar" (number of variables)') elseif ~isposint(pars.nvar) error('setdefaults: input "pars.nvar" (number of variables) must be a positive integer') end if ~isfield(pars, 'fgname') error('setdefaults: input "pars" must have a field "fgname" (name of m-file computing function and gradient)') end if isfield(options, 'maxit') if ~isnonnegint(options.maxit) error('setdefaults: input "options.maxit" must be a nonnegative integer') end else options.maxit = 1000; end if isfield(options, 'normtol') if ~isposreal(options.normtol) error('setdefaults: input "options.normtol" must be a positive real scalar') end else options.normtol = 1.0e-6; end if isfield(options, 'fvalquit') if ~isreal(options.fvalquit)|~isscalar(options.fvalquit) error('setdefaults: input "options.fvalquit" must be a real scalar') end else options.fvalquit = -inf; end if isfield(options, 'xnormquit') if ~isreal(options.xnormquit)|~isscalar(options.xnormquit) error('setdefaults: input "options.fvalquit" must be a real scalar') end else options.xnormquit = inf; end if ~isfield(options, 'cpumax') options.cpumax = inf; end if ~isfield(options, 'prtlevel') options.prtlevel = 1; end function ipi = isposint(x) % return true if x is a positive integer, false otherwise % % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isscalar(x) ipi = 0; else % following is OK since x is scalar ipi = isreal(x) & round(x) == x & x > 0; end function inni = isnonnegint(x) % return true if x is a nonnegative integer, false otherwise % % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isscalar(x) inni = 0; else % following is OK since x is scalar inni = (isreal(x) & round(x) == x & x >= 0); end function ipr = isposreal(x) % return true if x is a positive real scalar, false otherwise % % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isscalar(x) ipr = 0; else % following is OK since x is scalar ipr = isreal(x) & x > 0; end function options = setx0(pars,options) % set columns of options.x0 randomly if not provided by user % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso" or "bfgs". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nvar = pars.nvar; if ~isfield(options, 'x0') options.x0 = []; end if isempty(options.x0) if isfield(options, 'nstart') if ~isposint(options.nstart) error('setx0: input "options.nstart" must be a positive integer when "options.x0" is not provided') else options.x0 = randn(nvar, options.nstart); end else options.x0 = randn(nvar, 10); end else if size(options.x0,1) ~= nvar error('setx0: input "options.x0" must have "pars.nvar" rows') end if isfield(options, 'nstart') if ~isnonnegint(options.nstart) error('setx0: input "options.nstart" must be a nonnegative integer') elseif options.nstart < size(options.x0,2) error('setx0: "options.nstart" is less than number of columns of "options.x0"') else % augment vectors in options.x0 with randomly generated ones nrand = options.nstart - size(options.x0,2); options.x0 = [options.x0 randn(nvar, nrand)]; end end % no else part, options.x0 is as provided end function options = setdefaultsbfgs(pars, options) % set defaults for BFGS (in addition to those already set by setdefaults) % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso" or "bfgs". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % line search options if isfield(options, 'strongwolfe') if options.strongwolfe ~= 0 & options.strongwolfe ~= 1 error('setdefaultsbfgs: input "options.strongwolfe" must be 0 or 1') end else % strong Wolfe is very complicated and is bad for nonsmooth functions options.strongwolfe = 0; end if isfield(options, 'wolfe1') % conventionally anything in (0,1), but 0 is OK while close to 1 is not if ~isreal(options.wolfe1) | options.wolfe1 < 0 | options.wolfe1 > 0.5 error('setdefaultsbfgs: input "options.wolfe1" must be between 0 and 0.5') end else options.wolfe1 = 1e-4; % conventionally this should be positive, and although % zero is usually fine in practice, there are exceptions end if isfield(options, 'wolfe2') % conventionally should be > wolfe1, but both 0 OK for e.g. Shor if ~isreal(options.wolfe2) | options.wolfe2 < options.wolfe1 | options.wolfe2 >= 1 error('setdefaultsbfgs: input "options.wolfe2" must be between max(0,options.wolfe1) and 1') end else options.wolfe2 = 0.5; % 0 and 1 are both bad choices end if options.strongwolfe if options.prtlevel > 0 if options.wolfe2 > 0 fprintf('setdefaultsbfgs: strong Wolfe line search selected, but weak Wolfe is usually preferable\n') fprintf('(especially if f is nonsmooth)\n') else fprintf('setdefaultsbfgs: simulating exact line search\n') end end if ~exist('linesch_sw') error('"linesch_sw" is not in path: it can be obtained from the NLCG distribution') end else if ~exist('linesch_ww') error('"linesch_ww" is not in path: it is required for weak Wolfe line search') end end if isfield(options, 'quitLSfail') if options.quitLSfail ~= 0 & options.quitLSfail ~= 1 error('setdefaultsbfgs: input "options.quitLSfail" must be 0 or 1') end else if options.strongwolfe == 1 & options.wolfe2 == 0 % simulated exact line search, so don't quit if it fails options.quitLSfail = 0; else % quit if line search fails options.quitLSfail = 1; end end % other default options n = pars.nvar; if isfield(options, 'nvec') if ~isnonnegint(options.nvec) error('setdefaultsbfgs: input "options.nvec" must be a nonnegative integer') end elseif n <= 100 options.nvec = 0; % full BFGS else options.nvec = 10; % limited memory BFGS end if isfield(options,'H0') % H0 should be positive definite but too expensive to check if any(size(options.H0) ~= [n n]) error('bfgs: input options.H0 must be matrix with order pars.nvar') end if options.nvec > 0 & ~issparse(options.H0) error('bfgs: input "options.H0" must be a sparse matrix when "options.nvec" is positive') end else if options.nvec == 0 options.H0 = eye(n); % identity for full BFGS else options.H0 = speye(n); % sparse identity for limited memory BFGS end end if isfield(options, 'scale') if options.scale ~= 0 & options.scale ~= 1 error('setdefaultsbfgs: input "options.scale" must be 0 or 1') end else options.scale = 1; end % note: if f is smooth, superlinear convergence will ensure that termination % takes place before too many gradients are used in the QP optimality check % so the optimality check will not be expensive in the smooth case if isfield(options,'ngrad') if ~isnonnegint(options.ngrad) error('setdefaultsbfgs: input "options.ngrad" must be a nonnegative integer') end else % note this could be more than options.nvec % rationale: it is only towards the end that we start accumulating % many gradients, and then they may be needed to veryify optimality options.ngrad = min([100, 2*pars.nvar, pars.nvar + 10]); end if isfield(options,'evaldist') if ~isposreal(options.ngrad) error('setdefaultsbfgs: input "options.evaldist" must be a positive real scalar') end else options.evaldist = 1e-4; end function [alpha, xalpha, falpha, gradalpha, fail, beta, gradbeta, fevalrec] = ... linesch_ww(x0, f0, grad0, d, pars, c1, c2, fvalquit, prtlevel) % LINESCH_WW Line search enforcing weak Wolfe conditions, suitable % for minimizing both smooth and nonsmooth functions % Version 2.0 for HANSO 2.0 % call: [alpha, xalpha, falpha, gradalpha, fail, beta, gradbeta, fevalrec] = ... % linesch_ww_mod(x0, f0, grad0, d, pars, c1, c2, fvalquit, prtlevel); % Input % x0: intial point % f0: function value at x0 % grad0: gradient at x0 % d: search direction % pars: a structure that specifies the function name as well % anything else that the user needs to access in programming the % function and gradient values % pars.fgname: name of function that returns function and gradient % it expects as input only x and pars, a parameter structure % it is invoked by: [f,g] = feval(fgname, x, pars) % c1: Wolfe parameter for the sufficient decrease condition % f(x0 + t d) ** < ** f0 + c1*t*grad0'*d (DEFAULT 0) % c2: Wolfe parameter for the WEAK condition on directional derivative % (grad f)(x0 + t d)'*d ** > ** c2*grad0'*d (DEFAULT 0.5) % where 0 <= c1 <= c2 <= 1. % For usual convergence theory for smooth functions, normally one % requires 0 < c1 < c2 < 1, but c1=0 is fine in practice. % May want c1 = c2 = 0 for some nonsmooth optimization % algorithms such as Shor or bundle, but not BFGS. % Setting c2=0 may interfere with superlinear convergence of % BFGS in smooth case. % fvalquit: quit immediately if f drops below this value, regardless % of the Wolfe conditions (default -inf) % prtlevel: 0 for no printing, 1 minimal (default), 2 verbose % % Output: % alpha: steplength satisfying weak Wolfe conditions if one was found, % otherwise left end point of interval bracketing such a point % (possibly 0) % xalpha: x0 + alpha*d % falpha: f(x0 + alpha d) % gradalpha:(grad f)(x0 + alpha d) % fail: 0 if both Wolfe conditions satisfied, or falpha < fvalquit % 1 if one or both Wolfe conditions not satisfied but an % interval was found bracketing a point where both satisfied % -1 if no such interval was found, function may be unbounded below % beta: same as alpha if it satisfies weak Wolfe conditions, % otherwise right end point of interval bracketing such a point % (inf if no such finite interval found) % gradbeta: (grad f)(x0 + beta d) (this is important for bundle methods) % (vector of nans if beta is inf) % % fevalrec: record of function evaluations % The weak Wolfe line search is far less complicated that the standard % strong Wolfe line search that is discussed in many texts. It appears % to have no disadvantages compared to strong Wolfe when used with % Newton or BFGS methods on smooth functions, and it is essential for % the application of BFGS or bundle to nonsmooth functions as done in HANSO. % However, it is NOT recommended for use with conjugate gradient methods, % which require a strong Wolfe line search for convergence guarantees. % Weak Wolfe requires two conditions to be satisfied: sufficient decrease % in the objective, and sufficient increase in the directional derivative % (not reduction in its absolute value, as required by strong Wolfe). % % There are some subtleties for nonsmooth functions. In the typical case % that the directional derivative changes sign somewhere along d, it is % no problem to satisfy the 2nd condition, but descent may not be possible % if the change of sign takes place even when the step is tiny. In this % case it is important to return the gradient corresponding to the positive % directional derivative even though descent was not obtained. On the other % hand, for some nonsmooth functions the function decrease is steady % along the line until at some point it jumps to infinity, because an % implicit constraint is violated. In this case, the first condition is % satisfied but the second is not. All cases are covered by returning % the end points of an interval [alpha, beta] and returning the function % value at alpha, but the gradients at both alpha and beta. % % The assertion that [alpha,beta] brackets a point satisfying the % weak Wolfe conditions depends on an assumption that the function % f(x + td) is a continuous and piecewise continuously differentiable % function of t, and that in the unlikely event that f is evaluated at % a point of discontinuity of the derivative, g'*d, where g is the % computed gradient, is either the left or right derivative at the point % of discontinuity, or something in between these two values. % % For functions that are known to be nonsmooth, setting the second Wolfe % parameter to zero makes sense, especially for a bundle method, and for % the Shor R-algorithm, for which it is essential. However, it's not % a good idea for BFGS, as for smooth functions this may prevent superlinear % convergence, and it can even make trouble for BFGS on, e.g., % f(x) = x_1^2 + eps |x_2|, when eps is small. % % Line search quits immediately if f drops below fvalquit. % % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso" or "bfgs". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if nargin < 6 % check if the optional Wolfe parameters were passed c1 = 0; % not conventional, but seems OK. See note at top. end if nargin < 7 c2 = 0.5; % see note at top end if nargin < 8 fvalquit = -inf; end if nargin < 9 prtlevel = 1; end if (c1 < 0 | c1 > c2 | c2 > 1) & prtlevel > 0 % allows c1 = 0, c2 = 0 and c2 = 1 fprintf('linesch_ww_mod: Wolfe parameters do not satisfy 0 <= c1 <= c2 <= 1\n') end fgname = pars.fgname; alpha = 0; % lower bound on steplength conditions xalpha = x0; falpha = f0; gradalpha = grad0; % need to pass grad0, not grad0'*d, in case line search fails beta = inf; % upper bound on steplength satisfying weak Wolfe conditions gradbeta = nan*ones(size(x0)); g0 = grad0'*d; if g0 >= 0 % error('linesch_ww_mod: g0 is nonnegative, indicating d not a descent direction') fprintf('linesch_ww_mod: WARNING, not a descent direction\n') end dnorm = norm(d); if dnorm == 0 error('linesch_ww_mod: d is zero') end t = 1; % important to try steplength one first nfeval = 0; nbisect = 0; nexpand = 0; % the following limits are rather arbitrary % nbisectmax = 30; % 50 is TOO BIG, because of rounding errors nbisectmax = max(30, round(log2(1e5*dnorm))); % allows more if ||d|| big nexpandmax = max(10, round(log2(1e5/dnorm))); % allows more if ||d|| small done = 0; while ~done x = x0 + t*d; nfeval = nfeval + 1; [f,grad] = feval(fgname, x, pars); fevalrec(nfeval) = f; if f < fvalquit % nothing more to do, quit fail = 0; alpha = t; % normally beta is inf xalpha = x; falpha = f; gradalpha = grad; return end gtd = grad'*d; % the first condition must be checked first. NOTE THE >=. if f >= f0 + c1*t*g0 | isnan(f) % first condition violated, gone too far beta = t; gradbeta = grad; % discard f % now the second condition. NOTE THE <= elseif gtd <= c2*g0 | isnan(gtd) % second condition violated, not gone far enough alpha = t; xalpha = x; falpha = f; gradalpha = grad; else % quit, both conditions are satisfied fail = 0; alpha = t; xalpha = x; falpha = f; gradalpha = grad; beta = t; gradbeta = grad; return end % setup next function evaluation if beta < inf if nbisect < nbisectmax nbisect = nbisect + 1; t = (alpha + beta)/2; % bisection else done = 1; end else if nexpand < nexpandmax nexpand = nexpand + 1; t = 2*alpha; % still in expansion mode else done = 1; end end end % loop % Wolfe conditions not satisfied: there are two cases if beta == inf % minimizer never bracketed fail = -1; if prtlevel > 1 fprintf('Line search failed to bracket point satisfying weak '); fprintf('Wolfe conditions, function may be unbounded below\n') end else % point satisfying Wolfe conditions was bracketed fail = 1; if prtlevel > 1 fprintf('Line search failed to satisfy weak Wolfe conditions') fprintf(' although point satisfying conditions was bracketed\n') end end function ini = isnaninf(M) % returns the scalar 1 if ANY entry of M is nan or inf; 0 otherwise % note: isnan and isinf return matrices if M is a matrix, and % if treats [0 1] as false, not true. % ini = sum(sum(isnan(M))) > 0 | sum(sum(isinf(M))) > 0; ini = any(any(isnan(M))) | any(any(isinf(M))); % % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function r = hgprod(H0, g, S, Y) % compute the product required by the LM-BFGS method % see Nocedal and Wright % Send comments/bug reports to Michael Overton, [email protected], % with a subject header containing the string "hanso" or "gradsamp". % Version 2.0, 2010, see GPL license info below. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Michael Overton %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% N = size(S,2); % number of saved vector pairs (s,y) q = g; for i = N:-1:1 s = S(:,i); y = Y(:,i); rho(i) = 1/(s'*y); alpha(i) = rho(i)*(s'*q); q = q - alpha(i)*y; end r = H0*q; for i=1:N s = S(:,i); y = Y(:,i); beta = rho(i)*(y'*r); r = r + (alpha(i)-beta)*s; end function [x,d,q,info] = qpspecial(G,varargin) % Call: % [x,d,q,info] = qpspecial(G,varargin) % % Solves the QP % % min q(x) = || G*x ||_2^2 = x'*(G'*G)*x % s.t. sum(x) = 1 % x >= 0 % % The problem corresponds to finding the smallest vector % (2-norm) in the convex hull of the columns of G % % Inputs: % G -- (M x n double) matrix G, see problem above % varargin{1} -- (int) maximum number of iterates allowed % If not present, maxit = 100 is used % varargin{2} -- (n x 1 double) vector x0 with initial (FEASIBLE) iterate. % If not present, (or requirements on x0 not met) a % useable default x0 will be used % % Outputs: % x -- Optimal point attaining optimal value % d = G*x -- Smallest vector in the convex hull % q -- Optimal value found = d'*d % info -- Run data: % info(1) = % 0 = everything went well, q is optimal % 1 = maxit reached and final x is feasible. so q % might not be optimal, but it is better than q(x0) % 2 = something went wrong % info(2) = #iterations used % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% HANSO 2.0 Copyright (C) 2010 Anders Skajaa %% This program is free software: you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published by %% the Free Software Foundation, either version 3 of the License, or %% (at your option) any later version. %% %% This program is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public License %% along with this program. If not, see <http://www.gnu.org/licenses/>. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% echo = 0; % set echo = 1 for printing % (for debugging). Otherwise 0. % [m,n] = size(G); % size of problem if ~(m*n>0) % in this case fprintf(['qpspecial:',... % G is empty, so nothing we can do ' G is empty.\n']); % exit with warning info = [2,0]; % info(1) = 2; x = []; d = []; q = inf; % and empty structs return; % and optimal value is inf end % % e = ones(n,1); % vector of ones % if nargin > 1 % set defauls maxit = varargin{1}; % maximal # iterations maxit = ceil(maxit); % in case of a non-integer input maxit = max(maxit,5); % always allow at least 5 iterations else % maxit = 100; % default is 100 end % which is always plenty if nargin > 2 % x = varargin{2}; % if x0 is specified x = x(:); % if given as row instead of col nx = size(x,1); % check that size is right if any(x<0) || nx~=n % use it, unless it is x = e; % infeasible in the ineq end % constraints. else % use it, otherwise x = e; % use (1,1,...,1) end % which is an interior point % idx = (1:(n+1):(n^2))'; % needed many times Q = G'*G; % Hessian in QP z = x; % intialize z y = 0; % intialize y eta = 0.9995; % step size dampening delta = 3; % for the sigma heuristic mu0 = (x'*z) / n; % first my tolmu = 1e-5; % relative stopping tolerance, mu tolrs = 1e-5; % and residual norm kmu = tolmu*mu0; % constant for stopping, mu nQ = norm(Q,inf)+2; % norm of [Q,I,e] krs = tolrs*nQ; % constant for stopping, residuals ap = 0; ad = 0; % init steps just for printing if echo > 0 % print first line fprintf(['k mu ',... % ' stpsz res\n',... % '-----------------',... % '-----------------\n']); % end % % for k = 1:maxit % % r1 = -Q*x + e*y + z; % residual r2 = -1 + sum(x); % residual r3 = -x.*z; % slacks rs = norm([r1;r2],inf); % residual norm mu = -sum(r3)/n; % current mu % % printing (for debugging) if echo > 0 fprintf('%-3.1i %9.2e %9.2e %9.2e \n',... k,mu/mu0,max(ap,ad),rs/nQ); end % stopping if mu < kmu % mu must be small if rs < krs % primal feas res must be small info = [0,k-1]; % in this case, all went well break; % so exit with info = 0 end % so exit loop end % % zdx = z./x; % factorization QD = Q; % QD(idx) = QD(idx) + zdx; % [C,ef] = chol(QD); % C'*C = QD if ef > 0 % safety to catch possible info = [2,k]; % problems in the choleschy break; % in this case, end % break with info = 2 KT = C'\e; % K' = (C')^(-1) * e M = KT'*KT; % M = K*K' % r4 = r1+r3./x; % compute approx r5 = KT'*(C'\r4); % tangent direction r6 = r2+r5; % using factorization dy = -r6/M; % from above r7 = r4 + e*dy; % dx = C\(C'\r7); % dz = (r3 - z.*dx)./x; % % p = -x ./ dx; % Determine maximal step ap = min(min(p(p>0)),1); % possible in the if isempty(ap) % approx tangent direction ap = 1; % here primal step size end % p = -z ./ dz; % here dual step size ad = min(min(p(p>0)),1); % if isempty(ad) % using different step sizes ad = 1; % in primal and dual improves end % performance a bit % muaff = ((x + ap*dx)'*... % heuristic for (z + ad*dz))/n; % the centering parameter sig = (muaff/mu)^delta; % % r3 = r3 + sig*mu; % compute the new corrected r3 = r3 - dx.*dz; % search direction that now r4 = r1+r3./x; % includes the appropriate r5 = KT'*(C'\r4); % amount of centering and r6 = r2+r5; % mehrotras second order dy = -r6/M; % correction term (see r3). r7 = r4 + e*dy; % we of course reuse the dx = C\(C'\r7); % factorization from above dz = (r3 - z.*dx)./x; % % p = -x ./ dx; % Determine maximal step ap = min(min(p(p>0)),1); % possible in the if isempty(ap) % new direction ap = 1; % here primal step size end % p = -z ./ dz; % here dual step size ad = min(min(p(p>0)),1); % if isempty(ad) % ad = 1; % end % % update variables x = x + eta * ap * dx; % primal y = y + eta * ad * dy; % dual multipliers z = z + eta * ad * dz; % dual slacks % end % end main loop % if k == maxit % if reached maxit info = [1,k]; % set info(1) = 1 end % x = max(x,0); % project x onto R+ x = x/sum(x); % so that sum(x) = 1 exactly d = G*x; % and set other output q = d'*d; % variables using best % found x % if echo > 0 % printing str = 'optimal'; % status string to print if info(1)==1 % in the last line str = 'maxit reached';% elseif info(1)==2 % str = 'failed'; % end % fprintf(['---------',... % print last line '-------------------',... % '------\n',... % ' result: %s \n',... % '-------------------',... % '---------------\n'],str);% end %
github
mathematical-tours/mathematical-tours.github.io-master
distinguishable_colors.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/pocs/toolbox/distinguishable_colors.m
5,753
utf_8
57960cf5d13cead2f1e291d1288bccb2
function colors = distinguishable_colors(n_colors,bg,func) % DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct % % When plotting a set of lines, you may want to distinguish them by color. % By default, Matlab chooses a small set of colors and cycles among them, % and so if you have more than a few lines there will be confusion about % which line is which. To fix this problem, one would want to be able to % pick a much larger set of distinct colors, where the number of colors % equals or exceeds the number of lines you want to plot. Because our % ability to distinguish among colors has limits, one should choose these % colors to be "maximally perceptually distinguishable." % % This function generates a set of colors which are distinguishable % by reference to the "Lab" color space, which more closely matches % human color perception than RGB. Given an initial large list of possible % colors, it iteratively chooses the entry in the list that is farthest (in % Lab space) from all previously-chosen entries. While this "greedy" % algorithm does not yield a global maximum, it is simple and efficient. % Moreover, the sequence of colors is consistent no matter how many you % request, which facilitates the users' ability to learn the color order % and avoids major changes in the appearance of plots when adding or % removing lines. % % Syntax: % colors = distinguishable_colors(n_colors) % Specify the number of colors you want as a scalar, n_colors. This will % generate an n_colors-by-3 matrix, each row representing an RGB % color triple. If you don't precisely know how many you will need in % advance, there is no harm (other than execution time) in specifying % slightly more than you think you will need. % % colors = distinguishable_colors(n_colors,bg) % This syntax allows you to specify the background color, to make sure that % your colors are also distinguishable from the background. Default value % is white. bg may be specified as an RGB triple or as one of the standard % "ColorSpec" strings. You can even specify multiple colors: % bg = {'w','k'} % or % bg = [1 1 1; 0 0 0] % will only produce colors that are distinguishable from both white and % black. % % colors = distinguishable_colors(n_colors,bg,rgb2labfunc) % By default, distinguishable_colors uses the image processing toolbox's % color conversion functions makecform and applycform. Alternatively, you % can supply your own color conversion function. % % Example: % c = distinguishable_colors(25); % figure % image(reshape(c,[1 size(c)])) % % Example using the file exchange's 'colorspace': % func = @(x) colorspace('RGB->Lab',x); % c = distinguishable_colors(25,'w',func); % Copyright 2010-2011 by Timothy E. Holy % Parse the inputs if (nargin < 2) bg = [1 1 1]; % default white background else if iscell(bg) % User specified a list of colors as a cell aray bgc = bg; for i = 1:length(bgc) bgc{i} = parsecolor(bgc{i}); end bg = cat(1,bgc{:}); else % User specified a numeric array of colors (n-by-3) bg = parsecolor(bg); end end % Generate a sizable number of RGB triples. This represents our space of % possible choices. By starting in RGB space, we ensure that all of the % colors can be generated by the monitor. n_grid = 30; % number of grid divisions along each axis in RGB space x = linspace(0,1,n_grid); [R,G,B] = ndgrid(x,x,x); rgb = [R(:) G(:) B(:)]; if (n_colors > size(rgb,1)/3) error('You can''t readily distinguish that many colors'); end % Convert to Lab color space, which more closely represents human % perception if (nargin > 2) lab = func(rgb); bglab = func(bg); else C = makecform('srgb2lab'); lab = applycform(rgb,C); bglab = applycform(bg,C); end % If the user specified multiple background colors, compute distances % from the candidate colors to the background colors mindist2 = inf(size(rgb,1),1); for i = 1:size(bglab,1)-1 dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color end % Iteratively pick the color that maximizes the distance to the nearest % already-picked color colors = zeros(n_colors,3); lastlab = bglab(end,:); % initialize by making the "previous" color equal to background for i = 1:n_colors dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color [~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors colors(i,:) = rgb(index,:); % save for output lastlab = lab(index,:); % prepare for next iteration end end function c = parsecolor(s) if ischar(s) c = colorstr2rgb(s); elseif isnumeric(s) && size(s,2) == 3 c = s; else error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.'); end end function c = colorstr2rgb(c) % Convert a color string to an RGB value. % This is cribbed from Matlab's whitebg function. % Why don't they make this a stand-alone function? rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0]; cspec = 'rgbwcmyk'; k = find(cspec==c(1)); if isempty(k) error('MATLAB:InvalidColorString','Unknown color string.'); end if k~=3 || length(c)==1, c = rgbspec(k,:); elseif length(c)>2, if strcmpi(c(1:3),'bla') c = [0 0 0]; elseif strcmpi(c(1:3),'blu') c = [0 0 1]; else error('MATLAB:UnknownColorString', 'Unknown color string.'); end end end
github
mathematical-tours/mathematical-tours.github.io-master
plot_mesh.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/spherical-wavelets/toolbox_multires/plot_mesh.m
11,185
utf_8
f48aac5032a78db13e31a0504dde8ce4
function h = plot_mesh(vertex,face,options) % plot_mesh - plot a 3D mesh. % % plot_mesh(vertex,face, options); % % 'options' is a structure that may contains: % - 'normal' : a (nvertx x 3) array specifying the normals at each vertex. % - 'edge_color' : a float specifying the color of the edges. % - 'face_color' : a float specifying the color of the faces. % - 'face_vertex_color' : a color per vertex or face. % - 'vertex' % - 'texture' : a 2-D image to be mapped on the surface % - 'texture_coords' : a (nvertx x 2) array specifying the texture % coordinates in [0,1] of the vertices in the texture. % - 'tmesh' : set it to 1 if this corresponds to a volumetric tet mesh. % % See also: mesh_previewer. % % Copyright (c) 2004 Gabriel Peyr? if nargin<2 error('Not enough arguments.'); end options.null = 0; name = getoptions(options, 'name', ''); normal = getoptions(options, 'normal', []); face_color = getoptions(options, 'face_color', .7); edge_color = getoptions(options, 'edge_color', 0); normal_scaling = getoptions(options, 'normal_scaling', .8); sanity_check = getoptions(options, 'sanity_check', 1); view_param = getoptions(options, 'view_param', []); texture = getoptions(options, 'texture', []); texture_coords = getoptions(options, 'texture_coords', []); tmesh = getoptions(options, 'tmesh', 0); if size(vertex,1)==2 % 2D triangulation % vertex = cat(1,vertex, zeros(1,size(vertex,2))); plot_graph(triangulation2adjacency(face),vertex); return; end % can flip to accept data in correct ordering [vertex,face] = check_face_vertex(vertex,face); if size(face,1)==4 && tmesh==1 %%%% tet mesh %%%% % normal to the plane <x,w><=a w = getoptions(options, 'cutting_plane', [0.2 0 1]'); w = w(:)/sqrt(sum(w.^2)); t = sum(vertex.*repmat(w,[1 size(vertex,2)])); a = getoptions(options, 'cutting_offs', median(t(:)) ); b = getoptions(options, 'cutting_interactive', 0); plot_points = getoptions(options, 'plot_points', 0); while true; % in/out I = ( t<=a ); % trim e = sum(I(face)); J = find(e==4); facetrim = face(:,J); % convert to triangular mesh hold on; if not(isempty(facetrim)) face1 = tet2tri(facetrim, vertex, 1); % options.method = 'slow'; face1 = perform_faces_reorientation(vertex,face1, options); h{1} = plot_mesh(vertex,face1, options); end view(3); % camlight; shading faceted; if plot_points K = find(e==0); K = face(:,K); K = unique(K(:)); h{2} = plot3(vertex(1,K), vertex(2,K), vertex(3,K), 'k.'); end hold off; if b==0 break; end [x,y,b] = ginput(1); if b==1 a = a+.03; elseif b==3 a = a-.03; else break; end end return; end vertex = vertex'; face = face'; if strcmp(name, 'bunny') || strcmp(name, 'pieta') % vertex = -vertex; end if strcmp(name, 'armadillo') vertex(:,3) = -vertex(:,3); end if sanity_check && ( (size(face,2)~=3 && size(face,2)~=4) || (size(vertex,2)~=3 && size(vertex,2)~=2)) error('face or vertex does not have correct format.'); end if ~isfield(options, 'face_vertex_color') || isempty(options.face_vertex_color) options.face_vertex_color = zeros(size(vertex,1),1); end face_vertex_color = options.face_vertex_color; if not(isempty(texture)) %%% textured mesh %%% if isempty(texture_coords) error('You need to provide texture_coord.'); end if size(texture_coords,2)~=2 texture_coords = texture_coords'; end opts.EdgeColor = 'none'; patcht(face,vertex,face,texture_coords,texture',opts); if size(texture,3)==1 colormap gray(256); else colormap jet(256); end set_view(name, view_param); axis off; axis equal; % camlight; % problem with pithon notebook shading faceted; return; end shading_type = 'interp'; if isempty(face_vertex_color) h = patch('vertices',vertex,'faces',face,'facecolor',[face_color face_color face_color],'edgecolor',[edge_color edge_color edge_color]); else nverts = size(vertex,1); % vertex_color = rand(nverts,1); if size(face_vertex_color,1)==size(vertex,1) shading_type = 'interp'; else shading_type = 'flat'; end h = patch('vertices',vertex,'faces',face,'FaceVertexCData',face_vertex_color, 'FaceColor',shading_type); end colormap gray(256); lighting phong; % camlight infinite; camproj('perspective'); axis square; axis off; if ~isempty(normal) %%% plot the normals %%% n = size(vertex,1); subsample_normal = getoptions(options, 'subsample_normal', min(4000/n,1) ); sel = randperm(n); sel = sel(1:floor(end*subsample_normal)); hold on; quiver3(vertex(sel,1),vertex(sel,2),vertex(sel,3),normal(1,sel)',normal(2,sel)',normal(3,sel)',normal_scaling); hold off; end % cameramenu; set_view(name, view_param); shading(shading_type); % camlight; %% BUG WITH PYTHON %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function set_view(name, view_param) switch lower(name) case 'hammerheadtriang' view(150,-45); case 'horse' view(134,-61); case 'skull' view(21.5,-12); case 'mushroom' view(160,-75); case 'bunny' % view(0,-55); view(0,90); case 'david_head' view(-100,10); case 'screwdriver' view(-10,25); case 'pieta' view(15,31); case 'mannequin' view(25,15); view(27,6); case 'david-low' view(40,3); case 'david-head' view(-150,5); case 'brain' view(30,40); case 'pelvis' view(5,-15); case 'fandisk' view(36,-34); case 'earth' view(125,35); case 'camel' view(-123,-5); camroll(-90); case 'beetle' view(-117,-5); camroll(-90); zoom(.85); case 'cat' view(-60,15); case 'nefertiti' view(-20,65); end if not(isempty(view_param)) view(view_param(1),view_param(2)); end axis tight; axis equal; if strcmp(name, 'david50kf') || strcmp(name, 'hand') zoom(.85); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function patcht(FF,VV,TF,VT,I,Options) % This function PATCHT, will show a triangulated mesh like Matlab function % Patch but then with a texture. % % patcht(FF,VV,TF,VT,I,Options); % % inputs, % FF : Face list 3 x N with vertex indices % VV : Vertices 3 x M % TF : Texture list 3 x N with texture vertex indices % VT : Texture Coordinates s 2 x K, range must be [0..1] or real pixel postions % I : The texture-image RGB [O x P x 3] or Grayscale [O x P] % Options : Structure with options for the textured patch such as % EdgeColor, EdgeAlpha see help "Surface Properties :: Functions" % % Options.PSize : Special option, defines the image texturesize for each % individual polygon, a low number gives a more block % like texture, defaults to 64; % % note: % On a normal PC displaying 10,000 faces will take about 6 sec. % % Example, % % % Load Data; % load testdata; % % Show the textured patch % figure, patcht(FF,VV,TF,VT,I); % % Allow Camera Control (with left, right and center mouse button) % mouse3d % % Function is written by D.Kroon University of Twente (July 2010) % FaceColor is a texture Options.FaceColor='texturemap'; % Size of texture image used for every triangle if(isfield(Options,'PSize')) sizep=round(Options.PSize(1)); Options=rmfield(Options,'PSize'); else sizep=64; end % Check input sizes if(size(FF,2)~=size(TF,2)) error('patcht:inputs','Face list must be equal in size to texture-index list'); end if((ndims(I)~=2)&&(ndims(I)~=3)) error('patcht:inputs','No valid Input texture image'); end % Detect if grayscale or color image switch(size(I,3)) case 1 iscolor=false; case 3 iscolor=true; otherwise error('patcht:inputs','No valid Input texture image'); end if(max(VT(:))<2) % Remap texture coordinates to image coordinates VT2(:,1)=(size(I,1)-1)*(VT(:,1))+1; VT2(:,2)=(size(I,2)-1)*(VT(:,2))+1; else VT2=VT; end % Calculate the texture interpolation values [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep); % Split texture-image in r,g,b to allow fast 1D index Ir=I(:,:,1); if(iscolor), Ig=I(:,:,2); Ib=I(:,:,3); end % The Patch used for every triangle (rgb) Jr=zeros([(sizep+1) (sizep+1) 1],class(I)); if(iscolor) Jg=zeros([(sizep+1) (sizep+1) 1],class(I)); Jb=zeros([(sizep+1) (sizep+1) 1],class(I)); end hold on; % Loop through all triangles of the mesh for i=1:size(FF,1) % Get current triangle vertices and current texture-vertices V=VV(FF(i,:),:); Vt=VT2(TF(i,:),:); % Define the triangle as a surface x=[V(1,1) V(2,1); V(3,1) V(3,1)]; y=[V(1,2) V(2,2); V(3,2) V(3,2)]; z=[V(1,3) V(2,3); V(3,3) V(3,3)]; % Define the texture coordinates of the surface tx=[Vt(1,1) Vt(2,1) Vt(3,1) Vt(3,1)]; ty=[Vt(1,2) Vt(2,2) Vt(3,2) Vt(3,2)] ; xy=[tx(1) ty(1); tx(2) ty(2); tx(3) ty(3); tx(3) ty(3)]; % Calculate texture interpolation coordinates pos(:,1)=xy(1,1)*lambda1+xy(2,1)*lambda2+xy(3,1)*lambda3; pos(:,2)=xy(1,2)*lambda1+xy(2,2)*lambda2+xy(3,2)*lambda3; pos=round(pos); pos=max(pos,1); pos(:,1)=min(pos(:,1),size(I,1)); pos(:,2)=min(pos(:,2),size(I,2)); posind=(pos(:,1)-1)+(pos(:,2)-1)*size(I,1)+1; % Map texture to surface image Jr(jind)=Ir(posind); J(:,:,1)=Jr; if(iscolor) Jg(jind)=Ig(posind); Jb(jind)=Ib(posind); J(:,:,2)=Jg; J(:,:,3)=Jb; end % Show the surface surface(x,y,z,J,Options); end hold off; function [lambda1 lambda2 lambda3 jind]=calculateBarycentricInterpolationValues(sizep) % Define a triangle in the upperpart of an square, because only that % part is used by the surface function x1=sizep; y1=sizep; x2=sizep; y2=0; x3=0 ;y3=0; % Calculate the bary centric coordinates (instead of creating a 2D image % with the interpolation values, we map them directly to an 1D vector) detT = (x1-x3)*(y2-y3) - (x2-x3)*(y1-y3); [x,y]=ndgrid(0:sizep,0:sizep); x=x(:); y=y(:); lambda1=((y2-y3).*(x-x3)+(x3-x2).*(y-y3))/detT; lambda2=((y3-y1).*(x-x3)+(x1-x3).*(y-y3))/detT; lambda3=1-lambda1-lambda2; % Make from 2D (surface)image indices 1D image indices [jx jy]=ndgrid(sizep-(0:sizep)+1,sizep-(0:sizep)+1); jind=(jx(:)-1)+(jy(:)-1)*(sizep+1)+1;
github
mathematical-tours/mathematical-tours.github.io-master
load_spherical_function.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/spherical-wavelets/toolbox_multires/load_spherical_function.m
2,090
utf_8
e9c44feb124e0a5925b9c201378082dc
function f = load_spherical_function(name, pos, options) % load_spherical_function - load a function on the sphere % % f = load_spherical_function(name, pos, options); % % Copyright (c) 2007 Gabriel Peyre if iscell(pos) pos = pos{end}; end if size(pos,1)>size(pos,2) pos = pos'; end x = pos(1,:); x = x(:); M = []; if not(isstr(name)) M = name; name = 'image'; end switch name case 'linear' f = x; case 'cos' f = cos(6*pi*x); case 'singular' f = abs(x).^.4; case 'image' name = getoptions(options, 'image_name', 'lena'); if isempty(M) M = load_image(name); q = size(M,1); q = min(q,512); M = crop(M,q); M = perform_blurring(M,4); end f = perform_spherical_interpolation(pos,M); case 'etopo' resol = 15; fname = ['ETOPO' num2str(resol)]; fid = fopen(fname, 'rb'); if fid<0 error('Unable to read ETOPO file'); end s = [360*(60/resol), 180*(60/resol)]; M = fread(fid, Inf, 'short'); M = reshape(M, s(1),s(2) ); fclose(fid); f = perform_spherical_interpolation(pos,M, 0); case {'earth' 'earth-grad'} filename = 'earth-bw'; M = double( load_image(filename) ); M = perform_blurring(M,4); if strcmp(name, 'earth-grad') G = grad(M); M = sqrt(sum(G.^2,3)); M = perform_blurring(M,15); end f = perform_spherical_interpolation(pos,M,0); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = perform_spherical_interpolation(pos,M,center) if nargin<3 center = 0; end qx = size(M,1); qy = size(M,2); Y = atan2(pos(2,:),pos(1,:))/(2*pi) + 1/2; if center X = acos(pos(3,:))/(2*pi) + 1/4; else X = acos(pos(3,:))/(pi); end x = linspace(0,1,qx); y = linspace(0,1,qy); f = interp2( y,x,M, Y(:),X(:) );
github
mathematical-tours/mathematical-tours.github.io-master
perform_haar_transf.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/spherical-wavelets/toolbox_multires/perform_haar_transf.m
3,170
utf_8
14b7d7fd610eca05949ef196c55d7b83
function f = perform_haar_transf(f, Jmin, dir, options) % perform_haar_transf - peform fast Haar transform % % y = perform_haar_transf(x, Jmin, dir); % % Implement a Haar wavelets. % Works in any dimension. % % Copyright (c) 2008 Gabriel Peyre n = size(f,1); Jmax = log2(n)-1; if dir==1 %%% FORWARD %%% for j=Jmax:-1:Jmin sel = 1:2^(j+1); a = subselect(f,sel); for d=1:nb_dims(f) Coarse = ( subselectdim(a,1:2:size(a,d),d) + subselectdim(a,2:2:size(a,d),d) )/sqrt(2); Detail = ( subselectdim(a,1:2:size(a,d),d) - subselectdim(a,2:2:size(a,d),d) )/sqrt(2); a = cat(d, Coarse, Detail ); end f = subassign(f,sel,a); end else %%% BACKWARD %%% for j=Jmin:Jmax sel = 1:2^(j+1); a = subselect(f,sel); for d=1:nb_dims(f) Detail = subselectdim(a,2^j+1:2^(j+1),d); Coarse = subselectdim(a,1:2^j,d); a = subassigndim(a, 1:2:2^(j+1), ( Coarse + Detail )/sqrt(2),d ); a = subassigndim(a, 2:2:2^(j+1), ( Coarse - Detail )/sqrt(2),d ); end f = subassign(f,sel,a); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subselect(f,sel) switch nb_dims(f) case 1 f = f(sel); case 2 f = f(sel,sel); case 3 f = f(sel,sel,sel); case 4 f = f(sel,sel,sel,sel); case 5 f = f(sel,sel,sel,sel,sel); case 6 f = f(sel,sel,sel,sel,sel,sel); case 7 f = f(sel,sel,sel,sel,sel,sel,sel); case 8 f = f(sel,sel,sel,sel,sel,sel,sel,sel); otherwise error('Not implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subselectdim(f,sel,d) switch d case 1 f = f(sel,:,:,:,:,:,:,:); case 2 f = f(:,sel,:,:,:,:,:,:); case 3 f = f(:,:,sel,:,:,:,:,:); case 4 f = f(:,:,:,sel,:,:,:,:); case 5 f = f(:,:,:,:,sel,:,:,:); case 6 f = f(:,:,:,:,:,sel,:,:); case 7 f = f(:,:,:,:,:,:,sel,:); case 8 f = f(:,:,:,:,:,:,:,sel); otherwise error('Not implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subassign(f,sel,g) switch nb_dims(f) case 1 f(sel) = g; case 2 f(sel,sel) = g; case 3 f(sel,sel,sel) = g; case 4 f(sel,sel,sel,sel) = g; case 5 f(sel,sel,sel,sel,sel) = g; case 6 f(sel,sel,sel,sel,sel,sel) = g; case 7 f(sel,sel,sel,sel,sel,sel,sel) = g; case 8 f(sel,sel,sel,sel,sel,sel,sel,sel) = g; otherwise error('Not implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function f = subassigndim(f,sel,g,d) switch d case 1 f(sel,:,:,:,:,:,:,:) = g; case 2 f(:,sel,:,:,:,:,:,:) = g; case 3 f(:,:,sel,:,:,:,:,:) = g; case 4 f(:,:,:,sel,:,:,:,:) = g; case 5 f(:,:,:,:,sel,:,:,:) = g; case 6 f(:,:,:,:,:,sel,:,:) = g; case 7 f(:,:,:,:,:,:,sel,:) = g; case 8 f(:,:,:,:,:,:,:,sel) = g; otherwise error('Not implemented'); end
github
mathematical-tours/mathematical-tours.github.io-master
refine2.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-2d/refine2.m
40,907
utf_8
18e116aff5e1105226be34049478e95d
function [vert,conn,tria,tnum] = refine2(varargin) %REFINE2 (Frontal)-Delaunay-refinement for two-dimensional, %polygonal geometries. % [VERT,EDGE,TRIA,TNUM] = REFINE2(NODE,EDGE) returns a co- % nstrained Delaunay triangulation of the polygonal region % {NODE,EDGE}. NODE is an N-by-2 array of polygonal verti- % ces and EDGE is an E-by-2 array of edge indexing. Each % row in EDGE represents an edge of the polygon, such that % NODE(EDGE(JJ,1),:) and NODE(EDGE(JJ,2),:) are the coord- % inates of the endpoints of the JJ-TH edge. If the argum- % ent EDGE is omitted it assumed that the vertices in NODE % are connected in ascending order. % % [...] = REFINE2(NODE,EDGE,PART) computes a triangulation % for a multiply-connected geometry. PART is a cell-array % of polygonal "parts", where each element PART{KK} is an % array of edge indices defining a given polygonal region. % EDGE(PART{KK}, :) is the set of edges in the KK-TH part. % % VERT is a V-by-2 array of XY coordinates in the triangu- % lation, EDGE is an array of constrained edges, TRIA is a % T-by-3 array of triangles, and TNUM is a T-by-1 array of % part indices. Each row of TRIA and EDGE define an eleme- % nt. VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and VERT(TRIA % (II,3),:) are the coordinates of the II-TH triangle. The % edges in EDGE are defined in a similar manner. NUM is an % array of part indexing, such that TNUM(II) is the index % of the part in which the II-TH triangle resides. % % [...] = REFINE2(..., OPTS) passes an additional options % structure OPTS, containing various user-defined paramet- % ers, including: % % - OPTS.KIND = {'DELFRONT'}, 'DELAUNAY' -- the type of ref- % inement employed. The 'DELFRONT' algorithm is typically % slower, but produces higher quality output. % % - OPTS.RHO2 = {1.025} -- the maximum allowable radius-edge % ratio. Refinement proceeds until all interior triangles % satisfy the radius-edge threshold. Smaller radius-edge % ratios lead to improved triangle shape, with RHO2=1 req- % uiring that all angles exceed 30 degrees. Setting RHO2<1 % may lead to non-convergence. % % - OPTS.REF1 = {'REFINE'}, 'PRESERVE' -- refinement 'flag' % for 1-dimensional faces (i.e. edges). The 'PRESERVE' op- % tion results in minimal refinement, attempting to retain % the initial edges without further subdivision. Edges are % split only to satisfy basic geomertical conformance. % % - OPTS.REF2 = {'REFINE'}, 'PRESERVE' -- refinement 'flag' % for 2-dimensional faces (i.e. trias). The 'PRESERVE' op- % tion results in minimal refinement, attempting to retain % the initial trias without further subdivision. Trias are % split only to satisfy basic geomertical conformance. % % - OPTS.SIZ1 = {1.333} -- the normalised rel.-length th- % reshold for edge-elements. Each exterior edge is refined % until LL/HH<SIZ1, where LL is the edge-length, HH is the % edge-centred mesh-size value. % % - OPTS.SIZ2 = {1.300} -- the normalised rel.-length th- % reshold for tria-elements. Each interior tria is refined % until RE/HH<SIZ2, where RE is an effective tria length, % based on the circumradius, HH is the tria-centred mesh- % size value. % % - OPTS.DISP = { +10 } -- refinement verbosity. Set to INF % for quiet execution. % % [...] = REFINE2(..., HFUN,ARGS) also passes an optional % mesh-size function argument. Setting HFUN = HMAX, where % HMAX is a scalar value, imposes a constant size constra- % int over the full domain. HFUN can also be defined as a % general function handle [HH] = HFUN(PP), where PP is an % N-by-2 array of XY coordinates and HH is the associated % vector of mesh-size values. User-defined HFUN must be % fully vectorised. Additional arguments {A1,A2,...AN} for % HFUN can be passed as trailing parameters to REFINE2. In % such cases, HFUN must adopt a signature [HH] = HFUN(PP, % A1,A2,...,AN). HFUN must return positive values. % % See also SMOOTH2, TRIDIV2, TRICOST, TRIDEMO % This routine implements a "multi-refinement" variant of % Delaunay-refinement type mesh-generation. Both standard % Delaunay-refinement and Frontal-Delaunay type algorithms % are available. The Frontal-Delaunay approach is a simpl- % ified version of the JIGSAW algorithm, described in: % % * D. Engwirda, (2014): "Locally-optimal Delaunay-refineme- % nt and optimisation-based mesh generation", Ph.D. Thesis % School of Mathematics and Statistics, Univ. of Sydney. % http://hdl.handle.net/2123/13148 % % * D. Engwirda & D. Ivers, (2016): "Off-centre Steiner poi- % nts for Delaunay-refinement on curved surfaces", Comput- % er-Aided Design, (72), 157--171. % http://dx.doi.org/10.1016/j.cad.2015.10.007 % This work is an extension of the "off-centre" type tech- % niques introduced in: % % * H. Erten & A. Ungor, (2009): "Quality triangulation with % locally optimal Steiner points", SIAM Journal on Scient- % ific Comp. 31(3), 2103--2130. % http://doi.org/10.1137/080716748 % % * S. Rebay, (1993): "Efficient Unstructured Mesh Generati- % on by Means of Delaunay Triangulation and Bowyer-Watson % Algorithm, J. Comp. Physics 106(1), 125--138. % http://dx.doi.org/10.1006/jcph.1993.1097 % Generally speaking, the Delaunay-refinement method impl- % emented here is a variantion of the "classical" algorit- % hm introduced in: % % * J. Ruppert, (1995): "A Delaunay refinement algorithm for % quality 2-dimensional mesh generation." Journal of Algo- % rithms 18(3), 548--585. % http://dx.doi.org/10.1006/jagm.1995.1021 % % See also: S. Cheng, T. Dey & J. Shewchuk, (2012): "Dela- % unay mesh generation", CRC Press, for comprehensive cov- % erage of Delaunay-based meshing techniques. % A much more advanced, and fully three-dimensional imple- % mentation is available in the JIGSAW library. For addit- % ional information, see: % https://github.com/dengwirda/jigsaw-matlab %----------------------------------------------------------- % Darren Engwirda : 2017 -- % Email : [email protected] % Last updated : 09/07/2018 %----------------------------------------------------------- node = []; PSLG = []; part = {}; opts = [] ; hfun = []; harg = {}; %---------------------------------------------- extract args if (nargin>=+1), node = varargin{1}; end if (nargin>=+2), PSLG = varargin{2}; end if (nargin>=+3), part = varargin{3}; end if (nargin>=+4), opts = varargin{4}; end if (nargin>=+5), hfun = varargin{5}; end if (nargin>=+6), harg = varargin(6:end); end [opts] = makeopt(opts) ; %---------------------------------------------- default EDGE nnod = size(node,1) ; if (isempty(PSLG)) PSLG = [(1:nnod-1)',(2:nnod)'; nnod,1] ; end %---------------------------------------------- default PART ncon = size(PSLG,1) ; if (isempty(part)), part{1} = (1:ncon)'; end %---------------------------------------------- basic checks if (~isnumeric(node) || ~isnumeric(PSLG) || ... ~iscell (part) || ~isstruct (opts) ) error('refine2:incorrectInputClass' , ... 'Incorrect input class.') ; end %---------------------------------------------- basic checks if (ndims(node) ~= +2 || ndims(PSLG) ~= +2) error('refine2:incorrectDimensions' , ... 'Incorrect input dimensions.'); end if (size(node,2) < +2 || size(PSLG,2) < +2) error('refine2:incorrectDimensions' , ... 'Incorrect input dimensions.'); end %---------------------------------------------- basic checks if (min([PSLG(:)])<+1 || max([PSLG(:)])>nnod) error('refine2:invalidInputs', ... 'Invalid EDGE input array.') ; end pmin = cellfun(@min,part); pmax = cellfun(@max,part); if (min([pmin(:)])<+1 || max([pmax(:)])>ncon) error('refine2:invalidInputs', ... 'Invalid PART input array.') ; end %-------------------------------- prune any non-unique topo. [ivec,ivec,jvec] = ... unique(sort(PSLG,+2),'rows') ; PSLG = PSLG(ivec,:) ; for ppos = +1:length(part) if ( ~isnumeric(part{ppos}) ) error ( ... 'refine2:incorrectInputClass', ... 'Incorrect input class. ') ; end part{ppos} = ... unique(jvec(part{ppos})) ; end %-------------------------------- check part "manifold-ness" for ppos = +1:length(part) eloc = PSLG(part{ppos},:) ; nadj = ... accumarray(eloc(:),1) ; if (any(mod(nadj,2) ~= 0) ) error('refine2:nonmanifoldInputs', ... 'Non-manifold PART detected.') ; end end %---------------------------------------------- output title if (~isinf(opts.disp)) fprintf(1,'\n') ; fprintf(1,' Refine triangulation...\n') ; fprintf(1,'\n') ; fprintf(1,[... ' -------------------------------------------------------\n', ... ' |ITER.| |CDT1(X)| |CDT2(X)| \n', ... ' -------------------------------------------------------\n', ... ] ) ; end %-------------------------------- PASS 0: inflate box bounds vert = node; tria = []; tnum = []; iter = 0 ; conn = PSLG; vmin = min(vert,[],1); % inflate bbox for stability vmax = max(vert,[],1); vdel = vmax - 1.*vmin; vmin = vmin - .5*vdel; vmax = vmax + .5*vdel; vbox = [ vmin(1), vmin(2) vmax(1), vmin(2) vmax(1), vmax(2) vmin(1), vmax(2) ] ; vert = [vert ; vbox] ; %-------------------------------- PASS 0: shield sharp feat. [vert,conn,tria,tnum,iter] = ... cdtbal0(vert,conn,tria,tnum, ... node,PSLG,part,opts,hfun,harg,iter); %-------------------------------- PASS 1: refine 1-simplexes [vert,conn,tria,tnum,iter] = ... cdtref1(vert,conn,tria,tnum, ... node,PSLG,part,opts,hfun,harg,iter); %-------------------------------- PASS 2: refine 2-simplexes [vert,conn,tria,tnum,iter] = ... cdtref2(vert,conn,tria,tnum, ... node,PSLG,part,opts,hfun,harg,iter); if (~isinf(opts.disp)), fprintf(1,'\n'); end %-------------------------------- trim extra adjacency info. tria = tria( :,1:3) ; %-------------------------------- trim vert. - deflate bbox. keep = false(size(vert,1),1); keep(tria(:)) = true; keep(conn(:)) = true; redo = zeros(size(vert,1),1); redo(keep) = ... (+1:length(find(keep)))'; conn = redo(conn); tria = redo(tria); vert = vert(keep,:) ; end function [vert,conn,tria,tnum,iter] = ... cdtbal0(vert,conn,tria,tnum, ... node,PSLG,part,opts,hfun,harg,iter) %CDTBAL0 constrained Delaunay-refinement for "sharp" 0-dim. %features at PSLG vertices. % [...] = CDTBAL0(...) refines the set of 1-simplex eleme- % nts incident to "sharp" features in the PSLG. Specifica- % lly, edges that subtend "small" angles are split about a % set of new "collar" vertices, equi-distributed about the % centre of "sharp" features. Collar size is computed as a % min. of the incident edge-len. and local mesh-size cons- % traints. if (iter <= opts.iter) %------------------------------------- build current CDT [vert,conn, ... tria,tnum] = deltri2(vert,conn, ... node,PSLG, ... part, ... opts.dtri) ; %------------------------------------- build current adj [edge,tria] = tricon2(tria,conn) ; [feat,ftri] = isfeat2(vert, ... edge,tria) ; apex = false(size(vert,1), 1) ; apex(tria(ftri)) = true ; %------------------------------------- eval. length-fun. if (~isempty(hfun)) if (isnumeric(hfun)) vlen = hfun * ... ones(size(vert,1),1) ; else vlen = feval( ... hfun,vert,harg{:}) ; vlen = vlen(:) ; end else vlen = +inf * ... ones(size(vert,1),1) ; end %------------------------------------- form edge vectors evec = vert(conn(:,2),:) ... - vert(conn(:,1),:) ; elen = sqrt(sum(evec.^2,2)); evec = evec./[elen,elen] ; %------------------------------------- min. adj. lengths for epos = +1 : size(conn,1) ivrt = conn(epos,1) ; jvrt = conn(epos,2) ; vlen(ivrt) = min( ... vlen(ivrt), .67*elen(epos)) ; vlen(jvrt) = min( ... vlen(jvrt), .67*elen(epos)) ; end %------------------------------------- mark feature edge iref = apex(conn(:,1)) ... %- refine at vert. 1 & ~apex(conn(:,2)) ; jref = apex(conn(:,2)) ... %- refine at vert. 2 & ~apex(conn(:,1)) ; dref = apex(conn(:,1)) ... %- refine at both! & apex(conn(:,2)) ; keep =~apex(conn(:,1)) ... %- refine at neither & ~apex(conn(:,2)) ; %------------------------------------- protecting collar ilen = vlen(conn(iref,1)) ; inew = vert(conn(iref,1),:) ... + [ilen,ilen].*evec(iref,:) ; jlen = vlen(conn(jref,2)) ; jnew = vert(conn(jref,2),:) ... - [jlen,jlen].*evec(jref,:) ; Ilen = vlen(conn(dref,1)) ; Inew = vert(conn(dref,1),:) ... + [Ilen,Ilen].*evec(dref,:) ; Jlen = vlen(conn(dref,2)) ; Jnew = vert(conn(dref,2),:) ... - [Jlen,Jlen].*evec(dref,:) ; vnew = [inew; jnew; Inew; Jnew] ; %------------------------------------- add new vert/edge iset = (1:size(inew,1))' ... + size(vert,1) ; jset = (1:size(jnew,1))' ... + size(inew,1) + ... + size(vert,1) ; Iset = (1:size(Inew,1))' ... + size(inew,1) + ... + size(jnew,1) + ... + size(vert,1) ; Jset = (1:size(Jnew,1))' ... + size(inew,1) + ... + size(jnew,1) + ... + size(Inew,1) + ... + size(vert,1) ; vert = [vert ; vnew] ; cnew = [conn(iref,1), iset ; conn(iref,2), iset ; conn(jref,2), jset ; conn(jref,1), jset ; conn(dref,1), Iset ; conn(dref,2), Jset ; Iset, Jset] ; conn = [conn(keep,:); cnew ] ; end end function [vert,conn,tria,tnum,iter] = ... cdtref1(vert,conn,tria,tnum, ... node,PSLG,part,opts,hfun,harg,iter) %CDTREF1 constrained Delaunay-refinement for 1-simplex elem- %nts embedded in R^2. % [...] = CDTREF1(...) refines the set of 1-simplex eleme- % nts embedded in the triangulation until all constraints % are satisfied. Specifically, edges are refined until all % local mesh-spacing and encroachment conditions are met. % Refinement proceeds according to either a Delaunay-refi- % nement or Frontal-Delaunay type approach, depending on % user-settings. In either case, new steiner vertices are % introduced to split "bad" edges - those that violate the % set of prescribed constraints. In the "-DR" type process % edges are split about their circumballs (midpoints). In % the "-FD" approach, new vertices are positioned such th- % at mesh-spacing constraints are satisfied in a "locally- % optimal" fashion. tcpu.full = +0. ; tcpu.ball = +0. ; tcpu.hfun = +0. ; tcpu.encr = +0. ; tcpu.offc = +0. ; vidx = (1:size(vert,1))'; %- "new" vert list to test tnow = tic ; ntol = +1.55; while (strcmpi(opts.ref1,'refine')) iter = iter + 1 ; if (iter>=opts.iter),break; end %------------------------------------- calc. circumballs ttic = tic ; bal1 = cdtbal1(vert,conn) ; tcpu.ball = ... tcpu.ball + toc(ttic) ; %------------------------------------- eval. length-fun. ttic = tic ; if (~isempty(hfun)) if (isnumeric(hfun)) fun0 = hfun * ... ones(size(vert,1),1); fun1 = hfun ; else fun0(vidx) = ... feval(hfun, ... vert(vidx,:), harg{:}); fun0 = fun0(:) ; fun1 = fun0(conn(:,1))... + fun0(conn(:,2)); fun1 = fun1 / +2. ; end else fun0 = +inf * ... ones(size(vert,1),1); fun1 = +inf ; end siz1 = ... +4. * bal1(:,3)./(fun1.*fun1) ; tcpu.hfun = ... tcpu.hfun + toc(ttic) ; %------------------------------------- test encroachment ttic = tic ; bal1(:,3) = ... (1.-eps^.75) * bal1(:,3) ; [vp,vi] = ... findball(bal1,vert(:,1:2)); %------------------------------------- near=>[vert,edge] next = +0; ebad = false(size(conn,1),1) ; near = zeros(size(conn,1),1) ; for ii = +1 : size(vp,1) for ip = vp(ii,1):vp(ii,2) jj = vi(ip); if (ii ~= conn(jj,1) ... && ii ~= conn(jj,2) ) next = next + 1; near(next,1) = ii; near(next,2) = jj; end end end near = near(1:next-0,:); if (~isempty(near)) %-- mark edge "encroached" if there is a vert within its %-- dia.-ball that is not joined to either of its vert's %-- via an existing edge... ivrt = conn(near(:,2),1); jvrt = conn(near(:,2),2); pair = [near(:,1), ivrt]; ivec = setset2(pair,conn) ; pair = [near(:,1), jvrt]; jvec = setset2(pair,conn) ; okay = ~ivec & ~jvec ; ebad(near(okay,2))=true ; end tcpu.encr = ... tcpu.encr + toc(ttic); %------------------------------------- refinement queues ref1 = false(size(conn,1),1); ref1(ebad) = true ; %- edge encroachment ref1(siz1>opts.siz1* ... %- bad equiv. length opts.siz1) = true ; num1 = find(ref1) ; %------------------------------------- dump-out progess! if (mod(iter,opts.disp)==0) numc = size(conn,1) ; numt = size(tria,1) ; fprintf(+1, ... '%11i %18i %18i\n', ... [iter,numc,numt]) ; end %------------------------------------- nothing to refine if (isempty(num1)), break; end %------------------------------------- refine "bad" tria switch (lower(opts.kind)) case 'delaunay' %------------------------------------- do circ-ball pt's new1 = bal1(ref1, 1:2) ; vidx = (1:size(new1,1))' ... + size(vert,1) ; cnew = [conn( ref1,1), vidx conn( ref1,2), vidx]; conn = [conn(~ref1,:); cnew]; %------------------------------------- update vertex set vert = [vert; new1(:,1:2)]; case 'delfront' %-- symmetric off-centre scheme:- refine edges from both %-- ends simultaneously, placing new vertices to satisfy %-- the worst of mesh-spacing and local voronoi constra- %-- ints. ttic = tic ; evec = vert(conn(ref1,2),:) ... - vert(conn(ref1,1),:) ; elen = sqrt(sum(evec.^2,2)) ; evec = evec ./ [elen, elen] ; %------------------------------------- "voro"-type dist. vlen = sqrt(bal1(ref1,3)); %------------------------------------- "size"-type dist. ihfn = fun0(conn(ref1,1)); jhfn = fun0(conn(ref1,2)); %------------------------------------- bind "safe" dist. ilen = min(vlen,ihfn) ; jlen = min(vlen,jhfn) ; %------------------------------------- locate offcentres inew = vert(conn(ref1,1),:) ... + [ilen,ilen].*evec ; jnew = vert(conn(ref1,2),:) ... - [jlen,jlen].*evec ; %------------------------------------- iter. "size"-type for ioff = +1 : +3 %------------------------------------- eval. length-fun. if (~isempty(hfun)) if (isnumeric(hfun)) iprj = hfun * ... ones(size(inew,1),1); jprj = hfun * ... ones(size(jnew,1),1); else iprj = feval( ... hfun,inew,harg{:}); jprj = feval( ... hfun,jnew,harg{:}); iprj = iprj(:); jprj = jprj(:); end else iprj = +inf * ... ones(size(inew,1),1); jprj = +inf * ... ones(size(jnew,1),1); end iprj = 0.5*ihfn + 0.5*iprj; jprj = 0.5*jhfn + 0.5*jprj; %------------------------------------- bind "safe" dist. ilen = min(vlen,iprj) ; jlen = min(vlen,jprj) ; %------------------------------------- locate offcentres inew = vert(conn(ref1,1),:) ... + [ilen,ilen].*evec ; jnew = vert(conn(ref1,2),:) ... - [jlen,jlen].*evec ; end %------------------------------------- merge i,j if near near = ... ilen+jlen>=vlen*ntol ; znew = inew(near,:) * .5 ... + jnew(near,:) * .5 ; inew = inew(~near,1:2) ; jnew = jnew(~near,1:2) ; %------------------------------------- split constraints zset = (1:size(znew,1))' ... + size(vert,1) ; iset = (1:size(inew,1))' ... + size(znew,1) + ... + size(vert,1) ; jset = (1:size(jnew,1))' ... + size(znew,1) + ... + size(inew,1) + ... + size(vert,1) ; set1 = num1( near); set2 = num1(~near); cnew = [conn( set1,1), zset conn( set1,2), zset conn( set2,1), iset conn( set2,2), jset iset, jset ] ; conn = [conn(~ref1,:); cnew]; %------------------------------------- update vertex set vert = [vert; znew(:,1:2)]; vert = [vert; inew(:,1:2)]; vert = [vert; jnew(:,1:2)]; vidx = [zset; iset; jset] ; tcpu.offc = ... tcpu.offc + toc(ttic) ; end % switch(lower(opts.kind)) end tcpu.full = ... tcpu.full + toc(tnow) ; if (~isinf(opts.disp) ) %------------------------------------- print final stats numc = size(conn,1) ; numt = size(tria,1) ; fprintf(+1, ... '%11i %18i %18i\n', ... [iter,numc,numt]) ; end if (opts.dbug) %------------------------------------- print debug timer fprintf(1,'\n') ; fprintf(1,' 1-simplex REF. timer...\n'); fprintf(1,'\n') ; fprintf(1, ... ' FULL: %f \n', tcpu.full); fprintf(1, ... ' BALL: %f \n', tcpu.ball); fprintf(1, ... ' HFUN: %f \n', tcpu.hfun); fprintf(1, ... ' ENCR: %f \n', tcpu.encr); fprintf(1, ... ' OFFC: %f \n', tcpu.offc); fprintf(1,'\n') ; end end function [vert,conn,tria,tnum,iter] = ... cdtref2(vert,conn,tria,tnum, ... node,PSLG,part,opts,hfun,harg,iter) %CDTREF2 constrained Delaunay-refinement for 2-simplex elem- %nts embedded in R^2. % [...] = CDTREF2(...) refines the set of 2-simplex eleme- % nts embedded in the triangulation until all constraints % are satisfied. Specifically, triangles are refined until % all local mesh-spacing and element-shape conditions are % met. Refinement proceeds according to either a Delaunay- % refinement or Frontal-Delaunay type approach, depending % on user-settings. In either case, new steiner points are % introduced to split "bad" triangles - those that violate % the set of prescribed constraints. In the "-DR" type pr- % ocess triangles are split about their circumballs. In % the "-FD" approach, new vertices are positioned such th- % at mesh-spacing and element-shape constraints are satis- % fied in a "locally-optimal" fashion. tcpu.full = +0. ; tcpu.dtri = +0. ; tcpu.tcon = +0. ; tcpu.ball = +0. ; tcpu.hfun = +0. ; tcpu.offc = +0. ; tcpu.filt = +0. ; vidx = (1:size(vert,1))'; %- "new" vert list to test tnow = tic ; near = +.775; while (strcmpi(opts.ref2,'refine')) iter = iter + 1 ; %------------------------------------- build current CDT ttic = tic ; nold = size(vert,1) ; [vert,conn, ... tria,tnum]= deltri2(vert,conn, ... node,PSLG, ... part, .... opts.dtri) ; nnew = size(vert,1) ; vidx = ... [vidx; (nold:nnew)'] ; tcpu.dtri = ... tcpu.dtri + toc(ttic) ; %------------------------------------- build current adj ttic = tic ; [edge,tria]= tricon2(tria,conn) ; tcpu.tcon = ... tcpu.tcon + toc(ttic) ; if (iter>=opts.iter),break; end %------------------------------------- calc. circumballs ttic = tic ; bal1 = cdtbal1(vert,conn) ; bal2 = cdtbal2(vert, ... edge,tria) ; len2 = minlen2(vert,tria) ; rho2 = bal2(:,+3) ./ len2 ; %------------------------------------- refinement scores scr2 = rho2 .* bal2(:,+3) ; tcpu.ball = ... tcpu.ball + toc(ttic) ; %------------------------------------- eval. length-fun. ttic = tic ; if (~isempty(hfun)) if (isnumeric(hfun)) fun0 = hfun * ... ones(size(vert,1),1); fun2 = hfun ; else fun0(vidx) = ... feval(hfun, ... vert(vidx,:), harg{:}); fun0 = fun0(:) ; fun2 = fun0(tria(:,1))... + fun0(tria(:,2))... + fun0(tria(:,3)); fun2 = fun2 / +3. ; end else fun0 = +inf * ... ones(size(vert,1),1); fun2 = +inf ; end siz2 = ... +3. * bal2(:,3)./(fun2.*fun2) ; tcpu.hfun = ... tcpu.hfun + toc(ttic) ; %------------------------------------- refinement queues ref1 = false(size(conn,1),1); ref2 = false(size(tria,1),1); stri = isfeat2(vert,edge,tria) ; ref2(rho2>opts.rho2* ... %- bad rad-edge len. opts.rho2) = true ; ref2(stri) = false ; ref2(siz2>opts.siz2* ... %- bad equiv. length opts.siz2) = true ; num2 = find(ref2); %------------------------------------- dump-out progess! if (mod(iter,opts.disp)==0) numc = size(conn,1) ; numt = size(tria,1) ; fprintf(+1, ... '%11i %18i %18i\n', ... [iter,numc,numt]) ; end %------------------------------------- nothing to refine if (isempty(num2)), break; end [scr2,idx2] = sort( ... scr2(num2),'descend'); num2 = num2(idx2); %------------------------------------- refine "bad" tria switch (lower(opts.kind)) case 'delaunay' %------------------------------------- do circ-ball pt's new2 = zeros(length(num2),3); new2(:,1:2) = bal2(num2,1:2); rmin = ... %- min. insert radii len2(num2)*(1.-eps^.75)^2 ; new2(:, 3) = max( ... bal2(num2,3)*near^2,rmin) ; case 'delfront' %-- off-centre scheme -- refine triangles by positioning %-- new vertices along a local segment of the voronoi %-- diagram, bounded by assoc. circmballs. New points %-- are placed to satisfy the worst of local mesh-length %-- and element-shape constraints. ttic = tic ; %------------------------------------- find frontal edge [lmin,emin] = ... minlen2(vert,tria(num2,:)) ; ftri = false(length(num2),1) ; epos = zeros(length(num2),1) ; tadj = zeros(length(num2),1) ; for ii = +1 : length(epos) epos(ii) = tria( ... num2(ii),emin(ii)+3) ; end %------------------------------------- find frontal tria for enum = +1 : +3 eidx = tria(num2,enum+3) ; ftri = ... ftri | edge(eidx,5) > +0 ; ione = ... num2 ~= edge(eidx,3) ; itwo = ~ione ; tadj(ione) = ... edge(eidx(ione),3); tadj(itwo) = ... edge(eidx(itwo),4); okay = tadj > +0 ; tidx = tadj(okay); ftri(okay) = ... ftri(okay) | ~ref2(tidx) ; end if (~any(ftri)) %- can this happen!? ftri = true(length(num2),+1) ; end %------------------------------------- locate offcentres emid = vert(edge(epos,+1),:) ... + vert(edge(epos,+2),:) ; emid = emid * +0.50 ; elen = sqrt(lmin(:)); %------------------------------------- "voro"-type dist. vvec = bal2(num2,1:2)-emid ; vlen = sqrt(sum(vvec.^2,2)); vvec = vvec ./ [vlen,vlen] ; hmid = fun0(edge(epos,+1),:) ... + fun0(edge(epos,+2),:) ; hmid = hmid * +0.50 ; %------------------------------------- "ball"-type dist. rtri = elen * opts.off2 ; rfac = elen * +0.50 ; dsqr = rtri.^2 - rfac.^2; doff = rtri + ... sqrt(max(+0.,dsqr)) ; %------------------------------------- "size"-type dist. dsiz = +sqrt(3.)/2. * hmid ; %------------------------------------- bind "safe" dist. [dist,ioff] = ... min([dsiz,doff,vlen],[],2) ; %------------------------------------- locate offcentres off2 = ... emid + [dist,dist] .* vvec ; %------------------------------------- iter. "size"-type for isub = +1 : +3 %------------------------------------- eval. length-fun. if (~isempty(hfun)) if (isnumeric(hfun)) hprj = hfun * ... ones(size(off2,1),1) ; else hprj = feval( ... hfun,off2,harg{:}) ; hprj = hprj(:) ; end else hprj = +inf * ... ones(size(off2,1),1) ; end %------------------------------------- "size"-type dist. hprj = .33*hmid + .67*hprj ; dsiz = +sqrt(3.)/2. * hprj ; dsiz(dsiz<elen*.50) = +inf ; %- edge-ball limiter dsiz(dsiz>vlen*.95) = +inf ; %- circ-ball limiter %------------------------------------- bind "safe" dist. [dist,ioff] = ... min([dsiz,doff,vlen],[],2) ; %------------------------------------- locate offcentres off2 = ... emid + [dist,dist] .* vvec ; end orad = ... sqrt((elen*.5).^2 + dist.^2) ; %------------------------------------- do offcentre pt's new2 = ... zeros(length(find(ftri)),+3) ; new2(:,1:2) = off2(ftri,1:2) ; rmin = ... %- min. insert radii lmin(ftri)*(1.-eps^.75)^2 ; new2(:, 3) = max( ... (orad(ftri)*near).^2,rmin); tcpu.offc = ... tcpu.offc + toc (ttic) ; end % switch(lower(opts.kind)) %------------------------------------- inter.-ball dist. ttic = tic ; %------------------------------------- proximity filters [vp,vi] = ... findball(new2,new2(:,1:2)) ; keep = true (size(new2,1),1) ; for ii = size(vp,1):-1:+1 for ip = vp(ii,1) ... : vp(ii,2) jj = vi(ip); if (keep(jj) && ... keep(ii) && ... jj < ii ) keep(ii) = false ; break; end end end new2 = new2(keep,:); %------------------------------------- test encroachment bal1(:,3) = ... (1.-eps^.75) * bal1(:,3); [vp,vi] = ... findball(bal1,new2(:,1:2)); keep = true (size(new2,1),1); for ii = +1:+1:size(vp,1) for ip = vp(ii,1) ... : vp(ii,2) jj = vi(ip); ref1(jj) = true ; keep(ii) = false ; end end %------------------------------------- leave sharp edges ebnd = false(size(edge,1),1); ebnd(tria(stri,4:6)) = true ; enot = ... setset2(conn,edge(ebnd,1:2)); ref1(enot) = false ; %------------------------------------- preserve boundary if (strcmp(lower(opts.ref1),... 'preserve')) ref1(:) = false ; end %------------------------------------- refinement points new2 = new2(keep,:); new1 = bal1(ref1,:); tcpu.filt = ... tcpu.filt + toc(ttic) ; %------------------------------------- split constraints idx1 = ... (1:size(new1))'+size(vert,1) ; idx2 = ... (1:size(new2))'+size(new1,1) ... +size(vert,1) ; cnew = [conn( ref1,1), idx1 conn( ref1,2), idx1]; conn = [conn(~ref1,:); cnew]; vidx = [idx1; idx2]; %------------------------------------- update vertex set nold = size(vert,1); vert = [vert; new1(:,1:2)]; vert = [vert; new2(:,1:2)]; nnew = size(vert,1); if (nnew == nold), break; end %- we *must* be done end tcpu.full = ... tcpu.full + toc(tnow) ; if (~isinf(opts.disp) ) %------------------------------------- print final stats numc = size(conn,1) ; numt = size(tria,1) ; fprintf(+1, ... '%11i %18i %18i\n', ... [iter,numc,numt]) ; end if (opts.dbug) %------------------------------------- print debug timer fprintf(1,'\n') ; fprintf(1,' 2-simplex REF. timer...\n'); fprintf(1,'\n') ; fprintf(1, ... ' FULL: %f \n', tcpu.full); fprintf(1, ... ' DTRI: %f \n', tcpu.dtri); fprintf(1, ... ' TCON: %f \n', tcpu.tcon); fprintf(1, ... ' BALL: %f \n', tcpu.ball); fprintf(1, ... ' HFUN: %f \n', tcpu.hfun); fprintf(1, ... ' OFFC: %f \n', tcpu.offc); fprintf(1, ... ' FILT: %f \n', tcpu.filt); fprintf(1,'\n') ; end end function [opts] = makeopt(opts) %MAKEOPT setup the options structure for REFINE2. if (~isfield(opts,'dtri')) opts.dtri = 'constrained'; else if (~strcmpi(opts.dtri, 'conforming') && ... ~strcmpi(opts.dtri,'constrained') ) error( ... 'refine2:invalidOption','Invalid constraint DTRI.'); end end if (~isfield(opts,'kind')) opts.kind = 'delfront'; else if (~strcmpi(opts.kind, 'delfront') && ... ~strcmpi(opts.kind, 'delaunay') ) error( ... 'refine2:invalidOption','Invalid refinement KIND.'); end end if (~isfield(opts,'ref1')) opts.ref1 = 'refine'; else if (~strcmpi(opts.ref1, 'refine') && ... ~strcmpi(opts.ref1, 'preserve') ) error( ... 'refine2:invalidOption','Invalid refinement REF1.'); end end if (~isfield(opts,'ref2')) opts.ref2 = 'refine'; else if (~strcmpi(opts.ref2, 'refine') && ... ~strcmpi(opts.ref2, 'preserve') ) error( ... 'refine2:invalidOption','Invalid refinement REF2.'); end end if (~isfield(opts,'iter')) opts.iter = +inf; else if (~isnumeric(opts.iter)) error('refine2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.iter)~= +1) error('refine2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.iter <= +0) error('refine2:invalidOptionValues', ... 'Invalid OPT.ITER selection.') ; end end if (~isfield(opts,'disp')) opts.disp = +10 ; else if (~isnumeric(opts.disp)) error('refine2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.disp)~= +1) error('refine2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.disp <= +0) error('refine2:invalidOptionValues', ... 'Invalid OPT.DISP selection.') ; end end if (~isfield(opts,'rho2')) opts.rho2 = 1.025; else if (~isnumeric(opts.rho2)) error('refine2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.rho2)~= +1) error('refine2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.rho2 < +1.) error('refine2:invalidOptionValues', ... 'Invalid OPT.RHO2 selection.') ; end end if (~isfield(opts,'off2')) opts.off2 = 0.933; else if (~isnumeric(opts.off2)) error('refine2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.off2)~= +1) error('refine2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.off2 < +.7) error('refine2:invalidOptionValues', ... 'Invalid OPT.OFF2 selection.') ; end end if (~isfield(opts,'siz1')) opts.siz1 = 1.333; else if (~isnumeric(opts.siz1)) error('refine2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.siz1)~= +1) error('refine2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.siz1 <= 0.) error('refine2:invalidOptionValues', ... 'Invalid OPT.SIZ1 selection.') ; end end if (~isfield(opts,'siz2')) opts.siz2 = 1.300; else if (~isnumeric(opts.siz2)) error('refine2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.siz2)~= +1) error('refine2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.siz2 <= 0.) error('refine2:invalidOptionValues', ... 'Invalid OPT.SIZ2 selection.') ; end end if (~isfield(opts,'dbug')) opts.dbug = false; else if (~islogical(opts.dbug)) error('refine2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.dbug)~= +1) error('refine2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end end end
github
mathematical-tours/mathematical-tours.github.io-master
tridemo.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-2d/tridemo.m
27,638
utf_8
0d592600bfff8aa51497b1c6ea94a5a3
function tridemo(demo) %TRIDEMO run various triangulation demos for MESH2D. % TRIDEMO(N) runs the N-TH demo problem. The following de- % mo problems are currently available: % % - DEMO-0: very simple example to start with -- construct a % mesh for a square domain with a square hold cut from its % centre. % % - DEMO-1: explore the impact of the "radius-edge" thresho- % ld (RHO2) on mesh density/quality. % % - DEMO-2: explore the impact of the "Frontal-Delaunay" vs. % "Delaunay-refinement " algorithms. % % - DEMO-3: explore impact of user-defined mesh-size constr- % aints. % % - DEMO-4: explore impact of "hill-climbing" mesh optimisa- % tions. % % - DEMO-5: assemble triangulations for multi-part geometry % definitions. % % - DEMO-6: assemble triangulations for geometries with int- % ernal constraints. % % - DEMO-7: investigate the use of quadtree-type refinement. % % - DEMO-8: explore impact of user-defined mesh-size constr- % aints. % % - DEMO-9: larger-scale problem, mesh refinement + optimis- % ation. % % - DEMO10: medium-scale problem, mesh refinement + optimis- % ation. % % See also REFINE2, SMOOTH2, TRIDIV2, FIXGEO2 %----------------------------------------------------------- % Darren Engwirda : 2017 -- % Email : [email protected] % Last updated : 09/07/2018 %----------------------------------------------------------- close all; libpath(); switch (demo) case 0, demo0 (); case 1, demo1 (); case 2, demo2 (); case 3, demo3 (); case 4, demo4 (); case 5, demo5 (); case 6, demo6 (); case 7, demo7 (); case 8, demo8 (); case 9, demo9 (); case 10, demo10(); otherwise error('tridemo:invalidSelection', 'Invalid selection!') ; end end function demo0 %DEMO0 a very simple example to start with -- mesh a square %domain with a square hold cut from its centre. fprintf(1, [ ... ' A very simple example to start with -- construct a mesh for \n', ... ' a simple square domain with a square hole cut from its cen- \n', ... ' tre. The geometry is specified as a Planar Straight-Line \n', ... ' Graph (PSLG) -- a list of xy coordinates, or "nodes", and a \n', ... ' list of straight-line connections between nodes, or "edges".\n', ... ' The REFINE2 routine is used to build a triangulation of the \n', ... ' domain that: (a) conforms to the geometry, and (b) contains \n', ... ' only "nicely" shaped triangles. In the second panel, a mesh \n', ... ' that additionally satisfies "mesh-size" constrains is cons- \n', ... ' structed -- ' ] ) ; %------------------------------------------- setup geometry node = [ % list of xy "node" coordinates 0, 0 % outer square 9, 0 9, 9 0, 9 4, 4 % inner square 5, 4 5, 5 4, 5 ] ; edge = [ % list of "edges" between nodes 1, 2 % outer square 2, 3 3, 4 4, 1 5, 6 % inner square 6, 7 7, 8 8, 5 ] ; %------------------------------------------- call mesh-gen. [vert,etri, ... tria,tnum] = refine2(node,edge) ; %------------------------------------------- draw tria-mesh figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; %------------------------------------------- call mesh-gen. hfun = +.5 ; % uniform "target" edge-lengths [vert,etri, ... tria,tnum] = refine2(node,edge,[],[],hfun) ; %------------------------------------------- draw tria-mesh figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.35,.50,.30,.35]) ; end function demo1 %DEMO1 explore impact of RHO2 threshold on mesh density/qua- %lity. filename = mfilename('fullpath'); filepath = fileparts( filename ); meshfile = ... [filepath,'/poly-data/lake.msh']; [node,edge] = triread( meshfile ); fprintf(1, [ ... ' The REFINE2 routine can be used to build guaranteed-quality \n', ... ' Delaunay triangulations for general polygonal geometries in \n', ... ' the two-dimensional plane. The "quality" of elements in the \n', ... ' triangulation can be controlled using the "radius-edge" bo- \n', ... ' und RHO2. \n', ... ] ) ; %---------------------------------------------- RHO2 = +1.50 fprintf(1, ' \n') ; fprintf(1, [ ... ' Setting large values for RHO2, (RHO2 = 1.50 here) generates \n', ... ' sparse triangulations with poor worst-case angle bounds. \n', ... ] ) ; opts.kind = 'delaunay'; opts.rho2 = +1.50 ; [vert,etri, ... tria,tnum] = refine2(node,edge,[] ,opts) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['TRIA-MESH: RHO2<=+1.50, |TRIA|=' , ... num2str(size(tria,1))]) ; %---------------------------------------------- RHO2 = +1.00 fprintf(1, [ ... ' Setting small values for RHO2, (RHO2 = 1.00 here) generates \n', ... ' dense triangulations with good worst-case angle bounds. \n', ... ] ) ; opts.kind = 'delaunay'; opts.rho2 = +1.00 ; [vert,etri, ... tria,tnum] = refine2(node,edge,[] ,opts) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['TRIA-MESH: RHO2<=+1.00, |TRIA|=' , ... num2str(size(tria,1))]) ; drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.35,.50,.30,.35]) ; end function demo2 %DEMO2 explore impact of refinement "KIND" on mesh quality/- %density. filename = mfilename('fullpath'); filepath = fileparts( filename ); meshfile = ... [filepath,'/poly-data/lake.msh']; [node,edge] = triread( meshfile ); fprintf(1, [ ... ' The REFINE2 routine supports two Delaunay-based refinement \n', ... ' algorithms: a "standard" Delaunay-refinement type approach, \n', ... ' and a "Frontal-Delaunay" technique. For problems constrain- \n', ... ' ed by element "quality" alone, the Frontal-Delaunay approa- \n', ... ' ch typically produces sigificantly sparser meshes. in both \n', ... ' cases, the same worst-case element quality bounds are sati- \n', ... ' fied in a guaranteed manner. \n', ... ] ) ; %---------------------------------------------- = "DELAUNAY" opts.kind = 'delaunay'; opts.rho2 = +1.00 ; [vert,etri, ... tria,tnum] = refine2(node,edge,[] ,opts) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; hold on; axis image off; title(['TRIA-MESH: KIND=DELAUNAY, |TRIA|=', ... num2str(size(tria,1))]) ; %---------------------------------------------- = "DELFRONT" opts.kind = 'delfront'; opts.rho2 = +1.00 ; [vert,etri, ... tria,tnum] = refine2(node,edge,[] ,opts) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['TRIA-MESH: KIND=DELFRONT, |TRIA|=', ... num2str(size(tria,1))]) ; drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.35,.50,.30,.35]) ; end function demo3 %DEMO3 explore impact of user-defined mesh-size constraints. filename = mfilename('fullpath'); filepath = fileparts( filename ); meshfile = ... [filepath,'/poly-data/airfoil.msh']; [node,edge] = triread( meshfile ); fprintf(1, [ ... ' Additionally, the REFINE2 routine supports size-driven ref- \n', ... ' inement, producing meshes that satisfy constraints on elem- \n', ... ' ent edge-lengths. The LFSHFN2 routine can be used to create \n', ... ' mesh-size functions based on an estimate of the "local-fea- \n', ... ' ture-size" associated with a polygonal domain. The Frontal- \n', ... ' Delaunay refinement algorithm discussed in DEMO-2 is espec- \n', ... ' ially good at generating high-quality triangulations in the \n', ... ' presence of mesh-size constraints. \n', ... ] ) ; %---------------------------------------------- do size-fun. olfs.dhdx = +0.15; [vlfs,tlfs, ... hlfs] = lfshfn2(node,edge, ... [] ,olfs) ; [slfs] = idxtri2(vlfs,tlfs) ; figure; patch('faces',tlfs(:,1:3),'vertices',vlfs , ... 'facevertexcdata' , hlfs, ... 'facecolor','interp', ... 'edgecolor','none') ; hold on; axis image off; title(['MESH-SIZE: KIND=DELAUNAY, |TRIA|=', ... num2str(size(tlfs,1))]) ; %---------------------------------------------- do mesh-gen. hfun = @trihfn2; [vert,etri, ... tria,tnum] = refine2(node,edge,[],[],hfun , ... vlfs,tlfs,slfs,hlfs); figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['TRIA-MESH: KIND=DELFRONT, |TRIA|=', ... num2str(size(tria,1))]) ; drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.35,.50,.30,.35]) ; end function demo4 %DEMO4 explore impact of "hill-climbing" mesh optimisations. filename = mfilename('fullpath'); filepath = fileparts( filename ); meshfile = ... [filepath,'/poly-data/airfoil.msh']; [node,edge] = triread( meshfile ); fprintf(1, [ ... ' The SMOOTH2 routine provides iterative mesh "smoothing" ca- \n', ... ' pabilities, seeking to improve triangulation quality by ad- \n', ... ' justing the vertex positions and mesh topology. Specifical- \n', ... ' ly, a "hill-climbing" type optimisation is implemented, gu- \n', ... ' aranteeing that mesh-quality is improved monotonically. The \n', ... ' DRAWSCR routine provides detailed analysis of triangulation \n', ... ' quality, plotting histograms of various quality metrics. \n', ... ] ) ; %---------------------------------------------- do size-fun. olfs.dhdx = +0.15; [vlfs,tlfs, ... hlfs] = lfshfn2(node,edge, ... [] ,olfs) ; [slfs] = idxtri2(vlfs,tlfs) ; %---------------------------------------------- do mesh-gen. hfun = @trihfn2; [vert,etri, ... tria,tnum] = refine2(node,edge,[],[],hfun , ... vlfs,tlfs,slfs,hlfs); figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['MESH-REF.: KIND=DELFRONT, |TRIA|=', ... num2str(size(tria,1))]) ; %---------------------------------------------- do mesh-opt. [vnew,enew, ... tnew,tnum] = smooth2(vert,etri,tria,tnum) ; figure; patch('faces',tnew(:,1:3),'vertices',vnew, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['MESH-OPT.: KIND=DELFRONT, |TRIA|=', ... num2str(size(tnew,1))]) ; hvrt = trihfn2(vert,vlfs,tlfs,slfs,hlfs) ; hnew = trihfn2(vnew,vlfs,tlfs,slfs,hlfs) ; tricost(vert,etri,tria,tnum,hvrt) ; tricost(vnew,enew,tnew,tnum,hnew) ; drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.35,.50,.30,.35]) ; set(figure(3),'units','normalized', ... 'position',[.05,.05,.30,.35]) ; set(figure(4),'units','normalized', ... 'position',[.35,.05,.30,.35]) ; end function demo5 %DEMO5 assemble triangulations for multi-part geometry defi- %nitions. fprintf(1, [ ... ' Both the REFINE2 and SMOOTH2 routines also support "multi- \n', ... ' part" geometry definitions -- generating conforming triang- \n', ... ' ulations that conform to internal and external constraints. \n', ... ] ) ; %---------------------------------------------- create geom. nod1 = [ -1., -1.; +1., -1. +1., +1.; -1., +1. ] ; edg1 = [ 1 , 2 ; 2 , 3 3 , 4 ; 4 , 1 ] ; edg1(:,3) = +0; nod2 = [ +.1, +0.; +.8, +0. +.8, +.8; +.1, +.8 ] ; edg2 = [ 1 , 2 ; 2 , 3 3 , 4 ; 4 , 1 ] ; edg2(:,3) = +1; adel = 2.*pi / +64 ; amin = 0.*pi ; amax = 2.*pi - adel; xcir = +.33 * ... cos(amin:adel:amax)'; ycir = +.33 * ... sin(amin:adel:amax)'; xcir = xcir - .33; ycir = ycir - .25; ncir = [xcir,ycir] ; numc = size(ncir,1); ecir(:,1) = ... [(1:numc-1)'; numc] ; ecir(:,2) = ... [(2:numc-0)'; +1 ] ; ecir(:,3) = +2; edg2(:,1:2) = ... edg2(:,1:2)+size(nod1,1); edge = [edg1; edg2]; node = [nod1; nod2]; ecir(:,1:2) = ... ecir(:,1:2)+size(node,1); edge = [edge; ecir]; node = [node; ncir]; %-- the PART argument is a cell array that defines individu- %-- al polygonal "parts" of the overall geometry. Each elem- %-- ent PART{I} is a list of edge indexes, indicating which %-- edges make up the boundary of each region. part{1} = [ ... find(edge(:,3) == 0) find(edge(:,3) == 1) find(edge(:,3) == 2) ] ; part{2} = [ ... find(edge(:,3) == 1) ] ; part{3} = [ ... find(edge(:,3) == 2) ] ; edge = edge(:,1:2) ; %---------------------------------------------- do size-fun. hmax = +0.045 ; [vlfs,tlfs, ... hlfs] = lfshfn2(node,edge, ... part) ; hlfs = min(hmax,hlfs) ; [slfs] = idxtri2(vlfs,tlfs) ; %---------------------------------------------- do mesh-gen. hfun = @trihfn2; [vert,etri, ... tria,tnum] = refine2(node,edge,part, [], ... hfun, ... vlfs,tlfs,slfs,hlfs) ; %---------------------------------------------- do mesh-opt. [vert,etri, ... tria,tnum] = smooth2(vert,etri,tria,tnum) ; figure; patch('faces',tria(tnum==1,1:3),'vertices',vert, ... 'facecolor',[1.,1.,1.], ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',tria(tnum==2,1:3),'vertices',vert, ... 'facecolor',[.9,.9,.9], ... 'edgecolor',[.2,.2,.2]) ; patch('faces',tria(tnum==3,1:3),'vertices',vert, ... 'facecolor',[.8,.8,.8], ... 'edgecolor',[.2,.2,.2]) ; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['MESH-OPT.: KIND=DELFRONT, |TRIA|=', ... num2str(size(tria,1))]) ; figure; patch('faces',tlfs(:,1:3),'vertices',vlfs , ... 'facevertexcdata' , hlfs, ... 'facecolor','interp', ... 'edgecolor','none') ; hold on; axis image off; title(['MESH-SIZE: KIND=DELAUNAY, |TRIA|=', ... num2str(size(tlfs,1))]) ; tricost(vert,etri,tria,tnum); drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.35,.50,.30,.35]) ; set(figure(3),'units','normalized', ... 'position',[.05,.05,.30,.35]) ; end function demo6 %DEMO6 build triangulations for geometries with internal co- %nstraints. fprintf(1, [ ... ' Both the REFINE2 and SMOOTH2 routines also support geometr- \n', ... ' ies containing "internal" constraints. \n', ... ] ) ; %---------------------------------------------- create geom. node = [ -1., -1.; +1., -1. +1., +1.; -1., +1. +.0, +.0; +.2, +.7 +.6, +.2; +.4, +.8 +0., +.5; -.7, +.3 -.1, +.1; -.6, +.5 -.9, -.8; -.6, -.7 -.3, -.6; +.0, -.5 +.3, -.4; -.3, +.4 -.1, +.3 ] ; edge = [ 1 , 2 ; 2 , 3 3 , 4 ; 4 , 1 5 , 6 ; 5 , 7 5 , 8 ; 5 , 9 5 , 10 ; 5 , 11 5 , 12 ; 5 , 13 5 , 14 ; 5 , 15 5 , 16 ; 5 , 17 5 , 18 ; 5 , 19 ] ; %-- the geometry must be split into its "exterior" and "int- %-- erior" components using the optional PART argument. Each %-- PART{I} specified should define the "exterior" boundary %-- of a polygonal region. "Interior" constraints should not %-- be referenced by any polygon in PART -- they are imposed %-- as isolated edge constraints. part{1} = [1,2,3,4] ; %---------------------------------------------- do size-fun. hmax = +0.175 ; %---------------------------------------------- do mesh-gen. opts.kind = 'delaunay' ; [vert,etri, ... tria,tnum] = refine2(node,edge,part,opts, ... hmax) ; %---------------------------------------------- do mesh-opt. [vert,etri, ... tria,tnum] = smooth2(vert,etri,tria,tnum) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',2.0) ; title(['MESH-OPT.: KIND=DELAUNAY, |TRIA|=', ... num2str(size(tria,1))]) ; tricost(vert,etri,tria,tnum); drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.05,.05,.30,.35]) ; end function demo7 %DEMO7 investigate the use of quadtree-type mesh refinement. filename = mfilename('fullpath'); filepath = fileparts( filename ); meshfile = ... [filepath,'/poly-data/channel.msh']; [node,edge] = triread( meshfile ); fprintf(1, [ ... ' The TRIDIV2 routine can also be used to refine existing tr- \n', ... ' angulations. Each triangle is split into four new sub-tria- \n', ... ' ngles, such that element shape is preserved. Combining the \n', ... ' TRIDIV2 and SMOOTH2 routines allows for hierarchies of high \n', ... ' quality triangulations to be generated. \n', ... ] ) ; %---------------------------------------------- do size-fun. [vlfs,tlfs, ... hlfs] = lfshfn2(node,edge) ; [slfs] = idxtri2(vlfs,tlfs) ; pmax = max(node,[],1); pmin = min(node,[],1); hmax = mean(pmax-pmin)/+17 ; hlfs = min(hmax,hlfs); %---------------------------------------------- do mesh-gen. hfun = @trihfn2; [vert,etri, ... tria,tnum] = refine2(node,edge,[],[],hfun , ... vlfs,tlfs,slfs,hlfs); %---------------------------------------------- do mesh-opt. [vert,etri, ... tria,tnum] = smooth2(vert,etri,tria,tnum) ; [vnew,enew, ... tnew,tnum] = tridiv2(vert,etri,tria,tnum) ; [vnew,enew, ... tnew,tnum] = smooth2(vnew,enew,tnew,tnum) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['MESH-OPT.: KIND=DELFRONT, |TRIA|=', ... num2str(size(tria,1))]) ; figure; patch('faces',tnew(:,1:3),'vertices',vnew, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',etri(:,1:2),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['MESH-OPT.: KIND=DELFRONT, |TRIA|=', ... num2str(size(tnew,1))]) ; tricost(vert,etri,tria,tnum); tricost(vnew,enew,tnew,tnum); drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.35,.50,.30,.35]) ; set(figure(3),'units','normalized', ... 'position',[.05,.05,.30,.35]) ; set(figure(4),'units','normalized', ... 'position',[.35,.05,.30,.35]) ; end function demo8 %DEMO8 explore impact of "hill-climbing" mesh optimisations. %---------------------------------------------- create geom. node = [ -1., -1.; +3., -1. +3., +1.; -1., +1. ] ; edge = [ 1 , 2 ; 2 , 3 3 , 4 ; 4 , 1 ] ; adel = 2.*pi / +64 ; amin = 0.*pi ; amax = 2.*pi - adel; xcir = +.20 * ... cos(amin:adel:amax)'; ycir = +.20 * ... sin(amin:adel:amax)'; ncir = [xcir,ycir] ; numc = size(ncir,1); ecir(:,1) = ... [(1:numc-1)'; numc] ; ecir(:,2) = ... [(2:numc-0)'; +1 ] ; ecir = ecir+size(node,1); edge = [edge; ecir]; node = [node; ncir]; %---------------------------------------------- do mesh-gen. hfun = @hfun8 ; [vert,etri, ... tria,tnum] = refine2(node,edge,[],[],hfun); %---------------------------------------------- do mesh-opt. [vert,etri, ... tria,tnum] = smooth2(vert,etri,tria,tnum) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['MESH-OPT.: KIND=DELFRONT, |TRIA|=', ... num2str(size(tria,1))]) ; figure; patch('faces',tria(:,1:3),'vertices',vert , ... 'facevertexcdata' , hfun8(vert), ... 'facecolor','interp', ... 'edgecolor','none') ; hold on; axis image off; title('MESH-SIZE function.'); hvrt = feval(hfun,vert) ; tricost(vert,etri,tria,tnum,hvrt) ; drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.35,.50,.30,.35]) ; set(figure(3),'units','normalized', ... 'position',[.05,.05,.30,.35]) ; end function [hfun] = hfun8(test) %HFUN8 user-defined mesh-size function for DEMO-8. hmax = +.05 ; hmin = +.01 ; xmid = +0.0 ; ymid = +0.0 ; hcir = exp( -.5*(test(:,1)-xmid).^2 ... -2.*(test(:,2)-ymid).^2 ) ; hfun = hmax - (hmax-hmin) * hcir ; end function demo9 %DEMO9 larger-scale problem, mesh refinement + optimisation. filename = mfilename('fullpath'); filepath = fileparts( filename ); meshfile = ... [filepath,'/poly-data/islands.msh']; [node,edge] = triread( meshfile ); %---------------------------------------------- do size-fun. [vlfs,tlfs, ... hlfs] = lfshfn2(node,edge) ; [slfs] = idxtri2(vlfs,tlfs) ; %---------------------------------------------- do mesh-gen. hfun = @trihfn2; [vert,etri, ... tria,tnum] = refine2(node,edge,[],[],hfun , ... vlfs,tlfs,slfs,hlfs); %---------------------------------------------- do mesh-opt. [vert,etri, ... tria,tnum] = smooth2(vert,etri,tria,tnum) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['MESH-OPT.: KIND=DELFRONT, |TRIA|=', ... num2str(size(tria,1))]) ; tricost(vert,etri,tria,tnum); drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.05,.05,.30,.35]) ; end function demo10 %DEMO10 medium-scale problem mesh refinement + optimisation. filename = mfilename('fullpath'); filepath = fileparts( filename ); meshfile = ... [filepath,'/poly-data/river.msh']; [node,edge] = triread( meshfile ); %---------------------------------------------- do size-fun. [vlfs,tlfs, ... hlfs] = lfshfn2(node,edge) ; [slfs] = idxtri2(vlfs,tlfs) ; %---------------------------------------------- do mesh-gen. hfun = @trihfn2; [vert,etri, ... tria,tnum] = refine2(node,edge,[],[],hfun , ... vlfs,tlfs,slfs,hlfs); %---------------------------------------------- do mesh-opt. [vert,etri, ... tria,tnum] = smooth2(vert,etri,tria,tnum) ; figure; patch('faces',tria(:,1:3),'vertices',vert, ... 'facecolor','w', ... 'edgecolor',[.2,.2,.2]) ; hold on; axis image off; patch('faces',edge(:,1:2),'vertices',node, ... 'facecolor','w', ... 'edgecolor',[.1,.1,.1], ... 'linewidth',1.5) ; title(['MESH-OPT.: KIND=DELFRONT, |TRIA|=', ... num2str(size(tria,1))]) ; tricost(vert,etri,tria,tnum); drawnow; set(figure(1),'units','normalized', ... 'position',[.05,.50,.30,.35]) ; set(figure(2),'units','normalized', ... 'position',[.05,.05,.30,.35]) ; end
github
mathematical-tours/mathematical-tours.github.io-master
tricost.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-2d/tricost.m
15,234
utf_8
7da2993c7253435846c34a8b1244bc43
function tricost(varargin) %TRICOST draw quality-metrics for a 2-simplex triangulation %embedded in the two-dimensional plane. % TRICOST(VERT,EDGE,TRIA,TNUM) draws histograms of quality % metrics for the triangulation. % VERT is a V-by-2 array of XY coordinates in the triangu- % lation, EDGE is an array of constrained edges, TRIA is a % T-by-3 array of triangles, and TNUM is a T-by-1 array of % part indices. Each row of TRIA and EDGE define an eleme- % nt. VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and VERT(TRIA % (II,3),:) are the coordinates of the II-TH triangle. The % edges in EDGE are defined in a similar manner. NUM is an % array of part indexing, such that TNUM(II) is the index % of the part in which the II-TH triangle resides. % % TRICOST(...,HVRT) additionally draws histograms of rela- % tive edge-length, indicating conformance to the spacing % constraints. HVRT is a V-by-1 array of spacing informat- % ion, per an evaluation of the mesh-size function at the % mesh vertices VERT. % % See also REFINE2, SMOOTH2 %----------------------------------------------------------- % Darren Engwirda : 2017 -- % Email : [email protected] % Last updated : 09/07/2018 %----------------------------------------------------------- vert = [] ; conn = [] ; tria = [] ; tnum = [] ; hvrt = [] ; %---------------------------------------------- extract args if (nargin>=+1), vert = varargin{1}; end if (nargin>=+2), conn = varargin{2}; end if (nargin>=+3), tria = varargin{3}; end if (nargin>=+4), tnum = varargin{4}; end if (nargin>=+5), hvrt = varargin{5}; end %---------------------------------------------- basic checks if ( ~isnumeric(vert) || ... ~isnumeric(conn) || ... ~isnumeric(tria) || ... ~isnumeric(tnum) || ... ~isnumeric(hvrt) ) error('tricost:incorrectInputClass' , ... 'Incorrect input class.') ; end %---------------------------------------------- basic checks if (ndims(vert) ~= +2 || ... ndims(conn) ~= +2 || ... ndims(tria) ~= +2 ) error('tricost:incorrectDimensions' , ... 'Incorrect input dimensions.'); end if (size(vert,2)~= +2 || ... size(conn,2) < +2 || ... size(tria,2) < +3 ) error('tricost:incorrectDimensions' , ... 'Incorrect input dimensions.'); end nvrt = size(vert,1) ; ntri = size(tria,1) ; %---------------------------------------------- basic checks if (min(min(conn(:,1:2))) < +1 || ... max(max(conn(:,1:2))) > nvrt ) error('tricost:invalidInputs', ... 'Invalid EDGE input array.') ; end if (min(min(tria(:,1:3))) < +1 || ... max(max(tria(:,1:3))) > nvrt ) error('tricost:invalidInputs', ... 'Invalid TRIA input array.') ; end %-- borrowed from the JIGSAW library! %-- draw sub-axes directly -- sub-plot gives %-- silly inconsistent ax spacing...! axpos31 = [.125,.750,.800,.150] ; axpos32 = [.125,.450,.800,.150] ; axpos33 = [.125,.150,.800,.150] ; axpos41 = [.125,.835,.800,.135] ; axpos42 = [.125,.590,.800,.135] ; axpos43 = [.125,.345,.800,.135] ; axpos44 = [.125,.100,.800,.135] ; %-- draw cost histograms for 2-tria elements figure; set(gcf,'color','w','units','normalized', ... 'position',[.05,.10,.30,.30]); if (~isempty(hvrt)) %-- have size-func data axes('position',axpos41); hold on; scrhist(triscr2(vert,tria),'tria3'); axes('position',axpos42); hold on; anghist(triang2(vert,tria),'tria3'); axes('position',axpos43); hold on; hfnhist(relhfn2(vert, ... tria,hvrt),'tria3'); axes('position',axpos44); hold on; deghist(trideg2(vert,tria),'tria3'); else %-- null size-func data axes('position',axpos31); hold on; scrhist(triscr2(vert,tria),'tria3'); axes('position',axpos32); hold on; anghist(triang2(vert,tria),'tria3'); axes('position',axpos33); hold on; deghist(trideg2(vert,tria),'tria3'); end end function [mf] = mad(ff) %MAD return mean absolute deviation (from the mean). mf = mean(abs(ff-mean(ff))) ; end function deghist(dd,ty) %DEGHIST draw histogram for "degree" quality-metric. dd = dd(:); be = 1:max(dd); hc = histc(dd,be); r = [.85,.00,.00] ; y = [1.0,.95,.00] ; g = [.00,.90,.00] ; k = [.60,.60,.60] ; bar(be,hc,1.05,'facecolor',k,'edgecolor',k); axis tight; set(gca,'ycolor', get(gca,'color'),'ytick',[],... 'xtick',2:2:12,'layer','top','fontsize',... 14,'linewidth',2.,'ticklength',[.025,.025],... 'box','off','xlim',[0,12]); switch (ty) case 'tria4' if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-.225,0,'$|d|_{\tau}$',... 'horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-.225,0, '|d|_{\tau}' ,... 'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end case 'tria3' if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-.225,0,'$|d|_{f}$',... 'horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-.225,0, '|d|_{\tau}' ,... 'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end end end function anghist(ad,ty) %ANGHIST draw histogram for "angle" quality-metric. ad = ad(:); be = linspace(0.,180.,91); bm =(be(1:end-1)+be(2:end))/2.; hc = histc(ad,be); switch (ty) case 'tria4' poor = bm < 10. | bm >= 160. ; okay =(bm >= 10. & bm < 20. )| ... (bm >= 140. & bm < 160.); good =(bm >= 20. & bm < 30. )| ... (bm >= 120. & bm < 140.); best = bm >= 30. & bm < 120. ; case 'tria3' poor = bm < 15. | bm >= 150. ; okay =(bm >= 15. & bm < 30. )| ... (bm >= 120. & bm < 150.); good =(bm >= 30. & bm < 45. )| ... (bm >= 90. & bm < 120.); best = bm >= 45. & bm < 90. ; end r = [.85,.00,.00] ; y = [1.0,.95,.00] ; g = [.00,.90,.00] ; k = [.60,.60,.60] ; bar(bm(poor),hc(poor),1.05,... 'facecolor',r,'edgecolor',r) ; bar(bm(okay),hc(okay),1.05,... 'facecolor',y,'edgecolor',y) ; bar(bm(good),hc(good),1.05,... 'facecolor',g,'edgecolor',g) ; bar(bm(best),hc(best),1.05,... 'facecolor',k,'edgecolor',k) ; axis tight; set(gca,'ycolor', get(gca,'color'),'ytick',[],... 'xtick',0:30:180,'layer','top','fontsize',... 14,'linewidth',2.,'ticklength',[.025,.025],... 'box','off','xlim',[0.,180.]) ; mina = max(1.000,min(ad)); %%!! so that axes don't obscure! maxa = min(179.0,max(ad)); bara = mean(ad(:)); mada = mad (ad(:)); line([ mina, mina],... [0,max(hc)],'color','r','linewidth',1.5); line([ maxa, maxa],... [0,max(hc)],'color','r','linewidth',1.5); if ( mina > 25.0) text(mina-1.8,.90*max(hc),num2str(min(ad),'%16.1f'),... 'horizontalalignment',... 'right','fontsize',15) ; else text(mina+1.8,.90*max(hc),num2str(min(ad),'%16.1f'),... 'horizontalalignment',... 'left' ,'fontsize',15) ; end if ( maxa < 140.) text(maxa+1.8,.90*max(hc),num2str(max(ad),'%16.1f'),... 'horizontalalignment',... 'left' ,'fontsize',15) ; else text(maxa-1.8,.90*max(hc),num2str(max(ad),'%16.1f'),... 'horizontalalignment',... 'right','fontsize',15) ; end if ( maxa < 100.) if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(maxa-16.,.45*max(hc),... '$\bar{\sigma}_{\theta}\!= $',... 'horizontalalignment', 'left',... 'fontsize',16,'interpreter','latex') ; text(maxa+1.8,.45*max(hc),num2str(mad(ad),'%16.2f'),... 'horizontalalignment',... 'left' ,'fontsize',15) ; end else if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(maxa-16.,.45*max(hc),... '$\bar{\sigma}_{\theta}\!= $',... 'horizontalalignment', 'left',... 'fontsize',16,'interpreter','latex') ; text(maxa+1.8,.45*max(hc),num2str(mad(ad),'%16.3f'),... 'horizontalalignment',... 'left' ,'fontsize',15) ; end end switch (ty) case 'tria4' if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-9.0,0.0,'$\theta_{\tau}$',... 'horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-9.0,0.0, '\theta_{\tau}' ,... 'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end case 'tria3' if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-9.0,0.0,'$\theta_{f}$',... 'horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-9.0,0.0, '\theta_{f}' ,... 'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end end end function scrhist(sc,ty) %SCRHIST draw histogram for "score" quality-metric. sc = sc(:); be = linspace(0.,1.,101); bm = (be(1:end-1)+be(2:end)) / 2.; hc = histc(sc,be); switch (ty) case{'tria4','dual4'} poor = bm < .25 ; okay = bm >= .25 & bm < .50 ; good = bm >= .50 & bm < .75 ; best = bm >= .75 ; case{'tria3','dual3'} poor = bm < .30 ; okay = bm >= .30 & bm < .60 ; good = bm >= .60 & bm < .90 ; best = bm >= .90 ; end r = [.85,.00,.00] ; y = [1.0,.95,.00] ; g = [.00,.90,.00] ; k = [.60,.60,.60] ; bar(bm(poor),hc(poor),1.05,... 'facecolor',r,'edgecolor',r) ; bar(bm(okay),hc(okay),1.05,... 'facecolor',y,'edgecolor',y) ; bar(bm(good),hc(good),1.05,... 'facecolor',g,'edgecolor',g) ; bar(bm(best),hc(best),1.05,... 'facecolor',k,'edgecolor',k) ; axis tight; set(gca,'ycolor', get(gca,'color'),'ytick',[],... 'xtick',.0:.2:1.,'layer','top','fontsize',... 14,'linewidth',2.,'ticklength',[.025,.025],... 'box','off','xlim',[0.,1.]) ; mins = max(0.010,min(sc)); %%!! so that axes don't obscure! maxs = min(0.990,max(sc)); line([ mins, mins],... [0,max(hc)],'color','r','linewidth',1.5); line([mean(sc),mean(sc)],... [0,max(hc)],'color','r','linewidth',1.5); if ( mins > .4) text(mins-.01,.9*max(hc),num2str(min(sc),'%16.3f'),... 'horizontalalignment',... 'right','fontsize',15) ; else text(mins+.01,.9*max(hc),num2str(min(sc),'%16.3f'),... 'horizontalalignment',... 'left' ,'fontsize',15) ; end if ( mean(sc) > mins + .150) text(mean(sc)-.01,.9*max(hc),num2str(mean(sc),'%16.3f'),... 'horizontalalignment','right','fontsize',15) ; end switch (ty) case 'tria4' if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-.04,0.0, ... '$\mathcal{Q}^{\mathcal{T}}_{\tau}$',... 'horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-.04,0.0,'Q^{t}_{\tau}',... 'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end case 'tria3' if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-.04,0.0, ... '$\mathcal{Q}^{\mathcal{T}}_{f}$',... 'horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-.04,0.0,'Q^{t}_{f}',... 'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end case 'dual4' if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-.04,0.0, ... '$\mathcal{Q}^{\mathcal{D}}_{\tau}$',... 'horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-.04,0.0,'Q^{d}_{\tau}',... 'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end case 'dual3' if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-.04,0.0, ... '$\mathcal{Q}^{\mathcal{D}}_{f}$',... 'horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-.04,0.0,'Q^{d}_{f}',... 'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end end end function hfnhist(hf,ty) %HFNHIST draw histogram for "hfunc" quality-metric. be = linspace(0.,2.,101); bm = (be(1:end-1)+be(2:end)) / 2.; hc = histc(hf,be); poor = bm < .40 | bm >= 1.6 ; okay =(bm >= .40 & bm < .60 )| ... (bm >= 1.4 & bm < 1.6 ); good =(bm >= .60 & bm < .80 )| ... (bm >= 1.2 & bm < 1.4 ); best = bm >= .80 & bm < 1.2 ; r = [.85,.00,.00] ; y = [1.0,.95,.00] ; g = [.00,.90,.00] ; k = [.60,.60,.60] ; bar(bm(poor),hc(poor),1.05,... 'facecolor',r,'edgecolor',r) ; bar(bm(okay),hc(okay),1.05,... 'facecolor',y,'edgecolor',y) ; bar(bm(good),hc(good),1.05,... 'facecolor',g,'edgecolor',g) ; bar(bm(best),hc(best),1.05,... 'facecolor',k,'edgecolor',k) ; axis tight; set(gca,'ycolor', get(gca,'color'),'ytick',[],... 'xtick',.0:.5:2.,'layer','top','fontsize',... 14,'linewidth',2.,'ticklength',[.025,.025],... 'box','off','xlim',[0.,2.]); line([max(hf),max(hf)],... [0,max(hc)],'color','r','linewidth',1.5); text(max(hf)+.02,.90*max(hc),num2str(max(hf),'%16.2f'),... 'horizontalalignment','left','fontsize',15) ; if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(max(hf)-.18,.45*max(hc),'$\bar{\sigma}_{h}\! = $',... 'horizontalalignment','left',... 'fontsize',16,'interpreter','latex') ; text(max(hf)+.02,.45*max(hc),num2str(mad(hf),'%16.2f'),... 'horizontalalignment','left','fontsize',15) ; end if ( ~(exist('OCTAVE_VERSION','builtin') > +0) ) text(-0.10,0.0,'$h_{r}$','horizontalalignment','right',... 'fontsize',22,'interpreter','latex') ; else text(-0.10,0.0, 'h_{r}' ,'horizontalalignment','right',... 'fontsize',22,'interpreter', 'tex') ; end end
github
mathematical-tours/mathematical-tours.github.io-master
smooth2.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-2d/smooth2.m
18,053
utf_8
f11e4a411ca1d0f078610452258c13e9
function [vert,conn,tria,tnum] = smooth2(varargin) %SMOOTH2 "hill-climbing" mesh-smoothing for two-dimensional, %2-simplex triangulations. % [VERT,EDGE,TRIA,TNUM] = SMOOTH2(VERT,EDGE,TRIA,TNUM) re- % turns a "smoothed" triangulation {VERT,TRIA}, incorpora- % ting "optimised" vertex coordinates and mesh topology. % % VERT is a V-by-2 array of XY coordinates in the triangu- % lation, EDGE is an array of constrained edges, TRIA is a % T-by-3 array of triangles, and TNUM is a T-by-1 array of % part indices. Each row of TRIA and EDGE define an eleme- % nt. VERT(TRIA(II,1),:), VERT(TRIA(II,2),:) and VERT(TRIA % (II,3),:) are the coordinates of the II-TH triangle. The % edges in EDGE are defined in a similar manner. NUM is an % array of part indexing, such that TNUM(II) is the index % of the part in which the II-TH triangle resides. % % [VERT,EDGE,TRIA,TNUM] = SMOOTH2(... ,OPTS) passes an ad- % ditional options structure OPTS, containing user-defined % parameters, including: % % - OPTS.VTOL = {+1.0E-02} -- relative vertex movement tole- % rance, smoothing is converged when (VNEW-VERT) <= VTOL * % VLEN, where VLEN is a local effective length-scale. % % - OPTS.ITER = {+32} -- max. number of smoothing iterations % % - OPTS.DISP = {+ 4} -- smoothing verbosity. Set to INF for % quiet execution. % % See also REFINE2, TRICOST, TRIDEMO % This routine is loosely based on the DISTMESH algorithm, % employing a "spring-based" analogy to redistribute mesh % vertices. Such an approach is described in: P.O. Persson % and Gilbert Strang. "A simple mesh generator in MATLAB." % SIAM review 46(2) 2004, pp: 329--345. Details of the al- % gorithm used here are somewhat different, with an alter- % ative spring-based update employed, in addition to hill- % climbing element quality guarantees, and vertex density % controls. %----------------------------------------------------------- % Darren Engwirda : 2017 -- % Email : [email protected] % Last updated : 21/07/2017 %----------------------------------------------------------- vert = []; conn = []; tria = [] ; tnum = []; opts = []; hfun = []; harg = {} ; %---------------------------------------------- extract args if (nargin>=+1), vert = varargin{1}; end if (nargin>=+2), conn = varargin{2}; end if (nargin>=+3), tria = varargin{3}; end if (nargin>=+4), tnum = varargin{4}; end if (nargin>=+5), opts = varargin{5}; end [opts] = makeopt(opts) ; %---------------------------------------------- default CONN if (isempty(conn)) [edge] = tricon2(tria); ebnd = edge(:,4) < +1; %-- use bnd edge conn = edge(ebnd,1:2); end %---------------------------------------------- default TNUM if (isempty(tnum)) tnum = ones(size(tria, 1), 1) ; end %---------------------------------------------- basic checks if ( ~isnumeric(vert) || ... ~isnumeric(conn) || ... ~isnumeric(tria) || ... ~isnumeric(tnum) || ... ~isstruct (opts) ) error('smooth2:incorrectInputClass' , ... 'Incorrect input class.') ; end %---------------------------------------------- basic checks if (ndims(vert) ~= +2 || ... ndims(conn) ~= +2 || ... ndims(tria) ~= +2 || ... ndims(tnum) ~= +2 ) error('smooth2:incorrectDimensions' , ... 'Incorrect input dimensions.'); end if (size(vert,2)~= +2 || ... size(conn,2)~= +2 || ... size(tria,2)~= +3 || ... size(tnum,2)~= +1 || ... size(tria,1)~= size(tnum,1) ) error('smooth2:incorrectDimensions' , ... 'Incorrect input dimensions.'); end nvrt = size(vert,1) ; %---------------------------------------------- basic checks if (min(min(conn(:,1:2))) < +1 || ... max(max(conn(:,1:2))) > nvrt ) error('smooth2:invalidInputs', ... 'Invalid EDGE input array.') ; end if (min(min(tria(:,1:3))) < +1 || ... max(max(tria(:,1:3))) > nvrt ) error('smooth2:invalidInputs', ... 'Invalid TRIA input array.') ; end %---------------------------------------------- output title if (~isinf(opts.disp)) fprintf(1,'\n') ; fprintf(1,' Smooth triangulation...\n') ; fprintf(1,'\n') ; fprintf(1,[... ' -------------------------------------------------------\n', ... ' |ITER.| |MOVE(X)| |DTRI(X)| \n', ... ' -------------------------------------------------------\n', ... ] ) ; end %---------------------------------------------- polygon bnds node = vert; PSLG = conn; part = {}; pmax = max(tnum(:)); for ppos = +1 : pmax tsel = tnum == ppos ; tcur = tria(tsel,:) ; [ecur,tcur] ... = tricon2 (tcur) ; ebnd = ecur(:,4)==0 ; same = setset2( ... PSLG,ecur(ebnd,1:2)); part{ppos} = find(same) ; end %---------------------------------------------- inflate bbox vmin = min(vert,[],1); vmax = max(vert,[],1); vdel = vmax - 1.*vmin; vmin = vmin - .5*vdel; vmax = vmax + .5*vdel; vbox = [ vmin(1), vmin(2) vmax(1), vmin(2) vmax(1), vmax(2) vmin(1), vmax(2) ] ; vert = [vert ; vbox] ; %---------------------------------------------- DO MESH ITER tnow = tic ; tcpu = struct('full',0.,'dtri',0., ... 'tcon',0.,'iter',0.,'undo',0., ... 'keep',0.) ; for iter = +1 : opts.iter %------------------------------------------ inflate adj. ttic = tic ; [edge,tria] = tricon2(tria,conn) ; tcpu.tcon = ... tcpu.tcon + toc(ttic) ; %------------------------------------------ compute scr. oscr = triscr2(vert,tria) ; %------------------------------------------ vert. iter's ttic = tic ; nvrt = size(vert,1); nedg = size(edge,1); IMAT = sparse( ... edge(:,1),(1:nedg)',+1,nvrt,nedg) ; JMAT = sparse( ... edge(:,2),(1:nedg)',+1,nvrt,nedg) ; EMAT = IMAT + JMAT ; vdeg = sum(EMAT,2) ; %-- vertex |deg| free = (vdeg == 0) ; vold = vert ; for isub = +1 : max(+2,min(+8,iter)) %-- compute HFUN at vert/midpoints hvrt = evalhfn(vert, ... edge,EMAT,hfun,harg) ; hmid = hvrt(edge(:,1),:) ... + hvrt(edge(:,2),:) ; hmid = hmid * +.5 ; %-- calc. relative edge extensions evec = vert(edge(:,2),:) ... - vert(edge(:,1),:) ; elen = ... sqrt(sum(evec.^2,2)) ; scal = +1.0-elen./hmid ; scal = min (+1.0, scal); scal = max (-1.0, scal); %-- projected points from each end ipos = vert(edge(:,1),:) ... -.67*[scal,scal].*evec; jpos = vert(edge(:,2),:) ... +.67*[scal,scal].*evec; %scal = ... %-- nlin. weight % max(abs(scal).^.5,eps^.75); scal = ... max(abs(scal).^ 1,eps^.75); %-- sum contributions edge-to-vert vnew = ... IMAT*([scal,scal] .* ipos) ... + JMAT*([scal,scal] .* jpos) ; vsum = max(EMAT*scal,eps^.75); vnew = vnew ./ [vsum,vsum] ; %-- fixed points. edge projection? vnew(conn(:),1:2) = ... vert(conn(:),1:2) ; vnew(vdeg==0,1:2) = ... vert(vdeg==0,1:2) ; %-- reset for the next local iter. vert = vnew ; end tcpu.iter = ... tcpu.iter + toc(ttic) ; %------------------------------------------ hill-climber ttic = tic ; %-- unwind vert. upadte if score lower nscr = ones(size(tria,1),1); btri = true(size(tria,1),1); umax = + 8 ; for undo = +1 : umax nscr(btri) = triscr2( ... vert,tria(btri,:)) ; %-- TRUE if tria needs "unwinding" smin = +.70 ; smax = +.90 ; sdel = .025 ; stol = smin+iter*sdel; stol = min (smax,stol) ; btri = nscr <= stol ... & nscr < oscr ; if (~any(btri)), break; end %-- relax toward old vert. coord's ivrt = ... unique(tria(btri,1:3)); bvrt = ... false(size(vert,1),1) ; bvrt(ivrt) = true; if (undo ~= umax) bnew = +.75 ^ undo ; bold = +1.0 - bnew ; else bnew = +0.0 ; bold = +1.0 - bnew ; end vert(bvrt,:) = ... bold * vold(bvrt,:) ... + bnew * vert(bvrt,:) ; btri = any( ... bvrt(tria(:,1:3)),2) ; end oscr = nscr ; tcpu.undo = ... tcpu.undo + toc(ttic) ; %------------------------------------- test convergence! ttic = tic ; vdel = ... sum((vert-vold).^2,2) ; evec = vert(edge(:,2),:) ... - vert(edge(:,1),:) ; elen = ... sqrt(sum(evec.^2,2)) ; hvrt = evalhfn(vert, ... edge,EMAT,hfun,harg) ; hmid = hvrt(edge(:,1),:) ... + hvrt(edge(:,2),:) ; hmid = hmid * 0.5 ; scal = elen./hmid ; emid = vert(edge(:,1),:) ... + vert(edge(:,2),:) ; emid = emid * 0.5 ; %------------------------------------- |deg|-based prune keep = false(size(vert,1),1); keep(vdeg>+4) = true ; keep(conn(:)) = true ; keep(free(:)) = true ; %------------------------------------- 'density' control lmax = +5. / +4. ; lmin = +1. / lmax ; less = scal<=lmin ; more = scal>=lmax ; vbnd = false(size(vert,1),1); vbnd(conn(:,1)) = true ; vbnd(conn(:,2)) = true ; ebad = vbnd(edge(:,1)) ... %-- not at boundaries | vbnd(edge(:,2)) ; less(ebad(:)) = false; more(ebad(:)) = false; %------------------------------------- force as disjoint lidx = find (less) ; for lpos = 1 : length(lidx) epos = lidx(lpos,1); inod = edge(epos,1); jnod = edge(epos,2); %--------------------------------- if still disjoint if (keep(inod) && ... keep(jnod) ) keep(inod) = false ; keep(jnod) = false ; else less(epos) = false ; end end ebad = ... keep(edge(less,1)) ... & keep(edge(less,2)) ; more(ebad(:)) = false ; %------------------------------------- reindex vert/tria redo = ... zeros(size(vert,1),1); itop = ... length(find(keep)); iend = ... length(find(less)); redo(keep) = (1:itop)'; redo(edge(less,1)) = ... %-- to new midpoints (itop+1 : itop+iend)'; redo(edge(less,2)) = ... (itop+1 : itop+iend)'; vnew =[vert(keep,:) ; emid(less,:) ; ] ; tnew = redo(tria(:,1:3)) ; ttmp = sort(tnew,2) ; %-- filter collapsed okay = all( ... diff(ttmp,1,2)~=0,2) ; okay = ... okay & ttmp(:,1) > 0 ; tnew = tnew(okay,:) ; %------------------------------------- quality preserver nscr = ... triscr2 (vnew,tnew) ; stol = +0.80 ; tbad = nscr < stol ... & nscr < oscr(okay) ; vbad = ... false(size(vnew,1),1); vbad(tnew(tbad,:)) = true; %------------------------------------- filter edge merge lidx = find (less) ; ebad = ... vbad(redo(edge(lidx,1))) | ... vbad(redo(edge(lidx,2))) ; less(lidx(ebad)) = false ; keep(edge(... lidx(ebad),1:2)) = true ; %------------------------------------- reindex vert/conn redo = ... zeros(size(vert,1),1); itop = ... length(find(keep)); iend = ... length(find(less)); redo(keep) = (1:itop)'; redo(edge(less,1)) = ... (itop+1 : itop+iend)'; redo(edge(less,2)) = ... (itop+1 : itop+iend)'; vert =[vert(keep,:); emid(less,:); emid(more,:); ] ; conn = redo(conn(:,1:2)) ; tcpu.keep = ... tcpu.keep + toc(ttic) ; %------------------------------------- build current CDT ttic = tic ; [vert,conn,tria,tnum] = ... deltri2 (vert, ... conn,node,PSLG,part) ; tcpu.dtri = ... tcpu.dtri + toc(ttic) ; %------------------------------------- dump-out progess! vdel = vdel./(hvrt.*hvrt) ; move = vdel > opts.vtol^2 ; nmov = ... length(find(move)); ntri = size(tria,1) ; if (mod(iter,opts.disp)==+0) fprintf(+1, ... '%11i %18i %18i\n', ... [iter,nmov,ntri]) ; end %------------------------------------- loop convergence! if (nmov == +0), break; end end tria = tria( :,1:3); %----------------------------------------- prune unused vert keep = false(size(vert,1),1); keep(tria(:)) = true ; keep(conn(:)) = true ; redo = zeros(size(vert,1),1); redo(keep) = ... (+1:length(find(keep)))'; conn = redo(conn); tria = redo(tria); vert = vert(keep,:); tcpu.full = ... tcpu.full + toc(tnow) ; if (opts.dbug) %----------------------------------------- print debug timer fprintf(1,'\n') ; fprintf(1,' Mesh smoothing timer...\n'); fprintf(1,'\n') ; fprintf(1, ... ' FULL: %f \n', tcpu.full); fprintf(1, ... ' DTRI: %f \n', tcpu.dtri); fprintf(1, ... ' TCON: %f \n', tcpu.tcon); fprintf(1, ... ' ITER: %f \n', tcpu.iter); fprintf(1, ... ' UNDO: %f \n', tcpu.undo); fprintf(1, ... ' KEEP: %f \n', tcpu.keep); fprintf(1,'\n') ; end if (~isinf(opts.disp)), fprintf(1,'\n'); end end function [hvrt] = evalhfn(vert,edge,EMAT,hfun,harg) %EVALHFN eval. the spacing-fun. at mesh vertices. if (~isempty (hfun)) if (isnumeric(hfun)) hvrt = hfun * ... ones(size(vert,1),1) ; else hvrt = feval( ... hfun,vert,harg{:}) ; end else %-- no HFUN - HVRT is mean edge-len. at vertices! evec = vert(edge(:,2),:) - ... vert(edge(:,1),:) ; elen = sqrt(sum(evec.^2,2)) ; hvrt = (EMAT*elen) ... ./ max(sum(EMAT,2),eps) ; free = true(size(vert,1),1) ; free(edge(:,1)) = false; free(edge(:,2)) = false; hvrt(free) = +inf; end end function [opts] = makeopt(opts) %MAKEOPT setup the options structure for SMOOTH2. if (~isfield(opts,'iter')) opts.iter = +32; else if (~isnumeric(opts.iter)) error('smooth2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.iter)~= +1) error('smooth2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.iter <= +0) error('smooth2:invalidOptionValues', ... 'Invalid OPT.ITER selection.') ; end end if (~isfield(opts,'disp')) opts.disp = + 4; else if (~isnumeric(opts.disp)) error('smooth2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.disp)~= +1) error('smooth2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.disp <= +0) error('smooth2:invalidOptionValues', ... 'Invalid OPT.DISP selection.') ; end end if (~isfield(opts,'vtol')) opts.vtol = +1.0E-02; else if (~isnumeric(opts.vtol)) error('smooth2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.vtol)~= +1) error('smooth2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end if (opts.vtol <= 0.) error('smooth2:invalidOptionValues', ... 'Invalid OPT.VTOL selection.') ; end end if (~isfield(opts,'dbug')) opts.dbug = false; else if (~islogical(opts.dbug)) error('refine2:incorrectInputClass', ... 'Incorrect input class.'); end if (numel(opts.dbug)~= +1) error('refine2:incorrectDimensions', ... 'Incorrect input dimensions.') ; end end end
github
mathematical-tours/mathematical-tours.github.io-master
savemsh.m
.m
mathematical-tours.github.io-master/tweets-sources/codes/mesh-2d/mesh-file/savemsh.m
16,535
utf_8
dfee52330f9c2c724696cbf905df56bb
function savemsh(name,mesh) %SAVEMSH save a *.MSH file for JIGSAW. % % SAVEMSH(NAME,MESH); % % The following are optionally written to "NAME.MSH". Ent- % ities are written if they are present in MESH: % % .IF. MESH.MSHID == 'EUCLIDEAN-MESH': % ----------------------------------- % % MESH.POINT.COORD - [NPxND+1] array of point coordinates, % where ND is the number of spatial dimenions. % COORD(K,ND+1) is an ID tag for the K-TH point. % % MESH.POINT.POWER - [NPx 1] array of vertex "weights", % associated with the dual "power" tessellation. % % MESH.EDGE2.INDEX - [N2x 3] array of indexing for EDGE-2 % elements, where INDEX(K,1:2) is an array of % "point-indices" associated with the K-TH edge, and % INDEX(K,3) is an ID tag for the K-TH edge. % % MESH.TRIA3.INDEX - [N3x 4] array of indexing for TRIA-3 % elements, where INDEX(K,1:3) is an array of % "point-indices" associated with the K-TH tria, and % INDEX(K,4) is an ID tag for the K-TH tria. % % MESH.QUAD4.INDEX - [N4x 5] array of indexing for QUAD-4 % elements, where INDEX(K,1:4) is an array of % "point-indices" associated with the K-TH quad, and % INDEX(K,5) is an ID tag for the K-TH quad. % % MESH.TRIA4.INDEX - [M4x 5] array of indexing for TRIA-4 % elements, where INDEX(K,1:4) is an array of % "point-indices" associated with the K-TH tria, and % INDEX(K,5) is an ID tag for the K-TH tria. % % MESH.HEXA8.INDEX - [M8x 9] array of indexing for HEXA-8 % elements, where INDEX(K,1:8) is an array of % "point-indices" associated with the K-TH hexa, and % INDEX(K,9) is an ID tag for the K-TH hexa. % % MESH.WEDG6.INDEX - [M6x 7] array of indexing for WEDG-6 % elements, where INDEX(K,1:6) is an array of % "point-indices" associated with the K-TH wedg, and % INDEX(K,7) is an ID tag for the K-TH wedg. % % MESH.PYRA5.INDEX - [M5x 6] array of indexing for PYRA-5 % elements, where INDEX(K,1:5) is an array of % "point-indices" associated with the K-TH pyra, and % INDEX(K,6) is an ID tag for the K-TH pyra. % % MESH.VALUE - [NPxNV] array of "values" associated with % the vertices of the mesh. NV values are associated % with each vertex. % % % .IF. MESH.MSHID == 'ELLIPSOID-MESH': % ----------------------------------- % % MESH.RADII - [ 3x 1] array of principle ellipsoid radii. % % % .IF. MESH.MSHID == 'EUCLIDEAN-GRID': % .OR. MESH.MSHID == 'ELLIPSOID-GRID': % ----------------------------------- % % MESH.POINT.COORD - [NDx1] cell array of grid coordinates % where ND is the number of spatial dimenions. Each % array COORD{ID} should be a vector of grid coord.'s, % increasing or decreasing monotonically. % % MESH.VALUE - [NMxNV] array of "values" associated with % the vertices of the grid, where NM is the product of % the dimensions of the grid. NV values are associated % with each vertex. % % See also JIGSAW, LOADMSH % %----------------------------------------------------------- % Darren Engwirda % github.com/dengwirda/jigsaw/ % 03-Dec-2017 % [email protected] %----------------------------------------------------------- % if (~ischar (name)) error('NAME must be a valid file-name!') ; end if (~isstruct(mesh)) error('MESH must be a valid structure!') ; end [path,file,fext] = fileparts(name) ; if(~strcmp(lower(fext),'.msh')) name = [name,'.msh']; end try %-- try to write data to file ffid = fopen(name, 'w') ; nver = +3; if (exist('OCTAVE_VERSION','builtin') > 0) fprintf(ffid,[ ... '# %s.msh; created by JIGSAW''s OCTAVE interface\n'],file) ; else fprintf(ffid,[ ... '# %s.msh; created by JIGSAW''s MATLAB interface\n'],file) ; end if (isfield(mesh,'mshID')) mshID = mesh.mshID ; else mshID = 'EUCLIDEAN-MESH'; end switch (upper(mshID)) case 'EUCLIDEAN-MESH' save_euclidean_mesh(ffid,nver,mesh) ; case 'EUCLIDEAN-GRID' save_euclidean_grid(ffid,nver,mesh) ; case 'EUCLIDEAN-DUAL' %save_euclidean_dual(ffid,nver,mesh) ; case 'ELLIPSOID-MESH' save_ellipsoid_mesh(ffid,nver,mesh) ; case 'ELLIPSOID-GRID' save_ellipsoid_grid(ffid,nver,mesh) ; case 'ELLISPOID-DUAL' %save_ellipsoid_dual(ffid,nver,mesh) ; otherwise error('Invalid mshID!') ; end fclose(ffid); catch err %-- ensure that we close the file regardless! if (ffid>-1) fclose(ffid) ; end rethrow(err) ; end end function save_euclidean_mesh(ffid,nver,mesh) %SAVE-EUCLIDEAN-MESH save mesh data in EUCLDIEAN-MESH format fprintf(ffid,'MSHID=%u;EUCLIDEAN-MESH \n',nver); npts = +0; if (isfield(mesh,'point') && ... isfield(mesh.point,'coord') && ... ~isempty(mesh.point.coord) ) %-- write "POINT" data if (~isnumeric(mesh.point.coord)) error('Incorrect input types'); end if (ndims(mesh.point.coord) ~= 2) error('Incorrect dimensions!'); end ndim = size(mesh.point.coord,2) - 1 ; npts = size(mesh.point.coord,1) - 0 ; fprintf(ffid,['NDIMS=%u','\n'],ndim); fprintf(ffid, ... ['POINT=%u','\n'],size(mesh.point.coord,1)); if (isa(mesh.point.coord,'double')) vstr = sprintf('%%1.%ug;',+16); else vstr = sprintf('%%1.%ug;',+ 8); end fprintf(ffid, ... [repmat(vstr,1,ndim),'%i\n'],mesh.point.coord'); end if (isfield(mesh,'point') && ... isfield(mesh.point,'power') && ... ~isempty(mesh.point.power) ) %-- write "POWER" data if (~isnumeric(mesh.point.power)) error('Incorrect input types'); end if (ndims(mesh.point.power) ~= 2) error('Incorrect dimensions!'); end npwr = size(mesh.point.power,2) - 0 ; nrow = size(mesh.point.power,1) - 0 ; if (isa(mesh.point.power,'double')) vstr = sprintf('%%1.%ug;',+16) ; else vstr = sprintf('%%1.%ug;',+ 8) ; end vstr = repmat(vstr,+1,npwr) ; fprintf(ffid,['POWER=%u;%u','\n'],[nrow,npwr]); fprintf(ffid, ... [vstr(+1:end-1), '\n'], mesh.point.power'); end if (isfield(mesh,'value')) %-- write "VALUE" data if (~isnumeric(mesh.value)) error('Incorrect input types'); end if (ndims(mesh.value) ~= 2) error('Incorrect dimensions!'); end if (size(mesh.value,1) ~= npts) error('Incorrect dimensions!'); end nrow = size(mesh.value,1); nval = size(mesh.value,2); if (isa(mesh.value, 'double')) vstr = sprintf('%%1.%ug;',+16) ; else vstr = sprintf('%%1.%ug;',+ 8) ; end vstr = repmat(vstr,+1,nval) ; fprintf(ffid,['VALUE=%u;%u','\n'],[nrow,nval]); fprintf(ffid,[vstr(1:end-1),'\n'],mesh.value'); end if (isfield(mesh,'edge2') && ... isfield(mesh.edge2,'index') && ... ~isempty(mesh.edge2.index) ) %-- write "EDGE2" data if (~isnumeric(mesh.edge2.index)) error('Incorrect input types'); end if (ndims(mesh.edge2.index) ~= 2) error('Incorrect dimensions!'); end if (min(min(mesh.edge2.index(:,1:2))) < +1 || ... max(max(mesh.edge2.index(:,1:2))) > npts) error('Invalid EDGE-2 indexing!') ; end index = mesh.edge2.index; index(:,1:2) = index(:,1:2)-1 ; % file is zero-indexed! fprintf(ffid,['EDGE2=%u','\n'],size(index,1)); fprintf( ... ffid,[repmat('%u;',1,2),'%i','\n'],index'); end if (isfield(mesh,'tria3') && ... isfield(mesh.tria3,'index') && ... ~isempty(mesh.tria3.index) ) %-- write "TRIA3" data if (~isnumeric(mesh.tria3.index)) error('Incorrect input types'); end if (ndims(mesh.tria3.index) ~= 2) error('Incorrect dimensions!'); end if (min(min(mesh.tria3.index(:,1:3))) < +1 || ... max(max(mesh.tria3.index(:,1:3))) > npts) error('Invalid TRIA-3 indexing!') ; end index = mesh.tria3.index; index(:,1:3) = index(:,1:3)-1 ; % file is zero-indexed! fprintf(ffid,['TRIA3=%u','\n'],size(index,1)); fprintf( ... ffid,[repmat('%u;',1,3),'%i','\n'],index'); end if (isfield(mesh,'quad4') && ... isfield(mesh.quad4,'index') && ... ~isempty(mesh.quad4.index) ) %-- write "QUAD4" data if (~isnumeric(mesh.quad4.index)) error('Incorrect input types'); end if (ndims(mesh.quad4.index) ~= 2) error('Incorrect dimensions!'); end if (min(min(mesh.quad4.index(:,1:4))) < +1 || ... max(max(mesh.quad4.index(:,1:4))) > npts) error('Invalid QUAD-4 indexing!') ; end index = mesh.quad4.index; index(:,1:4) = index(:,1:4)-1 ; % file is zero-indexed! fprintf(ffid,['QUAD4=%u','\n'],size(index,1)); fprintf( ... ffid,[repmat('%u;',1,4),'%i','\n'],index'); end if (isfield(mesh,'tria4') && ... isfield(mesh.tria4,'index') && ... ~isempty(mesh.tria4.index) ) %-- write "TRIA4" data if (~isnumeric(mesh.tria4.index)) error('Incorrect input types'); end if (ndims(mesh.tria4.index) ~= 2) error('Incorrect dimensions!'); end if (min(min(mesh.tria4.index(:,1:4))) < +1 || ... max(max(mesh.tria4.index(:,1:4))) > npts) error('Invalid TRIA-4 indexing!') ; end index = mesh.tria4.index; index(:,1:4) = index(:,1:4)-1 ; % file is zero-indexed! fprintf(ffid,['TRIA4=%u','\n'],size(index,1)); fprintf( ... ffid,[repmat('%u;',1,4),'%i','\n'],index'); end if (isfield(mesh,'hexa8') && ... isfield(mesh.hexa8,'index') && ... ~isempty(mesh.hexa8.index) ) %-- write "HEXA8" data if (~isnumeric(mesh.hexa8.index)) error('Incorrect input types'); end if (ndims(mesh.hexa8.index) ~= 2) error('Incorrect dimensions!'); end if (min(min(mesh.hexa8.index(:,1:8))) < +1 || ... max(max(mesh.hexa8.index(:,1:8))) > npts) error('Invalid HEXA-8 indexing!') ; end index = mesh.hexa8.index; index(:,1:8) = index(:,1:8)-1 ; % file is zero-indexed! fprintf(ffid,['HEXA8=%u','\n'],size(index,1)); fprintf( ... ffid,[repmat('%u;',1,8),'%i','\n'],index'); end if (isfield(mesh,'wedg6') && ... isfield(mesh.wedg6,'index') && ... ~isempty(mesh.wedg6.index) ) %-- write "WEDG6" data if (~isnumeric(mesh.wedg6.index)) error('Incorrect input types'); end if (ndims(mesh.wedg6.index) ~= 2) error('Incorrect dimensions!'); end if (min(min(mesh.wedg6.index(:,1:6))) < +1 || ... max(max(mesh.wedg6.index(:,1:6))) > npts) error('Invalid WEDG-6 indexing!') ; end index = mesh.wedg6.index; index(:,1:6) = index(:,1:6)-1 ; % file is zero-indexed! fprintf(ffid,['WEDG6=%u','\n'],size(index,1)); fprintf( ... ffid,[repmat('%u;',1,6),'%i','\n'],index'); end if (isfield(mesh,'pyra5') && ... isfield(mesh.pyra5,'index') && ... ~isempty(mesh.pyra5.index) ) %-- write "PYRA5" data if (~isnumeric(mesh.pyra5.index)) error('Incorrect input types'); end if (ndims(mesh.pyra5.index) ~= 2) error('Incorrect dimensions!'); end if (min(min(mesh.pyra5.index(:,1:5))) < +1 || ... max(max(mesh.pyra5.index(:,1:5))) > npts) error('Invalid PYRA-5 indexing!') ; end index = mesh.pyra5.index; index(:,1:5) = index(:,1:5)-1 ; % file is zero-indexed! fprintf(ffid,['PYRA5=%u','\n'],size(index,1)); fprintf( ... ffid,[repmat('%u;',1,6),'%i','\n'],index'); end end function save_ellipsoid_mesh(ffid,nver,mesh) %SAVE-ELLIPSOID-MESH save mesh data in ELLIPSOID-MESH format fprintf(ffid,'MSHID=%u;ELLIPSOID-MESH \n',nver); npts = +0; if (isfield(mesh,'radii') && ... ~isempty(mesh.radii) ) %-- write "RADII" data if (~isnumeric(mesh.radii)) error('Incorrect input types'); end if (ndims(mesh.radii) ~= 2) error('Incorrect dimensions!'); end if (numel(mesh.radii) ~= 3) error('Incorrect dimensions!'); end fprintf(ffid,'RADII=%f;%f;%f\n',mesh.radii'); end %-- to-do: coast edges... end function save_euclidean_grid(ffid,nver,mesh) %SAVE-EUCLIDEAN-GRID save mesh data in EUCLIDEAN-GRID format save_monotonic_grid(ffid,nver,mesh, ... 'EUCLIDEAN-GRID') ; end function save_ellipsoid_grid(ffid,nver,mesh) %SAVE-ELLIPSOID-GRID save mesh data in ELLIPSOID-GRID format save_monotonic_grid(ffid,nver,mesh, ... 'ELLIPSOID-GRID') ; end function save_monotonic_grid(ffid,nver,mesh, ... kind) %SAVE-MONOTONIC-GRID save mesh data in MONOTONIC-GRID format % ==> EUCLIDEAN-GRID, ELLIPSOID-GRID, etc... switch (upper(kind)) case 'EUCLIDEAN-GRID' fprintf( ... ffid,'MSHID=%u;EUCLIDEAN-GRID\n',nver) ; case 'ELLIPSOID-GRID' fprintf( ... ffid,'MSHID=%u;ELLIPSOID-GRID\n',nver) ; end dims = [] ; if (isfield(mesh,'point') && ... isfield(mesh.point,'coord') && ... ~isempty(mesh.point.coord) ) %-- write "COORD" data if(~iscell(mesh.point.coord) ) error('Incorrect input types') ; end if ( numel(mesh.point.coord) ~= ... length(mesh.point.coord) ) error('Incorrect dimensions!') ; end ndim = length(mesh.point.coord); dims = zeros(1,ndim); fprintf(ffid, ... ['NDIMS=%u \n'],length(mesh.point.coord)) ; for idim = +1 : length(mesh.point.coord) if ( numel(mesh.point.coord{idim}) ~= ... length(mesh.point.coord{idim}) ) error('Incorrect dimensions!') ; end dims(ndim-idim+1) = ... length(mesh.point.coord{idim}) ; if (isa(mesh.point.coord{idim}, 'double')) vstr = sprintf('%%1.%ug\n',+16); else vstr = sprintf('%%1.%ug\n',+ 8); end fprintf(ffid,... 'COORD=%u;%u\n',[idim,dims(ndim-idim+1)]); fprintf(ffid,vstr,mesh.point.coord{idim}); end end if (isfield(mesh,'value')) %-- write "VALUE" data if (~isnumeric(mesh.value)) error('Incorrect input types') ; end if (ndims(mesh.value) ~= length(dims)+0 && ... ndims(mesh.value) ~= length(dims)+1 ) error('Incorrect dimensions!') ; end if (ndims(mesh.value) == length(dims)) nval = size(mesh.value); nval = [nval, +1] ; else nval = size(mesh.value); end if (~all(nval(1:end-1) == dims)) error('Incorrect dimensions!') ; end if (isa(mesh.value, 'double')) vstr = sprintf('%%1.%ug;',+16) ; else vstr = sprintf('%%1.%ug;',+ 8) ; end vstr = repmat(vstr,+1,nval(end)) ; vals = ... reshape(mesh.value,[],nval(end)) ; fprintf(ffid, ... 'VALUE=%u;%u\n',[prod(dims),nval(end)]); fprintf(ffid,[vstr(+1:end-1),'\n'],vals'); end end