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
nickabattista/Ark-master
FitzHugh_Nagumo_PDE.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Neurons/PDE/FitzHugh_Nagumo_PDE.m
4,837
utf_8
11b8baf57f96b55fa8f793aebbf8a477
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This script solves the FitzHugh-Nagumo Equations in 1d, which are % a simplified version of the more complicated Hodgkin-Huxley Equations. % % Author: Nick Battista % Created: 09/11/2015 % % Equations: % dv/dt = D*Laplacian(v) - v*(v-a)*(v-1) - w + I(t) % dw/dt = eps*(v-gamma*w) % % Variables & Parameters: % v(x,t): membrane potential % w(x,t): blocking mechanism % D: diffusion rate of potential % a: threshold potential % gamma: resetting rate % eps: strength of blocking % I(t): initial condition for applied activation % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function FitzHugh_Nagumo_PDE() % Parameters in model % D = 1.0; % Diffusion coefficient a = 0.3; % Threshold potential (Note: a=0.3 is traveling wave value, a=0.335 is interesting) gamma = 1.0; % Resetting rate (Note: large values give 'funky thick' traveling wave, gamma = 1.0 is desired) eps = 0.001; % Blocking strength (Note: eps = 0.001 is desired) I_mag = 0.05; % Activation strength % Discretization/Simulation Parameters % N = 800; % # of discretized points %800 L = 2000; % Length of domain, [0,L] %500 dx = L/N; % Spatial Step x = 0:dx:L; % Computational Domain % Temporal Parameters % T_final = 10000; % Sets the final time Np = 10; % Set the number of pulses pulse = T_final/Np; % determines the length of time between pulses. NT = 800000; % Number of total time-steps to be taken dt = T_final/NT; % Time-step taken i1 = 0.475; % fraction of total length where current starts i2 = 0.525; % fraction of total length where current ends dp = pulse/50; % Set the duration of the current pulse pulse_time = 0; % pulse time is used to store the time that the next pulse of current will happen IIapp=zeros(1,N+1); % this vector holds the values of the applied current along the length of the neuron dptime = T_final/100; % This sets the length of time frames that are saved to make a movie. % Initialization % v = zeros(1,N+1); w = v; t=0; ptime = 0; tVec = 0:dt:T_final; Nsteps = length(tVec); vNext = zeros(Nsteps,N+1); vNext(1,:) = v; wNext = zeros(Nsteps,N+1); wNext(1,:) = w; % % **** % **** BEGIN SIMULATION! **** % **** % % for i=2:Nsteps % Update the time t = t+dt; % Give Laplacian DD_v_p = give_Me_Laplacian(v,dx); % Gives applied current activation wave [IIapp,pulse_time] = Iapp(pulse_time,i1,i2,I_mag,N,pulse,dp,t,IIapp); % Update potential and blocking mechanism, using Forward Euler vN = v + dt * ( D*DD_v_p - v.*(v-a).*(v-1) - w + IIapp ); wN = w + dt * ( eps*( v - gamma*w ) ); % Update time-steps v = vN; w = wN; % Store time-step values vNext(i,:) = v; wNext(i,:) = w; %This is used to determine if the current time step will be a frame in the movie if t > ptime figure(1) plot(x, v,'r-','LineWidth',5); axis([0 L -0.2 1.0]); set(gca,'Linewidth',7); xlabel('Distance (x)'); ylabel('Electropotenital (v)'); ptime = ptime+dptime; fprintf('Time(s): %d\n',t); pause(0.05); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: the injection function, Iapp = activation wave for system, and % returns both the activation as well as updated pulse_time % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [app,pulse_time] = Iapp(pulse_time,i1,i2,I_mag,N,pulse,dp,t,app) %Check to see if there should be a pulse if t > (pulse_time) % Sets pulsing region to current amplitude of I_mag x\in[i1*N,i2*N] for j=(floor(i1*N):floor(i2*N)) app(j) = I_mag; end % Checks if the pulse is over & then resets pulse_time to the next pulse time. if t > (pulse_time+dp) pulse_time = pulse_time+pulse; end else % Resets to no activation app = zeros(1,N+1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: gives Laplacian of the membrane potential, note: assumes % periodicity and uses the 2nd order central differencing operator. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function DD_v = give_Me_Laplacian(v,dx) Npts = length(v); DD_v = zeros(1,Npts); for i=1:Npts if i==1 DD_v(i) = ( v(i+1) - 2*v(i) + v(end) ) / dx^2; elseif i == Npts DD_v(i) = ( v(1) - 2*v(i) + v(i-1) ) / dx^2; else DD_v(i) = ( v(i+1) - 2*v(i) + v(i-1) ) /dx^2; end end
github
nickabattista/Ark-master
FitzHugh_Nagumo_ODE.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Neurons/ODE/FitzHugh_Nagumo_ODE.m
3,604
utf_8
a3bd5dcc0ee16452a9f9503e871068aa
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This script solves the FitzHugh-Nagumo Equations in 1d, which are % a simplified version of the more complicated Hodgkin-Huxley Equations. % % Author: Nick Battista % Created: 04/21/2019 % % Equations: % dv/dt = - v*(v-a)*(v-1) - w + I(t) % dw/dt = eps*(v-gamma*w) % % Variables & Parameters: % v(t): membrane potential % w(t): blocking mechanism % D: diffusion rate of potential % a: threshold potential % gamma: resetting rate % eps: strength of blocking % I(t): initial condition for applied activation % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function FitzHugh_Nagumo_ODE() % Parameters in model % a = 0.15; % Threshold potential (Note: a=0.3 is traveling wave value, a=0.335 is interesting) gamma = 1.0; % Resetting rate (Note: large values give 'funky thick' traveling wave, gamma = 1.0 is desired) eps = 0.001; % Blocking strength (Note: eps = 0.001 is desired) I_mag = 0.05; % Activation strength % Temporal Parameters % T_final = 5000; % Sets the final time Np = 5; % Set the number of pulses pulse = T_final/Np; % determines the length of time between pulses. NT = 400000; % Number of total time-steps to be taken dt = T_final/NT; % Time-step taken dp = pulse/50; % Set the duration of the current pulse pulse_time = 0; % pulse time is used to store the time that the next pulse of current will happen % Initialization % v = 0; w = v; t=0; tVec = 0:dt:T_final; Nsteps = length(tVec); vVec = zeros(Nsteps,1); vVec(1) = v; wVec = zeros(Nsteps,1); wVec(1) = w; % % **** % **** BEGIN SIMULATION! **** % **** % % for i=2:Nsteps % Update the time t = t+dt; % Gives applied current activation wave [IIapp,pulse_time] = Iapp(pulse_time,I_mag,pulse,dp,t); % Update potential and blocking mechanism, using Forward Euler vN = v + dt * ( - v.*(v-a).*(v-1) - w + IIapp ); wN = w + dt * ( eps*( v - gamma*w ) ); % Update time-steps v = vN; w = wN; % Store time-step values vVec(i) = v; wVec(i) = w; end % % Plots Action Potential (cell voltage) / Blocking Strength vs. Time % figure(1) lw = 5; % LineWidth fs = 18; % FontSize plot(tVec,vVec,'r-','LineWidth',lw); hold on; plot(tVec,wVec,'b-','LineWidth',lw-2); hold on; xlabel('Time'); ylabel('Quantity'); leg = legend('Potential','Blocking Strength'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); % % Plots Phase Plane: Action Potential vs. Blocking Strength % figure(2) lw = 5; % LineWidth fs = 18; % FontSize plot(wVec,vVec,'k-','LineWidth',lw); hold on; xlabel('Blocking Strength'); ylabel('Potential'); set(gca,'FontSize',fs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: the injection function, Iapp = activation wave for system, and % returns both the activation as well as updated pulse_time % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [app,pulse_time] = Iapp(pulse_time,I_mag,pulse,dp,t) %Check to see if there should be a pulse if t > (pulse_time) % Sets pulsing region to current amplitude of I_mag x\in[i1*N,i2*N] app = I_mag; % Checks if the pulse is over & then resets pulse_time to the next pulse time. if t > (pulse_time+dp) pulse_time = pulse_time+pulse; end else % Resets to no activation app = 0; end
github
nickabattista/Ark-master
please_Compare_Logistic.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Compare_Discrete_to_Continuous/please_Compare_Logistic.m
2,847
utf_8
1b392d5975b96baed60b1d4ca04aad34
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Compares Discrete to Continuous Logistic Equation % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function please_Compare_Logistic(k) % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % TFinal = 100; % Simulation runs until TFinal % % Initial Values % x0 = 25; % % Parameter Values % %k = 2.0; % growth rate C = 250; % carrying capacity % % Call function to solve Discrete Dynamical System % [X_dis,tVec_Discrete] = please_Solve_Discrete_System(TFinal,k,C,x0); % % Call function to solve Continuous Dynamical System % [X_con,tVec_Continuous] = please_Solve_Continuous_System(TFinal,k,C,x0); % % Plot Attributes % lw = 3; % LineWidth (how thick the lines should be) ms = 30; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(tVec_Discrete,X_dis,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(tVec_Continuous,X_con,'r-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Discrete','Continuous'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: solves Logistic Differential Equation % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [X,tVec] = please_Solve_Continuous_System(TFinal,k,C,x0) % % Initialize Time Information % dt = 0.02; % Time-step t= 0; % Initial Time % % Initialize Initial Population / Time Storage Vector / Counter for While Loop Indexing % X(1) = x0; tVec(1) = 0; n = 1; % % Solve ODE using Euler's Method % while t<TFinal % Update Time / Counter t = t + dt; n = n + 1; % Euler's Method to Solve for Solution X(n) = X(n-1) + dt*k*X(n-1)*( 1 - X(n-1) / C ); % Update time-Vec tVec(n) = tVec(n-1) + dt; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: solves the Discrete Dynamical System for the Logistic Eqn % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [X,tVec] = please_Solve_Discrete_System(TFinal,k,C,x0) % % Initializing storage for populations % X = zeros( TFinal, 1); % Initializing storage for population X tVec = X; % Initializing storage for time % Storing initial values X(1) = x0; tVec(1) = 0; % % For-loop that iteratively solves the discrete dynamical system % for n=1:TFinal % Obtain Next Population X(n+1) = X(n) + k*X(n)*( 1 - X(n)/C ); % Store Next Time Value tVec(n+1) = tVec(n) + 1; end
github
nickabattista/Ark-master
please_Compare_Predator_Prey.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Compare_Discrete_to_Continuous/please_Compare_Predator_Prey.m
3,794
utf_8
437a026212b96bf91ee068a6e5a6de97
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Compares Discrete to Continuous Predator-Prey % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function please_Compare_Predator_Prey(b2) % % Clears any previous plots that are open in MATLAB close all; % % Time Information / Initialization % TFinal = 125; % Simulation runs until TFinal % % Initial Values % x0 = 25; y0 = 2; % % Parameter Values % k = 0.5; % growth rate for prey C = 120; % carrying capacity for prey d = 0.1; % death rate for predator b1= 0.005; % prey death rate from interactions w/ predator %b2= 0.025; % predator growth rate from interactions w/ prey % % Call function to solve Discrete Dynamical System % [X_dis,Y_dis,tVec_Discrete] = please_Solve_Discrete_System(TFinal,k,C,d,b1,b2,x0,y0); % % Call function to solve Continuous Dynamical System % [X_con,Y_con,tVec_Continuous] = please_Solve_Continuous_System(TFinal,k,C,d,b1,b2,x0,y0); % % Plot Attributes % lw = 3; % LineWidth (how thick the lines should be) ms = 30; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Prey Populations vs. Time % figure(1); plot(tVec_Discrete,X_dis,'b.','LineWidth',lw,'MarkerSize',ms); hold on; plot(tVec_Continuous,X_con,'r-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Prey Populations'); leg = legend('Discrete','Continuous'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); % % PLOT 2: Predator Populations vs. Time % figure(2); plot(tVec_Discrete,Y_dis,'b.','LineWidth',lw,'MarkerSize',ms); hold on; plot(tVec_Continuous,Y_con,'r-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Predator Populations'); leg = legend('Discrete','Continuous'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: solves Logistic Differential Equation % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [X,Y,tVec] = please_Solve_Continuous_System(TFinal,k,C,d,b1,b2,x0,y0) % % Initialize Time Information % dt = 0.00125; % Time-step t= 0; % Initial Time % % Initialize Initial Population / Time Storage Vector / Counter for While Loop Indexing % X(1) = x0; Y(1) = y0; tVec(1) = 0; n = 1; % % Solve ODE using Euler's Method % while t<TFinal % Update Time / Counter t = t + dt; n = n + 1; % % Euler's Method to Solve for Solution % % Prey X(n) = X(n-1) + dt*( k*X(n-1)*( 1 - X(n-1) / C ) - b1*X(n-1)*Y(n-1) ); % Predator Y(n) = Y(n-1) + dt*( -d*Y(n-1) + b2*X(n-1)*Y(n-1) ); % Update time-Vec tVec(n) = tVec(n-1) + dt; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: solves the Discrete Dynamical System for the Logistic Eqn % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [X,Y,tVec] = please_Solve_Discrete_System(TFinal,k,C,d,b1,b2,x0,y0) % % Initializing storage for populations % X = zeros( TFinal, 1); % Initializing storage for prey Y = X; % Initializing storage for predator tVec = X; % Initializing storage for time % Storing initial values X(1) = x0; Y(1) = y0; tVec(1) = 0; % % For-loop that iteratively solves the discrete dynamical system % for n=1:TFinal % Obtain Next Population for Prey X(n+1) = X(n) + k*X(n)*( 1 - X(n)/C ) - b1*X(n)*Y(n); % Obtain Next Population for Predator Y(n+1) = Y(n) - d*Y(n) + b2*X(n)*Y(n); % Store Next Time Value tVec(n+1) = tVec(n) + 1; end
github
nickabattista/Ark-master
go_Go_SIR_ode45.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/ode45/go_Go_SIR_ode45.m
4,259
utf_8
e6e9c66473bb2ff062aee5421711dd8a
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Solves Standard Base Case SIR Model (no deaths) using MATLAB's % ODE 45 built in differential equation solver, which uses RK-4 % (4th Order Runge-Kutta Method) % % dS/dt = Lambda - mu*S - beta*S*I % dI/dt = beta*S*I - muStar*S*I - gamma*I % dR/dt = gamma*I - mu*R % % Parameters: Lambda <-- total births added to system (Lambda = mu*S + muStar*I + mu*R) % mu <-- natural death rate % muStar <-- enhanced death rate (natural death rate + death rate from disease) % beta <-- rate of disease transmission from interactions btwn healthy and sick person % gamma <-- rate of recovery % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function go_Go_SIR_ode45() % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % Tstart = 0; % Simulation starts a tstart (initial value) Tstop = 150; % Simulation runs until time = TFinal % % Initial Values % s0 = 0.99; % Initial Population for Susceptible, S i0 = 0.01; % Initial Population for Infected, I r0 = 0; % Initial Population for Recovered, R Initial_Values = [s0 i0 r0]; % Stores initial values in vector % % ode45 is matlab's ode solver % options=odeset('RelTol',1e-4); [t,sol] = ode45(@f,[Tstart Tstop],Initial_Values,options); % % storing solutions for each variable, theta_k. % S = sol(:,1); %gives us S(t) I = sol(:,2); %gives us I(t) R = sol(:,3); %gives us R(t) % % Plotting solutions % plot_Phase_Planes(S,I,R); plot_Time_Evolutions(t,S,I,R) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: RHS vector of the problem: this function evaluates the % RHS of the ODEs and passes it back to the ode45 solver % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dvdt = f(t,sol) % % Components of vectors % S = sol(1); % Susceptible I = sol(2); % Infected R = sol(3); % Recovered % % ODE Parameter Values % beta = 0.55; % rate of disease transmission gamma = 0.45; % rate of recovery mu = 0.0074; % natural death rate muStar = 2*mu; % enhanced death rate (natural death rate + death rate from disease) Lambda = mu*S + muStar*I + mu*R; % birth rate to equal death rate % % ODES (RHS) % dSdt = Lambda - mu*S - beta*S*I; dIdt = beta*S*I - muStar*I - gamma*I; dRdt = gamma*I - mu*R; % % Vector to be evaluated % dvdt = [dSdt dIdt dRdt]'; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: plots the time evolutions (solutions to ODEs)! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Time_Evolutions(t,S,I,R) % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(t,S,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(t,I,'r.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(t,R,'g.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Susceptible','Infected','Recovered'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: plots the phase planes! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Phase_Planes(S,I,R) % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) figure(2) plot(S,I,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Susceptible'); ylabel('Infected'); set(gca,'FontSize',fs);
github
nickabattista/Ark-master
Opioid_ODE_Model.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/ode45/Opioid_ODE_Model.m
4,458
utf_8
7edcab7a41bc86c9c6455bbd8113d7d1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This code solves a model of a basic opioid addiction epidemic % % % Author: Nick Battista % Date Created: August 10, 2017 % Date Updated: September 23, 2017 (NAB) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Opioid_Basic_Model() % % STOCHASTIC? TIME DELAY? % global stochastic_flag; stochastic_flag = 0; time_delay_flag = 0; % % Temporal information % Tstart = 0; Tstop = 100; % % initial conditions % S_0 = 0.9; P_0 = 0.10; R_0 = 0.00; % Initial_Values = [S_0 P_0 R_0]; % % ode45 is matlab's ode solver % if time_delay_flag == 0 options=odeset('RelTol',1e-3); [t,sol] = ode45(@f,[Tstart Tstop],Initial_Values,options); else options=odeset('RelTol',1e-3); [t,sol] = ode45(@f,[Tstart Tstop],Initial_Values,options); end % % storing solutions for each variable, theta_k. % S = sol(:,1); %gives us S(t) P = sol(:,2); %gives us G(t) R = sol(:,3); %gives us R(t) A = 1 - S - P - R; %gives us H(t) % % Plotting solutions % plot_Phase_Planes(S,P,A,R); plot_Time_Evolutions(t,S,P,A,R) return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: RHS vector of the problem: this function evaluates the % RHS of the ODEs and passes it back to the ode45 solver % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dvdt = f(t,sol) global stochastic_flag; % % ODE Coupling Parameters % % xi = 0.505; coeff = 0.293; % % Dynamical Coupling Parameters % alpha = 0.9; % S->G : people who are prescribed prescription opioids eps = 0.74; % G->S : people who use their prescriptions and then go back to susceptible beta = 0.006; % S->H : people who get opioids from their relatives/friends/etc to abuse them mu = 0.00824; % : natural death rate muSTAR = 0.00834 ; % : enhanced death rate for opioid abusers gamma =(1-eps); % G->H : percent of prescribed opioid class who get addicted to opioids zeta = 0.75; % H->R : rate at which Opioid abusers start treatment delta = 0.09; % R->S : people who finish their treatment and then go back to susceptible class nu = coeff*(1-delta); % R->H : rate at which users in treatment fall back into drug use sigma = (1-coeff)*(1-delta); % R->H : rate at which people in treatment fall back into use themselves. % NOTE: sigma+delta+mu = 1.0; % NOTE: eps+gamma = 1.0; % % Components of vectors % S = sol(1); % Susceptible Class P = sol(2); % Prescribed Opioid Class R = sol(3); % People in Treatment A = 1 - S - P - R; % Abusing Opioid Class Lambda = mu*(S+R+P) + muSTAR*A; % % Stochastic Piece ("white noise") % if stochastic_flag == 1 white_noise = awgn(x1,1,'measured'); else white_noise = 0; end % % ODES (RHS) % Lambda = mu*(S+P+R) + muSTAR*A; dS = Lambda - (alpha+mu)*S - beta*(1-xi)*S*A - beta*xi*S*P + eps*P + delta*R; dP = alpha*S - (gamma+eps+mu)*P; dR = zeta*A - nu*R*A - (delta+mu+sigma)*R; % OLD %dS = Lambda + delta*R - alpha*S - beta*S*H + eps*G - mu*S; %dP = alpha*S - gamma*G - eps*G - mu*G; %dR = zeta*H - nu*R*H - delta*R - mu*R - sigma*R; % % Vector to be evaluated % dvdt = [dS dP dR]'; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: plots phase planes! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Phase_Planes(x1,x2,x3,x4) figure(1) plot(x1,x2,'r-','LineWidth',3); hold on; plot(x1,x3,'b-','LineWidth',3); hold on; plot(x1,x4,'k-','LineWidth',3); hold on; xlabel('x1'); ylabel('x2,x3,x4'); legend('G vs. S','H vs. S','R vs. S'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: plots phase planes! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Time_Evolutions(t,x1,x2,x3,x4) lw = 5; ms = 10; figure(2) plot(t,x1,'-','LineWidth',lw,'MarkerSize',ms,'Color',[0.25 0.5 1]); hold on; plot(t,x2,'-','LineWidth',lw,'MarkerSize',ms,'Color',[0.9 0.35 0.1]); hold on; plot(t,x3,'r-','LineWidth',lw,'MarkerSize',ms); hold on; % plot(t,x4,'-','LineWidth',lw,'MarkerSize',ms,'Color',[0 .4 0]); hold on; %,, ,'Color',[0.3 0 0.9] xlabel('time'); ylabel('populations'); leg=legend('Susceptible', 'Prescribed', 'Opioid Abuse', 'Treatment'); set(gca,'FontSize',20) set(leg,'FontSize',18)
github
nickabattista/Ark-master
compute_Jacobian_for_SIR_w_Deaths.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/ode45/compute_Jacobian_for_SIR_w_Deaths.m
1,611
utf_8
c8af14f9401c16e45c0fadc12959fe42
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: sets up a Jacobian Matrix and finds eigenvalues % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function compute_Jacobian_for_SIR_w_Deaths() % % SIR Model Parameters % beta = 0.5; % rate of disease transmission gamma = 0.5; % rate of recovery mu = 0.01; % natural death rate muStar = 2*mu; % enhanced death rate (natural death rate + death rate from disease) Lambda = 0.005; % birth rate % % Equilibrium Population Values % S = ( gamma + muStar ) / beta; I = Lambda/(gamma+muStar) - mu/beta; R = (gamma/mu)*I; % % Compute elements of Jacobian % J11 = -beta*I - mu; % d(Sdot)/dS J12 = -beta*S; % d(Sdot)/dI J13 = 0; % d(Sdot)/dR % J21 = beta*I; % d(Idot)/dS J22 = beta*S - gamma - muStar; % d(Idot)/dI J23 = 0; % d(Idot)/dR % J31 = 0; % d(Rdot)/dS J32 = gamma; % d(Rdot)/dI J33 = -mu; % d(Rdot)/dR % % Construct Jacobian Matrix % J = [J11 J12 J13; J21 J22 J23; J31 J32 J33]; % % Compute eigenvalues of Jacobian (returns them in a vector array) % eigVals = eigs(J); % % Print Eigenvalues to Screen % fprintf('\n\nTheEIGENVALUES of the JACOBIAN are:'); fprintf('\n\neig1 = %4.4f\n',eigVals(1)); fprintf('\n\neig2 = %4.4f\n',eigVals(2)); fprintf('\n\neig3 = %4.4f\n\n\n',eigVals(3)); % fprintf('LARGEST eigenvalue is: %4.4f\n\n',max(eigVals));
github
nickabattista/Ark-master
go_Go_Logistic_ode45.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/ode45/go_Go_Logistic_ode45.m
3,030
utf_8
9e86adb726a8dbdcad2d74ba767dae09
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Solves the Logistic Equation using MATLAB's % ODE 45 built in differential equation solver, which uses RK-4 % (4th Order Runge-Kutta Method) % % dP/dt = k*P*(1 - P/C) % % Parameters: k <- growth rate % C <- carrying capacity % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function go_Go_Logistic_ode45() % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % Tstart = 0; % Simulation starts a tstart (initial value) Tstop = 150; % Simulation runs until time = TFinal % % Initial Values % p0 = 5; % Initial Population, P Initial_Values = [p0]; % Stores initial values in vector % % ode45 is matlab's ode solver % options=odeset('RelTol',1e-4); [t,sol] = ode45(@f,[Tstart Tstop],Initial_Values,options); % % storing solutions for each variable after solving ODE/ODE System. % P = sol(:,1); %gives us P(t) % % Plotting solutions % plot_Time_Evolutions(t,P) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: RHS vector of the problem: this function evaluates the % RHS of the ODEs and passes it back to the ode45 solver % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dvdt = f(t,sol) % % Components of vectors % P = sol(1); % Susceptible % % ODE Parameter Values % k = 0.25; % logistic growth rate C = 150; % carrying capacity % % ODES (RHS) % dPdt = k*P*( 1 - P/C ); % % Vector to be evaluated % dvdt = [dPdt]'; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: plots the time evolutions (solutions to ODEs)! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Time_Evolutions(t,P) % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(t,P,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Logistic'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: plots the phase planes! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Phase_Planes(S,I,R) % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) figure(2) plot(S,I,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Susceptible'); ylabel('Infected'); set(gca,'FontSize',fs);
github
nickabattista/Ark-master
go_Go_SIR.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/Euler_Method/go_Go_SIR.m
2,370
utf_8
87c84e39cd53309415720450851e0d9b
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Solves Standard Base Case SIR Model (no deaths) % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function go_Go_SIR() % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % TFinal = 150; % Simulation runs until time = TFinal dt = 0.0025; % Time-step t = 0; % Initialize Time to 0. n = 0; % Initialize storage counter to 0. % % Initial Values % s0 = 0.95; % Initial Population for Susceptible, S i0 = 0.05; % Initial Population for Infected, I r0 = 0; % Initial Population for Recovered, R % % Parameter Values % beta = 0.65; % rate of disease transmission gamma = 0.45; % rate of recovery % % Saves Initial Values into Storage Vectors % S(1) = s0; I(1) = i0; R(1) = r0; TimeVec(1) = t; % % While-loop that iteratively solves the discrete dynamical system % while t<TFinal % Iterate storage counter and time, t n = n + 1; t = t + dt; % Solve Susceptible ODE w/ Euler Method S(n+1) = S(n) + dt * ( -beta*S(n)*I(n) ); % Solve Infected ODE w/ Euler Method I(n+1) = I(n) + dt * ( beta*S(n)*I(n) - gamma*I(n) ); % Solve Recovered ODE w/ Euler Method R(n+1) = R(n) + dt * ( gamma*I(n) ); % Next time in time storage vector TimeVec(n+1) = t; end % % Calculate Reproduction Number, R0, for the simulation % R0 = beta/gamma; fprintf('\n\nReproduction Number, R0 = %4.2f\n\n\n',R0); % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(TimeVec,S,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(TimeVec,I,'r.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(TimeVec,R,'g.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Susceptible','Infected','Recovered'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); % % PLOT 2: Phase Plane Plot % figure(2) plot(S,I,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Susceptible'); ylabel('Infected'); set(gca,'FontSize',fs);
github
nickabattista/Ark-master
go_Go_SIR_w_Vaccines.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/Euler_Method/go_Go_SIR_w_Vaccines.m
2,663
utf_8
66a6272fd616d0a84cc3bca6161ca735
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Solves SIR w/ Vaccination (and death) Model % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function go_Go_SIR_w_Vaccines() % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % TFinal = 150; % Simulation runs until time = TFinal dt = 0.0025; % Time-step t = 0; % Initialize Time to 0. n = 0; % Initialize storage counter to 0. % % Initial Values % s0 = 0.99; % Initial Population for Susceptible, S i0 = 0.1; % Initial Population for Infected, I r0 = 0; % Initial Population for Recovered, R % % Parameter Values % beta = 0.25; % rate of disease transmission gamma = 0.45; % rate of recovery nu = 0.25; % rate of vaccination mu = 0.0074; % natural death rate muStar = 1.5*mu; % enhanced death rate % % Saves Initial Values into Storage Vectors % S(1) = s0; I(1) = i0; R(1) = r0; TimeVec(1) = t; % % While-loop that iteratively solves the discrete dynamical system % while t<TFinal % Iterate storage counter and time, t n = n + 1; t = t + dt; % Define Lambda Lambda = mu*S(n) + mu*R(n) + muStar*I(n); % Solve Susceptible ODE w/ Euler Method S(n+1) = S(n) + dt * ( -beta*S(n)*I(n) - mu*S(n) + Lambda -nu*S(n) ); % Solve Infected ODE w/ Euler Method I(n+1) = I(n) + dt * ( beta*S(n)*I(n) - gamma*I(n) - muStar*I(n) ); % Solve Recovered ODE w/ Euler Method R(n+1) = R(n) + dt * ( gamma*I(n) - mu*R(n) + nu*S(n) ); % Next time in time storage vector TimeVec(n+1) = t; end % % Calculate Reproduction Number, R0, for the simulation % R0 = beta*Lambda / ((mu+nu)*(gamma+muStar)); fprintf('\n\nReproduction Number, R0 = %4.2f\n\n\n',R0); % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(TimeVec,S,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(TimeVec,I,'r.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(TimeVec,R,'g.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Susceptible','Infected','Recovered'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); % % PLOT 2: Phase Plane Plot % figure(2) plot(S,I,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Susceptible'); ylabel('Infected'); set(gca,'FontSize',fs);
github
nickabattista/Ark-master
go_Go_SIR_w_Deaths.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Epidemiology/Euler_Method/go_Go_SIR_w_Deaths.m
2,578
utf_8
14cb92cdc55a2122a7ee9044e861cb6d
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Solves SIR w/ Deaths Model % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function go_Go_SIR_w_Deaths() % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % TFinal = 150; % Simulation runs until time = TFinal dt = 0.005; % Time-step t = 0; % Initialize Time to 0. n = 0; % Initialize storage counter to 0. % % Initial Values % s0 = 0.99; % Initial Population for Susceptible, S i0 = 0.1; % Initial Population for Infected, I r0 = 0; % Initial Population for Recovered, R % % Parameter Values % beta = 0.25; % rate of disease transmission gamma = 0.45; % rate of recovery mu = 0.0074; % natural death rate muStar = 1.5*mu; % enhanced death rate % % Saves Initial Values into Storage Vectors % S(1) = s0; I(1) = i0; R(1) = r0; TimeVec(1) = t; % % While-loop that iteratively solves the discrete dynamical system % while t<TFinal % Iterate storage counter and time, t n = n + 1; t = t + dt; % Define Lambda Lambda = mu*S(n) + mu*R(n) + muStar*I(n); % Solve Susceptible ODE w/ Euler Method S(n+1) = S(n) + dt * ( -beta*S(n)*I(n) - mu*S(n) + Lambda ); % Solve Infected ODE w/ Euler Method I(n+1) = I(n) + dt * ( beta*S(n)*I(n) - gamma*I(n) - muStar*I(n) ); % Solve Recovered ODE w/ Euler Method R(n+1) = R(n) + dt * ( gamma*I(n) - mu*R(n) ); % Next time in time storage vector TimeVec(n+1) = t; end % % Calculate Reproduction Number, R0, for the simulation % R0 = beta*Lambda / (mu*(gamma+muStar)); fprintf('\n\nReproduction Number, R0 = %4.2f\n\n\n',R0); % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(TimeVec,S,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(TimeVec,I,'r.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(TimeVec,R,'g.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Susceptible','Infected','Recovered'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); % % PLOT 2: Phase Plane Plot % figure(2) plot(S,I,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Susceptible'); ylabel('Infected'); set(gca,'FontSize',fs);
github
nickabattista/Ark-master
Predator_Prey.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Ecology/Predator_Prey.m
2,201
utf_8
6f2a44b347324ff4136e40a366fde1ff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Solves Discrete Dynamical Systems in Population Ecology % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Predator_Prey() % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % TFinal = 150; % Simulation runs until time = TFinal dt = 0.0025; % Time-step t = 0; % Initialize Time to 0. n = 0; % Initialize storage counter to 0. % % Initial Values % x0 = 100; % Initial Population for Prey, X y0 = 2; % Initial Population for Predator, Y % % Parameter Values % k = 0.75; % growth rate C = 250; % carrying capacity b1 = 0.075; % death parameter for prey from predator interactions b2 = 0.05; % growth parameter for predator from prey interactions d = 0.5; % death rate parameter for predator % % Saves Initial Values into Storage Vectors % X(1) = x0; Y(1) = y0; TimeVec(1) = t; % % While-loop that iteratively solves the discrete dynamical system % while t<TFinal % Iterate storage counter and time, t n = n + 1; t = t + dt; % Solve Prey ODE w/ Euler Method X(n+1) = X(n) + dt * ( k*X(n)*( 1 - X(n)/C ) - b1*X(n)*Y(n) ); % Solve Predator ODE w/ Euler Method Y(n+1) = Y(n) + dt * ( -d*Y(n) + b2*X(n)*Y(n) ); % Next time in time storage vector TimeVec(n+1) = t; end % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(TimeVec,X,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(TimeVec,Y,'r.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Prey','Predator'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); % % PLOT 2: Phase Plane Plot % figure(2) plot(X,Y,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Prey Population'); ylabel('Predator Population'); set(gca,'FontSize',fs);
github
nickabattista/Ark-master
go_Go_Logistic_ode45.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Ecology/go_Go_Logistic_ode45.m
3,030
utf_8
9e86adb726a8dbdcad2d74ba767dae09
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Solves the Logistic Equation using MATLAB's % ODE 45 built in differential equation solver, which uses RK-4 % (4th Order Runge-Kutta Method) % % dP/dt = k*P*(1 - P/C) % % Parameters: k <- growth rate % C <- carrying capacity % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function go_Go_Logistic_ode45() % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % Tstart = 0; % Simulation starts a tstart (initial value) Tstop = 150; % Simulation runs until time = TFinal % % Initial Values % p0 = 5; % Initial Population, P Initial_Values = [p0]; % Stores initial values in vector % % ode45 is matlab's ode solver % options=odeset('RelTol',1e-4); [t,sol] = ode45(@f,[Tstart Tstop],Initial_Values,options); % % storing solutions for each variable after solving ODE/ODE System. % P = sol(:,1); %gives us P(t) % % Plotting solutions % plot_Time_Evolutions(t,P) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: RHS vector of the problem: this function evaluates the % RHS of the ODEs and passes it back to the ode45 solver % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dvdt = f(t,sol) % % Components of vectors % P = sol(1); % Susceptible % % ODE Parameter Values % k = 0.25; % logistic growth rate C = 150; % carrying capacity % % ODES (RHS) % dPdt = k*P*( 1 - P/C ); % % Vector to be evaluated % dvdt = [dPdt]'; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: plots the time evolutions (solutions to ODEs)! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Time_Evolutions(t,P) % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(t,P,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Logistic'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: plots the phase planes! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Phase_Planes(S,I,R) % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) figure(2) plot(S,I,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Susceptible'); ylabel('Infected'); set(gca,'FontSize',fs);
github
nickabattista/Ark-master
Depensation_Model.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Ecology/Depensation_Model.m
1,591
utf_8
968761fd252a3957555a5c6208b707e5
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Models a depensation differential equation based on the % Logistic Model in in Ecology % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Depensation_Model(x0) % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % TFinal = 30; % Simulation runs until TFinal dt = 0.0025; % Time-step t = 0; % Initialize Time to 0. n = 0; % Initialize storage counter to 0. % % Initial Values % %x0 = 150; % Initial Population X(1) = x0; tVec(1) = t; % % Parameter Values % k = 2; % growth rate C = 250; % carrying capacity r = 125; % depensation constant % % While-loop that iteratively solves the differential equation % while t<TFinal % Iterate storage counter and time, t n = n + 1; t = t + dt; % Solve ODE w/ Euler Method X(n+1) = X(n) + dt* ( k*X(n)*( 1 - X(n)/C )*( X(n)/r - 1) ); % Next time in time storage vector tVec(n+1) = t; end % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Population vs. Time % figure(1) plot(tVec,X,'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); set(gca,'FontSize',fs); maxVal = 1.05*max(X); axis([0 TFinal 0 maxVal]);
github
nickabattista/Ark-master
sobol_method_sensitivity_zika.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/Mizuhara/sobol_method_sensitivity_zika.m
16,362
utf_8
e7ca22026dd9462bc6cd9de7a162604b
%Simulation of Brauer Zika SIR system; Morris sensitivity clear %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Physical Parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %av = [.3, 1]; Gao %f_hv = [.3, .75]; Gao %f_vh = [.1, .75]; Gao %k = [1/12,1/2]; Towers %g = [1/7,1/3]; Towers %m = [1/20, 1/6]; Towers %eta = [1/15, 1/4]; Towers %a = [.001,.1]; Gao %bv = av*f_hv = [.09,.75]; %b = bv*fvh/f_hv*N/Nv = [.0012, 1.875]; N/Nv ranges from .1 to 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Computational parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Timespan Tend = 365; tspan = [0 Tend]; N = 10; %number of simulations used in estimate d = 7; %number of params %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Sobol Matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% s = sobolset(2*d); sobol_mat = s(1:N,:); %N by 2d matrix of parameters %Rescale sobol_mat(:,1)=sobol_mat(:,1)*(1.875-.0012)+.0012; %beta sobol_mat(:,2)=sobol_mat(:,2)*(.1-.001)+.001; %alpha sobol_mat(:,3)=sobol_mat(:,3)*(1/2-1/12)+1/12;%kappa sobol_mat(:,4)=sobol_mat(:,4)*(1/3-1/7)+1/7; %gamma sobol_mat(:,5)=sobol_mat(:,5)*(1/6-1/20)+1/20;%mu sobol_mat(:,6)=sobol_mat(:,6)*(.75-.09)+.09; %beta_v sobol_mat(:,7)=sobol_mat(:,7)*(1/4-1/15)+1/15; %eta sobol_mat(:,8)=sobol_mat(:,8)*(1.875-.0012)+.0012; %beta sobol_mat(:,9)=sobol_mat(:,9)*(.1-.001)+.001; %alpha sobol_mat(:,10)=sobol_mat(:,10)*(1/2-1/12)+1/12;%kappa sobol_mat(:,11)=sobol_mat(:,11)*(1/3-1/7)+1/7; %gamma sobol_mat(:,12)=sobol_mat(:,12)*(1/6-1/20)+1/20;%mu sobol_mat(:,13)=sobol_mat(:,13)*(.75-.09)+.09; %beta_v sobol_mat(:,14)=sobol_mat(:,14)*(1/4-1/15)+1/15; %eta tic out = sobol_R0(sobol_mat,d,N); toc S_R0 = out(1,:); %ci = out(2:3,:); S_total_R0=out(2,:); %ci2 = out(5:6,:); x=1:d; figure() bar(x,S_R0) %errorbar(x,S_R0,ci(1,:),ci(2,:),'o') title('R_0: First order Sobol indices') xticklabels({'\beta','\alpha','\kappa','\gamma','\mu','\beta_v','\eta'}) axis([0 8 0 1.5]) savefig('r0_first_sobol.fig') saveas(gcf,'r0_first_sobol','png') figure() bar(x,S_total_R0) title('R_0: Total Sobol indices') xticklabels({'\beta','\alpha','\kappa','\gamma','\mu','\beta_v','\eta'}) axis([0 8 0 1.5]) savefig('r0_total_sobol.fig') saveas(gcf,'r0_total_sobol','png') tic out = sobol_crit_vir(sobol_mat,d,N); toc S_R0 = out(1,:); %ci = out(2:3,:); S_total_R0=out(2,:); %ci2 = out(5:6,:); x=1:d; figure() bar(x,S_R0) title('Critical virulence: First order Sobol indices') xticklabels({'\beta','\alpha','\kappa','\gamma','\mu','\beta_v','\eta'}) axis([0 8 0 1.5]) savefig('cv_first_sobol.fig') saveas(gcf,'cv_first_sobol','png') figure() bar(x,S_total_R0) title('Crticial virulence: Total Sobol indices') xticklabels({'\beta','\alpha','\kappa','\gamma','\mu','\beta_v','\eta'}) axis([0 8 0 1.5]) savefig('cv_total_sobol.fig') saveas(gcf,'cv_total_sobol','png') %%%%%%%%%%%%%%%% %% Sobol Calculations %%%%%%%%%%%%%%%% %% Input: A,B, d,N %% Output: out=[S_y ; S_total] function out= sobol_y(sobol_mat,d,N) %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix A %%%%%%%%%%%%%%%%%%%%%%%%%%% A = sobol_mat(1:N,1:d); %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% B = sobol_mat(1:N,d+1:2*d); mat_size = size(A); for i = 1:mat_size(1) %Vector of parameters X = A(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans y_A(i) = y(end,3); %Number of infected humans % R0_A(i) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7))); end %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% %B = sobol_mat(1:N,d+1:2*d); for i = 1:mat_size(1) %Vector of parameters X = B(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans y_B(i) = y(end,3); %Number of infected humans % R0_B(i) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7))); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Cross matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for j=1:d %%%each j is a new matrix A2 = A; A2(:,j) = B(:,j); %exchange jth column of A with B for i = 1:mat_size(1) %Vector of parameters X = A2(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans y_mix(i,j) = y(end,3); %Number of infected humans % R0_mix(i,j) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7))); end end %%y_mix(i,j) : i from 1:N (simulation number) and j from 1:d. var_y = var(y_A); %var_R0 = var(R0_A); %First order indices for i=1:d sumy=0; %sumR0 =0; for j=1:N sumy = sumy+ y_B(j)*(y_mix(j,i)-y_A(j)); % sumR0 = sumR0+ R0_B(j)*(R0_mix(j,i)-R0_A(j)); end S_y(i) = sumy/N/var_y; % S_R0(i) = sumR0/N/var_R0; end %Total order indices for i=1:d sumy=0; %sumR0 =0; for j=1:N sumy = sumy+ (y_A(j)-y_mix(j,i)).^2; % sumR0 = sumR0+ (R0_A(j)-R0_mix(j,i)).^2; end S_total_y(i) = sumy/(2*N)/var_y; % S_total_R0(i) = sumR0/(2*N)/var_R0; end out(1,:)=S_y; out(2,:)=S_total_y; end %%%%%%%%%%% %% Use Sobol to calculate R_0 sensitivities function out=sobol_R0(sobol_mat,d,N) %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix A %%%%%%%%%%%%%%%%%%%%%%%%%%% A = sobol_mat(1:N,1:d); %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% B = sobol_mat(1:N,d+1:2*d); mat_size = size(A); for i = 1:mat_size(1) %Vector of parameters X = A(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans % y_A(i) = y(end,3); %Number of infected humans %X = (beta, alpha,kappa,gamma, mu, beta_v,eta) R0_A(i) = R0_calc(X,1,10); end %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% %B = sobol_mat(1:N,d+1:2*d); for i = 1:mat_size(1) %Vector of parameters X = B(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans % y_B(i) = y(end,3); %Number of infected humans R0_B(i) = R0_calc(X,1,10); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Cross matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for j=1:d %%%each j is a new matrix A2 = A; A2(:,j) = B(:,j); %exchange jth column of A with B for i = 1:mat_size(1) %Vector of parameters X = A2(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans % y_mix(i,j) = y(end,3); %Number of infected humans R0_mix(i,j) = R0_calc(X,1,10); end end %%y_mix(i,j) : i from 1:N (simulation number) and j from 1:d. %var_y = var(y_A); var_R0 = var(R0_A); %First order indices %%%%%%%%%%%%%%%%%%% %% Matrix of all outputs %%%%%%%%%%%%%%%%%%% final_mat = [R0_A' R0_B' R0_mix]; %S_R0 = first_order_calc(final_mat,var_R0); S_R0 = first_order_ver2(final_mat); S_total_R0 = total_order_ver2(final_mat); %%Confidence interval % ci = bootci(10000,@(X) first_order_ver2(X),final_mat); % ci = bootci(1000,@(X) mean_R0(X),final_mat); %ci2 = bootci(1000,@(X) total_order_calc(X,var_R0),final_mat); figure() histogram(reshape(final_mat,1,N*(d+2)),'Normalization','pdf') title('Probability distribution of $R_0$ values','interpreter','latex') savefig('r0_pdf.fig') saveas(gcf,'r0_pdf','png') out(1,:)=S_R0; % out(2,:) = ci(1,:);%lower bounds % out(3,:) = ci(2,:); %upper bounds out(2,:)=S_total_R0; %out(5,:)=ci2(1,:); %out(6,:)=ci2(2,:); end %%%%%%%%%%%%%%%%%%%%%% %% Use Sobol to calculate critical virulence %%%%%%%%%%%%%%%%%%%%%% function out = sobol_crit_vir(sobol_mat,d,N) %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix A %%%%%%%%%%%%%%%%%%%%%%%%%%% A = sobol_mat(1:N,1:d); %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% B = sobol_mat(1:N,d+1:2*d); mat_size = size(A); for i = 1:mat_size(1) %Vector of parameters X = A(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans % y_A(i) = y(end,3); %Number of infected humans cv_A(i) = crit_vir_calc(X); end %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% %B = sobol_mat(1:N,d+1:2*d); for i = 1:mat_size(1) %Vector of parameters X = B(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans % y_B(i) = y(end,3); %Number of infected humans cv_B(i) = crit_vir_calc(X); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Cross matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for j=1:d %%%each j is a new matrix A2 = A; A2(:,j) = B(:,j); %exchange jth column of A with B for i = 1:mat_size(1) %Vector of parameters X = A2(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %%%%Measure number of infected humans % y_mix(i,j) = y(end,3); %Number of infected humans cv_mix(i,j) = crit_vir_calc(X); end end %%y_mix(i,j) : i from 1:N (simulation number) and j from 1:d. %var_y = var(y_A); var_cv = var(cv_A); %First order indices %%%%%%%%%%%%%%%%%%% %% Matrix of all outputs %%%%%%%%%%%%%%%%%%% final_mat = [cv_A', cv_B', cv_mix]; S_R0 = first_order_ver2(final_mat); S_total_R0 = total_order_ver2(final_mat); %%Confidence interval %ci = bootci(10000,{@(X) first_order_calc(X,var_cv),final_mat}); %ci2 = bootci(10000,{@(X) total_order_calc(X,var_cv),final_mat}); figure() histogram(reshape(final_mat,1,N*(d+2)),'Normalization','pdf') title('Probability distribution of critical virulence values','interpreter','latex') savefig('cv_pdf.fig') saveas(gcf,'cv_pdf','png') out(1,:)=S_R0; %out(2,:) = ci(1,:);%lower bounds %out(3,:) = ci(2,:); %upper bounds out(2,:)=S_total_R0; %out(5,:)=ci2(1,:); %out(6,:)=ci2(2,:); end function out = R0_calc(X,N,Nv) %X = (beta, alpha,kappa,gamma, mu, beta_v,eta) G = [X(2)/X(4), X(2)/X(4), X(1)*N/Nv*X(7)/(X(5)*(X(5)+X(7))), X(1)*N/Nv/X(5); 0, 0, 0, 0; X(6)*Nv/N/X(4),X(6)*Nv/N/X(4), 0, 0; 0, 0, 0, 0]; Geigs = eigs(G); out = max(Geigs); end function [out,index] = crit_vir_calc(X) %X = (beta, alpha,kappa,gamma, mu, beta_v,eta) cycles(1) = X(2)/X(4); cycles(2) = sqrt(X(1)*X(6)*X(7)/((X(5)+X(7))*X(4))); cycles(3) = (X(1)*X(6)*X(7)/((X(5)+X(7))*X(5)*X(4)))^(1/3); [out,index]=max(cycles); end function out = first_order_calc(final_mat,var_R0) size_mat = size(final_mat); N = size_mat(1); d= size_mat(2)-2; out = zeros(d,1); for i=1:d %sumy=0; sumR0 =0; %sumR01=0; for j=1:N %sumy = sumy+ y_B(j)*(y_mix(j,i)-y_A(j)); sumR0 = sumR0+ final_mat(j,2)*(final_mat(j,i)-final_mat(j,1)); %sumR0 = sumR0+ final_mat(j,2)*final_mat(j,i); % sumR01 = final_mat(j,1); end %sumR0/N^2 %var_R0 %S_y(i) = sumy/N/var_y; out(i) = sumR0/N/var_R0; end end function out = first_order_ver2(final_mat) size_mat = size(final_mat); Ns = size_mat(1); for j=1:size_mat(2)-2 out(j)=(Ns*final_mat(:,2)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/... (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2); end end function out = total_order_ver2(final_mat) size_mat = size(final_mat); Ns = size_mat(1); for j=1:size_mat(2)-2 out(j)=1-... (Ns*final_mat(:,1)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/... (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2); end end function out = total_order_calc(final_mat,var_R0) size_mat = size(final_mat); N = size_mat(1); d= size_mat(2)-2; out = zeros(d,1); for i=1:d %sumy=0; sumR0 =0; for j=1:N % sumy = sumy+ (y_A(j)-y_mix(j,i)).^2; sumR0 = sumR0+ (final_mat(j,1)-final_mat(j,i)).^2; end % S_total_y(i) = sumy/(2*N)/var_y; out(i) = sumR0/(2*N)/var_R0; end end
github
nickabattista/Ark-master
Sobol_R0.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/Mizuhara/Sobol_R0.m
8,774
utf_8
b91bc53d61c82cfb948a28baf1729fa0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Performs Sobol Sensitivity Analysis For Calculating Stability % of a Disease Free Equilibrium for the SIR Model w/ Deaths % % Orig. Author: Dr. Matthew S. Mizuhara (TCNJ) % % Modifications: Dr. Nick A. Battista (TCNJ) % Date: April 3, 2019 % % History: % 1. Code was originally designed to compute stability for DFE pertaining to % Zika (MSM). % 2. NAB modified for use in MAT/BIO 300 for SIR w/ Deaths. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Sobol_R0() % % Computational parameters % N = 100; % # of simulations used in estimate d = 5; % # of parameters used for sensitivity calculations % % Setting Up Sobol Matrix % % Constructs a new Sobol sequence point set in d-dimensions. s = sobolset(2*d); % Creates N by 2d matrix of parameters sobol_mat = s(1:N,:); %N by 2d matrix of parameters % Parameter Order to be Used Below (just for us to reference order here): % X = [beta gamma mu muStar Lambda] % % PARAMETER RANGES % % beta betaLow = 0.05; betaHigh= 0.5; % gamma gammaLow = 0.05; gammaHigh=0.5; % mu muLow = 0.005; muHigh = 2*muLow; % muStar muStarLow = 2*muLow; muStarHigh = 10*muLow; % Lambda LambdaLow = muLow; LambdaHigh= 3*muHigh; % % Rescale Sobol Matrix Automatically Based on Ranges Above % sobol_mat(:,1)=sobol_mat(:,1)*(betaHigh-betaLow)+betaLow; %beta sobol_mat(:,2)=sobol_mat(:,2)*(gammaHigh-gammaLow)+gammaLow; %gamma sobol_mat(:,3)=sobol_mat(:,3)*(muHigh-muLow)+muLow; %mu sobol_mat(:,4)=sobol_mat(:,4)*(muStarHigh-muStarLow)+muStarLow; %muStar sobol_mat(:,5)=sobol_mat(:,5)*(LambdaHigh-LambdaLow)+LambdaLow; %Lambda % sobol_mat(:,6)=sobol_mat(:,6)*(betaHigh-betaLow)+betaLow; %beta sobol_mat(:,7)=sobol_mat(:,7)*(gammaHigh-gammaLow)+gammaLow; %gamma sobol_mat(:,8)=sobol_mat(:,8)*(muHigh-muLow)+muLow; %mu sobol_mat(:,9)=sobol_mat(:,9)*(muStarHigh-muStarLow)+muStarLow; %muStar sobol_mat(:,10)=sobol_mat(:,10)*(LambdaHigh-LambdaLow)+LambdaLow; %Lambda % % Actually Perform Sobol Sensitivity (and record how long it takes using tic-toc) % fprintf('\n\nTime to run Sobol Sensitivity:\n'); tic out = sobol_R0(sobol_mat,d,N); toc fprintf('\n\n'); % Store First Order Sobol Indices For Each Parameter S_R0 = out(1,:); % Store Second Order Sobol Indices For Each Parameter S_total_R0=out(2,:); % Create Vector of #'s As Dummy for Each Parameter for Plotting x=1:d; % % Creates Bar Graph for 1st Order Sobol Indices % figure() bar(x,S_R0) title('R_0: First order Sobol indices') xticklabels({'\beta','\gamma','\mu','\mu^*','\Lambda'}) maxS = 1.05*max(S_R0); minS = min( 1.05*min(S_R0), 0 ); axis([0 6 minS maxS]) set(gca,'FontSize',18); % % Creates Bar Graph for Total Order Sobol Indices % figure() bar(x,S_total_R0) title('R_0: Total Sobol indices') xticklabels({'\beta','\gamma','\mu','\mu^*','\Lambda'}) maxS = 1.05*max(S_total_R0); minS = min( 1.05*min(S_total_R0), 0 ); axis([0 6 minS maxS]) set(gca,'FontSize',18); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: returns the "R0 value" for a particular parameter set % % Note: not exactly R_0 but a proxy for stability by returning % largest eigenvalue. If eigVal > 0, unstable. % % Input: X,N,Nv % Output: R_0 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function R_0 = R0_calc(X) % % SIR w/ Deaths Parameter Vector % X = [beta gamma mu muStar Lambda] beta = X(1); gamma = X(2); mu = X(3); muStar = X(4); Lambda = X(5); % % Disease Free Equilibria (DFE) Pop. Values % S = Lambda/mu; I = 0; R = 0; % % Construct Jacobian Matrix % % 1st Row of Jacobian J11 = -beta*I-mu; J12 = -beta*S; J13 = 0; % 2nd Row of Jacobian J21 = beta*I; J22 = beta*S-gamma-muStar; J23 = 0; % 3rd Row of Jacobian J31 = 0; J32 = gamma; J33 = -mu; % Fill in Jacobian Entries J = [J11 J12 J13; J21 J22 J23; J31 J32 J33]; % Compute Eigenvalues of Jacobian J_eigs = eigs(J); % Only Take Largest Eigenvalue (not exactly R_0, but proxy for stability, e.g., epidemic or no) R_0 = max(J_eigs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Performs the Sobol Calculations to calculate R_0 sensitivities % % Input: Sobol Matrices -> A and B, # of params -> d, # of simulations to be used -> N % Output: out=[S_y ; S_total] % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out=sobol_R0(sobol_mat,d,N) %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix A %%%%%%%%%%%%%%%%%%%%%%%%%%% A = sobol_mat(1:N,1:d); %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix A %%%%%%%%%%%%%%%%%%%%%%%%%%% B = sobol_mat(1:N,d+1:2*d); mat_size = size(A); for i = 1:mat_size(1) %Vector of parameters X = A(i,:); % % Compute R_0: note-> X = (beta, gamma, mu, muStar, Lambda) % R0_A(i) = R0_calc(X); end %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% %B = sobol_mat(1:N,d+1:2*d); for i = 1:mat_size(1) %Vector of parameters X = B(i,:); % % Compute R_0: note-> X = (beta, gamma, mu, muStar, Lambda) % R0_B(i) = R0_calc(X); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Cross matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for j=1:d %%%each j is a new matrix A2 = A; A2(:,j) = B(:,j); %exchange jth column of A with B for i = 1:mat_size(1) %Vector of parameters X = A2(i,:); % % Compute R_0: note-> X = (beta, gamma, mu, muStar, Lambda) % R0_mix(i,j) = R0_calc(X); end end % %y_mix(i,j) : i from 1:N (simulation number) and j from 1:d. % %var_y = var(y_A); var_R0 = var(R0_A); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix of all outputs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% final_mat = [R0_A' R0_B' R0_mix]; % First Order Sobol Indices S_R0 = first_order_ver2(final_mat); % Total Sobol Indices S_total_R0 = total_order_ver2(final_mat); %%Confidence interval % ci = bootci(10000,@(X) first_order_ver2(X),final_mat); % ci = bootci(1000,@(X) mean_R0(X),final_mat); % ci2 = bootci(1000,@(X) total_order_calc(X,var_R0),final_mat); figure() histogram(reshape(final_mat,1,N*(d+2)),'Normalization','pdf') title('Probability distribution of $\lambda_{max}$ values','interpreter','latex') set(gca,'FontSize',18) % % Sobol 1st Order and Total Indices % out(1,:)=S_R0; out(2,:)=S_total_R0; % % Confidence Intervals % % out(2,:) = ci(1,:); %lower bounds % out(3,:) = ci(2,:); %upper bounds % out(5,:)=ci2(1,:); % out(6,:)=ci2(2,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: computes First-Order Sobol Indices % % Input: matrix of all values from trials % Output: out (first order indices for each parameter) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = first_order_ver2(final_mat) size_mat = size(final_mat); Ns = size_mat(1); for j=1:size_mat(2)-2 out(j)=(Ns*final_mat(:,2)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/... (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: computes Total-Order Sobol Indices % % Input: matrix of all values from trials % Output: out (first order indices for each parameter) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = total_order_ver2(final_mat) size_mat = size(final_mat); Ns = size_mat(1); for j=1:size_mat(2)-2 out(j)=1-... (Ns*final_mat(:,1)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/... (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2); end
github
nickabattista/Ark-master
Sobol_ODE_System.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/Mizuhara/Sobol_ODE_System.m
11,988
utf_8
f37cee9dc49f21c939a117adc336394a
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Performs Sobol Sensitivity Analysis For Calculating Stability % of a Disease Free Equilibrium for the SIR Model w/ Deaths % % Orig. Author: Dr. Matthew Mizuhara (TCNJ) % % Modifications: Dr. Nick Battista (TCNJ) % Date: April 3, 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Sobol_ODE_System() % % Computational parameters % N = 100000; % # of simulations used in estimate d = 5; % # of parameters used for sensitivity calculations Tend = 365; % Time Final (Needed for ODE only) tspan = [0 Tend]; % Range of Time for ODE to be Solved % % Setting Up Sobol Matrix % % Constructs a new Sobol sequence point set in d-dimensions. s = sobolset(2*d); % Creates N by 2d matrix of parameters sobol_mat = s(1:N,:); %N by 2d matrix of parameters % Parameter Order to be Used Below (just for us to reference order here): % X = [beta gamma mu muStar Lambda] % % PARAMETER RANGES % % beta betaLow = 0.05; betaHigh= 0.5; % gamma gammaLow = 0.05; gammaHigh=0.5; % mu muLow = 0.005; muHigh = 2*muLow; % muStar muStarLow = 2*muLow; muStarHigh = 10*muLow; % Lambda LambdaLow = muLow; LambdaHigh= 3*muHigh; % %Rescale Sobol Matrix Automatically Based on Ranges Above % sobol_mat(:,1)=sobol_mat(:,1)*(betaHigh-betaLow)+betaLow; %beta sobol_mat(:,2)=sobol_mat(:,2)*(gammaHigh-gammaLow)+gammaLow; %gamma sobol_mat(:,3)=sobol_mat(:,3)*(muHigh-muLow)+muLow; %mu sobol_mat(:,4)=sobol_mat(:,4)*(muStarHigh-muStarLow)+muStarLow; %muStar sobol_mat(:,5)=sobol_mat(:,5)*(LambdaHigh-LambdaLow)+LambdaLow; %Lambda % sobol_mat(:,6)=sobol_mat(:,6)*(betaHigh-betaLow)+betaLow; %beta sobol_mat(:,7)=sobol_mat(:,7)*(gammaHigh-gammaLow)+gammaLow; %gamma sobol_mat(:,8)=sobol_mat(:,8)*(muHigh-muLow)+muLow; %mu sobol_mat(:,9)=sobol_mat(:,9)*(muStarHigh-muStarLow)+muStarLow; %muStar sobol_mat(:,10)=sobol_mat(:,10)*(LambdaHigh-LambdaLow)+LambdaLow; %Lambda % % Actually Perform Sobol Sensitivity (and record how long it takes using tic-toc) % fprintf('\n\nTime to run Sobol Sensitivity:\n'); tic out = sobol_R0(sobol_mat,d,N); toc fprintf('\n\n'); % Store First Order Sobol Indices S_R0 = out(1,:); % Store Second Order Sobol Indices S_total_R0=out(2,:); % Create Vector of #'s As Dummy for Each Parameter for Plotting x=1:d; % % Creates Bar Graph for 1st Order Sobol Indices % figure() bar(x,S_R0) title('R_0: First order Sobol indices') xticklabels({'\beta','\gamma','\mu','\mu^*','\Lambda'}) maxS = 1.05*max(S_R0); minS = min( 1.05*min(S_R0), 0 ); axis([0 6 minS maxS]) % % Creates Bar Graph for Total Order Sobol Indices % figure() bar(x,S_total_R0) title('R_0: Total Sobol indices') xticklabels({'\beta','\gamma','\mu','\mu^*','\Lambda'}) maxS = 1.05*max(S_total_R0); minS = min( 1.05*min(S_total_R0), 0 ); axis([0 6 minS maxS]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Performs the Sobol Calculations for ODE System % % Input: A,B, d,N % Output: out=[S_y ; S_total] % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out= sobol_y(sobol_mat,d,N) %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix A %%%%%%%%%%%%%%%%%%%%%%%%%%% A = sobol_mat(1:N,1:d); %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% B = sobol_mat(1:N,d+1:2*d); mat_size = size(A); for i = 1:mat_size(1) %Vector of parameters X = A(i,:); % Solves the ODE System y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) %Measure number of infected humans y_A(i) = y(end,3); %Number of infected humans % R0_A(i) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7))); end %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% %B = sobol_mat(1:N,d+1:2*d); for i = 1:mat_size(1) %Vector of parameters X = B(i,:); % Solves the ODE System y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) % Measure number of infected humans y_B(i) = y(end,3); %Number of infected humans % R0_B(i) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7))); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Cross matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for j=1:d %%%each j is a new matrix A2 = A; A2(:,j) = B(:,j); %exchange jth column of A with B for i = 1:mat_size(1) %Vector of parameters X = A2(i,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Solve ODE %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% y = brauer_zika_ode(X,N,Nv,Tend,I_init); % [t,f] = ode45(@(t,y) sir_ode(~,y,B1,B2,Bh,b1,b2,bh,nv,nh,n1,n2,m1,m2,mv,mh,dh,a) % Measure number of infected humans y_mix(i,j) = y(end,3); %Number of infected humans % R0_mix(i,j) = X(2)/X(4)+X(1)*X(6)*X(7)/(X(5)*X(4)*(X(5)+X(7))); end end %%y_mix(i,j) : i from 1:N (simulation number) and j from 1:d. var_y = var(y_A); %var_R0 = var(R0_A); %First order indices for i=1:d sumy=0; %sumR0 =0; for j=1:N sumy = sumy+ y_B(j)*(y_mix(j,i)-y_A(j)); % sumR0 = sumR0+ R0_B(j)*(R0_mix(j,i)-R0_A(j)); end S_y(i) = sumy/N/var_y; % S_R0(i) = sumR0/N/var_R0; end %Total order indices for i=1:d sumy=0; %sumR0 =0; for j=1:N sumy = sumy+ (y_A(j)-y_mix(j,i)).^2; % sumR0 = sumR0+ (R0_A(j)-R0_mix(j,i)).^2; end S_total_y(i) = sumy/(2*N)/var_y; % S_total_R0(i) = sumR0/(2*N)/var_R0; end out(1,:)=S_y; out(2,:)=S_total_y; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Performs the Sobol Calculations to calculate R_0 sensitivities % % Input: A,B, d,N % Output: out=[S_y ; S_total] % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out=sobol_R0(sobol_mat,d,N) %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix A %%%%%%%%%%%%%%%%%%%%%%%%%%% A = sobol_mat(1:N,1:d); %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix A %%%%%%%%%%%%%%%%%%%%%%%%%%% B = sobol_mat(1:N,d+1:2*d); mat_size = size(A); for i = 1:mat_size(1) %Vector of parameters X = A(i,:); % % Compute R_0: note-> X = (beta, alpha,kappa,gamma, mu, beta_v,eta) % R0_A(i) = R0_calc(X); end %%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix B %%%%%%%%%%%%%%%%%%%%%%%%%%% %B = sobol_mat(1:N,d+1:2*d); for i = 1:mat_size(1) %Vector of parameters X = B(i,:); % % Compute R_0: note-> X = (beta, alpha,kappa,gamma, mu, beta_v,eta) % R0_B(i) = R0_calc(X); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Cross matrices %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for j=1:d %%%each j is a new matrix A2 = A; A2(:,j) = B(:,j); %exchange jth column of A with B for i = 1:mat_size(1) %Vector of parameters X = A2(i,:); % % Compute R_0: note-> X = (beta, alpha,kappa,gamma, mu, beta_v,eta) % R0_mix(i,j) = R0_calc(X); end end % %y_mix(i,j) : i from 1:N (simulation number) and j from 1:d. % %var_y = var(y_A); var_R0 = var(R0_A); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Matrix of all outputs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% final_mat = [R0_A' R0_B' R0_mix]; % First Order Sobol Indices S_R0 = first_order_ver2(final_mat); % Total Sobol Indices S_total_R0 = total_order_ver2(final_mat); %%Confidence interval % ci = bootci(10000,@(X) first_order_ver2(X),final_mat); % ci = bootci(1000,@(X) mean_R0(X),final_mat); % ci2 = bootci(1000,@(X) total_order_calc(X,var_R0),final_mat); figure() histogram(reshape(final_mat,1,N*(d+2)),'Normalization','pdf') title('Probability distribution of $R_0$ values','interpreter','latex') % % Sobol 1st Order and Total Indices % out(1,:)=S_R0; out(2,:)=S_total_R0; % % Confidence Intervals % % out(2,:) = ci(1,:); %lower bounds % out(3,:) = ci(2,:); %upper bounds %out(5,:)=ci2(1,:); %out(6,:)=ci2(2,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: returns the "R0 value" for a particular parameter set % % Note: not exactly R_0 but a proxy for stability by returning % largest eigenvalue. If eigVal > 0, unstable. % % Input: X,N,Nv % Output: R_0 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function R_0 = R0_calc(X) % % SIR w/ Deaths Parameter Vector % X = [beta gamma mu muStar Lambda] beta = X(1); gamma = X(2); mu = X(3); muStar = X(4); Lambda = X(5); % % Disease Free Equilibria (DFE) Pop. Values % S = Lambda/mu; I = 0; R = 0; % % Construct Jacobian Matrix % % 1st Row of Jacobian J11 = -beta*I-mu; J12 = -beta*S; J13 = 0; % 2nd Row of Jacobian J21 = beta*I; J22 = beta*S-gamma-muStar; J23 = 0; % 3rd Row of Jacobian J31 = 0; J32 = gamma; J33 = -mu; % Fill in Jacobian Entries J = [J11 J12 J13; J21 J22 J23; J31 J32 J33]; % Compute Eigenvalues of Jacobian J_eigs = eigs(J); % Only Take Largest Eigenvalue (not exactly R_0, but proxy for stability, e.g., epidemic or no) R_0 = max(J_eigs); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: computes First-Order Sobol Indices % % Input: matrix of all values from trials % Output: out (first order indices for each parameter) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = first_order_ver2(final_mat) size_mat = size(final_mat); Ns = size_mat(1); for j=1:size_mat(2)-2 out(j)=(Ns*final_mat(:,2)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/... (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: computes Total-Order Sobol Indices % % Input: matrix of all values from trials % Output: out (first order indices for each parameter) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = total_order_ver2(final_mat) size_mat = size(final_mat); Ns = size_mat(1); for j=1:size_mat(2)-2 out(j)=1-... (Ns*final_mat(:,1)'*final_mat(:,j+2)-(final_mat(:,2)'*ones(Ns,1))^2)/... (Ns*final_mat(:,2)'*final_mat(:,2)-(final_mat(:,2)'*ones(Ns,1))^2); end
github
nickabattista/Ark-master
fnc_GetInputs.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_GetInputs.m
815
utf_8
c0043b47041ba0bc78f08e4bfbc311b0
%% fnc_GetInputs: give the vector of the inputs corresponding to the index % (useful to scan all the possible combinations of the % inputs) % % Usage: % ii = fnc_GetInputs(i) % % Inputs: % i scalar index of the inputs (given by fnc_GetIndex) % % Output: % ii array of the corresponding inputs % % ------------------------------------------------------------------------ % See also % fnc_GetIndex % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 29-01-2011 % % History: % 1.0 29-01-2011 First release. % 23-09-2014 Changed: de2bi to bitget %% function ii = fnc_GetInputs(i) ii = find(bitget(i, 1:(floor(log(i)/log(2)) + 1)));
github
nickabattista/Ark-master
GSA_GetSy_MultiOut_MultiSI.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_GetSy_MultiOut_MultiSI.m
6,532
utf_8
713a7c7a6ce495892c15cf3ec1efc17a
%% GSA_GetSy_MultiOut_MultiSI: calculate the Sobol' sensitivity indices % % Usage: % [S, eS, pro] = GSA_GetSy_MultiOut_MultiSI(pro, iset, verbose) % % Inputs: % pro project structure % iset cell array or array of inputs of the considered set, they can be selected % by index (1,2,3 ...) or by name ('in1','x',..) or % mixed % verbose if not empty, it shows the time (in hours) for % finishing % % Output: % S sensitivity coefficient % eS error of sensitivity coefficient % pro updated project structure % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 15-02-2011 % % History: % 1.0 15-04-2011 Added verbose parameter % 1.0 15-01-2011 First release. % 06-01-2014 Added comments. %% function [S, eS, pro] = GSA_GetSy_MultiOut_MultiSI(pro, iset, verbose) if ~exist('verbose','var') verbose = 0; else verbose = ~isempty(verbose) && verbose; end output = size(pro.GSA.fE,2); % get the indexes corresponding to the variables in iset index = fnc_SelectInput(pro, iset); if isempty(index) S = zeros(output,1); eS = zeros(output,1); else S = zeros(output,1); eS = zeros(output,1); % number of variables in iset n_index = length(index); % number of possibile combinations for the n variables in iset L = 2^n_index; if verbose tic end % for all the possible combinations of variables in iset for i=1:(L-1) % calculate the indexes of the variables in the i-th combination ii = fnc_GetInputs(i); % calculate the real indexes of the variables in the i-th % combination si = fnc_GetIndex(index(ii)); % if the part of sensitivity due to the si variables is not % calculated yet (useful to avoid to calculate again, saving time) if sum(isnan(pro.GSA.GSI(:,si))) > 0 %------- % if the part of variance in ANOVA corresponding to the si % variables is not calculated yet (useful to avoid to calculate % again, saving time) if sum(isnan(pro.GSA.Di(:,si))) > 0 % get the indexes of the variables in the current % combination of the variables in the iset ixi = fnc_GetInputs(si); s = length(ixi); l = 2^s - 1; %====== if sum(isnan(pro.GSA.Dmi(:,si))) > 0 n = length(pro.Inputs.pdfs); N = size(pro.SampleSets.E,1); H = pro.SampleSets.E(:,:); cii = fnc_GetComplementaryInputs(si,n); % create the new mixed (E and T) samples to perform the % quasi-Monte Carlo algorithm (see section 2.4) H(:,cii) = pro.SampleSets.T(:,cii); % Store the sample set in the project structure array pro.SampleSets.H{si} = H; % Parfor loop requirements model_function_handle = pro.Model.handle; fH_cell = cell(N,1); % Evaluate the model at the sample points in set H parfor j=1:N fH_cell{j} = feval(model_function_handle,H(j,:)); % the function output must be a single variable that takes the form of a row vector end % Convert the cell array to a numeric array, and store % the simulation results in the project structure array pro.GSA.fH{si} = cell2mat(fH_cell); % this will only work if all output generated by the function is numeric % calculate the elements of the summation reported in % section 2.4 as I ff = (pro.GSA.fE - repmat(pro.GSA.mfE,size(pro.GSA.fE,1),1)).*(pro.GSA.fH{si}-repmat(pro.GSA.mfE,size(pro.GSA.fH{si},1),1)); % calculate the I value in section 2.4 pro.GSA.Dmi(:,si) = nanmean(ff)'; pro.GSA.eDmi(:,si) = 1.96*sqrt((nanmean(ff.^2)' - pro.GSA.Dmi(:,si).^2)./sum(~isnan(ff))'); end %======= Di = pro.GSA.Dmi(:,si); eDi = pro.GSA.eDmi(:,si).^2; % compute the summation of the I values for all the % combinations of the current subset for j=1:(l-1) sii = fnc_GetInputs(j); k = fnc_GetIndex(ixi(sii)); s_r = s - length(sii); % add the part of variance due to the j-th subset of % variables or subtract it following eq. (20) Di = Di + pro.GSA.Dmi(:,k)*((-1)^s_r); eDi = eDi + pro.GSA.eDmi(:,k).^2; end % add/subtract the square of the mean value (here it's 0) pro.GSA.Di(:,si) = Di + ((pro.GSA.f0').^2)*((-1)^s); pro.GSA.eDi(:,si) = sqrt(eDi + 2*((pro.GSA.ef0').^2)); end %------ % calculate the partial sensitivity coefficient by definition pro.GSA.GSI(:,si) = pro.GSA.Di(:,si)./(pro.GSA.D'); pro.GSA.eGSI(:,si) = pro.GSA.GSI(:,si).*pro.GSA.eDi(:,si)./(pro.GSA.D'); end % sum the partial sensitivity coefficients for all the combinations % of the variables in iset S = S + pro.GSA.GSI(:,si); eS = eS + pro.GSA.eGSI(:,si); if verbose timelapse = toc; disp(timelapse*(L-1-i)/i/60/60); end end end
github
nickabattista/Ark-master
fnc_getSobolSequence.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_getSobolSequence.m
5,664
utf_8
476e90688fb596a2d7b46d05c269f9ea
%% fnc_getSobolSequence: give a set of sobol quasi-random % % Usage: % X = fnc_getSobolSequence(dim, N, dbpath) % % Inputs: % dim number of variables, the MAX number of variables is 40 % N number of samples % % Output: % X matrix [N x dim] with the quasti-random samples % % ------------------------------------------------------------------------ % % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 01-02-2011 % % History: % 1.0 01-02-2011 First release. % % % Credits: % This code is based on the one developed by John Burkardt % (http://people.sc.fsu.edu/~jburkardt/m_src/sobol_dataset/sobol_dataset.html) % and previously by Bennett Fox % %% function X = fnc_getSobolSequence(dim, N) p = fileparts(mfilename('fullpath')); dbpath = [p,'/SobolSets']; if exist(dbpath,'dir') nf = dir([dbpath,'/*.mat']); for i=1:length(nf) [DIM, remain] = strtok(nf(i).name(2:end), 'N'); if (str2double(DIM) == dim) NN = strtok(remain(2:end), '.'); if (str2double(NN) == N) load([dbpath,'/',nf(i).name]); return end end end end nextseed = 2^floor(log2(N)+1); X = nan(N,dim); MeM = InitSobol(dim); for j = 1:N [X(j,:), nextseed, MeM] = getNewSobolVector(dim, nextseed, MeM); end if exist(dbpath,'dir') save([dbpath,'/S',num2str(dim),'N',num2str(N),'.mat'],'X'); end %% ------------------------------------------------------------------------ function [ qrv, nextseed, MeM ] = getNewSobolVector (dim, seed, MeM) seed = max(floor(seed),0); if ( seed == 0 ) l = 1; MeM.lastq = zeros(1,dim); elseif ( seed == (MeM.seed_save + 1) ) l = smallest0bit(seed); elseif ( seed <= MeM.seed_save ) MeM.seed_save = 0; l = 1; MeM.lastq(1:dim) = 0; for seed_temp = MeM.seed_save : seed - 1 l = smallest0bit(seed_temp); for i = 1:dim MeM.lastq(i) = bitxor(MeM.lastq(i), MeM.v(i,l)); end end l = smallest0bit(seed); elseif ((MeM.seed_save + 1) < seed) for seed_temp = (MeM.seed_save + 1):(seed - 1) l = smallest0bit(seed_temp); for i = 1 : dim MeM.lastq(i) = bitxor(MeM.lastq(i),MeM.v(i,l) ); end end l = smallest0bit(seed); end qrv = nan(1,dim); for i = 1 : dim qrv(i) = MeM.lastq(i) * MeM.recipd; MeM.lastq(i) = bitxor ( MeM.lastq(i), MeM.v(i,l) ); end MeM.seed_save = seed; nextseed = seed + 1; %% ------------------------------------------------------------------------- function i = smallest0bit(b) i = 0; b = floor(b); while (true) i = i + 1; halfb = floor(b/2); if (b == 2*halfb) break; end b = halfb; end %% ---------------------------------------------------------------------- function MeM = InitSobol(dim) MeM.seed_save = -1; MeM.v = zeros(40,30); MeM.v(1:40,1) = 1; MeM.v(3:40,2) = [ ... 1, 3, 1, 3, 1, 3, 3, 1, ... 3, 1, 3, 1, 3, 1, 1, 3, 1, 3, ... 1, 3, 1, 3, 3, 1, 3, 1, 3, 1, ... 3, 1, 1, 3, 1, 3, 1, 3, 1, 3 ]'; MeM.v(4:40,3) = [ ... 7, 5, 1, 3, 3, 7, 5, ... 5, 7, 7, 1, 3, 3, 7, 5, 1, 1, ... 5, 3, 3, 1, 7, 5, 1, 3, 3, 7, ... 5, 1, 1, 5, 7, 7, 5, 1, 3, 3 ]'; MeM.v(6:40,4) = [ ... 1, 7, 9,13,11, ... 1, 3, 7, 9, 5,13,13,11, 3,15, ... 5, 3,15, 7, 9,13, 9, 1,11, 7, ... 5,15, 1,15,11, 5, 3, 1, 7, 9 ]'; MeM.v(8:40,5) = [ ... 9, 3,27, ... 15,29,21,23,19,11,25, 7,13,17, ... 1,25,29, 3,31,11, 5,23,27,19, ... 21, 5, 1,17,13, 7,15, 9,31, 9 ]'; MeM.v(14:40,6) = [ ... 37,33, 7, 5,11,39,63, ... 27,17,15,23,29, 3,21,13,31,25, ... 9,49,33,19,29,11,19,27,15,25 ]'; MeM.v(20:40,7) = [ ... 13, ... 33,115, 41, 79, 17, 29,119, 75, 73,105, ... 7, 59, 65, 21, 3,113, 61, 89, 45,107 ]'; MeM.v(38:40,8) = [ ... 7, 23, 39 ]'; MeM.poly(1:40)= [ ... 1, 3, 7, 11, 13, 19, 25, 37, 59, 47, ... 61, 55, 41, 67, 97, 91, 109, 103, 115, 131, ... 193, 137, 145, 143, 241, 157, 185, 167, 229, 171, ... 213, 191, 253, 203, 211, 239, 247, 285, 369, 299 ]; MeM.v(1,:) = 1; for i = 2 : dim j = MeM.poly(i); m = 0; while ( 1 ) j = floor ( j / 2 ); if ( j <= 0 ) break; end m = m + 1; end j = MeM.poly(i); for k = m : -1 : 1 j2 = floor ( j / 2 ); includ(k) = ( j ~= 2 * j2 ); j = j2; end for j = m + 1 : 30 newv = MeM.v(i,j-m); l = 1; for k = 1 : m l = 2 * l; if ( includ(k) ) newv = bitxor ( newv, l * MeM.v(i,j-k) ); end end MeM.v(i,j) = newv; end end l = 1; for j = 29 : -1 : 1 l = 2 * l; MeM.v(:,j) = MeM.v(:,j) * l; end MeM.recipd = 1.0 / ( 2 * l ); MeM.lastq(1:dim) = 0;
github
nickabattista/Ark-master
pro_SetModel.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pro_SetModel.m
737
utf_8
b5631a61b6e339d981141888764dbc4c
%% pro_SetModel: Set the model to the project % % Usage: % pro = pro_SetModel(pro, model, name) % % Inputs: % pro project structure % model handle to the @(x)model(x,...) where x is a vector % name optional, name of the model % % Output: % pro project structure % % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 28-01-2011 % % History: % 1.0 28-01-2011 First release. %% function pro = pro_SetModel(pro, model, name) pro.Model.handle = model; if nargin>2 pro.Model.Name = name; end
github
nickabattista/Ark-master
GSA_FAST_GetSi.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_FAST_GetSi.m
2,821
utf_8
615e97c23d674dc13c9495ed0581ec33
%% GSA_FAST_GetSi: calculate the FAST sensitivity indices % Ref: Cukier, R.I., C.M. Fortuin, K.E. Shuler, A.G. Petschek and J.H. % Schaibly (1973). Study of the sensitivity of coupled reaction systems to uncertainties in rate coefficients. I Theory. Journal of Chemical Physics % % Max number of input variables: 50 % % Usage: % Si = GSA_FAST_GetSi(pro) % % Inputs: % pro project structure % % Output: % Si vector of first order sensitivity coefficients % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 01-05-2011 % % History: % 1.0 01-05-2011 First release. % 06-01-2014 Added comments. %% function Si = GSA_FAST_GetSi(pro) % retrieve the number of input variables k = length(pro.Inputs.pdfs); % set the number of discrete intervals for numerical integration of (13) % increasing this parameter makes more precise the numerical integration M = 10; % read the table of incommensurate frequencies for k variables W = fnc_FAST_getFreqs(k); % set the maximum integer frequency Wmax = W(k); % calculate the Nyquist frequency and multiply it for the number of % intervals N = 2*M*Wmax+1; q = (N-1)/2; % set the variable of integration S = pi/2*(2*(1:N)-N-1)/N; alpha = W'*S; % calculate the new input variables, see (10) NormedX = 0.5 + asin(sin(alpha'))/pi; % retrieve the corresponding inputs for the new input variables. X = fnc_FAST_getInputs(pro, NormedX); Y = nan(N,1); % calculate the output of the model at input sample points for j=1:N Y(j) = pro.Model.handle(X(j,:)); end A = zeros(N,1); B = zeros(N,1); N0 = q+1; % ---- f1 = sum( reshape(Y(2:end),2,(N-1)/2) ); fdiff = -diff( reshape(Y(2:end),2,(N-1)/2) ); for j=1:N if mod(j,2)==0 % compute the real part of the Fourier coefficients sj = Y(1) ; for g=1:(N-1)/2 sj = sj + f1(g)*cos(j*g*pi/N) ; end A(j) = sj/N ; else % compute the imaginary part of the Fourier coefficients sj = 0 ; for g=1:(N-1)/2 sj = sj + fdiff(g)*sin(j*g*pi/N) ; end B(j) = sj/N ; end end % compute the total variance by summing the squares of the Fourier % coefficients V = 2*(A'*A + B'*B); % calculate the sensitivity coefficients for each input variable for i=1:k I = (1:M)*W(i) ; Si(i) = 2*(A(I)'*A(I) + B(I)'*B(I)) / V; end
github
nickabattista/Ark-master
GSA_Init_MultiOut_MultiSI.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_Init_MultiOut_MultiSI.m
2,732
utf_8
2865c383d6cf2056d97f442ab4257a9b
%% GSA_Init_MultiOut_MultiSI: initialize the variables used in the GSA computation % % Usage: % pro = GSA_Init_MultiOut_MultiSI(pro) % % Inputs: % pro project structure % % Output: % pro updated project structure % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 15-02-2011 % % History: % 1.0 15-01-2011 First release. % 06-01-2014 Added comments. %% function pro = GSA_Init_MultiOut_MultiSI(pro) % get two sets of samples of the input variables [E, T] = fnc_SampleInputs(pro); % Store the sample sets in the project structure array pro.SampleSets.E = E; pro.SampleSets.T = T; % get the number of input variables n = length(pro.Inputs.pdfs); % set the number of possible combinations of the input variables L = 2^n; N = pro.N; % Parfor loop requirements model_function_handle = pro.Model.handle; fE_cell = cell(N,1); % Evaluate the model at the sample points in set E parfor j=1:N fE_cell{j} = feval(model_function_handle,E(j,:)); % the function output must be a single variable that takes the form of a row vector end % Convert the cell array to a numeric array, and store the simulation % results in the project structure array pro.GSA.fE = cell2mat(fE_cell); % this will only work if all output generated by the function is numeric % Number of output variables output = size(pro.GSA.fE,2); % calculate the mean value for all the outcome variables pro.GSA.mfE = nanmean(pro.GSA.fE); pro.GSA.mfE(isnan(pro.GSA.mfE)) = 0; % calculate the mean value of the differences from the mean (it will be 0) pro.GSA.f0 = nanmean(pro.GSA.fE - repmat(pro.GSA.mfE,size(pro.GSA.fE,1),1)); % calculate the total variance of the model outcomes pro.GSA.D = nanmean((pro.GSA.fE - repmat(pro.GSA.mfE,size(pro.GSA.fE,1),1)).^2) - pro.GSA.f0.^2; % approximate the error of the mean value pro.GSA.ef0 = 1.96*sqrt(pro.GSA.D./sum(~isnan(pro.GSA.fE - repmat(pro.GSA.mfE,size(pro.GSA.fE,1),1)))); % prepare the structures for the temporary calculations of sensitivity % coefficients pro.SampleSets.H = cell(1,L-1); pro.GSA.fH = cell(1,L-1); pro.GSA.Dmi = nan(output,L-1); pro.GSA.eDmi = nan(output,L-1); pro.GSA.Di = nan(output,L-1); pro.GSA.eDi = nan(output,L-1); pro.GSA.GSI = nan(output,L-1); pro.GSA.eGSI = nan(output,L-1);
github
nickabattista/Ark-master
GSA_GetTotalSy.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_GetTotalSy.m
2,158
utf_8
eec4d448625695d12ae9bee76f277830
%% GSA_GetTotalSy: calculate the total sensitivity S of a subset of inputs % % Usage: % [Stot eStot pro] = GSA_GetTotalSy(pro, iset, verbose) % % Inputs: % pro project structure % iset cell array or array of inputs of the considered set, they can be selected % by index (1,2,3 ...) or by name ('in1','x',..) or % mixed % verbose if not empty, it shows the time (in hours) for % finishing % % Output: % Stot Total sensitiviy for the considered set % eStot associated error estimation (at 50%) % pro updated project structure % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 15-02-2011 % % History: % 1.0 15-04-2011 Added verbose parameter % 1.0 15-02-2011 First release. % 06-01-2014 Added comments. %% function [Stot eStot pro] = GSA_GetTotalSy(pro, iset, verbose) % calculate the total global sensitivity coefficient of the variable set % with index iset if ~exist('verbose','var') verbose = 0; else verbose = ~isempty(verbose) && verbose; end % get the number of input variables n = length(pro.Inputs.pdfs); % get the indexes corresponding to the variables in iset index = fnc_SelectInput(pro, iset); % calculate the complementary set of the input indexes compli = setdiff(1:n, index); if isempty(compli) Stot = 1; eStot = 0; else % calculate the global sensitivity coefficient for the complementary % set of input variables [S eS pro] = GSA_GetSy(pro, compli, verbose); % follow by equations in 2.3, calculate the total global sensitivity % coefficient Stot = 1 - S; eStot = eS; end
github
nickabattista/Ark-master
pdf_Sobol.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pdf_Sobol.m
587
utf_8
c70f1059c9562b2e2191a0fc5ebdec89
%% pdf_Sobol: Foo function for simulate a Sobol Set % % Usage: % pdf_Sobol() % % Inputs: % range vector [min max] range of the random variable % % Output: % range vector [min max] range of the random variable % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 01-02-2011 % % History: % 1.0 01-02-2011 First release. %% function range = pdf_Sobol(range) range = range(:)'; % empty function
github
nickabattista/Ark-master
fnc_GetComplementaryInputs.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_GetComplementaryInputs.m
860
utf_8
b49201eeff86fb5e3cf106d439e5da76
%% fnc_GetComplementaryInputs: give the vector of the complementary inputs %% corresponding to the index i % % Usage: % cii = fnc_GetComplementaryInputs(i, n) % % Inputs: % i scalar index of the inputs (given by fnc_GetIndex) % n number of total inputs % % Output: % cii array of the corresponding complementary inputs % % ------------------------------------------------------------------------ % See also % fnc_GetIndex % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 30-01-2011 % % History: % 1.0 30-01-2011 First release. % 23-09-2014 Changed: de2bi to bitget %% function cii = fnc_GetComplementaryInputs(i, n) cii = find(bitget(2^n - i - 1, 1:(n+1)));
github
nickabattista/Ark-master
GSA_GetTotalSy_MultiOut_MultiSI.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_GetTotalSy_MultiOut_MultiSI.m
2,289
utf_8
cd64bdc0cc001ee5445fa1eeb621e1c2
%% GSA_GetTotalSy_MultiOut_MultiSI: calculate the total sensitivity S of a subset of inputs % % Usage: % [Stot, eStot, pro] = GSA_GetTotalSy_MultiOut_MultiSI(pro, iset, verbose) % % Inputs: % pro project structure % iset cell array or array of inputs of the considered set, they can be selected % by index (1,2,3 ...) or by name ('in1','x',..) or % mixed % verbose if not empty, it shows the time (in hours) for % finishing % % Output: % Stot Total sensitiviy for the considered set % eStot associated error estimation (at 50%) % pro updated project structure % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 15-02-2011 % % History: % 1.0 15-04-2011 Added verbose parameter % 1.0 15-02-2011 First release. % 06-01-2014 Added comments. %% function [Stot, eStot, pro] = GSA_GetTotalSy_MultiOut_MultiSI(pro, iset, verbose) % calculate the total global sensitivity coefficient of the variable set % with index iset if ~exist('verbose','var') verbose = 0; else verbose = ~isempty(verbose) && verbose; end output = size(pro.GSA.fE,2); % get the number of input variables n = length(pro.Inputs.pdfs); % get the indexes corresponding to the variables in iset index = fnc_SelectInput(pro, iset); % calculate the complementary set of the input indexes compli = setdiff(1:n, index); if isempty(compli) Stot = ones(output,1); eStot = zeros(output,1); else % calculate the global sensitivity coefficient for the complementary % set of input variables [S, eS, pro] = GSA_GetSy_MultiOut_MultiSI(pro, compli, verbose); % follow by equations in 2.3, calculate the total global sensitivity % coefficient Stot = 1 - S; eStot = eS; end
github
nickabattista/Ark-master
pdf_LogNormal.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pdf_LogNormal.m
984
utf_8
8896cef0cd5300b0b762f35f13e2305c
%% pdf_LogNormal: LogNormal Probability Density Function % % Usage: % x = pdf_LogNormal(N, m, s) % % Inputs: % N scalar, number of samples % m mean of the lognormal distribution % s standard deviation of the lognormal distribution % % Output: % x vector with the sampled data % if N==0 -> x = [m - 3*s, m + 3*s] % % % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 28-12-2013 % % History: % 1.0 28-12-2013 First release. %% function x = pdf_LogNormal(N, m, s) if N==0 x = [m - 3*s, m + 3*s]; else mu = log((m^2)/sqrt(s^2+m^2)); sigma = sqrt(log((s^2)/(m^2)+1)); % sample a lognormal distribution function x = lognrnd(mu,sigma, [N 1]); end
github
nickabattista/Ark-master
GSA_FAST_GetSi_MultiOut.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_FAST_GetSi_MultiOut.m
3,673
utf_8
65d7e073de6289ba1a61082a24f2539b
%% GSA_FAST_GetSi: calculate the FAST sensitivity indices for multi-output systems % Ref: Cukier, R.I., C.M. Fortuin, K.E. Shuler, A.G. Petschek and J.H. % Schaibly (1973). Study of the sensitivity of coupled reaction systems to uncertainties in rate coefficients. I Theory. Journal of Chemical Physics % % Max number of input variables: 50 % % Usage: % Si = GSA_FAST_GetSi(pro) % % Inputs: % pro project structure % % Output: % Si vector of first order sensitivity coefficients for % sets comprising only a single input variable at a % time % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Simon Johnstone-Robertson % % Release: 1.0 % Date : 01-06-2015 % % History: % 1.0 01-06-2015 First release. %% function [Si,pro] = GSA_FAST_GetSi_MultiOut(pro) % retrieve the number of input variables n = length(pro.Inputs.pdfs); % set the number of discrete intervals for numerical integration of (13) % increasing this parameter makes the numerical integration more precise M = 10; % read the table of incommensurate frequencies for k variables W = fnc_FAST_getFreqs(n); % set the maximum integer frequency Wmax = W(n); % calculate the Nyquist frequency and multiply it for the number of % intervals N = 2*M*Wmax+1; q = (N-1)/2; % set the variable of integration S = pi/2*(2*(1:N)-N-1)/N; alpha = W'*S; % calculate the new input variables, see (10) NormedX = 0.5 + asin(sin(alpha'))/pi; % retrieve the corresponding inputs for the new input variables. X = fnc_FAST_getInputs(pro, NormedX); % Store the sample set in the project structure array pro.SampleSets.X = X; % Parfor loop requirements model_function_handle = pro.Model.handle; fX_cell = cell(N,1); % Evaluate the model at the sample points in set X parfor j=1:N fX_cell{j} = feval(model_function_handle,X(j,:)); % the function output must be a single variable that takes the form of a row vector end % Convert the cell array to a numeric array fX = cell2mat(fX_cell); % this will only work if all output generated by the function is numeric % Store simulation results in the project structure array pro.GSA.fX = fX; A = zeros(N,size(fX,2)); B = zeros(N,size(fX,2)); N0 = q+1; Si = NaN(size(fX,2),n); % Calculate the sensitivity indices of each input variable for all outcome variables for output = 1:size(fX,2) % compute the real part of the Fourier coefficients for j=2:2:N A(j,output) = 1/N*(fX(N0,output)+(fX(N0+(1:q),output)+fX(N0-(1:q),output))'* ... cos(pi*j*(1:q)/N)'); end % compute the imaginary part of the Fourier coefficients for j=1:2:N B(j,output) = 1/N*(fX(N0+(1:q),output)-fX(N0-(1:q),output))'* ... sin(pi*j*(1:q)/N)'; end % compute the total variance by summing the squares of the Fourier % coefficients V = 2*(A(:,output)'*A(:,output)+B(:,output)'*B(:,output)); % calculate the sensitivity coefficients for each input variable for i=1:n Vi=0; for j=1:M % numerical integration (13) Vi = Vi+A(j*W(i),output)^2+B(j*W(i),output)^2; end Vi = 2*Vi; % set the global first order sensitivity coefficient Si(output,i) = Vi/V; end end
github
nickabattista/Ark-master
pdf_Uniform.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pdf_Uniform.m
978
utf_8
f659aa1ae3c3b37bac6d0f07679b4dd6
%% pdf_Uniform: Uniform Probability Density Function % % Usage: % x = pdf_Uniform(N, range, seed) % % Inputs: % N scalar, number of samples % range vector [min max] range of the random variable % seed optional, seed for the random number generator % % Output: % x vector with the sampled data % if N==0 -> x = range % % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 28-01-2011 % % History: % 1.0 28-01-2011 First release. %% function x = pdf_Uniform(N, range, seed) if nargin>2 rand('twister',seed); else rand('twister', round(cputime*1000 + 100000*rand)); end if N==0 x = range(:)'; else % sample an uniform distribution function x = rand(N,1)*diff(range) + range(1); end
github
nickabattista/Ark-master
GSA_GetSy.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_GetSy.m
5,381
utf_8
893c7908ac99647e1f267405a09491d7
%% GSA_GetSy: calculate the Sobol' sensitivity indices % % Usage: % [S eS pro] = GSA_GetSy(pro, iset, verbose) % % Inputs: % pro project structure % iset cell array or array of inputs of the considered set, they can be selected % by index (1,2,3 ...) or by name ('in1','x',..) or % mixed % verbose if not empty, it shows the time (in hours) for % finishing % % Output: % S sensitivity coefficient % eS error of sensitivity coefficient % pro project structure % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 15-02-2011 % % History: % 1.0 15-04-2011 Added verbose parameter % 1.0 15-01-2011 First release. % 06-01-2014 Added comments. %% function [S eS pro] = GSA_GetSy(pro, iset, verbose) if ~exist('verbose','var') verbose = 0; else verbose = ~isempty(verbose) && verbose; end % get the indexes corresponding to the variables in iset index = fnc_SelectInput(pro, iset); if isempty(index) S = 0; eS = 0; else S = 0; eS = 0; % number of variables in iset n = length(index); % number of possibile combinations for the n variables in iset L = 2^n; if verbose tic end % for all the possible combinations of variables in iset for i=1:(L-1) % calculate the indexes of the variables in the i-th combination ii = fnc_GetInputs(i); % calculate the real indexes of the variables in the i-th % combination si = fnc_GetIndex(index(ii)); % if the part of sensitivity due to the si variables is not % calculated yet (useful to avoid to calculate again, saving time) if isnan(pro.GSA.GSI(si)) %------- % if the part of variance in ANOVA corresponding to the si % variables is not calculated yet (useful to avoid to calculate % again, saving time) if isnan(pro.GSA.Di(si)) % get the indexes of the variables in the current % combination of the variables in the iset ixi = fnc_GetInputs(si); s = length(ixi); l = 2^s - 1; %====== if isnan(pro.GSA.Dmi(si)) n = length(pro.Inputs.pdfs); N = size(pro.SampleSets.E,1); H = pro.SampleSets.E(:,:); cii = fnc_GetComplementaryInputs(si, n); % create the new mixed (E and T) samples to perform the % quasi-Monte Carlo algorithm (see section 2.4) H(:,cii) = pro.SampleSets.T(:,cii); ff = nan(N,1); % calculate the elements of the summation reported in % section 2.4 as I for j=1:N ff(j) = pro.GSA.fE(j)*(pro.Model.handle(H(j,:))-pro.GSA.mfE); end % calculate the I value in section 2.4 pro.GSA.Dmi(si) = nanmean(ff); pro.GSA.eDmi(si) = 0.9945*sqrt((nanmean(ff.^2) - pro.GSA.Dmi(si)^2)/sum(~isnan(ff))); end %======= Di = pro.GSA.Dmi(si); eDi = pro.GSA.eDmi(si)^2; % compute the summation of the I values for all the % combinations of the current subset for j=1:(l-1) sii = fnc_GetInputs(j); k = fnc_GetIndex(ixi(sii)); s_r = s - length(sii); % add the part of variance due to the j-th subset of % variables or subtract it following eq. (20) Di = Di + pro.GSA.Dmi(k)*((-1)^s_r); eDi = eDi + pro.GSA.eDmi(k)^2; end % add/subtract the square of the mean value (here it's 0) pro.GSA.Di(si) = Di + (pro.GSA.f0^2)*((-1)^s); pro.GSA.eDi(si) = sqrt(eDi + 2*(pro.GSA.ef0^2)); end %------ % calculate the partial sensitivity coefficient by definition pro.GSA.GSI(si) = pro.GSA.Di(si)/pro.GSA.D; pro.GSA.eGSI(si) = pro.GSA.GSI(si)*pro.GSA.eDi(si)/pro.GSA.D; end % sum the partial sensitivity coefficients for all the combinations % of the variables in iset S = S + pro.GSA.GSI(si); eS = eS + pro.GSA.eGSI(si); if verbose timelapse = toc; disp(timelapse*(L-1-i)/i/60/60); end end end
github
nickabattista/Ark-master
fnc_SampleInputs.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_SampleInputs.m
1,960
utf_8
0a48c67ce4e145af19646989a90059ae
%% fnc_SampleInputs: function that samples the input variables of a project % % Usage: % [Set1 Set2] = fnc_SampleInputs(pro) % % Inputs: % pro project structure % % Output: % Set1, Set2 matrix with the input pdfs sampled % % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 28-01-2011 % % History: % 1.0 28-01-2011 First release. %% function [Set1 Set2] = fnc_SampleInputs(pro) % get the number of input variables ninputs = length(pro.Inputs.pdfs); % prepare two sets of samples Set1 = nan(pro.N, ninputs); Set2 = nan(pro.N, ninputs); isobol = []; sobolRange = []; % scan all the input variables and select those that have to be sampled % with a Sobol' set (quasi-random). For the other other variables % create the stocastic sampling sets by using their pdfs for i=1:ninputs if ~isempty(strfind(func2str(pro.Inputs.pdfs{i}),'pdf_Sobol')) isobol(end+1) = i; sobolRange = [sobolRange; pro.Inputs.pdfs{i}()]; else Set1(:,i) = pro.Inputs.pdfs{i}(pro.N); Set2(:,i) = pro.Inputs.pdfs{i}(pro.N); end end if ~isempty(isobol) % create the Sobol quasi-random sets ninsobol = length(isobol); if exist('sobolset') % if the Matlab/Toolbox version includes the function get the set % by using it S = fnc_getSobolSetMatlab(ninsobol*2, pro.N); else % otherwise use the implemented function for Sobol sequences S = fnc_getSobolSequence(ninsobol*2, pro.N); end Min = repmat(sobolRange(:,1)', pro.N, 1); Max = repmat(sobolRange(:,2)', pro.N, 1); % denormalization of the sample points Set1(:,isobol) = Min + S(:,1:ninsobol).*(Max-Min); Set2(:,isobol) = Min + S(:,(ninsobol+1):end).*(Max-Min); end
github
nickabattista/Ark-master
pro_Create.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pro_Create.m
1,220
utf_8
90e9e94083a92c8114c2a3e7218fbf6d
%% pro_Create: Create an empty new project structure % % Usage: % pro = pro_Create() % % Inputs: % % Output: % pro project structure % .Inputs.pdfs: cell-array of the model inputs with the pdf handles % .Inputs.Names: cell-array with the input names % .N: scalar, number of samples of crude Monte Carlo % .Model.handle: handle to the model function % .Model.Name: string name of the model % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 28-01-2011 % % History: % 1.0 28-01-2011 First release. %% function pro = pro_Create() pro.Inputs.pdfs = {}; pro.Inputs.Names = {}; pro.N = 10000; pro.Model.handle = []; pro.Model.Name = [];
github
nickabattista/Ark-master
GSA_Init.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/GSA_Init.m
2,123
utf_8
7d0dad1cfa42510cc7dde92b3e61b394
%% GSA_Init: initialize the variables used in the GSA computation % % Usage: % pro = GSA_Init(pro) % % Inputs: % pro project structure % % Output: % pro project structure % % ------------------------------------------------------------------------ % Citation: Cannavo' F., Sensitivity analysis for volcanic source modeling quality assessment and model selection, Computers & Geosciences, Vol. 44, July 2012, Pages 52-59, ISSN 0098-3004, http://dx.doi.org/10.1016/j.cageo.2012.03.008. % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 15-02-2011 % % History: % 1.0 15-01-2011 First release. % 06-01-2014 Added comments. %% function pro = GSA_Init(pro) % get two sets of samples of the input variables [E T] = fnc_SampleInputs(pro); pro.SampleSets.E = E; pro.SampleSets.T = T; % get the number of input variables n = length(pro.Inputs.pdfs); % set the number of possible combinations of the input variables L = 2^n; N = pro.N; % prepare the structure for the evaluation of the model at the sample % points in the set E pro.GSA.fE = nan(N,1); % evaluate the model at the sample points in the set E for j=1:N pro.GSA.fE(j) = pro.Model.handle(pro.SampleSets.E(j,:)); end % calculate the mean value of the model outcomes pro.GSA.mfE = nanmean(pro.GSA.fE); if isnan(pro.GSA.mfE) pro.GSA.mfE = 0; end % subtract the mean values from the model outcomes pro.GSA.fE = pro.GSA.fE - pro.GSA.mfE; % calculate the mean values (it will be 0) pro.GSA.f0 = nanmean(pro.GSA.fE); % calculate the total variance of the model outcomes pro.GSA.D = nanmean(pro.GSA.fE.^2) - pro.GSA.f0^2; % approximate the error of the mean value pro.GSA.ef0 = 0.9945*sqrt(pro.GSA.D/sum(~isnan(pro.GSA.fE))); % prepare the structures for the temporary calculations of sensitivity % coefficients pro.GSA.Dmi = nan(1,L-1); pro.GSA.eDmi = nan(1,L-1); pro.GSA.Di = nan(1,L-1); pro.GSA.eDi = nan(1,L-1); pro.GSA.GSI = nan(1,L-1); pro.GSA.eGSI = nan(1,L-1);
github
nickabattista/Ark-master
fnc_SelectInput.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_SelectInput.m
1,288
utf_8
606f98697f0d34b9abcbe755c81cc9c2
%% fnc_SelectInput: select the input indexes from a generic list % % Usage: % index = fnc_SelectInput(pro, iset) % % Inputs: % pro project structure % iset cell array or array of inputs of the considered set, they can be selected % by index (1,2,3 ...) or by name ('in1','x',..) or % mixed % % Output: % index vector of indexes corresponding to the iset inputs % % ------------------------------------------------------------------------ % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 02-02-2011 % % History: % 1.0 02-02-2011 First release. %% function index = fnc_SelectInput(pro, iset) index = nan(size(iset)); if iscell(iset) for i=1:length(iset) in = iset{i}; if isnumeric(in) index(i) = floor(in); else for j=1:length(pro.Inputs.pdfs) if strcmp(in,pro.Inputs.Names{j}) index(i) = j; end end end end else index = iset; end if sum(isnan(index))>0 disp('Warning: some input is not well defined'); end index = sort(unique(index));
github
nickabattista/Ark-master
pdf_Normal.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pdf_Normal.m
825
utf_8
d49ba6d66f3efe7d058216c404a1f51c
%% pdf_Normal: Normal Probability Density Function % % Usage: % x = pdf_Normal(N, mu, sigma) % % Inputs: % N scalar, number of samples % mu mean % sigma standard deviation % % Output: % x vector with the sampled data % if N==0 -> x = [mu - 3*sigma, mu + 3*sigma] % % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 28-12-2013 % % History: % 1.0 28-12-2013 First release. %% function x = pdf_Normal(N, mu, sigma) if N==0 x = [mu - 3*sigma, mu + 3*sigma]; else % sample a normal distribution function x = normrnd(mu,sigma, [N 1]); end
github
nickabattista/Ark-master
SATestModel.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/SATestModel.m
332
utf_8
91dbcf8abd962cf881b22a89207e0f4d
% calculate the real analytical values of the global sensitivity % coefficients for the model "Sobol' function" in TestModel.m function [D Si] = SATestModel(p) Bi = 1./(3*((1+p).^2)); D = prod((1+Bi))-1; L = 2^length(p); Si = nan(1,L-1); for i=1:(L-1) ii = fnc_GetInputs(i); Si(i) = prod(Bi(ii))/D; end
github
nickabattista/Ark-master
fnc_GetIndex.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_GetIndex.m
622
utf_8
b74b5906e01446ab95d012835f362269
%% fnc_GetIndex: give the index of the element in the vector that %% corresponds to the set of inputs % % Usage: % i = fnc_GetIndex(C) % % Inputs: % C array of input indexes % % Output: % i index in the vector that contains all the variances % % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 29-01-2011 % % History: % 1.0 29-01-2011 First release. %% function i = fnc_GetIndex(C) i = sum(2.^(C-1));
github
nickabattista/Ark-master
pro_AddInput.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/pro_AddInput.m
722
utf_8
b2ea9c1585cfaa09d5707d2f9a28ee4e
%% pro_AddInput: Add a model input to the project % % Usage: % pro = pro_AddInput(pro, inputpdf, name, analyse) % % Inputs: % pro project structure % inputpdf reference to a @(N)pdf(N,...) % name name of the input % % Output: % pro project structure % % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 28-01-2011 % % History: % 1.0 28-01-2011 First release. %% function pro = pro_AddInput(pro, inputpdf, name) pro.Inputs.pdfs{end+1} = inputpdf; pro.Inputs.Names{end+1} = name;
github
nickabattista/Ark-master
fnc_FAST_getInputs.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_FAST_getInputs.m
1,359
utf_8
7170eb2a936173aa963f7daecb42c0b6
%% fnc_FAST_getInputs: transform the normed input in the real range inputs % % Usage: % X = fnc_FAST_getInputs(pro, NormedX) % % Inputs: % pro project structure % NormedX normed inputs % % Output: % X inputs in the correct ranges % % ------------------------------------------------------------------------ % See also % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 01-05-2011 % % History: % 1.0 01-05-2011 First release. % 06-01-2014 Added comments. %% function X = fnc_FAST_getInputs(pro, NormedX) % get the number of the input variables ninputs = length(pro.Inputs.pdfs); N = size(NormedX,1); Ranges = []; % retrieve the ranges for all the input variables for i=1:ninputs if ~isempty(strfind(func2str(pro.Inputs.pdfs{i}),'pdf_Sobol')) Ranges = [Ranges; pro.Inputs.pdfs{i}()]; else Ranges = [Ranges; pro.Inputs.pdfs{i}(0)]; end end m = zeros(1,size(NormedX,2));min(NormedX); M = ones(1,size(NormedX,2));max(NormedX); a = repmat(m,N,1); b = repmat(M,N,1); r = repmat(Ranges(:,1)',N,1); R = repmat(Ranges(:,2)',N,1); % map the normalized input variables into real input variables for the % model defined in pro X = (NormedX-a).*(R-r)./(b-a) + r;
github
nickabattista/Ark-master
fnc_getSobolSetMatlab.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/fnc_getSobolSetMatlab.m
789
utf_8
98add8889dc4652506337915fefc47ae
%% fnc_getSobolSetMatlab: give a set of sobol quasi-random by using Matlab % implemented functions % % Usage: % X = fnc_getSobolSetMatlab(dim, N) % % Inputs: % dim number of variables, the MAX number of variables is 40 % N number of samples % % Output: % X matrix [N x dim] with the quasti-random samples % % ------------------------------------------------------------------------ % % % Author : Flavio Cannavo' % e-mail: flavio(dot)cannavo(at)gmail(dot)com % Release: 1.0 % Date : 07-02-2011 % % History: % 1.0 07-02-2011 First release. % % % %% function X = fnc_getSobolSetMatlab(dim, N) p = sobolset(dim); p = scramble(p,'MatousekAffineOwen'); X = net(p,N);
github
nickabattista/Ark-master
TestModel2.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/ODE_Dynamical_Systems/Sensitivity/GSAT_Sensitivity/TestModel2.m
129
utf_8
361d787c542bcf214a94be2b91094ddd
% Ishigami test function (section 3.0.1) function g = TestModel2(x) g = sin(x(1))+5*(sin(x(2))^2) + 0.1*(x(3)^4)*sin(x(1));
github
nickabattista/Ark-master
Random_Walks_in_2D_Lattice.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walks_in_2D_Lattice.m
2,718
utf_8
a8dd0d3f7dc769ae3b3541802bfb2661
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Computes Random Walks in 2D to compute root-mean-squared % distance from starting point. % % % Author: Nick Battista % Institution: TCNJ % Created: April 8, 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Random_Walks_in_2D_Lattice() M = 10000; % # of Random Walkers N = 300; % # of steps for each walker ds = 0.1; % size of step (step-size) x = 0; % initial x-Position y = 0; % initial y-Position % Perform a Random Walk for Each Walker for i=1:M % Do Random Walk for i-th random walker [xDist,yDist,rSqr] = do_Random_Walk(N,ds,x,y); % Store displacement distance from starting point (can be + or -) xDist_Vec(i) = xDist; yDist_Vec(i) = yDist; % Store squared displacement distance from starting point (must be +) rSqr_Vec(i) = rSqr; end % Compute Avg. of Squared-Displacement Distance from Starting Pt. rSqr_Avg = mean(rSqr_Vec); % Compute root-mean-squared displacement (take sqrt of avg. r-Squared Displacement Vector) RMS = sqrt( rSqr_Avg ); % Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt. fprintf('Avg. Squared-Displacement: %2.4f\n',RMS); fprintf('Theory Says Avg. Displacement = %2.4f\n',sqrt(N)*ds); fprintf('Error: %2.4f\n\n\n',abs( RMS - sqrt(N)*ds)); % Plot ending point (x,y) for each Random Walk plot(xDist_Vec,yDist_Vec,'b.','MarkerSize',10); hold on; plot(0,0,'r.','MarkerSize',60); hold on; xlabel('x'); ylabel('y'); title('2D Random Walks Final Position'); %axis square; axis([-5 5 -5 5]); set(gca,'FontSize',18); grid on; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk starting at "x,y" and ending after "N" steps % % Inputs: x,y <-- starting point for x,y % N <-- length of Random Walk % ds <-- length of a step % % Outputs: % xDist: displacement distance from starting point (can be + or -) % xSqr: squared displacement distance from starting point (must be +) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [xDist,yDist,rSqr] = do_Random_Walk(N,ds,x,y) % Perform the Random Walk for i=1:N coin = rand(1); if (coin <= 0.25) x = x - ds; elseif (coin <= 0.5) x = x + ds; elseif (coin <=0.75) y = y - ds; else y = y + ds; end end % Store final positions of (x,y) for Random Walker xDist = x; yDist = y; % Store squared displacement distance from origin rSqr = x^2 + y^2;
github
nickabattista/Ark-master
Diffusion_2D.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Diffusion_2D.m
6,405
utf_8
bf1c5c526159fdbe6422092a07528cf6
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: solves Diffusion Equation in 2D and compares to Random Walkers % in 2D on a lattice % % % Author: Nick Battista % Institution: TCNJ % Created: April 8, 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Diffusion_2D() L=10; % size of domain [0,L]x[0,L] ds = 0.05; % ds = dx = dy (step-size) M = 250; % # of random walkers dt = 1e-3; % time-step size x0 = L/2; % Initial x-Position of Random Walkers y0 = L/2; % Initial y-Position of Random Walkers dumpInt = 50; % storing dump interval TFinal = 5; % final simulation time D = ( ds^2 + ds^2 ) / (5*dt); % diffusion coefficient % % Solve Diffusion Equation fprintf('\n\n...Solving 2D Diffusion PDE...\n\n'); [U_store,X,Y,numStored] = please_Solve_Diffusion(L,ds,dt,TFinal,D,dumpInt,M); fprintf('\n\nFinished solving 2D Diffusion PDE...\n'); pause(); % % Perform Random Walks fprintf('\n\n\n...Computing Random Walks...\n\n'); [xMat,yMat,RMS_Sims,RMS_Theory] = please_Perform_Random_Walk(x0,y0,ds,dt,dumpInt,TFinal,M); % % Compute Circles of where RMS-Distance is for Simulation Npts = 100; for j=2:length(RMS_Sims) xC(:,j) = ( -RMS_Sims(j):2*RMS_Sims(j)/Npts:RMS_Sims(j) )'; yC_T(:,j) = sqrt( RMS_Sims(j)^2 - xC(:,j).^2 ); xC(:,j) = xC(:,j); yC_T(:,j) = yC_T(:,j); end % % Plot Solutions for j=1:numStored uD = U_store(:,:,j); figure(1) % Plot Contours for Diffusion and RMS-Simulation Distance Contour subplot(1,3,1) contourf(X,Y,uD,4,'ShowText','on'); hold on; if j==1 plot(x0,y0,'r.','MarkerSize',20); hold on; else plot(xC(:,j)+x0,yC_T(:,j)+y0,'r-','LineWidth',6); hold on; plot(xC(:,j)+x0,-yC_T(:,j)+y0,'r-','LineWidth',6); hold on; end axis square; % Plot Surface in 3D for Diffusion subplot(1,3,2) surf(X(1,:),Y(:,1),uD); %surf(X,Y,uD,'EdgeColor', 'None', 'facecolor', 'interp'); view(2); %axis square; % Plot Contours for Diffusion and Random Walkers after same amount of time-steps subplot(1,3,3) contourf(X,Y,uD,4); hold on; plot(xMat(:,j),yMat(:,j),'r.','MarkerSize',20); hold on; axis square; % For Class Demonstration if j==1 pause(); else pause(0.5); end clf; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walks! % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [xMat,yMat,RMS_SimVec,RMS_Theory] = please_Perform_Random_Walk(x0,y0,ds,dt,dumpInt,TFinal,M) numSteps = TFinal / dt; % # of steps for Random Walk ct = 1; % counter for storing values xVec = x0*ones(M,1); % initial starting places in x-Position yVec = y0*ones(M,1); % initial starting places in y-Position xMat = zeros(M,1); % initialize storage yMat = xMat; % initialize storage xMat(:,ct) = xVec; % store initial starting places in x-Position yMat(:,ct) = yVec; % store initial starting places in x-Position RMS_SimVec(ct) = 0; RMS_Theory(ct) = 0; for i=1:numSteps rand_Vec = rand(M); for j=1:M % Random Walker Has Choice to Stay in Same Place w/ equal probabiltiy if rand_Vec(j) <= 0.20 xVec(j) = xVec(j) + ds; elseif rand_Vec(j) <= 0.4 xVec(j) = xVec(j) - ds; elseif rand_Vec(j) <= 0.6 yVec(j) = yVec(j) + ds; elseif rand_Vec(j) <= 0.8 yVec(j) = yVec(j) - ds; end end if mod(i,dumpInt)==0 ct = ct + 1; xMat(:,ct) = xVec; yMat(:,ct) = yVec; aux = (xVec-x0).^2 + (yVec-y0).^2; RMS_SimVec(ct) = sqrt( mean( aux ) ); RMS_Theory(ct) = sqrt(i)*ds; fprintf('%d of %d Steps in Random Walk\n',i,numSteps); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: solve Diffusion PDE in 2D and returns solution and mesh grid % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [U_store,X,Y,ct] = please_Solve_Diffusion(L,ds,dt,TFinal,D,dumpInt,M) % % Give Initial Background Grid for Diffusion [U,X,Y] = give_Me_Initial_Condition(L,ds,M); % % Solve Diffusion Equation ct = 1; % counter for storage U_store(:,:,ct) = U; % Store initial configuration t = 0; % time in simulatio n = 0; % number of total time-steps % while t<TFinal n = n+1; U = Solve_Diffusion(dt,ds,U,D); if mod(n,dumpInt)==0 ct = ct+1; U_store(:,:,ct) = U; fprintf('Current Time: %2.3f (of Final Time = %d) for 2D Diffusion\n',t,TFinal); end t = t+dt; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: solves 2D Diffusion Equation w/ Dirichlet Boundary Conditions % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function U = Solve_Diffusion(dt,ds,U,D) [Ny,Nx] = size(U); for i=1:Nx if i==1 U(:,1) = 0; %Dirichlet Boundary Condition in x elseif i==Nx U(:,Nx) = 0; %Dirichlet Boundary Condition in x else for j=1:Ny if j==1 U(1,:) = 0; %Dirichlet Boundary Condition in y elseif j==Ny U(Ny,:) = 0; %Dirichlet Boundary Condition in y else % Solves 2D Diffusion Equation using Finite Differences U(j,i) = U(j,i) + dt/ds^2*D*( U(j+1,i) + U(j-1,i) + U(j,i+1) + U(j,i-1) - 4*U(j,i) ); end end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: give initial condition of background % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [U,X,Y] = give_Me_Initial_Condition(L,ds,M) % Give number of grid points numPts = ceil(L/ds); % Make Computational Mesh [X,Y] = meshgrid(0:ds:L,0:ds:L); % % Initialize Grid to Zero U = zeros(numPts+1,numPts+1); % % Initial Value of 1 at (x,y)=(L/2,L/2) U(numPts/2+1,numPts/2+1) = M;
github
nickabattista/Ark-master
Random_Walks_in_1D.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walks_in_1D.m
2,691
utf_8
792aad56a90df41816eb874964ad3f81
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Computes Random Walks in 1D to compute root-mean-squared % distance from starting point. % % % Author: Nick Battista % Institution: TCNJ % Created: April 8, 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function errRMS = Random_Walks_in_1D() M = 1000; % # of Random Walkers N = 50; % # of steps for each walker ds = 0.1; % size of step (step-size) x = 0; % initial position % Perform a Random Walk for Each Walker for i=1:M % Do Random Walk for i-th random walker [xDist,xSqr] = do_Random_Walk(N,ds,x); % Store displacement distance from starting point (can be + or -) xDist_Vec(i) = xDist; % Store squared displacement distance from starting point (must be +) xSqr_Vec(i) = xSqr; end % Compute Avg. of Displacement Distances from Starting Pt. xDist_Avg = mean(xDist_Vec); % Compute Avg. of Squared-Displacement Distance from Starting Pt. RMS_Avg = sqrt(mean(xSqr_Vec)); % Store RMS Error between average RMS from simulation and theory errRMS = abs( RMS_Avg - sqrt(N)*ds); % Print Information to Screen for Avg. Displacement From Starting Pt. fprintf('\n\nAvg. Displacement: %2.4f\n',xDist_Avg); fprintf('Theory Says Avg. Displacement = 0\n'); fprintf('Error: %2.4f\n\n\n',abs(xDist_Avg)); % Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt. fprintf('Avg. Squared-Displacement: %2.4f\n',RMS_Avg); fprintf('Theory Says Avg. Displacement = %2.4f\n',sqrt(N)*ds); fprintf('Error: %2.4f\n\n\n',errRMS); % Plot ending point (x,y) for each Random Walk plot(0,0,'r.','MarkerSize',50); hold on; plot(xDist_Vec,zeros(length(xDist_Vec)),'b.','MarkerSize',10); hold on; % 'b.' <- blue, 'r.' <- red, 'g.' <- green, 'k.' <-black xlabel('x'); ylabel('y'); title('1D Random Walks Final Position'); set(gca,'FontSize',18); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk starting at "x" and ending after "N" steps % % Inputs: x <-- starting point % N <-- length of Random Walk % ds <-- length of a step % % Outputs: % xDist: displacement distance from starting point (can be + or -) % xSqr: squared displacement distance from starting point (must be +) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [xDist,xSqr] = do_Random_Walk(N,ds,x) % Perform the Random Walk for i=1:N coin = rand(1); if coin > 0.5 x = x - ds; else x = x + ds; end end xDist = x; xSqr = x^2;
github
nickabattista/Ark-master
Random_Walks_in_2D.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walks_in_2D.m
2,452
utf_8
b9b682be6e347f675e29b4a3d65b7c76
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Computes Random Walks in 2D to compute root-mean-squared % distance from starting point. % % % Author: Nick Battista % Institution: TCNJ % Created: April 8, 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Random_Walks_in_2D() M = 10000; % # of Random Walkers N = 50; % # of steps for each walker ds = 0.1; % size of step (step-size) x = 0; % initial x-Position y = 0; % initial y-Position % Perform a Random Walk for Each Walker for i=1:M % Do Random Walk for i-th random walker [xFinal,yFinal,rSqr] = do_Random_Walk(N,ds,x,y); % Store x,y-Final positions xFinal_Vec(i) = xFinal; yFinal_Vec(i) = yFinal; % Store squared displacement distance from starting point (must be +) rSqr_Vec(i) = rSqr; end % Compute Avg. of Squared-Displacement Distance from Starting Pt. RMS = sqrt( mean( rSqr_Vec ) ); % Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt. fprintf('Avg. Squared-Displacement: %2.4f\n',RMS); fprintf('Theory Says Avg. Displacement = %2.4f\n',sqrt(N)*ds); fprintf('Error: %2.4f\n\n\n',abs(RMS - sqrt(N)*ds)); % Plot ending point (x,y) for each Random Walk figure(2) plot(xFinal_Vec,yFinal_Vec,'b.','MarkerSize',10); hold on; plot(0,0,'r.','MarkerSize',50); hold on; xlabel('x'); ylabel('y'); title('2D Random Walks Final Position'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk starting at "x,y" and ending after "N" steps % % Inputs: x,y <-- starting point for x,y % N <-- length of Random Walk % ds <-- length of a step % % Outputs: % xDist: displacement distance from starting point (can be + or -) % xSqr: squared displacement distance from starting point (must be +) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [xFinal,yFinal,rSqr] = do_Random_Walk(N,ds,x,y) % Perform the Random Walk for i=1:N % Get random angle between 0 and 2*pi ang = 2*pi*rand(1); % Move in x-direction (based on trig relations) x = x + ds*cos(ang); % Move in y-direction (based on trig relations) y = y + ds*sin(ang); end % Define final positions of (x,y) for output xFinal = x; yFinal = y; % Save r^2 value rSqr = x^2 + y^2;
github
nickabattista/Ark-master
compute_Random_Walks_2D_Lattice_Convergence.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walker_Convergence/compute_Random_Walks_2D_Lattice_Convergence.m
3,765
utf_8
ac300c7f03a5c71f66adff56efeb17c9
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Computes error btwn simulation and theory for different numbers % of random walkers in 2D. As # of RWs goes up, error goes down. % % Author: Nick Battista % Institution: TCNJ % Created: April 8, 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function compute_Random_Walks_2D_Lattice_Convergence() % Vector of all #'s of Random Walker Trials to Do MVec = [10:10:90 100:100:900 1e3:1e3:9e3 1e4:1e4:9e4 1e5:1e5:5e5]; for i=1:length(MVec) % Define # of Random Walkers for Trial M = MVec(i); % Print Simulation Case Info to Screen fprintf('Simulation Case w/ M=%d\n',M); % Call Random Walk Function that Returns Error btwn theory and simulation for RMS err = Random_Walks_in_2D_Lattice(M); % Store RMS Error for Simulation with M random walkers errVec(i) = err; end figure(2) lw=4; ms=24; loglog(MVec,errVec,'-.','MarkerSize',ms,'LineWidth',lw); xlabel('# of Random Walkers'); ylabel('RMS Error'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk with M-Random Walkers to compute avg. % error in RMS % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function errRMS = Random_Walks_in_2D_Lattice(M) %M = 10000; % # of Random Walkers N = 25; % # of steps for each walker ds = 0.1; % size of step (step-size) x = 0; % initial x-Position y = 0; % initial y-Position % Perform a Random Walk for Each Walker for i=1:M % Do Random Walk for i-th random walker [xDist,yDist,rSqr] = do_Random_Walk(N,ds,x,y); % Store displacement distance from starting point (can be + or -) xDist_Vec(i) = xDist; yDist_Vec(i) = yDist; % Store squared displacement distance from starting point (must be +) rSqr_Vec(i) = rSqr; end % Compute Avg. of Squared-Displacement Distance from Starting Pt. rSqr_Avg = mean(rSqr_Vec); % Compute root-mean-squared displacement (take sqrt of avg. r-Squared Displacement Vector) RMS_Avg = sqrt( rSqr_Avg ); % Store RMS Error between average RMS from simulation and theory errRMS = abs( RMS_Avg - sqrt(N)*ds); % Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt. % fprintf('Avg. Squared-Displacement: %2.4f\n',RMS_Avg); % fprintf('Theory Says Avg. Displacement = %2.4f\n',sqrt(N)*ds); % fprintf('Error: %2.4f\n\n\n',errRMS); % Plot ending point (x,y) for each Random Walk % plot(xDist_Vec,yDist_Vec,'b.','MarkerSize',10); hold on; % plot(0,0,'r.','MarkerSize',50); hold on; % xlabel('x'); % ylabel('y'); % title('2D Random Walks Final Position'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk starting at "x,y" and ending after "N" steps % % Inputs: x,y <-- starting point for x,y % N <-- length of Random Walk % ds <-- length of a step % % Outputs: % xDist: displacement distance from starting point (can be + or -) % xSqr: squared displacement distance from starting point (must be +) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [xDist,yDist,rSqr] = do_Random_Walk(N,ds,x,y) % Perform the Random Walk for i=1:N coin = rand(1); if (coin <= 0.25) x = x - ds; elseif (coin <= 0.5) x = x + ds; elseif (coin <=0.75) y = y - ds; else y = y + ds; end end % Store final positions of (x,y) for Random Walker xDist = x; yDist = y; % Store squared displacement distance from origin rSqr = x^2 + y^2;
github
nickabattista/Ark-master
compute_Random_Walks_2D_Convergence.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walker_Convergence/compute_Random_Walks_2D_Convergence.m
3,553
utf_8
596fbde1f0dba70b0fff6afa4fe5e5d1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Computes error btwn simulation and theory for different numbers % of random walkers in 2D. As # of RWs goes up, error goes down. % % Author: Nick Battista % Institution: TCNJ % Created: April 8, 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function compute_Random_Walks_2D_Convergence() % Vector of all #'s of Random Walker Trials to Do MVec = [10:10:90 100:100:900 1e3:1e3:9e3 1e4:1e4:9e4 1e5:1e5:5e5]; for i=1:length(MVec) % Define # of Random Walkers for Trial M = MVec(i); % Print Simulation Case Info to Screen fprintf('Simulation Case w/ M=%d\n',M); % Call Random Walk Function that Returns Error btwn theory and simulation for RMS err = Random_Walks_in_2D(M); % Store RMS Error for Simulation with M random walkers errVec(i) = err; end figure(2) lw=4; ms=24; loglog(MVec,errVec,'-.','MarkerSize',ms,'LineWidth',lw); xlabel('# of Random Walkers'); ylabel('RMS Error'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk with M-Random Walkers to compute avg. % error in RMS % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function errRMS = Random_Walks_in_2D(M) %M = 10000; % # of Random Walkers N = 25; % # of steps for each walker ds = 0.1; % size of step (step-size) x = 0; % initial x-Position y = 0; % initial y-Position % Perform a Random Walk for Each Walker for i=1:M % Do Random Walk for i-th random walker [xFinal,yFinal,rSqr] = do_Random_Walk(N,ds,x,y); % Store x,y-Final positions xFinal_Vec(i) = xFinal; yFinal_Vec(i) = yFinal; % Store squared displacement distance from starting point (must be +) rSqr_Vec(i) = rSqr; end % Compute Avg. of Squared-Displacement Distance from Starting Pt. RMS_Avg = sqrt( mean( rSqr_Vec ) ); % Store RMS Error between average RMS from simulation and theory errRMS = abs( RMS_Avg - sqrt(N)*ds); % Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt. % fprintf('Avg. Squared-Displacement: %2.4f\n',RMS_Avg); % fprintf('Theory Says Avg. Displacement = %2.4f\n',sqrt(N)*ds); % fprintf('Error: %2.4f\n\n\n',errRMS); % Plot ending point (x,y) for each Random Walk % figure(2) % plot(xFinal_Vec,yFinal_Vec,'b.','MarkerSize',10); hold on; % plot(0,0,'r.','MarkerSize',50); hold on; % xlabel('x'); % ylabel('y'); % title('2D Random Walks Final Position'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk starting at "x,y" and ending after "N" steps % % Inputs: x,y <-- starting point for x,y % N <-- length of Random Walk % ds <-- length of a step % % Outputs: % xDist: displacement distance from starting point (can be + or -) % xSqr: squared displacement distance from starting point (must be +) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [xFinal,yFinal,rSqr] = do_Random_Walk(N,ds,x,y) % Perform the Random Walk for i=1:N % Get random angle between 0 and 2*pi ang = 2*pi*rand(1); % Move in x-direction (based on trig relations) x = x + ds*cos(ang); % Move in y-direction (based on trig relations) y = y + ds*sin(ang); end % Define final positions of (x,y) for output xFinal = x; yFinal = y; % Save r^2 value rSqr = x^2 + y^2;
github
nickabattista/Ark-master
compute_Random_Walks_1D_Convergence.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Random_Walks_Diffusive_Processes/Random_Walker_Convergence/compute_Random_Walks_1D_Convergence.m
3,601
utf_8
d6a7d4a9214e792641f99db6c5944701
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Computes error btwn simulation and theory for different numbers % of random walkers in 1D. As # of RWs goes up, error goes down. % % Author: Nick Battista % Institution: TCNJ % Created: April 8, 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function compute_Random_Walks_1D_Convergence() % Vector of all #'s of Random Walker Trials to Do MVec = [10:10:90 100:100:900 1e3:1e3:9e3 1e4:1e4:9e4 1e5:1e5:5e5]; for i=1:length(MVec) % Define # of Random Walkers for Trial M = MVec(i); % Print Simulation Case Info to Screen fprintf('Simulation Case w/ M=%d\n',M); % Call Random Walk Function that Returns Error btwn theory and simulation for RMS err = Random_Walks_in_1D(M); % Store RMS Error for Simulation with M random walkers errVec(i) = err; end figure(2) lw=4; ms=24; loglog(MVec,errVec,'-.','MarkerSize',ms,'LineWidth',lw); xlabel('# of Random Walkers'); ylabel('RMS Error'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk with M-Random Walkers to compute avg. % error in RMS % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function errRMS = Random_Walks_in_1D(M) %M = 1000; % # of Random Walkers N = 20; % # of steps for each walker dx = 0.1; % size of step (step-size) x = 0; % initial position % Perform a Random Walk for Each Walker for i=1:M % Do Random Walk for i-th random walker [xDist,xSqr] = do_Random_Walk(N,dx,x); % Store displacement distance from starting point (can be + or -) xDist_Vec(i) = xDist; % Store squared displacement distance from starting point (must be +) xSqr_Vec(i) = xSqr; end % Compute Avg. of Displacement Distances from Starting Pt. xDist_Avg = mean(xDist_Vec); % Compute Avg. of Squared-Displacement Distance from Starting Pt. RMS_Avg = sqrt(mean(xSqr_Vec)); % Store RMS Error between average RMS from simulation and theory errRMS = abs( RMS_Avg - sqrt(N)*dx); % Print Information to Screen for Avg. Displacement From Starting Pt. %fprintf('\n\nAvg. Displacement: %2.4f\n',xDist_Avg); %fprintf('Theory Says Avg. Displacement = 0\n'); %fprintf('Error: %2.4f\n\n\n',abs(xDist_Avg)); % Print Information to Screen for RMS (Room Mean Squared-Displacement) From Starting Pt. %fprintf('Avg. Squared-Displacement: %2.4f\n',RMS_Avg); %fprintf('Theory Says Avg. Displacement = %2.4f\n',sqrt(N)*dx); %fprintf('Error: %2.4f\n\n\n',errRMS); % Plot ending point (x,y) for each Random Walk %plot(0,0,'r.','MarkerSize',50); hold on; %plot(xDist_Vec,zeros(length(xDist_Vec)),'b.','MarkerSize',10); hold on; %xlabel('x'); %ylabel('y'); %title('1D Random Walks Final Position'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: perform Random Walk starting at "x" and ending after "N" steps % % Inputs: x <-- starting point % N <-- length of Random Walk % dx <-- length of a step % % Outputs: % xDist: displacement distance from starting point (can be + or -) % xSqr: squared displacement distance from starting point (must be +) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [xDist,xSqr] = do_Random_Walk(N,dx,x) % Perform the Random Walk for i=1:N coin = rand(1); if coin > 0.5 x = x - dx; else x = x + dx; end end xDist = x; xSqr = x^2;
github
nickabattista/Ark-master
go_Go_Zombie_Model.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Discrete_Dynamical_Systems/go_Go_Zombie_Model.m
2,590
utf_8
bf0679b2de0eff1d2feb30b51765dc86
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Models a Zombie outbreak using Dynamical Systems % % Author: Nick Battista % Created: Jan. 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function go_Go_Zombie_Model(TFinal) % % Time Information / Initialization %TFinal = 100; % Simulation runs until TFinal dt = 1e-3; % Time-Step TimeVec = 0:dt:TFinal; % TimeVector = (1,2,3,...,TFinal+1) H = zeros( TFinal, 1); % Initializing storage for populations P = H; Z = H; % % Human birth and death rates % b1 = 0.000040; % Human birth rate (2016) d1 = 0.000019; % Natural human death rate (2016) % % Human-Zombie Interaction Parameters % beta1 = 0.5; % Human-Zombie Interaction 'Probability' (human -> zombie) beta2 = 0.05; % Human-Zombie Interaction 'Probability' (human dies, no turning) beta3 = 0.05; % Human-Zombie Interaction 'Probability' (human kills pre-Zombie) beta4 = 0.025; % Human-Zombie Interaction 'Probability' (human kills zombie) % % pre-Zombie residence time before turning full zombie % c1 = 0.1; % Lag time before pre-Zombie (post-Human) turns Zombie % % Zombie death rates % d2 = d1*3; % Zombie "natural" death rate % % Initial "Populations" (population %) % H(1) = 0.99; P(1) = 0; Z(1) = 0.01; for n=1:1:TFinal/dt % TFinal b/c of the way we are array indexing (index 1 = initial time) % How Human Population Changes H(n+1) = H(n) + dt * ( (b1-d1)*H(n) - beta1*H(n)*Z(n) - beta2*H(n)*Z(n) ); % How pre-Zombie Population Changes P(n+1) = P(n) + dt * ( - c1*P(n) + beta1*H(n)*Z(n) - beta3*H(n)*P(n) ); % How Zombie Population Changes Z(n+1) = Z(n) + dt * ( c1*P(n) - beta4*H(n)*Z(n) - d2*Z(n) ); end % % PRINT SIMULATION INFO TO SCREEN % fprintf('\n\n --- ZOMBIE MODEL RESULTS --- \n\n'); fprintf('Human Pop. Percentage: %.3f\n\n', 100*H(end) ); fprintf('pre-Zombie Pop. Percentage: %.3f\n\n', 100*P(end) ); fprintf('Zombie Pop. Percentage: %.3f\n\n', 100*Z(end) ); fprintf('Percent Loss (not humans, pre-Z, or Zombies): %.3f\n\n\n', 100*(1-H(end)-P(end)-Z(end) ) ); % % FIGURE 1: POPULATIONS VS. TIME % ms = 30; % MarkerSize for plotting lw = 4; % LineWidth for plotting fs = 18; % plot(TimeVec,H,'b.-','MarkerSize',ms,'LineWidth',lw); hold on; plot(TimeVec,P,'k.-','MarkerSize',ms,'LineWidth',lw); hold on; plot(TimeVec,Z,'r.-','MarkerSize',ms,'LineWidth',lw); hold on; xlabel('Time (hours)'); ylabel('Population %'); leg = legend('Humans','pre-Zombies','Zombies'); set(gca,'FontSize',fs); set(leg,'FontSize',fs);
github
nickabattista/Ark-master
Population_Ecology.m
.m
Ark-master/MATBIO330_Mathematical_Biology/Class_Codes/Discrete_Dynamical_Systems/Ecology/Population_Ecology.m
1,858
utf_8
34aa6f090b803ab05f6a29af3c707ea3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FUNCTION: Solves Discrete Dynamical Systems in Population Ecology % % Author: Nick Battista % Institution: TCNJ % Created: March 2019 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Population_Ecology(TFinal) % % Clears any previous plots that are open in MATLAB clf; % % Time Information / Initialization % %TFinal = 100; % Simulation runs until TFinal TimeVec = 1:1:TFinal; % TimeVector = (1,2,3,...,TFinal+1) % % Initializing storage for populations % X = zeros( TFinal, 1); % Initializing storage for population X Y = X; % Initializing storage for population Y % % Initial Values % X(1) = 25; Y(1) = 2; % % Parameter Values % k = 0.75; % growth rate C = 250; % carrying capacity b1 = 0.008; % death parameter for prey from predator interactions b2 = 0.00825; % growth parameter for predator from prey interactions % % For-loop that iteratively solves the discrete dynamical system % for n=1:TFinal X(n+1) = X(n) + k*X(n)*( 1 - X(n)/C ) - b1*X(n)*Y(n); Y(n+1) = b2*X(n)*Y(n); end % % Plot Attributes % lw = 4; % LineWidth (how thick the lines should be) ms = 25; % MarkerSize (how big the plot points should be) fs = 18; % FontSize (how big the font should be for labels) % % PLOT 1: Populations vs. Time % figure(1) plot(TimeVec,X(1:end-1),'b.-','LineWidth',lw,'MarkerSize',ms); hold on; plot(TimeVec,Y(1:end-1),'r.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Time'); ylabel('Population'); leg = legend('Prey','Predator'); set(gca,'FontSize',fs); set(leg,'FontSize',fs); % % PLOT 2: Phase Plane Plot % figure(2) plot(X(200:end),Y(200:end),'b.-','LineWidth',lw,'MarkerSize',ms); hold on; xlabel('Prey Population'); ylabel('Predator Population'); set(gca,'FontSize',fs);
github
nickabattista/Ark-master
Eulers.m
.m
Ark-master/Euler_Method/Eulers.m
9,009
utf_8
bd348d60b6ed1b254925695e7b547e95
function Eulers() %Author: Nicholas Battista %Created: August 12, 2014 %Date of Last Revision: August 23, 2014 % %This function solves the following ODE: %dy/dt = f(t,y) %y(0) = y0 %using Eulers Method. It then does a convergence study for various h values. % %Note: It performs the convergence study for the known ODEs, % %dy/dt = y, with y(0) = 1; w/ exact solution is: y(t) = e^t %and %dy/dt = 2*pi*cos(2*pi*t), w/ y(0)=1 w/ exact solution y(t) = sin(2*pi*t)+1 print_info(); y0 = 1; %Initial Condition, y(0)=y0 tS = 0; %Starting Time for Simulation tE = 2.0; %End Time for Simulation %Makes vector of time iterates for convergence study NVec = give_Me_NumberOfGridPts(); %Allocate memory to storage vectors hVec = zeros(1,length(NVec)); err_h = hVec; Y_SOL = zeros(1e5,5); ct = 1; %For loop for convergence study for j=1:length(NVec) %Begin counting time for integration tic N = NVec(j); %# of time-steps h = (tE-tS)/N; %time-step hVec(j) = h; %stores time-step time=tS:h:tE; yFOR = zeros(1,length(time)); yFOR2= yFOR; %Performs the Euler Method Time-Stepping Scheme for i=1:length(time) if i==1 yFOR(i) = y0; yFOR2(i)= y0; else yFOR(i) = yFOR(i-1) + h*f(time(i-1),yFOR(i-1),1); yFOR2(i)= yFOR2(i-1)+ h*f(time(i-1),yFOR(i-1),2); end end %Gives Error at each time-step err = compute_Error(time,yFOR,y0,1); err2= compute_Error(time,yFOR2,y0,2); %Computes Inf-Norm of Error err_h(j) = max( abs(err) ); err_h2(j) = max( abs(err2) ); %Stores time for computation timeV(j) = toc/2; %Stores numerical solution / info for plotting soln. if ( ( (mod(j,3)==0) && (j<10) ) || (j==11) || (j==14) ) Y_SOL(1:N+1,ct) = yFOR; Y_SOL2(1:N+1,ct)= yFOR2; hVecPlot(ct) = h; NVecPlot(ct) = N; errMat(1:N+1,ct) = err; errMat2(1:N+1,ct) = err2; ct = ct+1; end clear h; clear time; clear yFOR; end %Ends looping over different h-values %Plot Solution vs. Exact plot_Solution(Y_SOL,Y_SOL2,NVecPlot,hVecPlot,tE,tS,y0,errMat,errMat2) %Plots Convergence Study plot_Convergence_Study(hVec,err_h,err_h2); %Plots time study plot_Time_Study(NVec,timeV) fprintf('\nWelp, thats it folks!\n\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function that plots the numerical soln. vs. exact solution for different % time-step sizes, h, as well as for two different ODEs. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Solution(Y_Sol,Y_Sol2,NVec2,hVec2,tE,tS,y0,errMat,errMat2) fprintf('\nplotting numerical vs. exact solutions...\n\n'); figure(1) subplot(2,2,1); strColor = {'k-','-','m-','g-','c-'}; for i=1:length(Y_Sol(1,:)) h = hVec2(i); hVec{i} = strcat('h = ',num2str(h)); N= NVec2(i); t = tS:h:tE; str = strColor{i}; plot(t,Y_Sol(1:N+1,i),str,'LineWidth',2); hold on; end t=tS:0.005:tE; for i=1:length(t) yExact(i) = Exact(t(i),y0,1); end plot(t,yExact,'r-','LineWidth',3); hold on; legend(hVec{1},hVec{2},hVec{3},hVec{4},hVec{5},'Exact Solution','Location','NorthWest'); title('Exact Solns vs Numerical Solns for y(t)=y0*exp(y)'); xlabel('t'); ylabel('y(t)'); % % subplot(2,2,2) for i=1:length(Y_Sol(1,:)) N= NVec2(i); h = hVec2(i); t = tS:h:tE; err = abs ( errMat(1:N+1,i) ); str = strColor{i}; plot(t,err,str,'LineWidth',2); hold on; end legend(hVec{1},hVec{2},hVec{3},hVec{4},hVec{5},'Location','NorthWest'); title('ERROR(t) for various h values for y(t)=y0*exp(y)'); xlabel('t'); ylabel('error(t)'); % % % subplot(2,2,3); for i=1:length(Y_Sol2(1,:)) h = hVec2(i); N= NVec2(i); t = tS:h:tE; str = strColor{i}; plot(t,Y_Sol2(1:N+1,i),str,'LineWidth',2); hold on; end t=tS:0.005:tE; for i=1:length(t) yExact(i) = Exact(t(i),y0,2); end plot(t,yExact,'r-','LineWidth',3); hold on; legend(hVec{1},hVec{2},hVec{3},hVec{4},hVec{5},'Exact Solution','Location','NorthEast'); title('Exact Solns vs Numerical Solns for y(t)=sin(2*pi*t)+1'); xlabel('t'); ylabel('y(t)'); % % subplot(2,2,4) for i=1:length(Y_Sol(1,:)) N= NVec2(i); h = hVec2(i); t = tS:h:tE; err = abs ( errMat2(1:N+1,i) ); str = strColor{i}; plot(t,err,str,'LineWidth',2); hold on; end legend(hVec{1},hVec{2},hVec{3},hVec{4},hVec{5},'Location','NorthEast'); title('ERROR(t) for various h values for y(t)=sin(2*pi*t)+1'); xlabel('t'); ylabel('error(t)'); fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function that plots the computational time vs. time iterates for [0,T] % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Time_Study(Nvec,time) fprintf('\nplotting computational time study...\n\n'); figure(3) loglog(Nvec,time,'ro-'); hold on; xlabel('Number of Time-Steps on [tS,tE]'); ylabel('Log(Time for Each Integration)'); title('Computational Time Study'); fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function that plots the convergence study, i.e., Error vs. h % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plot_Convergence_Study(hVec,err_h,err_h2) fprintf('\nplotting convergence studies...\n\n'); figure(2) subplot(3,4,1) plot(hVec,err_h,'*'); hold on; xlabel('h'); ylabel('Inf-Norm Error'); title('Convergence Study: y(t) = exp(t)'); subplot(3,4,2) semilogx(hVec,err_h,'*'); hold on; xlabel('Log(h)'); ylabel('Inf-Norm Error'); title('Convergence Study: y(t) = exp(t)'); subplot(3,4,[5,6,9,10]) loglog(hVec,err_h,'*'); hold on; xlabel('Log(h)'); ylabel('Log(Inf-Norm Error)'); title('Convergence Study: y(t) = exp(t)'); figure(2) subplot(3,4,3) plot(hVec,err_h2,'*'); hold on; xlabel('h'); ylabel('Inf-Norm Error'); title('Convergence Study: y(t) = sin(2*pi*t)+1'); subplot(3,4,4) semilogx(hVec,err_h2,'*'); hold on; xlabel('Log(h)'); ylabel('Inf-Norm Error'); title('Convergence Study: y(t) = sin(2*pi*t)+1'); subplot(3,4,[7,8,11,12]) loglog(hVec,err_h2,'*'); hold on; xlabel('Log(h)'); ylabel('Log(Inf-Norm Error)'); title('Convergence Study: y(t) = sin(2*pi*t)+1'); fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function that computes Error % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function error = compute_Error(time,y,y0,flag) %Computes Error During Simulation exact_sol = zeros(1,length(time)); for i=1:length(time) exact_sol(i) = Exact(time(i),y0,flag); end error = y - exact_sol; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This is the RHS of the ODE: y' = f(t,y) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function val = f(t,y,flag) %y' = f(t,y) if flag == 1 val = y; elseif flag==2 val = 2*pi*cos(2*pi*t); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This is the Exact Sol'n % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function val = Exact(t,y0,flag) %Exact sol'n to ODE if flag == 1 val = y0*exp(t); elseif flag == 2 val = sin(2*pi*t)+1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This function tells you how many time-steps you have for the simulation % (This is used for the convergence study) % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function NVec = give_Me_NumberOfGridPts() N1 = 1:1:9; N2 = 10:10:90; N3 = 100:100:900; N4 = 1000:1000:9*1e3; N5 = 1e4:1e4:9*1e4; N6 = 1e5:1e5:9*1e5; NVec = [N1 N2 N3 N4 N5 N6]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Function that prints the info about the simulation % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function print_info() fprintf('\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'); fprintf('\nAuthor: Nicholas Battista\n'); fprintf('Created: August 12, 2014\n'); fprintf('Date of Last Revision: August 23, 2014\n\n'); fprintf('This function solves the following ODE:\n\n'); fprintf('dy/dt = f(t,y)\n'); fprintf('y(0) = y0\n\n'); fprintf('using Eulers Method. It then does a convergence study for various h values \n\n'); fprintf('Note: It performs the convergence study for the known ODEs,\n\n'); fprintf('dy/dt = y, with y(0) = 1; so exact solution is: y(t) = e^t\n\n'); fprintf('and\n\n'); fprintf('dy/dt = 2*pi*cos(2*pi*t), w/ y(0)=1 w/ exact solution y(t) = sin(2*pi*t)+1\n\n'); fprintf('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n');
github
boom-lab/oce_tools-master
gasBunsen.m
.m
oce_tools-master/gas_toolbox/gasBunsen.m
1,856
utf_8
94c0adfe3ec20268a6a2ebbb53528cf7
% beta = gasBunsen(SP,pt,gas) % Function to calculate Bunsen coefficient % % USAGE:------------------------------------------------------------------- % beta=gasBunsen(SP,pt,gas) % % DESCRIPTION:------------------------------------------------------------- % Calculate the Bunsen coefficient, which is defined as the volume of pure % gas at standard temperature and pressure (0 degC, 1 atm) that will % dissolve into a volume of water at equilibrium when exposed to a % pressure of 1 atm of the gas. % % INPUTS:------------------------------------------------------------------ % SP: Practical salinity (PSS) % pt: Potential temperature (deg C) % gas: code for gas (He, Ne, Ar, Kr, Xe, N2, or O2) % % OUTPUTS:----------------------------------------------------------------- % beta: Bunsen coefficient (L gas)/(L soln * atm gas) % % REFERENCE:--------------------------------------------------------------- % % See references for individual gas solubility functions. % % AUTHORS:----------------------------------------------------------------- % Cara Manning ([email protected]) Woods Hole Oceanographic Institution % David Nicholson ([email protected]) % Version: 1.0 // September 2015 % % COPYRIGHT:--------------------------------------------------------------- % % Copyright 2015 Cara Manning % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License, which % is available at http://www.apache.org/licenses/LICENSE-2.0 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function beta=gasBunsen(SP,pt,gas) pdry = 1 - vpress(SP,pt); % pressure of dry air for 1 atm total pressure % equilib solubility in mol/m3 Geq = gasmoleq(SP,pt,gas); % calc beta beta = Geq.*(gasmolvol(gas)./1000)./(pdry.*gasmolfract(gas)); end
github
boom-lab/oce_tools-master
kgas.m
.m
oce_tools-master/gas_toolbox/kgas.m
4,654
utf_8
20a6385160fb787a02149b3afb863af9
% ========================================================================= % KGAS - gas transfer coefficient for a range of windspeed-based % parameterizations % % [kv] = kgas(u10,Sc,param) % % ------------------------------------------------------------------------- % INPUTS: % ------------------------------------------------------------------------- % u10 10-m windspeed (m/s) % Sc Schmidt number % param abbreviation for parameterization: % W92a = Wanninkhof 1992 - averaged winds % W92b = Wanninkhof 1992 - instantaneous or steady winds % Sw07 = Sweeney et al. 2007 % Ho06 = Ho et al. 2006 % Ng00 = Nightingale et al. 2000 % LM86 = Liss and Merlivat 1986 % % ------------------------------------------------------------------------- % OUTPUTS: % ------------------------------------------------------------------------- % kv Gas transfer velocity in m s-1 % % ------------------------------------------------------------------------- % USAGE: % ------------------------------------------------------------------------- % k = kgas(10,1000,'W92b') % k = 6.9957e-05 % % ------------------------------------------------------------------------- % REFERENCES: % ------------------------------------------------------------------------- % Wanninkhof, R. (1992). Relationship between wind speed and gas exchange. % J. Geophys. Res, 97(25), 7373-7382. % % Sweeney, C., Gloor, E., Jacobson, A. R., Key, R. M., McKinley, G., % Sarmiento, J. L., & Wanninkhof, R. (2007). Constraining global air?sea % gas exchange for CO2 with recent bomb 14C measurements. Global % Biogeochem. Cy.,21(2). % % Ho, D. T., Law, C. S., Smith, M. J., Schlosser, P., Harvey, M., & Hill, % P. (2006). Measurements of air?sea gas exchange at high wind speeds in % the Southern Ocean: Implications for global parameterizations. Geophys. % Res. Lett., 33(16). % % Nightingale, P. D., Malin, G., Law, C. S., Watson, A. J., Liss, P. S., % Liddicoat, M. I., et al. (2000). In situ evaluation of air-sea gas % exchange parameterizations using novel conservative and volatile tracers. % Global Biogeochem. Cy., 14(1), 373-387. % % Liss, P. S., & Merlivat, L. (1986). Air-sea gas exchange rates: % Introduction and synthesis. In The role of air-sea exchange in % geochemical cycling (pp. 113-127). Springer Netherlands. % % ------------------------------------------------------------------------- % AUTHORS % ------------------------------------------------------------------------- % David Nicholson [email protected], Woods Hole Oceanographic Institution % Modified by Cara Manning [email protected] % Version 2.0 % % ------------------------------------------------------------------------- % COPYRIGHT % ------------------------------------------------------------------------- % Copyright 2015 David Nicholson and Cara Manning % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % http://www.apache.org/licenses/LICENSE-2.0 % % Unless required by applicable law or agreed to in writing, software % distributed under the License is distributed on an "AS IS" BASIS, % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. % % ========================================================================= function [kv] = kgas(u10,Sc,param) quadratics = {'W92a','W92b','Sw07','Ho06'}; % should be case insensitive if ismember(upper(param),upper(quadratics)) if strcmpi(param,'W92a') A = 0.39; elseif strcmpi(param,'W92b') A = 0.31; elseif strcmpi(param,'Sw07') A = 0.27; elseif strcmpi(param,'Ho06') A = 0.254; %k_600 = 0.266 else error('parameterization not found'); end k_cm = A*u10.^2.*(Sc./660).^-0.5; %cm/h kv = k_cm./(100*60*60); %m/s elseif strcmpi(param,'Ng00') k600 = 0.222.*u10.^2 + 0.333.*u10; k_cm = k600.*(Sc./600).^-0.5; % cm/h kv = k_cm./(100*60*60); % m/s elseif strcmpi(param,'LM86') k600 = zeros(1,length(u10)); l = find(u10 <= 3.6); k600(l) = 0.17.*u10(l); m = find(u10 > 3.6 & u10 <= 13); k600(m) = 2.85.*u10(m)-9.65; h = find(u10 > 13); k600(h) = 5.9.*u10(h)-49.3; k_cm = k600.*(Sc./600).^-0.5; k_cm(l) = k600(l).*(Sc./600).^(-2/3); kv = k_cm./(100*60*60); % m/s end
github
boom-lab/oce_tools-master
fas_L13.m
.m
oce_tools-master/gas_toolbox/fas_L13.m
6,356
utf_8
bc2b614f86938e6d5b49f9c201f44c0a
% Function to calculate air-sea fluxes with Liang 2013 parameterization % % USAGE:------------------------------------------------------------------- % % [Fd, Fp, Fc, Deq] = fas_L13(0.282,10,35,10,1,'O2') % >Fd = 2.2559e-08 % >Fp = 6.8604e-08 % >Fc = 2.9961e-08 % >Deq = 0.0062 % % DESCRIPTION:------------------------------------------------------------- % % Calculate air-sea fluxes and steady-state supersat based on: % Liang, J.-H., C. Deutsch, J. C. McWilliams, B. Baschek, P. P. Sullivan, % and D. Chiba (2013), Parameterizing bubble-mediated air-sea gas exchange % and its effect on ocean ventilation, Global Biogeochem. Cycles, 27, % 894?905, doi:10.1002/gbc.20080. % % INPUTS:------------------------------------------------------------------ % C: gas concentration (mol m-3) % u10: 10 m wind speed (m/s) % SP: Sea surface salinity (PSS) % pt: Sea surface temperature (deg C) % pslp: sea level pressure (atm) % gas: two letter code for gas (He, Ne, Ar, Kr, Xe, N2, or O2) % rh: relative humidity as a fraction of saturation (0.5 = 50% RH) % rh is an optional but recommended argument. If not provided, it % will be automatically set to 0.8. % % Code Gas name Reference % ---- ---------- ----------- % He Helium Weiss 1971 % Ne Neon Hamme and Emerson 2004 % Ar Argon Hamme and Emerson 2004 % Kr Krypton Weiss and Keiser 1978 % Xe Xenon Wood and Caputi 1966 % N2 Nitrogen Hamme and Emerson 2004 % O2 Oxygen Garcia and Gordon 1992 % % OUTPUTS:----------------------------------------------------------------- % % Fd: Surface gas flux (mol m-2 s-1) % Fp: Flux from partially collapsing large bubbles (mol m-2 s-1) % Fc: Flux from fully collapsing small bubbles (mol m-2 s-1) % Deq: Equilibrium supersaturation (unitless (%sat/100)) % % REFERENCE:--------------------------------------------------------------- % % Liang, J.-H., C. Deutsch, J. C. McWilliams, B. Baschek, P. P. Sullivan, % and D. Chiba (2013), Parameterizing bubble-mediated air-sea gas % exchange and its effect on ocean ventilation, Global Biogeochem. Cycles, % 27, 894?905, doi:10.1002/gbc.20080. % % AUTHOR:--------------------------------------------------------------- % Written by David Nicholson [email protected] % Modified by Cara Manning [email protected] % Woods Hole Oceanographic Institution % Version: 2.0 // September 2015 % % COPYRIGHT:--------------------------------------------------------------- % % Copyright 2015 David Nicholson and Cara Manning % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License, which % is available at http://www.apache.org/licenses/LICENSE-2.0 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ Fd, Fp, Fc, Deq, Ks] = fas_L13(C,u10,SP,pt,pslp,gas,rh) % ------------------------------------------------------------------------- % Conversion factors % ------------------------------------------------------------------------- m2cm = 100; % cm in a meter h2s = 3600; % sec in hour atm2Pa = 1.01325e5; % Pascals per atm % ------------------------------------------------------------------------- % Calculate water vapor pressure and adjust sea level pressure % ------------------------------------------------------------------------- % if humidity is not provided, set to 0.8 for all values if nargin == 6 rh =0.8.*ones(size(C)); end ph2oveq = vpress(SP,pt); ph2ov = rh.*ph2oveq; % slpc = (observed dry air pressure)/(reference dry air pressure) % see Description section in header of fas_N11.m pslpc = (pslp - ph2ov)./(1 - ph2oveq); % ------------------------------------------------------------------------- % Parameters for COARE 3.0 calculation % ------------------------------------------------------------------------- % Calculate potential density at surface SA = SP.*35.16504./35; CT = gsw_CT_from_pt(SA,pt); rhow = gsw_sigma0(SA,CT)+1000; rhoa = 1.0; lam = 13.3; A = 1.3; phi = 1; tkt = 0.01; hw=lam./A./phi; ha=lam; % air-side schmidt number ScA = 0.9; R = 8.314; % units: m3 Pa K-1 mol-1 % ------------------------------------------------------------------------- % Calculate gas physical properties % ------------------------------------------------------------------------- xG = gasmolfract(gas); Geq = gasmoleq(SP,pt,gas); alc = (Geq/atm2Pa).*R.*(pt+273.15); Gsat = C./Geq; [~, ScW] = gasmoldiff(SP,pt,gas); % ------------------------------------------------------------------------- % Calculate COARE 3.0 and gas transfer velocities % ------------------------------------------------------------------------- % ustar cd10 = cdlp81(u10); ustar = u10.*sqrt(cd10); % water-side ustar ustarw = ustar./sqrt(rhow./rhoa); % water-side resistance to transfer rwt = sqrt(rhow./rhoa).*(hw.*sqrt(ScW)+(log(.5./tkt)/.4)); % air-side resistance to transfer rat = ha.*sqrt(ScA)+1./sqrt(cd10)-5+.5*log(ScA)/.4; % diffusive gas transfer coefficient (L13 eqn 9) Ks = ustar./(rwt+rat.*alc); % bubble transfer velocity (L13 eqn 14) Kb = 1.98e6.*ustarw.^2.76.*(ScW./660).^(-2/3)./(m2cm.*h2s); % overpressure dependence on windspeed (L13 eqn 16) dP = 1.5244.*ustarw.^1.06; % ------------------------------------------------------------------------- % Calculate air-sea fluxes % ------------------------------------------------------------------------- Fd = Ks.*Geq.*(pslpc-Gsat); % Fs in L13 eqn 3 Fp = Kb.*Geq.*((1+dP).*pslpc-Gsat); % Fp in L13 eqn 3 Fc = xG.*5.56.*ustarw.^3.86; % L13 eqn 15 % ------------------------------------------------------------------------- % Calculate steady-state supersaturation % ------------------------------------------------------------------------- Deq = (Kb.*Geq.*dP.*pslpc+Fc)./((Kb+Ks).*Geq.*pslpc); % L13 eqn 5 end function [ cd ] = cdlp81( u10) % Calculates drag coefficient from u10, wind speed at 10 m height cd = (4.9e-4 + 6.5e-5 * u10); cd(u10 <= 11) = 0.0012; cd(u10 >= 20) = 0.0018; end
github
boom-lab/oce_tools-master
fas_S09.m
.m
oce_tools-master/gas_toolbox/fas_S09.m
6,754
utf_8
f6e99dc7f66955ce601e76053f538654
% [Fd, Fc, Fp, Deq] = fas_S09(C,u10,S,T,slp,gas,rh) % Function to calculate air-sea gas exchange flux using Stanley 09 % parameterization % % USAGE:------------------------------------------------------------------- % [Fd, Fc, Fp, Deq] = fas_S09(C,u10,S,T,slp,gas,rh) % [Fd, Fc, Fp, Deq] = fas_S09(0.01410,5,35,10,1,'Ar',0.9) % > Fd = -4.9960e-09 % > Fc = 7.3493e-10 % > Fp = 1.8653e-13 % > Deq = 0.0027 % % DESCRIPTION:------------------------------------------------------------- % Calculate air-sea fluxes and steady-state supersaturation based on: % Stanley, R.H., Jenkins, W.J., Lott, D.E., & Doney, S.C. (2009). Noble % gas constraints on air-sea gas exchange and bubble fluxes. Journal of % Geophysical Research: Oceans, 114(C11), doi: 10.1029/2009JC005396 % % These estimates are valid over the range of wind speeds observed at % Bermuda (0-13 m/s) and for open ocean, oligotrophic waters low in % surfactants. Additionally, the estimates were determined using QuikSCAT % winds, and if using another global wind product (e.g., NCEP reanalysis), % a correction for biases between the wind products may be appropriate. % Contact Rachel Stanley ([email protected]) with questions. % % Explanation of slpc: % slpc = (observed dry air pressure)/(reference dry air pressure) % slpc is a pressure correction factor to convert from reference to % observed conditions. Equilibrium gas concentration in gasmoleq is % referenced to 1 atm total air pressure, including saturated water vapor % (RH=1), but observed sea level pressure is usually different from 1 atm, % and humidity in the marine boundary layer is usually less than % saturation. Thus, the observed sea level pressure of each gas will % usually be different from the reference. % % INPUTS:------------------------------------------------------------------ % C: gas concentration (mol/m^3) % u10: 10 m wind speed (m/s) % S: Sea surface salinity (PSS) % T: Sea surface temperature (deg C) % slp: sea level pressure (atm) % gas: two letter code for gas (He, Ne, Ar, Kr, Xe, N2, or O2) % rh: relative humidity in the marine boundary layer as a fraction of % saturation (0.5 = 50% RH). % rh is an optional but recommended argument. If not provided, it % will be automatically set to 0.8. % % OUTPUTS:----------------------------------------------------------------- % Fd: Diffusive air-sea flux (mol m-2 s-1) % Fp: Flux from partially collapsing large bubbles (mol m-2 s-1) % Fc: Flux from fully collapsing small bubbles (mol m-2 s-1) % Deq: Equilibrium supersaturation (unitless (%sat/100)) % % REFERENCE:--------------------------------------------------------------- % % Stanley, R.H., Jenkins, W.J., Lott, D.E., & Doney, S.C. (2009). Noble % gas constraints on air-sea gas exchange and bubble fluxes. Journal of % Geophysical Research: Oceans, 114(C11), doi: 10.1029/2009JC005396 % % Bubble penetration depth parameterization: % Graham, A., D. K. Woolf, and A. J. Hall (2004), Aeration due to breaking % waves. Part I: Bubble populations, J. Phys. Oceanogr., 34(5), 989?1007, % doi:10.1175/1520-0485(2004)034<0989:ADTBWP>2.0.CO;2. % % AUTHOR:------------------------------------------------------------------ % % Cara Manning ([email protected]) Woods Hole Oceanographic Institution % Version: 1.0 // September 2015 % Checked and approved by Rachel Stanley on September 20, 2015. % % COPYRIGHT:--------------------------------------------------------------- % % Copyright 2015 Cara Manning % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License, which % is available at http://www.apache.org/licenses/LICENSE-2.0 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Fd, Fc, Fp, Deq] = fas_S09(C,u10,S,T,slp,gas,rh) % ------------------------------------------------------------------------- % Conversion factors and constants % ------------------------------------------------------------------------- atm2Pa = 1.01325e5; % Pascals per atm R = 8.314; % ideal gas constant in m3 Pa / (K mol) % ------------------------------------------------------------------------- % Scaling factors for gas exchange coefficients % ------------------------------------------------------------------------- Ac = 9.09E-11; Ap = 2.29E-3; gammaG = 0.97; diffexp=2/3; betaexp=1; % ------------------------------------------------------------------------- % Check for humidity % ------------------------------------------------------------------------- % if humidity is not provided, set to 0.8 for all values if nargin == 6 rh =0.8.*ones(size(C)); end; % ------------------------------------------------------------------------- % Calculate diffusive flux % ------------------------------------------------------------------------- [D,Sc] = gasmoldiff(S,T,gas); Geq = gasmoleq(S,T,gas); k = gammaG*kgas(u10,Sc,'W92b'); % k_660 = 0.31 cm/hr % slpc = (observed dry air pressure)/(reference dry air pressure) % see Description section in header ph2oveq = vpress(S,T); ph2ov = rh.*ph2oveq; slpc = (slp-ph2ov)./(1-ph2oveq); % calculate diffusive flux with correction for local humidity Fd = -k.*(C-Geq.*slpc); % ------------------------------------------------------------------------- % Calculate complete trapping / air injection flux % ------------------------------------------------------------------------- % air injection factor as a function of wind speed % set to 0 below u10 = 2.27 m/s wfact=(u10-2.27)^3; wfact(wfact<0) = 0; % calculate dry atmospheric pressure in atm patmdry=slp-ph2ov; % pressure of dry air in atm ai=gasmolfract(gas).*wfact.*patmdry*atm2Pa/(R*(273.15+T)); Fc = Ac*ai; % ------------------------------------------------------------------------- % Calculate partial trapping / exchange flux % ------------------------------------------------------------------------- % calculate bubble penetration depth, Zbub, then calculate hydrostatic % pressure in atm Zbub = 0.15*u10 - 0.55; Zbub(Zbub<0)=0; phydro=(gsw_sigma0(S,T)+1000)*9.81*Zbub/atm2Pa; % multiply by scaling factor Ap by beta raised to power betaexp and % diffusivity raised to power diffexp apflux=ai.*Ap.*D.^diffexp.*(gasBunsen(S,T,gas).^betaexp); Fp=apflux.*(phydro./patmdry-C./Geq+1); % ------------------------------------------------------------------------- % Calculate steady-state supersaturation % ------------------------------------------------------------------------- Deq = ((Fc+Fp)./k)./Geq; end
github
boom-lab/oce_tools-master
fas_N11.m
.m
oce_tools-master/gas_toolbox/fas_N11.m
7,418
utf_8
ca85c60e47fa4e8b77675c14034cc8a1
<<<<<<< HEAD % Function to calculate air-sea bubble flux % % USAGE:------------------------------------------------------------------- % % [Fi Fe] = Fbub_N11(8,35,20,1,'O2') % % > Fi = 9.8910e-08 % > Fe = 2.3665e-08 % % DESCRIPTION:------------------------------------------------------------- % % Calculates the equilibrium concentration of gases as a function of % temperature and salinity (equilibrium concentration is at 1 atm including % atmospheric pressure % % Finj = Ainj * slp * Xg * u3 % Fex = Aex * slp * Geq * D^n * u3 % % where u3 = (u-2.27)^3 (and zero for u < 2.27) % % INPUTS:------------------------------------------------------------------ % % C: gas concentration in mol m-3 % u10: 10 m wind speed (m/s) % S: Sea surface salinity % T: Sea surface temperature (deg C) % slp: sea level pressure (atm) % % gas: two letter code for gas % % Code Gas name Reference % ---- ---------- ----------- % He Helium Weiss 1971 % Ne Neon Hamme and Emerson 2004 % Ar Argon Hamme and Emerson 2004 % Kr Krypton Weiss and Keiser 1978 % Xe Xenon Wood and Caputi 1966 % N2 Nitrogen Hamme and Emerson 2004 % O2 Oxygen Garcia and Gordon 1992 % % OUTPUTS:------------------------------------------------------------------ % % Finj and Fex, Injection and exchange bubble flux in mol m-2 s-1 % Fas: surface air-sea flux based on Sweeney et al. 2007 % Deq: steady-state supersaturation % REFERENCE:--------------------------------------------------------------- % % Nicholson, D., S. Emerson, S. Khatiwala, R. C. Hamme. (2011) % An inverse approach to estimate bubble-mediated air-sea gas flux from % inert gas measurements. Proceedings on the 6th International Symposium % on Gas Transfer at Water Surfaces. Kyoto University Press. % % AUTHOR:--------------------------------------------------------------- % David Nicholson [email protected] % Woods Hole Oceanographic Institution % Version: September 2014 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Fas, Finj, Fex, Deq, k] = fas_N11(C,u10,S,T,slp,gas,varargin) if nargin > 6 rhum = varargin{1}; else rhum = 0.8; end ph2oveq = vpress(S,T); ph2ov = rhum.*ph2oveq; Ainj = 2.357e-9; Aex = 1.848e-5; u3 = (u10-2.27).^3; u3(u3 < 0) = 0; [D,Sc] = gasmoldiff(S,T,gas); Geq = gasmoleq(S,T,gas); k = kgas(u10,Sc,'Sw07'); Fas = k.*(Geq.*(slp-ph2ov)./(1-ph2oveq)-C); Finj = Ainj.*slp.*gas_mole_fract(gas).*u3; Fex = Aex.*slp.*Geq.*D.^0.5.*u3; Deq = ((Finj+Fex)./k)./Geq; ======= % Function to calculate air-sea gas exchange flux using Nicholson 11 % parameterization % % USAGE:------------------------------------------------------------------- % % [Fd, Fc, Fp, Deq] = fas_N11(C,u10,S,T,slp,gas,rh) % [Fd, Fc, Fp, Deq] = fas_N11(0.01410,5,35,10,1,'Ar',0.9) % % > Fd = -4.4860e-09 % > Fc = 3.1432e-10 % > Fp = 9.0980e-11 % > Deq = 1.6882e-03 % % DESCRIPTION:------------------------------------------------------------- % % Calculate air-sea fluxes and steady-state supersaturation based on: % Nicholson, D., S. Emerson, S. Khatiwala, R. C. Hamme. (in press) % An inverse approach to estimate bubble-mediated air-sea gas flux from % inert gas measurements. Proceedings on the 6th International Symposium % on Gas Transfer at Water Surfaces. Kyoto University Press. % % Fc = Ainj * slpc * Xg * u3 % Fp = Aex * slpc * Geq * D^n * u3 % % where u3 = (u-2.27)^3 (and zero for u < 2.27) % % Explanation of slpc: % slpc = (observed dry air pressure)/(reference dry air pressure) % slpc is a pressure correction factor to convert from reference to % observed conditions. Equilibrium gas concentration in gasmoleq is % referenced to 1 atm total air pressure, including saturated water vapor % (RH=1), but observed sea level pressure is usually different from 1 atm, % and humidity in the marine boundary layer is usually less than % saturation. Thus, the observed sea level pressure of each gas will % usually be different from the reference. % % INPUTS:------------------------------------------------------------------ % % C: gas concentration in mol m-3 % u10: 10 m wind speed (m/s) % S: Sea surface salinity (PSS) % T: Sea surface temperature (deg C) % slp: sea level pressure (atm) % % gas: two letter code for gas % Code Gas name Reference % ---- ---------- ----------- % He Helium Weiss 1971 % Ne Neon Hamme and Emerson 2004 % Ar Argon Hamme and Emerson 2004 % Kr Krypton Weiss and Keiser 1978 % Xe Xenon Wood and Caputi 1966 % N2 Nitrogen Hamme and Emerson 2004 % O2 Oxygen Garcia and Gordon 1992 % % varargin: optional but recommended arguments % rhum: relative humidity as a fraction of saturation (0.5 = 50% RH). % If not provided, it will be automatically set to 0.8. % % OUTPUTS:----------------------------------------------------------------- % Fd: Surface air-sea diffusive flux based on % Sweeney et al. 2007 [mol m-2 s-1] % Fc: Injection bubble flux (complete trapping) [mol m-2 s-1] % Fp: Exchange bubble flux (partial trapping) [mol m-2 s-1] % Deq: Steady-state supersaturation [unitless (%sat/100)] % % REFERENCE:--------------------------------------------------------------- % Nicholson, D., S. Emerson, S. Khatiwala, R. C. Hamme. (in press) % An inverse approach to estimate bubble-mediated air-sea gas flux from % inert gas measurements. Proceedings on the 6th International Symposium % on Gas Transfer at Water Surfaces. Kyoto University Press. % % AUTHORS:----------------------------------------------------------------- % David Nicholson [email protected] % Cara Manning [email protected] % Woods Hole Oceanographic Institution % Version 2.0 September 2015 % % COPYRIGHT:--------------------------------------------------------------- % % Copyright 2015 David Nicholson and Cara Manning % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License, which % is available at http://www.apache.org/licenses/LICENSE-2.0 % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Fd, Fc, Fp, Deq] = fas_N11(C,u10,S,T,slp,gas,varargin) % 1.5 factor converts from average winds to instantaneous - see N11 ref. Ainj = 2.51e-9./1.5; Aex = 1.15e-5./1.5; % if humidity is not provided, set to 0.8 for all values if nargin > 6 rhum = varargin{1}; else rhum = 0.8; end % slpc = (observed dry air pressure)/(reference dry air pressure) % see Description section in header ph2oveq = vpress(S,T); ph2ov = rhum.*ph2oveq; slpc = (slp-ph2ov)./(1-ph2oveq); slpd = slp-ph2ov; [D,Sc] = gasmoldiff(S,T,gas); Geq = gasmoleq(S,T,gas); % calculate wind speed term for bubble flux u3 = (u10-2.27).^3; u3(u3 < 0) = 0; k = kgas(u10,Sc,'Sw07'); Fd = -k.*(C-slpc.*Geq); Fc = Ainj.*slpd.*gasmolfract(gas).*u3; Fp = Aex.*slpc.*Geq.*D.^0.5.*u3; Deq = ((Fp+Fc)./k)./Geq; >>>>>>> cara-gtws
github
boom-lab/oce_tools-master
fas_Sw07.m
.m
oce_tools-master/gas_toolbox/fas_Sw07.m
4,246
utf_8
aabc9958150462fd4140a234ddf0fa24
% [Fd, Fc, Fp, Deq] = fas_Sw07(C,u10,S,T,slp,gas,rh) % Function to calculate air-sea gas exchange flux using Sweeney 07 % parameterization (k_660 = 0.27 cm/hr) % % USAGE:------------------------------------------------------------------- % [Fd, Fc, Fp, Deq] = fas_Sw07(C,u10,S,T,slp,gas,rh) % [Fd, Fc, Fp, Deq] = fas_Sw07(0.01410,5,35,10,1,'Ar',0.9) % > Fd = -4.4860e-09 % > Fc = 0 % > Fp = 0 % > Deq = 0 % % DESCRIPTION:------------------------------------------------------------- % Calculate air-sea fluxes and steady-state supersaturation based on: % Sweeney, C., Gloor, E., Jacobson, A. R., Key, R. M., McKinley, G., % Sarmiento, J. L., & Wanninkhof, R. (2007). Constraining global air?sea % gas exchange for CO2 with recent bomb 14C measurements. Global % Biogeochemical Cycles, 21(2). % % INPUTS:------------------------------------------------------------------ % % C: gas concentration in mol m-3 % u10: 10 m wind speed (m/s) % S: Sea surface salinity % T: Sea surface temperature (deg C) % slp: sea level pressure (atm) % gas: two letter code for gas (He, Ne, Ar, Kr, Xe, O2, N2) % rh: relative humidity as a fraction of saturation (0.5 = 50% RH) % rh is an optional but recommended argument. If not provided, it % will be automatically set to 0.8. % % OUTPUTS:----------------------------------------------------------------- % Fd: Diffusive air-sea flux (mol m-2 s-1) % Fc: Flux from fully collapsing small bubbles (mol m-2 s-1) % Fp: Flux from partially collapsing large bubbles (mol m-2 s-1) % Deq: Equilibrium supersaturation (unitless (%sat/100)) % % Note: Fp, Fc, and Deq will always be 0 and are included as outputs for % consistency with the other fas functions. % % REFERENCE:--------------------------------------------------------------- % Sweeney, C., Gloor, E., Jacobson, A. R., Key, R. M., McKinley, G., % Sarmiento, J. L., & Wanninkhof, R. (2007). Constraining global air?sea % gas exchange for CO2 with recent bomb 14C measurements. Global % Biogeochemical Cycles, 21(2). % % AUTHOR:--------------------------------------------------------------- % Cara Manning [email protected] % Woods Hole Oceanographic Institution % Version: August 2015 % % COPYRIGHT:--------------------------------------------------------------- % % Copyright 2015 Cara Manning % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % http://www.apache.org/licenses/LICENSE-2.0 % % Unless required by applicable law or agreed to in writing, software % distributed under the License is distributed on an "AS IS" BASIS, % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [Fd, Fc, Fp, Deq] = fas_Sw07(C,u10,S,T,slp,gas,rh) % ------------------------------------------------------------------------- % Check for humidity, calculate dry pressure % ------------------------------------------------------------------------- % if humidity is not provided, set to 0.8 for all values if nargin == 6 rh = 0.8.*ones(size(C)); end; % Equilibrium gas conc is referenced to 1 atm total air pressure, % including saturated water vapor (rh=1). % Calculate ratio (observed dry air pressure)/(reference dry air pressure). ph2oveq = vpress(S,T); ph2ov = rh.*ph2oveq; slpc = (slp-ph2ov)./(1-ph2oveq); % ------------------------------------------------------------------------- % Calc gas exchange fluxes % ------------------------------------------------------------------------- Geq = gasmoleq(S,T,gas); [~,Sc] = gasmoldiff(S,T,gas); k = kgas(u10,Sc,'Sw07'); Fd = -k.*(C-Geq.*slpc); % Set Finj, Fex to 0. They are included to be consistent with the other % fas_ functions. Fc = zeros(size(Fd)); Fp = zeros(size(Fd)); % Calculate steady state equilibrium supersaturation. This will also be 0. Deq = ((Fc+Fp)./k)./Geq;
github
boom-lab/oce_tools-master
gasmolsol.m
.m
oce_tools-master/gas_toolbox/gasmolsol.m
1,341
utf_8
6e4780f3679e3ea17ac369365f554331
% ========================================================================= % GASMOLSOL.M - calculates Henry's Law solubility (for a pure gas) % in mol m-3 atm-1 % % This is a wrapper function. See individual solubility functions for more % details. % % [sol] = gasmolsol(SP,pt,gas) % % ------------------------------------------------------------------------- % INPUTS: % ------------------------------------------------------------------------- % SP Practical Salinity % pt Potential temperature [degC] % gas gas string: He, Ne, Ar, Kr, Xe, O2 or N2 % % ------------------------------------------------------------------------- % OUTPUTS: % ------------------------------------------------------------------------- % sol Henry's Law solubility in mol m-3 atm-1 % % ------------------------------------------------------------------------- % USGAGE: % ------------------------------------------------------------------------- % [KH_O2] = gasmolsol(35,20,'O2') % KH_O2 = 1.1289 % % Author: David Nicholson [email protected] % Also see: gasmolfract.m, gasmoleq.m % ========================================================================= function [sol] = gasmolsol(SP,pt,gas) soleq = gasmoleq(SP,pt,gas); [p_h2o] = vpress(SP,pt); % water vapour pressure correction sol = soleq./(gasmolfract(gas).*(1-p_h2o));
github
boom-lab/oce_tools-master
calc_u10.m
.m
oce_tools-master/gas_toolbox/calc_u10.m
2,088
utf_8
09c687c95196c23b80507092d86febf5
% u10 = calc_u10(umeas,hmeas) % % USAGE:------------------------------------------------------------------- % % [u10] = calc_u10(5,4) % % >u10 = 5.5302 % % DESCRIPTION:------------------------------------------------------------- % Scale wind speed from measurement height to 10 m height % % INPUTS:------------------------------------------------------------------ % umeas: measured wind speed (m/s) % hmeas: height of measurement (m), can have dimension 1x1 or same as umeas % % OUTPUTS:----------------------------------------------------------------- % % Fs: Surface gas flux (mol m-2 s-1) % Fp: Flux from partially collapsing large bubbles (mol m-2 s-1) % Fc: Flux from fully collapsing small bubbles (mol m-2 s-1) % Deq: Equilibrium supersaturation (unitless (%sat/100)) % % REFERENCE:--------------------------------------------------------------- % % Hsu S, Meindl E A and Gilhousen D B (1994) Determining the Power-Law % Wind-Profile Exponent under Near-Neutral Stability Conditions at Sea % J. Appl. Meteor. 33 757?765 % % AUTHOR:--------------------------------------------------------------- % Cara Manning [email protected] % MIT/WHOI Joint Program in Oceanography % Version: 1.0 // September 2015 % % COPYRIGHT:--------------------------------------------------------------- % % Copyright 2015 Cara Manning % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % http://www.apache.org/licenses/LICENSE-2.0 % % Unless required by applicable law or agreed to in writing, software % distributed under the License is distributed on an "AS IS" BASIS, % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function u10 = calc_u10(umeas,hmeas) u10 = umeas.*(10./hmeas).^0.11; end
github
boom-lab/oce_tools-master
gasmoleq.m
.m
oce_tools-master/gas_toolbox/gasmoleq.m
3,626
utf_8
ef6936be137426f8dcab022b7eb2c9a6
% ========================================================================= % [sol] = gasmoleq(SP,pt,gas) % % GASMOLEQ.M - calculates equilibrium solubility of a dissolved gas % in mol/m^3 at an absolute pressure of 101325 Pa (sea pressure of 0 % dbar) including saturated water vapor. % % This is a wrapper function. See individual solubility functions for more % details. % % This function uses the GSW Toolbox solubility functions when available, % except for Ne. There is a bug in gsw_Nesol_SP_pt and gsw_Nesol version % 3.05 (they return solubility in nmol kg-1 instead of umol kg-1), so we % have provided a correct function for the solubility of Ne. % % ------------------------------------------------------------------------- % USAGE: % ------------------------------------------------------------------------- % [O2eq] = gasmoleq(35,20,'O2') % O2eq = 0.2311 % % ------------------------------------------------------------------------- % INPUTS: % ------------------------------------------------------------------------- % SP Practical salinity [PSS-78] % pt Potential temperature [degC] % gas gas string: He, Ne, Ar, Kr, Xe, O2 or N2 % % ------------------------------------------------------------------------- % OUTPUTS: % ------------------------------------------------------------------------- % sol gas equilibrium solubility in mol/m^3 % % ------------------------------------------------------------------------- % REFERENCES: % ------------------------------------------------------------------------- % IOC, SCOR and IAPSO, 2010: The international thermodynamic equation of % seawater - 2010: Calculation and use of thermodynamic properties. % Intergovernmental Oceanographic Commission, Manuals and Guides No. 56, % UNESCO (English), 196 pp. Available from http://www.TEOS-10.org % % See also the references within each solubility function. % % ------------------------------------------------------------------------- % AUTHORS: % ------------------------------------------------------------------------- % Cara Manning, [email protected] % David Nicholson, [email protected] % % ------------------------------------------------------------------------- % LICENSE: % ------------------------------------------------------------------------- % Copyright 2015 Cara Manning and David Nicholson % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License, which % is available at http://www.apache.org/licenses/LICENSE-2.0 % % ========================================================================= function [sol] = gasmoleq(SP,pt,gas) % Calculate potential density at surface SA = SP.*35.16504./35; CT = gsw_CT_from_pt(SA,pt); rho = gsw_sigma0(SA,CT)+1000; % calculate equilibrium solubility gas concentration in micro-mol/kg if strcmpi(gas, 'He') sol_umolkg = gsw_Hesol_SP_pt(SP,pt); elseif strcmpi(gas, 'Ne') % bug in gsw_Nesol... v. 3.05 - returns nmol kg-1 instead of umol kg-1 sol_umolkg = Nesol(SP,pt); elseif strcmpi(gas, 'Ar') sol_umolkg = gsw_Arsol_SP_pt(SP,pt); elseif strcmpi(gas, 'Kr') sol_umolkg = gsw_Krsol_SP_pt(SP,pt); elseif strcmpi(gas, 'Xe') sol_umolkg = Xesol(SP,pt); elseif strcmpi(gas, 'N2') sol_umolkg = gsw_N2sol_SP_pt(SP,pt); elseif strcmpi(gas, 'O2') sol_umolkg = gsw_O2sol_SP_pt(SP,pt); else error('Gas name must be He, Ne, Ar, Kr, Xe, O2 or N2'); end % convert from micro-mol/kg to mol/m3 sol = rho.*sol_umolkg./1e6;
github
boom-lab/oce_tools-master
fas.m
.m
oce_tools-master/gas_toolbox/fas.m
4,077
utf_8
6f31976e074eea8855be4c2d18ef3f34
% ========================================================================= % FAS - wrapper function for calculating air-sea gas transfer using a % specific GE parameterization % % [Fs, Fc, Fp, Deq] = fas(C,u10,S,T,slp,gas,param,rh) % % ------------------------------------------------------------------------- % USAGE: % ------------------------------------------------------------------------- % [Fd, Fc, Fp, Deq] = fas(C,u10,S,T,slp,gas,param,rh) % [Fd, Fc, Fp, Deq] = fas(0.01410,5,35,10,1,'Ar','N11',0.9) % > Fd = -4.4859e-09 % > Fc = 4.4807e-10 % > Fp = 2.1927e-10 % > Deq = -0.0168 % % ------------------------------------------------------------------------- % INPUTS: % ------------------------------------------------------------------------- % C: gas concentration (mol m-3) % u10: 10 m wind speed (m/s) % S: Sea surface salinity (PSS) % T: Sea surface temperature (deg C) % slp: sea level pressure (atm) % gas: two letter code for gas (He, Ne, Ar, Kr, Xe, O2, or N2) % sol: choice of solubility function % param: abbreviation for parameterization: % Sw07 = Sweeney et al. 2007 % S09 = Stanley et al. 2009 % N11 = Nicholson et al. 2011 % L13 = Liang et al. 2013 % rh: relative humidity expressed as the fraction of saturation % (0.5 = 50% RH). % rh is an optional but recommended argument. If not provided, it % will be set to 0.8 within the function. % % Code Gas name Reference % ---- ---------- ----------- % He Helium Weiss 1971 % Ne Neon Hamme and Emerson 2004 % Ar Argon Hamme and Emerson 2004 % Kr Krypton Weiss and Keiser 1978 % Xe Xenon Wood and Caputi 1966 % N2 Nitrogen Hamme and Emerson 2004 % O2 Oxygen Garcia and Gordon 1992 % % ------------------------------------------------------------------------- % OUTPUTS: % ------------------------------------------------------------------------- % Fd Diffusive flux (mol m-2 s-1) % Fc: Flux from fully collapsing small bubbles (mol m-2 s-1) % Fp: Flux from partially collapsing large bubbles (mol m-2 s-1) % Deq: Equilibrium supersaturation (unitless (%sat/100)) % % ------------------------------------------------------------------------- % AUTHOR: % ------------------------------------------------------------------------- % Author: Cara Manning [email protected] % % COPYRIGHT:--------------------------------------------------------------- % % Copyright 2015 David Nicholson and Cara Manning % % Licensed under the Apache License, Version 2.0 (the "License"); % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % http://www.apache.org/licenses/LICENSE-2.0 % % Unless required by applicable law or agreed to in writing, software % distributed under the License is distributed on an "AS IS" BASIS, % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. % % ========================================================================= function [Fd, Fc, Fp, Deq] = fas(C,u10,S,T,slp,gas,param,rh) % if humidity is not provided, set to 0.8 for all values if nargin == 8 if mean(rh) < 0 || mean(rh) > 1 error('Relative humidity must be 0 <= rh <= 1'); end else rh =0.8.*ones(size(C)); end switch upper(param) case 'S09' [Fd, Fc, Fp, Deq] = fas_S09(C,u10,S,T,slp,gas,rh); case 'N11' [Fd, Fc, Fp, Deq] = fas_N11(C,u10,S,T,slp,gas,rh); case 'SW07' [Fd, Fc, Fp, Deq] = fas_Sw07(C,u10,S,T,slp,gas,rh); case 'L13' [Fd, Fp, Fc, Deq] = fas_L13(C,u10,S,T,slp,gas,rh); otherwise error('only S09,N11,Sw07 and L13 are supported'); end end
github
boom-lab/oce_tools-master
sw_ptmp.m
.m
oce_tools-master/gas_toolbox/other_functions/sw_ptmp.m
3,684
utf_8
cf912e62bc1cde2044b0471353899d97
function PT = sw_ptmp(S,T,P,PR) % SW_PTMP Potential temperature %=========================================================================== % SW_PTMP $Id: sw_ptmp.m,v 1.1 2003/12/12 04:23:22 pen078 Exp $ % Copyright (C) CSIRO, Phil Morgan 1992. % % USAGE: ptmp = sw_ptmp(S,T,P,PR) % % DESCRIPTION: % Calculates potential temperature as per UNESCO 1983 report. % % INPUT: (all must have same dimensions) % S = salinity [psu (PSS-78) ] % T = temperature [degree C (ITS-90)] % P = pressure [db] % PR = Reference pressure [db] % (P & PR may have dims 1x1, mx1, 1xn or mxn for S(mxn) ) % % OUTPUT: % ptmp = Potential temperature relative to PR [degree C (ITS-90)] % % AUTHOR: Phil Morgan 92-04-06, Lindsay Pender ([email protected]) % % DISCLAIMER: % This software is provided "as is" without warranty of any kind. % See the file sw_copy.m for conditions of use and licence. % % REFERENCES: % Fofonoff, P. and Millard, R.C. Jr % Unesco 1983. Algorithms for computation of fundamental properties of % seawater, 1983. _Unesco Tech. Pap. in Mar. Sci._, No. 44, 53 pp. % Eqn.(31) p.39 % % Bryden, H. 1973. % "New Polynomials for thermal expansion, adiabatic temperature gradient % and potential temperature of sea water." % DEEP-SEA RES., 1973, Vol20,401-408. %========================================================================= % Modifications % 99-06-25. Lindsay Pender, Fixed transpose of row vectors. % 03-12-12. Lindsay Pender, Converted to ITS-90. % CALLER: general purpose % CALLEE: sw_adtg.m %------------- % CHECK INPUTS %------------- if nargin ~= 4 error('sw_ptmp.m: Must pass 4 parameters ') end %if % CHECK S,T,P dimensions and verify consistent [ms,ns] = size(S); [mt,nt] = size(T); [mp,np] = size(P); [mpr,npr] = size(PR); % CHECK THAT S & T HAVE SAME SHAPE if (ms~=mt) | (ns~=nt) error('check_stp: S & T must have same dimensions') end %if % CHECK OPTIONAL SHAPES FOR P if mp==1 & np==1 % P is a scalar. Fill to size of S P = P(1)*ones(ms,ns); elseif np==ns & mp==1 % P is row vector with same cols as S P = P( ones(1,ms), : ); % Copy down each column. elseif mp==ms & np==1 % P is column vector P = P( :, ones(1,ns) ); % Copy across each row elseif mp==ms & np==ns % PR is a matrix size(S) % shape ok else error('check_stp: P has wrong dimensions') end %if [mp,np] = size(P); % CHECK OPTIONAL SHAPES FOR PR if mpr==1 & npr==1 % PR is a scalar. Fill to size of S PR = PR(1)*ones(ms,ns); elseif npr==ns & mpr==1 % PR is row vector with same cols as S PR = PR( ones(1,ms), : ); % Copy down each column. elseif mpr==ms & npr==1 % P is column vector PR = PR( :, ones(1,ns) ); % Copy across each row elseif mpr==ms & npr==ns % PR is a matrix size(S) % shape ok else error('check_stp: PR has wrong dimensions') end %if %***check_stp %------ % BEGIN %------ % theta1 del_P = PR - P; del_th = del_P.*sw_adtg(S,T,P); th = T * 1.00024 + 0.5*del_th; q = del_th; % theta2 del_th = del_P.*sw_adtg(S,th/1.00024,P+0.5*del_P); th = th + (1 - 1/sqrt(2))*(del_th - q); q = (2-sqrt(2))*del_th + (-2+3/sqrt(2))*q; % theta3 del_th = del_P.*sw_adtg(S,th/1.00024,P+0.5*del_P); th = th + (1 + 1/sqrt(2))*(del_th - q); q = (2 + sqrt(2))*del_th + (-2-3/sqrt(2))*q; % theta4 del_th = del_P.*sw_adtg(S,th/1.00024,P+del_P); PT = (th + (del_th - 2*q)/6)/1.00024; return %=========================================================================
github
boom-lab/oce_tools-master
oc_url.m
.m
oce_tools-master/ocean_color/oc_url.m
5,048
utf_8
7d60af451fb1283f252c478781e4a8a7
function [ fname ] = oc_url(t,var,varargin) % oc_url % ------------------------------------------------------------------------- % construncts netCDF filename for NASA Ocean Color OpenDAP server % link - http://oceandata.sci.gsfc.nasa.gov/opendap/ % ------------------------------------------------------------------------- % USAGE: % ------------------------------------------------------------------------- % [fname] = oc_url(t,'par') % % [fname] = oc_url(t,'par','sensor','VIIRS','trange','DAY','res','4km') % % ------------------------------------------------------------------------- % INPUTS: % ------------------------------------------------------------------------- % Required % t: datetime or datenum time input - vector or scalar % var: string of input variable % % Optional parameters % NAME DEFAULT % -- ----- % sensor: 'MODISA' % level: 'L3SMI' % trange: '8D' temporal option % res: '9km' spatial resolution % ------------------------------------------------------------------------- % OUTPUTS: % ------------------------------------------------------------------------- % fname: full opendap address of requested file % % ------------------------------------------------------------------------- % ABOUT: David Nicholson // [email protected] // 29 JUN 2015 % ------------------------------------------------------------------------- froot = 'http://oceandata.sci.gsfc.nasa.gov/opendap'; %% parse inputs defaultLevel = 'L3SMI'; expectedLevel = {'L3SMI'}; defaultSensor = 'MODISA'; expectedSensor = {'MODISA','MODIST','VIIRS','SeaWiFS','Aquarius'}; defaultTrange = '8D'; expectedTrange = {'8D','R32','DAY','MO','YR'}; defaultRes = '9km'; expectedRes = {'4km','9km'}; %%% parse input parameters persistent p if isempty(p) p = inputParser; addRequired(p,'t',@(x) isnumeric(x) || isdatetime(x)); addRequired(p,'var',@isstr); addParameter(p,'trange',defaultTrange,@(x) any(validatestring(x,expectedTrange))); addParameter(p,'res',defaultRes,@(x) any(validatestring(x,expectedRes))); addParameter(p,'sensor',defaultSensor,@(x) any(validatestring(x,expectedSensor))); addParameter(p,'level',defaultLevel,@(x) any(validatestring(x,expectedLevel))); end parse(p,t,var,varargin{:}); inputs = p.Results; % OPENDAP root directory for sensor and level sensor = inputs.sensor; level = inputs.level; res = inputs.res; trange = inputs.trange; sensorCode = {'A','T','V','S','Q'}; sensor2code = containers.Map(expectedSensor,sensorCode); %% clean up t and construct full filename % determine variable suite from variable name % valid suites are RRS, CHL, KD490, PAR, PIC, POC, FLH, SST, SST4, and NSST % !!! sst shows up twice !!! switch var case {'chl_ocx','chlor_a'} suite = 'CHL'; case {'ipar','nflh'} suite = 'FLH'; case {'a_','adg_','aph_','bb_','bbp_'} suite = 'IOP'; case {'Kd_490'} suite = 'KD490'; case 'nsst' % call 'nsst' to get 'sst' var from NSST suite suite = 'NSST'; var = 'sst'; case 'par' suite = 'PAR'; case 'pic' suite = 'PIC'; case 'poc' suite = 'POC'; case strncmpi(var,'RRS_',4) suite = 'RRS'; case 'sst4' suite = 'SST4'; case 'sst' suite = 'SST'; otherwise if strncmpi(var,'Rrs_',4) suite = 'RRS'; elseif ismember(var(1:3),{'a_4','a_5','a_6','adg','aph','bb_','bbp'}) suite = 'IOP'; else error('unsuported/invalid variable name'); end end % append NPP prefix to VIIRS file path if strcmpi(sensor,'VIIRS') suite = ['NPP_' suite]; end % time in datetime - dateshift ensures there are not artifacts from % numerical rounding errors in conversion from datenum if ~isdatetime(t) dtm = datetime(t, 'ConvertFrom', 'datenum'); else dtm = t; end dtm = dateshift(dtm,'start','second','nearest'); % adjust time to nearest date with available data sCode = sensor2code(sensor); switch trange case {'8D','R32'} % round to 8th days (1,9,17,25,....) t1 = dtm-rem(day(dtm,'dayofyear'),8) + 1; if strcmpi(trange,'8D') tStr = [sCode,dstr(t1),dstr(t1+7)]; else tStr = [sCode,dstr(t1),dstr(t1+31)]; end case 'DAY' t1 = dtm; tStr = [sCode,dstr(dtm)]; case 'MO' t1 = dateshift(dtm,'start','month'); t2 = dateshift(dtm,'end','month'); tStr = [sCode,dstr(t1),dstr(t2)]; case 'YR' t1 = dateshift(dtm,'start','year'); t2 = dateshift(dtm,'end','year'); tStr = [sCode,dstr(t1),dstr(t2)]; otherwise error('time string is invalid'); end % construct OPENDAP address string for first file fname = fullfile(froot,sensor,level,num2str(year(t1)),... num2str(day(t1,'dayofyear'),'%03d'),... [tStr,'.L3m_',trange,'_',suite,'_',var,'_',res,'.nc']); end function [outstr] = dstr(t) outstr = [num2str(year(t)), num2str(day(t,'dayofyear'),'%03d')]; end
github
spm/spm5-master
spm_config_results.m
.m
spm5-master/spm_config_results.m
4,712
utf_8
c9c6c0c2c47b93a33eda1a7aadfe4072
function conf = spm_config_results % Configuration file for results reporting %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % $Id: spm_config_results.m 1563 2008-05-07 14:16:43Z ferath $ %------------------------------------------------------------------------- spm.type = 'files'; spm.name = 'Select SPM.mat'; spm.tag = 'spmmat'; spm.num = [1 1]; spm.filter = 'mat'; spm.ufilter = '^SPM\.mat$'; spm.help = {'Select the SPM.mat file that contains the design specification.'}; print.type = 'menu'; print.name = 'Print results'; print.tag = 'print'; print.labels = {'Yes','No'}; print.values = {1,0}; print.val = {1}; %------------------------------------------------------------------------- threshdesc.type = 'menu'; threshdesc.name = 'Threshold type'; threshdesc.tag = 'threshdesc'; threshdesc.labels = {'FWE','FDR','none'}; threshdesc.values = {'FWE','FDR','none'}; thresh.type = 'entry'; thresh.name = 'Threshold'; thresh.tag = 'thresh'; thresh.strtype = 'e'; thresh.num = [1 1]; thresh.val = {.05}; extent.type = 'entry'; extent.name = 'Extent (voxels)'; extent.tag = 'extent'; extent.strtype = 'e'; extent.num = [1 1]; extent.val = {0}; titlestr.type = 'entry'; titlestr.name = 'Results Title'; titlestr.tag = 'titlestr'; titlestr.strtype = 's'; titlestr.num = [1 1]; titlestr.help = {['Heading on results page - determined automatically if' ... ' left empty']}; titlestr.val = {''}; contrasts.type = 'entry'; contrasts.name = 'Contrast(s)'; contrasts.tag = 'contrasts'; contrasts.strtype = 'e'; contrasts.num = [1 Inf]; contrasts.help = {['Index of contrast(s). If more than one number is' ... ' entered, analyse a conjunction hypothesis.'], ... '',... ['If only one number is entered, and this number is' ... ' "Inf", then results are printed for all contrasts' ... ' found in the SPM.mat file.']}; %------------------------------------------------------------------------- mthresh = thresh; mthresh.name = 'Mask threshold'; mcons = contrasts; mcons.help = {'Index of contrast(s) for masking - leave empty for no masking.'}; mtype.type = 'menu'; mtype.name = 'Nature of mask'; mtype.tag = 'mtype'; mtype.labels = {'Inclusive','Exclusive'}; mtype.values = {0,1}; mask.type = 'branch'; mask.name = 'Mask definition'; mask.tag = 'mask'; mask.val = {mcons, mthresh, mtype}; masks.type = 'repeat'; masks.name = 'Masking'; masks.tag = 'masks'; masks.values = {mask}; masks.num = [0 1]; %------------------------------------------------------------------------- conspec.type = 'branch'; conspec.name = 'Contrast query'; conspec.tag = 'conspec'; conspec.val = {titlestr, contrasts, threshdesc, thresh, extent, masks}; conspecs.type = 'repeat'; conspecs.name = 'Contrasts'; conspecs.tag = 'conspecs'; conspecs.values = {conspec}; conspecs.num = [1 Inf]; %------------------------------------------------------------------------- conf.type = 'branch'; conf.name = 'Results Report'; conf.tag = 'results'; conf.val = {spm,conspecs,print}; conf.prog = @run_results; conf.modality = {'FMRI','PET'}; return; %======================================================================= %======================================================================= function run_results(job) cspec = job.conspec; for k = 1:numel(cspec) job.conspec=cspec(k); if (numel(cspec(k).contrasts) == 1) && isinf(cspec(k).contrasts) tmp=load(job.spmmat{1}); for l=1:numel(tmp.SPM.xCon) cspec1(l) = cspec(k); cspec1(l).contrasts = l; end; job1 = job; job1.print = 1; job1.conspec = cspec1; run_results(job1); else xSPM.swd = spm_str_manip(job.spmmat{1},'H'); xSPM.Ic = job.conspec.contrasts; xSPM.u = job.conspec.thresh; xSPM.Im = []; if ~isempty(job.conspec.mask) xSPM.Im = job.conspec.mask.contrasts; xSPM.pm = job.conspec.mask.thresh; xSPM.Ex = job.conspec.mask.mtype; end xSPM.thresDesc = job.conspec.threshdesc; xSPM.u = job.conspec.thresh; xSPM.title = job.conspec.titlestr; xSPM.k = job.conspec.extent; [hReg xSPM SPM] = spm_results_ui('Setup',xSPM); if job.print spm_list('List',xSPM,hReg); spm_figure('Print'); end assignin('base','hReg',hReg); assignin('base','xSPM',xSPM); assignin('base','SPM',SPM); end end
github
spm/spm5-master
spm_eeg_inv_datareg.m
.m
spm5-master/spm_eeg_inv_datareg.m
13,392
utf_8
1618e2bb99be5372a0829b942500f881
function [varargout] = spm_eeg_inv_datareg(varargin) %========================================================================== % Rigid registration of the EEG/MEG data and sMRI spaces % % FORMAT D = spm_eeg_inv_datareg(S) % rigid co-registration % 1: fiducials based (3 landmarks: nasion, left ear, right ear) % 2: surface matching between sensor mesh and headshape % (starts with a type 1 registration) % Input: % D - input data struct (optional) % Output: % D - data struct including the new files and parameters % % FORMAT [eeg2mri,sen_reg,fid_reg,hsp_reg,orient_reg,mri2eeg,hsp2eeg] % = spm_eeg_inv_datareg(sensors,fid_eeg,fid_mri,headshape,scalpvert,megorient,template) % Input: % % sensors - a matrix coordinate of the sensor % locations ([Sx1 Sy1 Sz1 ; Sx2 Sy2 Sz2 ; ...]) % fid_eeg - the fiducial coordinates in sensor % space ([Nx Ny Nz ; LEx LEy LEz ; REx REy REz]) % fid_mri - the fiducial coordinates in sMRI % space ([nx ny nz ; lex ley lez ; rex rey rez]) % headshape - the headshape point coordinates in % sensor space ([hx1 hy1 hz1 ; hx2 hy2 hz2 ; ...]) % scalpvert - the vertices coordinates of the scalp % tesselation in mri space ([vx1 vy1 vz1 ; vx2 vy2 vz2 ; % ...]) % megorient - the sensor orientations ([ox1 oy1 oz1 ; ox2 oy2 oz2 ; ...]) % (MEG only) % template - 0/1 switch to enable affine mri2eeg transform % % IMPORTANT: all the coordinates must be in the same units (mm). % % Output: % eeg2mri - rigid transformation (Rotation + Translation) % sen_reg - the registered sensor coordinates in sMRI space % fid_reg - the registered fiduicals coordinates in sMRI space % hsp_reg - the registered headshap point coordinates in sMRI space % orient_reg - the registrated sensor orientations (MEG only) % % If a template is used, the senor locations are transformed using an % affine (rigid body) mapping. If headshape locations are supplied % this is generalized to a full twelve parameter affine mapping (n.b. % this might not be appropriate for MEG data). %========================================================================== % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Jeremie Mattout % $Id: spm_eeg_inv_datareg.m 1058 2008-01-03 15:58:02Z guillaume $ % Modified by Rik Henson to handle gradiometers (with two positions/orientations % for component coils) 4/6/07 % Check input arguments %========================================================================== % % spm_eeg_inv_datareg(D) %-------------------------------------------------------------------------- if nargin < 3 try [D val] = spm_eeg_inv_check(varargin{:}); sensors = D.inv{val}.datareg.sensors; fid_eeg = D.inv{val}.datareg.fid_eeg; fid_mri = D.inv{val}.datareg.fid_mri; headshape = D.inv{val}.datareg.headshape; scalpvert = D.inv{val}.datareg.scalpvert; if strcmp(D.modality,'MEG') megorient = D.inv{val}.datareg.megorient; else megorient = sparse(0,3); end template = D.inv{val}.mesh.template; catch D = spm_eeg_inv_datareg_ui(varargin{:}); D = spm_eeg_inv_datareg(D); end % spm_eeg_inv_datareg(sensors,fid_eeg,fid_mri,headshape,scalpvert,megorient,template) %-------------------------------------------------------------------------- else sensors = varargin{1}; fid_eeg = varargin{2}; fid_mri = varargin{3}; try, headshape = varargin{4}; catch, headshape = sparse(0,3); end try, scalpvert = varargin{5}; catch, scalpvert = sparse(0,3); end try, megorient = varargin{6}; catch, megorient = sparse(0,3); end try, template = varargin{7}; catch, template = 0; end end % The fiducial coordinates must be in the same order (usually: NZ & LE, RE) %-------------------------------------------------------------------------- nfid = size(fid_eeg,1); if nfid ~= size(fid_mri,1) warndlg('Please specify the same number of MRI and EEG/MEG fiducials'); return end % Estimate-apply rigid body transform to sensor space %-------------------------------------------------------------------------- M1 = spm_eeg_inv_rigidreg(fid_mri', fid_eeg'); fid_eeg = M1*[fid_eeg'; ones(1,nfid)]; fid_eeg = fid_eeg(1:3,:)'; if template % constatined affine transform %-------------------------------------------------------------------------- aff = 1; for i = 1:16 % scale %---------------------------------------------------------------------- M = pinv(fid_eeg(:))*fid_mri(:); M = sparse(1:4,1:4,[M M M 1]); fid_eeg = M*[fid_eeg'; ones(1,nfid)]; fid_eeg = fid_eeg(1:3,:)'; M1 = M*M1; % and move %---------------------------------------------------------------------- M = spm_eeg_inv_rigidreg(fid_mri', fid_eeg'); fid_eeg = M*[fid_eeg'; ones(1,nfid)]; fid_eeg = fid_eeg(1:3,:)'; M1 = M*M1; end else aff = 0; end % assume headshape locations are registered to sensor fiducials %-------------------------------------------------------------------------- M2 = M1; % Surface matching between the scalp vertices in MRI space and % the headshape positions in data space %-------------------------------------------------------------------------- if length(headshape) % load surface locations from sMRI %---------------------------------------------------------------------- if size(headshape,2) > size(headshape,1) headshape = headshape'; end if size(scalpvert,2) > size(scalpvert,1) scalpvert = scalpvert'; end % move headshape locations (NB: future code will allow for hsp fiducials) %---------------------------------------------------------------------- % fid_hsp = headshape(1:3,:); % M2 = spm_eeg_inv_rigidreg(fid_eeg', fid_hsp'); headshape = M2*[headshape'; ones(1,size(headshape,1))]; headshape = headshape(1:3,:)'; % intialise plot %---------------------------------------------------------------------- h = spm_figure('GetWin','Graphics'); clf(h); figure(h) set(h,'DoubleBuffer','on','BackingStore','on'); Fmri = plot3(scalpvert(:,1),scalpvert(:,2),scalpvert(:,3),'ro','MarkerFaceColor','r'); hold on; Fhsp = plot3(headshape(:,1),headshape(:,2),headshape(:,3),'bs','MarkerFaceColor','b'); axis off image drawnow % nearest point registration %---------------------------------------------------------------------- M = spm_eeg_inv_icp(scalpvert',headshape',fid_mri',fid_eeg',Fmri,Fhsp,aff); % transform headshape and eeg fiducials %---------------------------------------------------------------------- headshape = M*[headshape'; ones(1,size(headshape,1))]; headshape = headshape(1:3,:)'; fid_eeg = M*[fid_eeg'; ones(1,nfid)]; fid_eeg = fid_eeg(1:3,:)'; M1 = M*M1; end % Update the sensor locations and orientation %-------------------------------------------------------------------------- if size(sensors,2) == 3 % Only one coil sensors = M1*[sensors'; ones(1,size(sensors,1))]; sensors = sensors(1:3,:)'; megorient = megorient*M1(1:3,1:3)'; elseif size(sensors,2) == 6 % Two coils (eg gradiometer) tmp1 = M1*[sensors(:,1:3)'; ones(1,size(sensors,1))]; tmp2 = M1*[sensors(:,4:6)'; ones(1,size(sensors,1))]; sensors = [tmp1(1:3,:); tmp2(1:3,:)]'; tmp1 = megorient(:,1:3)*M1(1:3,1:3)'; tmp2 = megorient(:,4:6)*M1(1:3,1:3)'; megorient = [tmp1 tmp2]; else error('Unknown sensor coil locations') end % grad - for use of fieldtrip leadfield functions %-------------------------------------------------------------------------- try grad = D.inv{val}.datareg.grad; grad_coreg.pnt = M1*[grad.pnt'*10; ones(1,size(grad.pnt,1))]; grad_coreg.pnt = grad_coreg.pnt(1:3,:)'/10; grad_coreg.ori = grad.ori*M1(1:3,1:3)'; grad_coreg.tra = grad.tra; catch grad_coreg = []; end % retain valid sensor locations for leadfield computation %-------------------------------------------------------------------------- if nargin < 3 try sens = setdiff(D.channels.eeg, D.channels.Bad); catch sens = D.channels.eeg; D.channels.Bad = []; end sensors = sensors(sens,:); if strcmp(D.modality,'MEG') megorient = megorient(sens,:); end end % ensure sensors lie outside the scalp %-------------------------------------------------------------------------- if length(scalpvert) && strcmp(D.modality,'EEG') tri = delaunayn(scalpvert); j = dsearchn(scalpvert, tri, sensors(:,1:3)); dist = sqrt(sum(sensors(:,1:3).^2,2)./sum(scalpvert(j,:).^2,2)); dist = min(dist,1); sensors(:,1:3) = diag(1./dist)*sensors(:,1:3); end % Ouptut arguments %-------------------------------------------------------------------------- if nargout == 1 D.inv{val}.datareg.eeg2mri = M1; D.inv{val}.datareg.sens_coreg = sensors; D.inv{val}.datareg.fid_coreg = fid_eeg; D.inv{val}.datareg.hsp_coreg = headshape; D.inv{val}.datareg.sens_orient_coreg = megorient; D.inv{val}.datareg.sens = sens; D.inv{val}.datareg.grad_coreg = grad_coreg; varargout{1} = D; else % varargout = {RT,sensors_reg,fid_reg,headshape_reg,orient_reg} %---------------------------------------------------------------------- varargout{1} = M1; varargout{2} = sensors; varargout{3} = fid_eeg; varargout{4} = headshape; varargout{5} = megorient; end return %========================================================================== function [M1] = spm_eeg_inv_icp(data1,data2,fid1,fid2,Fmri,Fhsp,aff) % Iterative Closest Point (ICP) registration algorithm. % Surface matching computation: registration from one 3D surface (set data2 = [Dx1 Dy1 Dz1 ; Dx2 Dy2 Dz2 ; ...]) % onto another 3D surface (set data1 = [dx1 dy1 dz1 ; dx2 dy2 dz2 ; ...]) % % FORMAT [M1] = spm_eeg_inv_icp(data1,data2,fid1,fid2,Fmri,Fhsp,[aff]) % Input: % data1 - locations of the first set of points corresponding to the % 3D surface to register onto (p points) % data2 - locations of the second set of points corresponding to the % second 3D surface to be registered (m points) % fid1 - sMRI fiducials % fid2 - sens fiducials % Fmri - graphics handle for sMRI points % Fhsp - graphics handle for headshape % aff - flag for 12 - parameter affine transform % % Output: % M1 - 4 x 4 affine transformation matrix for sensor space %========================================================================== % Adapted from (http://www.csse.uwa.edu.au/~ajmal/icp.m) written by Ajmal Saeed Mian {[email protected]} % Computer Science, The University of Western Australia. % Jeremie Mattout & Guillaume Flandin % Landmarks (fiduciales) based registration % Fiducial coordinates must be given in the same order in both files % use figure and fiducials if specified %-------------------------------------------------------------------------- try, fid1; catch, fid1 = []; end try, fid2; catch, fid2 = []; end try, aff; catch, aff = 0; end % initialise rotation and translation of sensor space %-------------------------------------------------------------------------- M1 = speye(4,4); tri = delaunayn(data1'); for i = 1:16 % find nearest neighbours %---------------------------------------------------------------------- [corr, D] = dsearchn(data1', tri, data2'); corr(:,2) = [1 : length(corr)]'; i = find(D > 32); corr(i,:) = []; M = [fid1 data1(:,corr(:,1))]; S = [fid2 data2(:,corr(:,2))]; % apply and accumlate affine scaling %---------------------------------------------------------------------- if aff M = pinv([S' ones(length(S),1)])*M'; M = [M'; 0 0 0 1]; else % 6-parmaeter affine (i.e. rigid body) %---------------------------------------------------------------------- M = spm_eeg_inv_rigidreg(M,S); end data2 = M*[data2; ones(1,size(data2,2))]; data2 = data2(1:3,:); fid2 = M*[fid2; ones(1,size(fid2,2))]; fid2 = fid2(1:3,:); M1 = M*M1; % plot %---------------------------------------------------------------------- try set(Fmri,'XData',data1(1,:),'YData',data1(2,:),'ZData',data1(3,:)); set(Fhsp,'XData',data2(1,:),'YData',data2(2,:),'ZData',data2(3,:)); drawnow end end return %========================================================================== %========================================================================== function [M1] = spm_eeg_inv_rigidreg(data1, data2) M = spm_detrend(data1'); S = spm_detrend(data2'); [U A V] = svd(S'*M); R1 = V*U'; if det(R1) < 0 B = eye(3); B(3,3) = det(V*U'); R1 = V*B*U'; end t1 = mean(data1,2) - R1*mean(data2,2); M1 = [R1 t1; 0 0 0 1]; return
github
spm/spm5-master
spm_vb_ppm_anova.m
.m
spm5-master/spm_vb_ppm_anova.m
3,883
utf_8
cf4c32a78589f807a84ec4b5826260ab
function spm_vb_ppm_anova(SPM) % Bayesian ANOVA using model comparison % FORMAT spm_vb_ppm_anova(SPM) % % SPM - Data structure corresponding to a full model (ie. one % containing all experimental conditions). % % This function creates images of differences in log evidence % which characterise the average effect, main effects and interactions % in a factorial design. % % The factorial design is specified in SPM.factor. For a one-way ANOVA % the images % % avg_effect.img % main_effect.img % % are produced. For a two-way ANOVA the following images are produced % % avg_effect.img % main_effect_'factor1'.img % main_effect_'factor2'.img % interaction.img % % These images can then be thresholded. For example a threshold of 4.6 % corresponds to a posterior effect probability of [exp(4.6)] = 0.999. % See paper VB4 for more details. %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Will Penny % $Id: spm_vb_ppm_anova.m 300 2005-11-16 21:05:24Z guillaume $ disp('Warning: spm_vb_ppm_anova only works for single session data.'); model = spm_vb_models(SPM,SPM.factor); analysis_dir = pwd; for m=1:length(model)-1, model_subdir = ['model_',int2str(m)]; mkdir(analysis_dir,model_subdir); SPM.swd = fullfile(analysis_dir,model_subdir); SPM.Sess(1).U = model(m).U; SPM.Sess(1).U = spm_get_ons(SPM,1); SPM = spm_fMRI_design(SPM,0); % 0 = don't save SPM.mat SPM.PPM.update_F = 1; % Compute evidence for each model SPM.PPM.compute_det_D = 1; spm_spm_vb(SPM); end % Compute differences in contributions to log-evidence images % to assess main effects and interactions nf = length(SPM.factor); if nf==1 % For a single factor % Average effect image1 = fullfile(analysis_dir, 'model_1','LogEv.img'); image2 = fullfile(analysis_dir, 'model_2','LogEv.img'); imout = fullfile(analysis_dir, 'avg_effect.img'); img_subtract(image1,image2,imout); % Main effect of factor image1 = fullfile(analysis_dir, 'model_2','LogEv.img'); image2 = fullfile(analysis_dir, 'LogEv.img'); imout = fullfile(analysis_dir, 'main_effect.img'); img_subtract(image1,image2,imout); elseif nf==2 % For two factors % Average effect image1 = fullfile(analysis_dir, 'model_1','LogEv.img'); image2 = fullfile(analysis_dir, 'model_2','LogEv.img'); imout = fullfile(analysis_dir, 'avg_effect.img'); img_subtract(image1,image2,imout); % Main effect of factor 1 image1 = fullfile(analysis_dir, 'model_2','LogEv.img'); image2 = fullfile(analysis_dir, 'model_3','LogEv.img'); imout = fullfile(analysis_dir, ['main_effect_',SPM.factor(1).name,'.img']); img_subtract(image1,image2,imout); % Main effect of factor 2 image1 = fullfile(analysis_dir, 'model_2','LogEv.img'); image2 = fullfile(analysis_dir, 'model_4','LogEv.img'); imout = fullfile(analysis_dir, ['main_effect_',SPM.factor(2).name,'.img']); img_subtract(image1,image2,imout); % Interaction image1 = fullfile(analysis_dir, 'model_5','LogEv.img'); image2 = fullfile(analysis_dir, 'LogEv.img'); imout = fullfile(analysis_dir, 'interaction.img'); img_subtract(image1,image2,imout); end %----------------------------------------------------------------------- function img_subtract(image1,image2,image_out) % Subtract image 1 from image 2 and write to image out % Note: parameters are names of files Vi = spm_vol(strvcat(image1,image2)); Vo = struct(... 'fname', image_out,... 'dim', [Vi(1).dim(1:3)],... 'dt', [spm_type('float32') spm_platform('bigend')],... 'mat', Vi(1).mat,... 'descrip', 'Difference in Log Evidence'); f = 'i2-i1'; flags = {0,0,1}; Vo = spm_imcalc(Vi,Vo,f,flags);
github
spm/spm5-master
spm_eeg_inv_vde.m
.m
spm5-master/spm_eeg_inv_vde.m
4,817
utf_8
fe334e835d70d0ec1f54bf41a895ab9e
function varargout = spm_eeg_inv_vde(varargin) % SPM_EEG_INV_VDE M-file for spm_eeg_inv_vde.fig % SPM_EEG_INV_VDE, by itself, creates a new SPM_EEG_INV_VDE or raises the existing % singleton*. % % H = SPM_EEG_INV_VDE returns the handle to a new SPM_EEG_INV_VDE or the handle to % the existing singleton*. % % SPM_EEG_INV_VDE('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SPM_EEG_INV_VDE.M with the given input arguments. % % SPM_EEG_INV_VDE('Property','Value',...) creates a new SPM_EEG_INV_VDE or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before spm_eeg_inv_vde_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to spm_eeg_inv_vde_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 % Copyright 2002-2003 The MathWorks, Inc. % Edit the above text to modify the response to help spm_eeg_inv_vde % Last Modified by GUIDE v2.5 05-Dec-2006 09:07:07 % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Jeremie Mattout % $Id: spm_eeg_inv_vde.m 1039 2007-12-21 20:20:38Z karl $ % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @spm_eeg_inv_vde_OpeningFcn, ... 'gui_OutputFcn', @spm_eeg_inv_vde_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 spm_eeg_inv_vde is made visible. function spm_eeg_inv_vde_OpeningFcn(hObject, eventdata, handles, varargin) handles.main_handles = varargin{1}; set(handles.Location,'Enable','on'); set(handles.Display,'Enable','off'); handles.output = hObject; guidata(hObject,handles); % --- Outputs from this function are returned to the command line. function varargout = spm_eeg_inv_vde_OutputFcn(hObject, eventdata, handles) varargout{1} = handles.output; % --- Executes on button press in Location. function Location_Callback(hObject, eventdata, handles) axes(handles.main_handles.sources_axes); vert = handles.main_handles.vert; handles.location = datacursormode(handles.main_handles.figure1); set(handles.location,'Enable','on','DisplayStyle','datatip','SnapToDataVertex','off'); waitforbuttonpress; vde = getCursorInfo(handles.location); vde = vde.Position; datacursormode off CurrVert = sum(((ones(length(vert),1)*vde - vert).^2)'); handles.vde = find(CurrVert == min(CurrVert)); set(handles.Location,'Enable','off'); set(handles.Display,'Enable','on'); guidata(hObject,handles); % --- Executes on button press in Size. function Size_Callback(hObject, eventdata, handles) axes(handles.main_handles.sources_axes); vert = handles.main_handles.vert; face = handles.main_handles.face; Neighbours = FindNeighB(handles.vde,face); amp = handles.main_handles.srcs_disp; ampref = amp(handles.vde(1)); ampnew = amp(Neighbours); amptemp = abs(ampnew - ampref); newsrc = find(amptemp == min(amptemp)); handles.vde = [handles.vde Neighbours(newsrc)]; axes(handles.main_handles.sources_axes); hold on; handles.hpts = plot3(vert(handles.vde,1),vert(handles.vde,2),vert(handles.vde,3),'sk','MarkerFaceColor','k','MarkerSize',14); guidata(hObject,handles); % --- Executes on button press in Display function Display_Callback(hObject, eventdata, handles) figure; if length(handles.vde) > 1 TimeSeries = mean(handles.main_handles.srcs_data(handles.vde,:)); else TimeSeries = handles.main_handles.srcs_data(handles.vde,:); end D = handles.main_handles.D; woi = D.inv{handles.main_handles.val}.inverse.woi; Xstep = (woi(2) - woi(1))/(handles.main_handles.dimT - 1); X = woi(1):Xstep:woi(2); plot(X,TimeSeries,'r','LineWidth',3); set(handles.hpts,'Visible','off'); hold off; close(handles.figure1); axes(handles.main_handles.sources_axes) cameramenu on function Neighbours = FindNeighB(CurrVert,face) Neighbours = []; for i = 1:length(CurrVert) [Icv,Jcv] = find(face == CurrVert(i)); CurrNeigh = []; for j = 1:length(Icv) CurrNeigh = [CurrNeigh face(Icv(j),:)]; end CurrNeigh = unique(CurrNeigh); Neighbours = [Neighbours CurrNeigh]; end Neighbours = setdiff(Neighbours,CurrVert); return function pushbutton1_Callback(hObject,eventdata,handles)
github
spm/spm5-master
spm_eeg_inv_ecd_DrawDip.m
.m
spm5-master/spm_eeg_inv_ecd_DrawDip.m
19,637
utf_8
d19eae00a8f30a0d46d376b1732237a5
function varargout = spm_eeg_inv_ecd_DrawDip(action,varargin) %___________________________________________________________________ % % spm_eeg_inv_ecd_DrawDip % % Function to display the dipoles as obtained from the optim routine. % % Use it with arguments or not: % - spm_eeg_inv_ecd_DrawDip('Init') % The routine asks for the dipoles file and image to display % - spm_eeg_inv_ecd_DrawDip('Init',sdip) % The routine will use the avg152T1 canonical image % - spm_eeg_inv_ecd_DrawDip('Init',sdip,P) % The routines dispays the dipoles on image P. % % If multiple seeds have been used, you can select the seeds to display % by pressing their index. % Given that the sources could have different locations, the slices % displayed will be the 3D view at the *average* or *mean* locations of % selected sources. % If more than 1 dipole was fitted at a time, then selection of source 1 % to N is possible through the pull-down selector. % % The location of the source/cut is displayed in mm and voxel, as well as % the underlying image intensity at that location. % The cross hair position can be hidden by clicking on its button. % % Nota_1: If the cross hair is manually moved by clicking in the image or % changing its coordinates, the dipole displayed will NOT be at % the right displayed location. That's something that needs to be improved... % % Nota_2: Some seeds may have not converged within the limits fixed, % these dipoles are not displayed... % % Fields needed in sdip structure to plot on an image: % + n_seeds: nr of seeds set used, i.e. nr of solutions calculated % + n_dip: nr of fitted dipoles on the EEG time series % + loc: location of fitted dipoles, cell{1,n_seeds}(3 x n_dip) % remember that loc is fixed over the time window. % + j: sources amplitude over the time window, % cell{1,n_seeds}(3*n_dip x Ntimebins) % + Mtb: index of maximum power in EEG time series used %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Christophe Phillips, % $Id$ global st global defaults sw = warning('off','all'); Fig = spm_figure('GetWin','Graphics'); colors = strvcat('y','b','g','r','c','m'); % 6 possible colors marker = strvcat('o','x','+','*','s','d','v','p','h'); % 9 possible markers Ncolors = length(colors); Nmarker = length(marker); if nargin == 0, action = 'Init'; end; switch lower(action), %________________________________________________________________________ case 'init' %------------------------------------------------------------------------ % FORMAT spm_eeg_inv_ecd_DrawDip('Init',sdip,P) % Initialise the variables with GUI % e.g. spm_eeg_inv_ecd_DrawDip('Init') %------------------------------------------------------------------------ if nargin < 2 load(spm_select(1,'^.*S.*dip.*\.mat$','Select dipole file')); if ~exist('sdip') & exist('result') sdip = result; end else sdip = varargin{1}; end % if the exit flag is not in the structure, assume everything went ok. if ~isfield(sdip,'exitflag') sdip.exitflag = ones(1,sdip.n_seeds); end try P = varargin{2}; catch P = fullfile(spm('dir'),'canonical','avg152T1.nii'); end if ischar(P), P = spm_vol(P); end; spm_orthviews('Reset'); spm_orthviews('Image', P, [0.0 0.45 1 0.55]); spm_orthviews('MaxBB'); st.callback = 'spm_image(''shopos'');'; WS = spm('WinScale'); % Build GUI %============================= % Location: %----------- uicontrol(Fig,'Style','Frame','Position',[60 25 200 325].*WS,'DeleteFcn','spm_image(''reset'');'); uicontrol(Fig,'Style','Frame','Position',[70 250 180 90].*WS); uicontrol(Fig,'Style','Text', 'Position',[75 320 170 016].*WS,'String','Crosshair Position'); uicontrol(Fig,'Style','PushButton', 'Position',[75 316 170 006].*WS,... 'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin'); % uicontrol(fg,'Style','PushButton', 'Position',[75 315 170 020].*WS,'String','Crosshair Position',... % 'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin'); uicontrol(Fig,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:'); uicontrol(Fig,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:'); uicontrol(Fig,'Style','Text', 'Position',[75 255 75 020].*WS,'String','Img Intens.:'); st.mp = uicontrol(Fig,'Style','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates'); st.vp = uicontrol(Fig,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates'); st.in = uicontrol(Fig,'Style','Text', 'Position',[150 255 85 020].*WS,'String',''); c = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;'; uicontrol(Fig,'Style','togglebutton','Position',[95 220 125 20].*WS,... 'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs'); % Dipoles/seeds selection: %-------------------------- uicontrol(Fig,'Style','Frame','Position',[300 25 180 325].*WS); sdip.hdl.hcl = uicontrol(Fig,'Style','pushbutton','Position',[310 320 100 20].*WS, ... 'String','Clear all','CallBack','spm_eeg_inv_ecd_DrawDip(''ClearAll'')'); sdip.hdl.hseed=zeros(sdip.n_seeds,1); for ii=1:sdip.n_seeds if sdip.exitflag(ii)==1 sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','togglebutton','String',num2str(ii),... 'Position',[310+rem(ii-1,8)*20 295-fix((ii-1)/8)*20 20 20].*WS,... 'CallBack','spm_eeg_inv_ecd_DrawDip(''ChgSeed'')'); else sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','Text','String',num2str(ii), ... 'Position',[310+rem(ii-1,8)*20 293-fix((ii-1)/8)*20 20 20].*WS) ; end end uicontrol(Fig,'Style','text','String','Select dipole # :', ... 'Position',[310 255-fix((sdip.n_seeds-1)/8)*20 110 20].*WS); txt_box = cell(sdip.n_dip,1); for ii=1:sdip.n_dip, txt_box{ii} = num2str(ii); end txt_box{sdip.n_dip+1} = 'all'; sdip.hdl.hdip = uicontrol(Fig,'Style','popup','String',txt_box, ... 'Position',[420 258-fix((sdip.n_seeds-1)/8)*20 40 20].*WS, ... 'Callback','spm_eeg_inv_ecd_DrawDip(''ChgDip'')'); % Dipoles orientation and strength: %----------------------------------- uicontrol(Fig,'Style','Frame','Position',[70 120 180 90].*WS); uicontrol(Fig,'Style','Text', 'Position',[75 190 170 016].*WS, ... 'String','Dipole orientation & strength'); uicontrol(Fig,'Style','Text', 'Position',[75 165 65 020].*WS,'String','vn_x_y_z:'); uicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS,'String','theta, phi:'); uicontrol(Fig,'Style','Text', 'Position',[75 125 75 020].*WS,'String','Dip intens.:'); sdip.hdl.hor1 = uicontrol(Fig,'Style','Text', 'Position',[140 165 105 020].*WS,'String','a'); sdip.hdl.hor2 = uicontrol(Fig,'Style','Text', 'Position',[150 145 85 020].*WS,'String','b'); sdip.hdl.int = uicontrol(Fig,'Style','Text', 'Position',[150 125 85 020].*WS,'String','c'); st.vols{1}.sdip = sdip; % First plot = all the seeds that converged ! l_conv = find(sdip.exitflag==1); if isempty(l_conv) error('No seed converged towards a stable solution, nothing to be displayed !') else spm_eeg_inv_ecd_DrawDip('DrawDip',l_conv,1) set(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons end % get(sdip.hdl.hseed(1),'Value') % for ii=1:sdip.n_seeds, delete(hseed(ii)); end % h1 = uicontrol(Fig,'Style','togglebutton','Position',[600 25 10 10].*WS) % h2 = uicontrol(Fig,'Style','togglebutton','Position',[620 100 20 20].*WS,'String','1') % h2 = uicontrol(Fig,'Style','checkbox','Position',[600 100 10 10].*WS) % h3 = uicontrol(Fig,'Style','radiobutton','Position',[600 150 20 20].*WS) % h4 = uicontrol(Fig,'Style','radiobutton','Position',[700 150 20 20].*WS) % delete(h2),delete(h3),delete(h4), % delete(hdip) %________________________________________________________________________ case 'drawdip' %------------------------------------------------------------------------ % FORMAT spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip,sdip) % e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',1,1,sdip) % e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',[1:5],1,sdip) % when displaying a set of 'close' dipoles % this defines the limit between 'close' and 'far' % lim_cl = 10; %mm % No more limit. All source displayed as projected on mean 3D cut. if nargin < 2 error('At least i_seed') end i_seed = varargin{1}; if nargin<3 i_dip = 1; else i_dip = varargin{2}; end if nargin<4 if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else error('I can''t find sdip structure'); end else sdip = varargin{3}; st.vols{1}.sdip = sdip; end if any(i_seed>sdip.n_seeds) | i_dip>(sdip.n_dip+1) error('Wrong i_seed or i_dip index in spm_eeg_inv_ecd_DrawDip'); end % Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously if i_dip == (sdip.n_dip+1) i_dip = 1:sdip.n_dip; end % if seed indexes passed is wrong (no convergence) remove the wrong ones i_seed(find(sdip.exitflag(i_seed)~=1)) = []; if isempty(i_seed) error('You passed the wrong seed indexes...') end if size(i_seed,2)==1, i_seed=i_seed'; end % Display business %----------------- loc_mm = sdip.loc{i_seed(1)}(:,i_dip); if length(i_seed)>1 % unit = ones(1,sdip.n_dip); for ii = i_seed(2:end) loc_mm = loc_mm + sdip.loc{ii}(:,i_dip); end loc_mm = loc_mm/length(i_seed); end if length(i_dip)>1 loc_mm = mean(loc_mm,2); end % Place the underlying image at right cuts spm_orthviews('Reposition',loc_mm); if length(i_dip)>1 tabl_seed_dip = [kron(ones(length(i_dip),1),i_seed') ... kron(i_dip',ones(length(i_seed),1))]; else tabl_seed_dip = [i_seed' ones(length(i_seed),1)*i_dip]; end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % First point to consider % loc_mm = sdip.loc{i_seed(1)}(:,i_dip); % % % PLace the underlying image at right cuts % spm_orthviews('Reposition',loc_mm); % % spm_orthviews('Reposition',loc_vx); % % spm_orthviews('Xhairs','off') % % % if i_seed = set, Are there other dipoles close enough ? % tabl_seed_dip=[i_seed(1) i_dip]; % table summarising which set & dip to use. % if length(i_seed)>1 % unit = ones(1,sdip.n_dip); % for ii = i_seed(2:end)' % d2 = sqrt(sum((sdip.loc{ii}-loc_mm*unit).^2)); % l_cl = find(d2<=lim_cl); % if ~isempty(l_cl) % for jj=l_cl % tabl_seed_dip = [tabl_seed_dip ; [ii jj]]; % end % end % end % end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Scaling, according to all dipoles in the selected seed sets. % The time displayed is the one corresponding to the maximum EEG power ! Mn_j = -1; l3 = -2:0; for ii = 1:length(i_seed) for jj = 1:sdip.n_dip Mn_j = max([Mn_j sqrt(sum(sdip.j{ii}(jj*3+l3,sdip.Mtb).^2))]); end end st.vols{1}.sdip.tabl_seed_dip = tabl_seed_dip; % Display all dipoles, the 1st one + the ones close enough. % Run through the 6 colors and 9 markers to differentiate the dipoles. % NOTA: 2 dipoles coming from the same set will have same colour/marker ind = 1 ; dip_h = zeros(6,size(tabl_seed_dip,1),1); % each dipole displayed has 6 handles: % 2 per view (2*3): one for the line, the other for the circle js_m = zeros(3,1); % Deal with case of multiple i_seed and i_dip displayed. % make sure dipole from same i_seed have same colour but different marker. pi_dip = find(diff(tabl_seed_dip(:,2))); if isempty(pi_dip) % i.e. only one dip displayed per seed, use old fashion for ii=1:size(tabl_seed_dip,1) if ii>1 if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1) ind = ind+1; end end ic = mod(ind-1,Ncolors)+1; im = fix(ind/Ncolors)+1; loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2)); js = sdip.j{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb); dip_h(:,ii) = add1dip(loc_pl,js/Mn_j*20,marker(im),colors(ic),st.vols{1}.ax,Fig,st.bb); js_m = js_m+js; end else for ii=1:pi_dip(1) if ii>1 if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1) ind = ind+1; end end ic = mod(ind-1,Ncolors)+1; for jj=1:sdip.n_dip im = mod(jj-1,Nmarker)+1; loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,jj); js = sdip.j{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb); js_m = js_m+js; dip_h(:,ii+(jj-1)*pi_dip(1)) = ... add1dip(loc_pl,js/Mn_j*20,marker(im),colors(ic), ... st.vols{1}.ax,Fig,st.bb); end end end st.vols{1}.sdip.ax = dip_h; % Display dipoles orientation and strength js_m = js_m/size(tabl_seed_dip,1); [th,phi,Ijs_m] = cart2sph(js_m(1),js_m(2),js_m(3)); Njs_m = round(js_m'/Ijs_m*100)/100; Angle = round([th phi]*1800/pi)/10; set(sdip.hdl.hor1,'String',[num2str(Njs_m(1)),' ',num2str(Njs_m(2)), ... ' ',num2str(Njs_m(3))]); set(sdip.hdl.hor2,'String',[num2str(Angle(1)),' ',num2str(Angle(2))]); set(sdip.hdl.int,'String',Ijs_m); % Change the colour of toggle button of dipoles actually displayed for ii=tabl_seed_dip(:,1) set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 1 .7]); end %________________________________________________________________________ case 'clearall' %------------------------------------------------------------------------ % Clears all dipoles, and reset the toggle buttons if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else error('I can''t find sdip structure'); end disp('Clears all dipoles') spm_eeg_inv_ecd_DrawDip('ClearDip'); for ii=1:st.vols{1}.sdip.n_seeds if sdip.exitflag(ii)==1 set(st.vols{1}.sdip.hdl.hseed(ii),'Value',0); end end set(st.vols{1}.sdip.hdl.hdip,'Value',1); %________________________________________________________________________ case 'chgseed' %------------------------------------------------------------------------ % Changes the seeds displayed % disp('Change seed') sdip = st.vols{1}.sdip; if isfield(sdip,'tabl_seed_dip') prev_seeds = p_seed(sdip.tabl_seed_dip); else prev_seeds = []; end l_seed = zeros(sdip.n_seeds,1); for ii=1:sdip.n_seeds if sdip.exitflag(ii)==1 l_seed(ii) = get(sdip.hdl.hseed(ii),'Value'); end end l_seed = find(l_seed); % Modify the list of seeds displayed if length(l_seed)==0 % Nothing left displayed i_seed=[]; elseif isempty(prev_seeds) % Just one dipole added, nothing before i_seed=l_seed; elseif length(prev_seeds)>length(l_seed) % One seed removed i_seed = prev_seeds; for ii=1:length(l_seed) p = find(prev_seeds==l_seed(ii)); if ~isempty(p) prev_seeds(p) = []; end % prev_seeds is left with the index of the one removed end i_seed(find(i_seed==prev_seeds)) = []; % Remove the dipole & change the button colour spm_eeg_inv_ecd_DrawDip('ClearDip',prev_seeds); set(sdip.hdl.hseed(prev_seeds),'BackgroundColor',[.7 .7 .7]); else % One dipole added i_seed = prev_seeds; for ii=1:length(prev_seeds) p = find(prev_seeds(ii)==l_seed); if ~isempty(p) l_seed(p) = []; end % l_seed is left with the index of the one added end i_seed = [i_seed ; l_seed]; end i_dip = get(sdip.hdl.hdip,'Value'); spm_eeg_inv_ecd_DrawDip('ClearDip'); if ~isempty(i_seed) spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip); end %________________________________________________________________________ case 'chgdip' %------------------------------------------------------------------------ % Changes the dipole index for the first seed displayed disp('Change dipole') sdip = st.vols{1}.sdip; i_dip = get(sdip.hdl.hdip,'Value'); if isfield(sdip,'tabl_seed_dip') i_seed = p_seed(sdip.tabl_seed_dip); else i_seed = []; end if ~isempty(i_seed) spm_eeg_inv_ecd_DrawDip('ClearDip') spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip); end %________________________________________________________________________ case 'cleardip' %------------------------------------------------------------------------ % FORMAT spm_eeg_inv_ecd_DrawDip('ClearDip',seed_i) % e.g. spm_eeg_inv_ecd_DrawDip('ClearDip') % clears all displayed dipoles % e.g. spm_eeg_inv_ecd_DrawDip('ClearDip',1) % clears the first dipole displayed if nargin>2 seed_i = varargin{1}; else seed_i = 0; end if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else return; % I don't do anything, as I can't find sdip strucure end if isfield(sdip,'ax') Nax = size(sdip.ax,2); else return; % I don't do anything, as I can't find axes info end if seed_i==0 % removes everything for ii=1:Nax for jj=1:6 delete(sdip.ax(jj,ii)); end end for ii=sdip.tabl_seed_dip(:,1) set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 .7 .7]); end sdip = rmfield(sdip,'tabl_seed_dip'); sdip = rmfield(sdip,'ax'); elseif seed_i<=Nax % remove one seed only l_seed = find(sdip.tabl_seed_dip(:,1)==seed_i); for ii=l_seed for jj=1:6 delete(sdip.ax(jj,ii)); end end sdip.ax(:,l_seed) = []; sdip.tabl_seed_dip(l_seed,:) = []; else error('Trying to clear unspecified dipole'); end st.vols{1}.sdip = sdip; %________________________________________________________________________ otherwise, warning('Unknown action string') end; warning(sw); return; %________________________________________________________________________ %________________________________________________________________________ %________________________________________________________________________ %________________________________________________________________________ % % SUBFUNCTIONS %________________________________________________________________________ %________________________________________________________________________ function dh = add1dip(loc,js,mark,col,ax,Fig,bb) % Plots the dipoles on the 3 views % Then returns the handle to the plots loc(1,:) = loc(1,:) - bb(1,1)+1; loc(2,:) = loc(2,:) - bb(1,2)+1; loc(3,:) = loc(3,:) - bb(1,3)+1; % +1 added to be like John's orthview code dh = zeros(6,1); figure(Fig) % Transverse slice, # 1 set(Fig,'CurrentAxes',ax{1}.ax) set(ax{1}.ax,'NextPlot','add') dh(1) = plot(loc(1),loc(2),[mark,col],'LineWidth',2); dh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2); set(ax{1}.ax,'NextPlot','replace') % Coronal slice, # 2 set(Fig,'CurrentAxes',ax{2}.ax) set(ax{2}.ax,'NextPlot','add') dh(3) = plot(loc(1),loc(3),[mark,col],'LineWidth',2); dh(4) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2); set(ax{2}.ax,'NextPlot','replace') % Sagital slice, # 3 set(Fig,'CurrentAxes',ax{3}.ax) set(ax{3}.ax,'NextPlot','add') % dh(5) = plot(dim(2)-loc(2),loc(3),[mark,col],'LineWidth',2); % dh(6) = plot(dim(2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2); dh(5) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',2); dh(6) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2); set(ax{3}.ax,'NextPlot','replace') return %________________________________________________________________________ function pr_seed = p_seed(tabl_seed_dip) % Gets the list of seeds used in the previous display ls = sort(tabl_seed_dip(:,1)); if length(ls)==1 pr_seed = ls; else pr_seed = ls([find(diff(ls)) ; length(ls)]); end
github
spm/spm5-master
spm_eeg_display_ui.m
.m
spm5-master/spm_eeg_display_ui.m
25,402
utf_8
25f7e44690f054e724956833781be5da
function Heeg = spm_eeg_display_ui(varargin) % user interface for displaying EEG/MEG channel data. % Heeg = spm_eeg_display_ui(varargin) % % optional argument: % S - struct % fields of S: % D - EEG struct % Hfig - Figure (or axes) to work in (Defaults to SPM graphics window) % rebuild - indicator variable: if defined spm_eeg_display_ui has been % called after channel selection % % output: % Heeg - Handle of resulting figure %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Stefan Kiebel % $Id: spm_eeg_display_ui.m 955 2007-10-17 15:15:09Z rik $ if nargin == 1 S = varargin{1}; end if nargin == 0 | ~isfield(S, 'rebuild') try D = S.D; catch D = spm_select(1, '\.mat$', 'Select EEG mat file'); try D = spm_eeg_ldata(D); catch error(sprintf('Trouble reading file %s', D)); end end if ~isfield(D.channels, 'Bad') D.channels.Bad = []; end if D.Nevents == 1 & ~isfield(D.events, 'start') errordlg({'Continuous data cannot be displayed (yet).', 'Epoch first please.'}); return; end % units, default EEG if ~isfield(D, 'units') D.units = '\muV'; end try % Use your own window F = S.Hfig; catch % use SPM graphics window F = findobj('Tag', 'Graphics'); if isempty(F) F = spm_figure('create','Graphics','Graphics','on'); end end set(F, 'SelectionType', 'normal'); handles = guihandles(F); handles.colour = {[0 0 1], [1 0 0], [0 1 0], [1 0 1]}; % variable needed to store current trial listbox selection handles.Tselection = 1; % fontsize used troughout % (better compute that fontsize) % FS1 = spm('FontSize', 14); FS1 = spm('FontSize', 8); figure(F);clf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % setup of GUI elements %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Slider for trial number %------------------------ if D.Nevents > 1 % text above slider uicontrol(F, 'Style', 'text', 'Units', 'normalized',... 'String', 'Trial number',... 'Position',[0.11 0.072 0.15 0.029],... 'HorizontalAlignment', 'right', 'FontSize', FS1,... 'BackgroundColor', 'w'); handles.trialslider = uicontrol(F, 'Tag', 'trialslider', 'Style', 'slider',... 'Min', 1, 'Max', D.Nevents, 'Value', 1, 'Units',... 'normalized', 'Position', [0.05 0.045 0.25 0.03],... 'SliderStep', [1/(D.Nevents-1) min(D.Nevents-1, 10/(D.Nevents-1))],... 'TooltipString', 'Choose trial number',... 'Callback', @trialslider_update,... 'Parent', F, 'Interruptible', 'off'); % frame for trialslider text uicontrol(F, 'Style','Frame','BackgroundColor',spm('Colour'), 'Units',... 'normalized', 'Position',[0.05 0.019 0.25 0.031]); % trials slider texts uicontrol(F, 'Style', 'text', 'Units', 'normalized',... 'String', '1',... 'Position',[0.06 0.02 0.07 0.029],... 'HorizontalAlignment', 'left', 'FontSize', FS1,... 'BackgroundColor', spm('Colour')); handles.trialtext = uicontrol(F, 'Style', 'text', 'Tag', 'trialtext',... 'Units', 'normalized',... 'String', int2str(get(handles.trialslider, 'Value')),... 'Position',[0.14 0.02 0.07 0.029],... 'HorizontalAlignment', 'center', 'FontSize', FS1,... 'BackgroundColor', spm('Colour')); uicontrol(F, 'Style', 'text', 'Units', 'normalized',... 'String', mat2str(D.Nevents),... 'Position',[0.23 0.02 0.06 0.029],... 'HorizontalAlignment', 'right', 'FontSize', FS1,... 'BackgroundColor', spm('Colour')); end % Scaling slider %----------------- % estimate of maximum scaling value if isfield (D,'Nfrequencies') handles.scalemax = 2*ceil(max(max(max(abs(D.data(setdiff(D.channels.eeg, D.channels.Bad), :,:, 1)))))); else % handles.scalemax = 2*ceil(max(max(max(abs(D.data(setdiff([1:D.Nchannels], D.channels.Bad), :, :)))))); handles.scalemax = 2*ceil(max(max(abs(D.data(setdiff(D.channels.eeg, D.channels.Bad), :, 1))))); end scale = handles.scalemax/2; % text above slider uicontrol(F, 'Style', 'text', 'Units', 'normalized',... 'String', 'Scaling',... 'Position',[0.37 0.072 0.15 0.029],... 'HorizontalAlignment', 'right', 'FontSize', FS1,... 'BackgroundColor', 'w'); % slider handles.scaleslider = uicontrol('Tag', 'scaleslider', 'Style', 'slider',... 'Min', 1, 'Max', handles.scalemax, 'Value', scale, 'Units',... 'normalized', 'Position', [0.35 0.045 0.25 0.03],... 'SliderStep', [1/(handles.scalemax-1) 10/(handles.scalemax-1)],... 'TooltipString', 'Choose scaling',... 'Callback', @scaleslider_update,... 'Parent', F); % frame for text uicontrol(F, 'Style','Frame','BackgroundColor',spm('Colour'), 'Units',... 'normalized', 'Position',[0.35 0.019 0.25 0.031]); % text uicontrol(F, 'Style', 'text', 'Units', 'normalized', 'String', '1',... 'Position',[0.36 0.02 0.07 0.029],... 'HorizontalAlignment', 'left', 'FontSize', FS1,... 'BackgroundColor',spm('Colour')); handles.scaletext = uicontrol(F, 'Style', 'text', 'Tag', 'scaletext',... 'Units', 'normalized',... 'String', mat2str(handles.scalemax/2),... 'Position',[0.44 0.02 0.07 0.029],... 'HorizontalAlignment', 'center', 'FontSize', FS1,... 'BackgroundColor',spm('Colour')); uicontrol(F, 'Style', 'text', 'Units', 'normalized',... 'String', mat2str(handles.scalemax),... 'Position',[0.52 0.02 0.07 0.029],... 'HorizontalAlignment', 'right', 'FontSize', FS1,... 'BackgroundColor',spm('Colour')); %--------------------- % Save pushbutton uicontrol('Tag', 'savebutton', 'Style', 'pushbutton',... 'Units', 'normalized', 'Position', [0.615 0.02 0.11 0.03],... 'String', 'Save', 'FontSize', FS1,... 'BackgroundColor', spm('Colour'),... 'CallBack', @savebutton_update,... 'Parent', F); % Reject selection pushbutton uicontrol('Tag', 'channelselectbutton', 'Style', 'pushbutton',... 'Units', 'normalized', 'Position', [0.615 0.05 0.11 0.03],... 'String', 'Reject', 'FontSize', FS1,... 'BackgroundColor', spm('Colour'),... 'CallBack', @rejectbutton_update,... 'Parent', F); % Channel selection pushbutton uicontrol('Tag', 'channelselectbutton', 'Style', 'pushbutton',... 'Units', 'normalized', 'Position', [0.615 0.08 0.11 0.03],... 'String', 'Channels', 'FontSize', FS1,... 'BackgroundColor', spm('Colour'),... 'CallBack', @channelselectbutton_update,... 'Parent', F); % Topography display pushbutton uicontrol('Tag', '3Dtopographybutton', 'Style', 'pushbutton',... 'Units', 'normalized', 'Position', [0.615 0.11 0.11 0.03],... 'String', 'Topography', 'FontSize', FS1,... 'BackgroundColor', spm('Colour'),... 'CallBack', @scalp3d_select,... 'Parent', F); % trial listbox if D.Nevents > 1 trialnames = {}; for i = 1:D.Nevents trialnames{i} = [sprintf('%-12s', sprintf('trial %d', i)) sprintf('%-4s', sprintf('%d', D.events.code(i)))]; if D.events.reject(i) trialnames{i} = [trialnames{i} sprintf('%-8s', 'reject')]; end end handles.trialnames = trialnames; handles.triallistbox = uicontrol('Tag', 'triallistbox', 'Style', 'listbox',... 'Units', 'normalized', 'Position', [0.74 0.02 0.2 0.2],... 'Min', 0, 'Max', 2, 'String', trialnames,... 'HorizontalAlignment', 'left',... 'Value', 1,... 'BackgroundColor', [1 1 1],... 'CallBack', @triallistbox_update,... 'Parent', F); end % display file name at top of page uicontrol('Style', 'text', 'String', fullfile(D.path, D.fname),... 'Units', 'normalized', 'Position', [0.05 0.98 0.8 0.02],... 'Background', 'white', 'FontSize', 14, 'HorizontalAlignment', 'Left'); % axes with scaling and ms display axes('Position', [0.05 0.15 0.2 0.07]); set(gca, 'YLim', [-scale scale], 'XLim', [1 D.Nsamples],... 'XTick', [], 'YTick', [], 'LineWidth', 2); handles.scaletexttop = text(0, scale, sprintf(' %d', 2*scale), 'Interpreter', 'Tex',... 'FontSize', FS1, 'VerticalAlignment', 'top',... 'Tag', 'scaletext2'); ylabel(D.units, 'Interpreter', 'tex', 'FontSize', FS1); text(D.Nsamples, -scale, sprintf('%d', round((D.Nsamples-1)*1000/D.Radc)), 'Interpreter', 'Tex',... 'FontSize', FS1, 'HorizontalAlignment', 'right', 'VerticalAlignment', 'bottom'); xlabel('ms', 'Interpreter', 'tex', 'FontSize', FS1); % Added option to specify in advance only subset of channels to display RH % ([] = prompt for channel file; char = load channel file; No error checking yet) try D.gfx.channels = S.chans; if isempty(S.chans) S.chans = spm_select(1, '\.mat$', 'Select channel mat file'); S.load = load(S.chans); D.gfx.channels = S.load.Iselectedchannels; elseif ischar(S.chans) S.load = load(S.chans); D.gfx.channels = S.load.Iselectedchannels; end catch % channels to display, initially exclude bad channels D.gfx.channels = setdiff([1:length(D.channels.order)], D.channels.Bad); end else % this is a re-display with different set of selected channels, delete plots handles = guidata(S.Hfig); delete(handles.Heegaxes); handles.Heegaxes = []; for i = 1:length(handles.Heegfigures) if ~isempty(handles.Heegfigures{i}) delete(handles.Heegfigures{i}); end end D = S.D; F = S.Hfig; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subplots of EEG data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % position of plotting area for eeg data in graphics figure Pos = [0.03 0.23 0.95 0.75]; % Compute width of display boxes %------------------------------- Csetup = load(fullfile(spm('dir'), 'EEGtemplates', D.channels.ctf)); % indices of displayed channels (in order of data) handles.Cselection2 = D.gfx.channels; % indices of displayed channels (in order of the channel template file) handles.Cselection = D.channels.order(handles.Cselection2); p = Csetup.Cpos(:, handles.Cselection); Rxy = Csetup.Rxy; % ratio of x- to y-axis lengths Npos = size(p, 2); % number of positions if Npos > 1 % more than 1 channel for display for i = 1:Npos for j = 1:Npos % distance between channels d(i,j) = sqrt(sum((p(:,j)-p(:,i)).^2)); % their angle alpha(i,j) = acos((p(1,j)-p(1,i))/(d(i,j)+eps)); end end d = d/2; alpha(alpha > pi/2) = pi-alpha(alpha > pi/2); Talpha = asin(1/(sqrt(1+Rxy^2))); for i = 1:Npos for j = 1:Npos if alpha(i,j) <= Talpha x(i,j) = d(i,j)*cos(alpha(i,j)); else x(i,j) = Rxy*d(i,j)*cos(pi/2-alpha(i,j)); end end end % half length of axes in x-direction Lxrec = min(x(find(x~=0))); else % only one channel Lxrec = 1; end % coordinates of lower left corner of drawing boxes p(1, :) = p(1, :) - Lxrec; p(2, :) = p(2, :) - Lxrec/Rxy; % envelope of coordinates e = [min(p(1,:)) max(p(1,:))+2*Lxrec min(p(2,:)) max(p(2,:))+2*Lxrec/Rxy]; % shift coordinates to zero p(1,:) = p(1,:) - mean(e(1:2)); p(2,:) = p(2,:) - mean(e(3:4)); % scale such that envelope goes from -0.5 to 0.5 Sf = 0.5/max(max(abs(p(1,:))), (max(abs(p(2,:))))); p = Sf*p; Lxrec = Sf*Lxrec; % and back to centre p = p+0.5; % translate and scale to fit into drawing area of figure p(1,:) = Pos(3)*p(1,:)+Pos(1); p(2,:) = Pos(4)*p(2,:)+Pos(2); scale = get(handles.scaleslider, 'Value'); % cell vector for figures handles of separate single channel plots handles.Heegfigures = cell(1, Npos); % cell vector for axes handles of single channel plots handles.Heegaxes2 = cell(1, Npos); % plot the graphs for i = 1:Npos % uicontextmenus for axes Heegmenus(i) = uicontextmenu; if ismember(i, D.channels.Bad) labelstring = 'Declare as good'; else labelstring = 'Declare as bad'; end uimenu(Heegmenus(i), 'Label',... sprintf('%s (%d)', D.channels.name{handles.Cselection2(i)}, handles.Cselection2(i))); uimenu(Heegmenus(i), 'Separator', 'on'); uimenu(Heegmenus(i), 'Label', labelstring,... 'CallBack', {@switch_bad, i}); handles.Heegaxes(i) = axes('Position',... [p(1,i) p(2,i) 2*Lxrec*Pos(3) 2*Lxrec/Rxy*Pos(4)],... 'ButtonDownFcn', {@windowplot, i},... 'NextPlot', 'add',... 'Parent', F,... 'UIContextMenu', Heegmenus(i)); % make axes current axes(handles.Heegaxes(i)); for j = 1:length(handles.Tselection) if isfield(D,'Nfrequencies') h = imagesc(squeeze(D.data(handles.Cselection2(i), :,:, handles.Tselection(j)))); set(h, 'ButtonDownFcn', {@windowplot, i},... 'Clipping', 'off', 'UIContextMenu', Heegmenus(i)); else h = plot([-D.events.start:D.events.stop]*1000/D.Radc,... D.data(handles.Cselection2(i), :, handles.Tselection(j)),... 'Color', handles.colour{j}); set(h, 'ButtonDownFcn', {@windowplot, i},... 'Clipping', 'off', 'UIContextMenu', Heegmenus(i)); end end if isfield(D,'Nfrequencies') set(gca, 'ZLim', [-scale scale],... 'XLim', [1 D.Nsamples], 'YLim', [1 D.Nfrequencies], 'XTick', [], 'YTick', [], 'ZTick', [],'Box', 'off'); caxis([-scale scale]) colormap('jet') else if Lxrec > 0.1 % boxes are quite large set(gca, 'YLim', [-scale scale],... 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'Box', 'off', 'Xgrid', 'on'); else % otherwise remove tickmarks set(gca, 'YLim', [-scale scale],... 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'XTick', [], 'YTick', [], 'Box', 'off'); end end end handles.Lxrec = Lxrec; handles.D = D; % store handles guidata(F, handles); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % callbacks for GUI elements %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function switch_bad(hObject, events, ind) % update called from channel contextmenu handles = guidata(hObject); % ind1 = handles.Cselection(ind); ind2 = handles.Cselection2(ind); if ismember(ind2, handles.D.channels.Bad) handles.D.channels.Bad = setdiff(handles.D.channels.Bad, ind2); else handles.D.channels.Bad = unique([handles.D.channels.Bad ind2]); end Heegmenu = uicontextmenu; if ismember(ind, handles.D.channels.Bad) labelstring = sprintf('Declare %s as good', handles.D.channels.name{ind2}); else labelstring = sprintf('Declare %s as bad', handles.D.channels.name{ind2}); end uimenu(Heegmenu, 'Label', labelstring,... 'CallBack', {@switch_bad, ind}); set(handles.Heegaxes(ind), 'UIContextMenu', Heegmenu); guidata(hObject, handles); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function trialslider_update(hObject, events) % update called from trialslider handles = guidata(hObject); % slider value ind = round(get(hObject, 'Value')); set(hObject, 'Value', ind); % update triallistbox set(handles.triallistbox, 'Value', ind); % Update display of current trial number set(handles.trialtext, 'String', mat2str(ind)); % make plots draw_subplots(handles, ind) handles.Tselection = ind; guidata(hObject, handles); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function triallistbox_update(hObject, events) % update called from triallistbox handles = guidata(hObject); % listbox selection ind = get(hObject, 'Value'); if length(ind) > length(handles.colour) warning('Can only display %d different traces', length(handles.colour)); ind = handles.Tselection; set(hObject, 'Value', handles.Tselection); elseif length(ind) < 1 % can happen if user presses with cntl on already selected trial ind = handles.Tselection; set(hObject, 'Value', handles.Tselection); else % update trialslider to minimum of selection set(handles.trialslider, 'Value', min(ind)); % Update display of current trial number set(handles.trialtext, 'String', mat2str(min(ind))); handles.Tselection = ind; guidata(hObject, handles); % make plots draw_subplots(handles, ind) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function scaleslider_update(hObject, events) % update called from scaleslider handles = guidata(hObject); D = handles.D; % slider value scale = round(get(hObject, 'Value')); set(hObject, 'Value', scale); % text below slider set(handles.scaletext, 'String', mat2str(scale)); % text at top of figure set(handles.scaletexttop, 'String', sprintf(' %d', 2*scale)); % rescale plots for i = 1:length(handles.Heegaxes) % make ith subplot current axes(handles.Heegaxes(i)); if isfield(D,'Nfrequencies') set(gca, 'ZLim', [0 scale],... 'XLim', [1 D.Nsamples], 'YLim', [1 D.Nfrequencies], 'XTick', [], 'YTick', [], 'ZTick', [],'Box', 'off'); caxis([-scale scale]) else if handles.Lxrec > 0.1 % boxes are quite large set(gca, 'YLim', [-scale scale],... 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'Box', 'off', 'Xgrid', 'on'); else % otherwise remove tickmarks set(gca, 'YLim', [-scale scale],... 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'XTick', [], 'YTick', [], 'Box', 'off'); end end end % rescale separate windows (if there are any) for i = 1:length(handles.Heegfigures) if ~isempty(handles.Heegfigures{i}) axes(handles.Heegaxes2{i}); if isfield(D,'Nfrequencies') caxis([-scale scale]) else set(gca, 'YLim', [-scale scale],... 'XLim', [-D.events.start D.events.stop]*1000/D.Radc); end % update legend legend; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_subplots(handles, ind) % This function plots data in the subplots D = handles.D; scale = round(get(handles.scaleslider, 'Value')); for i = 1:length(handles.Heegaxes) % make ith subplot current axes(handles.Heegaxes(i)); cla set(handles.Heegaxes(i), 'NextPlot', 'add'); for j = 1:length(ind) if isfield(D,'Nfrequencies') h = imagesc(squeeze(D.data(handles.Cselection2(i), :,:, ind(j)))); set(h, 'ButtonDownFcn', {@windowplot, i},... 'Clipping', 'off'); else h = plot([-D.events.start:D.events.stop]*1000/D.Radc,... D.data(handles.Cselection2(i), :, ind(j)),... 'Color', handles.colour{j}); set(h, 'ButtonDownFcn', {@windowplot, i},... 'Clipping', 'off'); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function windowplot(hObject, events, ind) % this function plots data from channel ind in a separate window st = get(gcf,'SelectionType'); % do nothing for right button click if strcmp(st, 'alt') return; end handles = guidata(hObject); D = handles.D; w = handles.Heegfigures{ind}; % index to get the channel name if ~isempty(w) % delete the existing window delete(w); handles.Heegfigures{ind} = []; else handles.Heegfigures{ind} = figure; set(gcf,... 'Name', (sprintf('Channel %s', D.channels.name{handles.Cselection2(ind)})),... 'NumberTitle', 'off',... 'DeleteFcn', {@delete_Heegwindows, ind}); handles.Heegaxes2{ind} = gca; set(handles.Heegaxes2{ind}, 'NextPlot', 'add'); if isfield(D,'Nfrequencies') xlabel('ms', 'FontSize', 16); ylabel('Hz', 'FontSize', 16, 'Interpreter', 'Tex') for i = 1:length(handles.Tselection) imagesc([-D.events.start:D.events.stop]*1000/D.Radc,D.tf.frequencies,squeeze(D.data(handles.Cselection2(ind), :,:, handles.Tselection(i)))); end scale = get(handles.scaleslider, 'Value'); set(gca, 'ZLim', [-scale scale],... 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'YLim', [min(D.tf.frequencies) max(D.tf.frequencies)], 'Box', 'on'); colormap('jet') caxis([-scale scale]) else xlabel('ms', 'FontSize', 16); ylabel(D.units, 'FontSize', 16, 'Interpreter', 'Tex') for i = 1:length(handles.Tselection) plot([-D.events.start:D.events.stop]*1000/D.Radc,... D.data(handles.Cselection2(ind), :, handles.Tselection(i)),... 'Color', handles.colour{i}, 'LineWidth', 2); end scale = get(handles.scaleslider, 'Value'); set(gca, 'YLim', [-scale scale],... 'XLim', [-D.events.start D.events.stop]*1000/D.Radc, 'Box', 'on'); grid on end title(sprintf('%s (%d)', D.channels.name{handles.Cselection2(ind)}, handles.Cselection2(ind)), 'FontSize', 16); if D.Nevents > 1 legend(handles.trialnames{handles.Tselection}, 0); end % save handles structure to new figure guidata(handles.Heegaxes2{ind}, handles); end guidata(hObject, handles); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function delete_Heegwindows(hObject, events, ind) % deletes window of ind-th channel when delete was not via the eeg channel % plot in the SPM graphics window % returns handles structure of the graphics window handles = guidata(hObject); handles = guidata(handles.Graphics); delete(handles.Heegfigures{ind}); handles.Heegfigures{ind} = []; % save to handles structure in main Graphics figure guidata(handles.Graphics, handles); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function savebutton_update(hObject, events) % save updated matfile handles = guidata(hObject); D = handles.D; spm('Pointer', 'Watch'); % remove gfx struct D = rmfield(D, 'gfx'); if spm_matlab_version_chk('7') >= 0 save(fullfile(D.path, D.fname), '-V6', 'D'); else save(fullfile(D.path, D.fname), 'D'); end spm('Pointer', 'Arrow'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rejectbutton_update(hObject, events) % called from reject button handles = guidata(hObject); D = handles.D; % listbox selection ind = handles.Tselection; if ind > 1 % toggle first select only ind = ind(1); end if D.events.reject(ind) == 0 % reject this trial tmp = [sprintf('%-12s', sprintf('trial %d', ind)) sprintf('%-4s', sprintf('%d', D.events.code(ind)))]; tmp = [tmp sprintf('%-8s', 'reject')]; D.events.reject(ind) = 1; else % un-reject this trial tmp = [sprintf('%-12s', sprintf('trial %d', ind)) sprintf('%-4s', sprintf('%d', D.events.code(ind)))]; D.events.reject(ind) = 0; end handles.trialnames{ind} = tmp; set(handles.triallistbox, 'String', handles.trialnames); handles.D = D; guidata(hObject, handles); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function channelselectbutton_update(hObject, events) handles = guidata(hObject); D = handles.D; ind = spm_eeg_select_channels(D); D.gfx.channels = ind; S.D = D; S.rebuild = 1; S.Hfig = handles.Graphics; spm_eeg_display_ui(S); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function scalp3d_select(hObject, events) % ask user for peri-stimulus time and call scalp3d handles = guidata(hObject); D = handles.D; ok = 0; while ~ok try answer = spm_eeg_scalp_dlg; catch return end t = answer{1}; s = answer{2}; for n=1:length(t) if t(n) >= -D.events.start*1000/D.Radc... & t(n) <= D.events.stop*1000/D.Radc... & (strcmpi(s, '2d') | strcmpi(s, '3d')) ok = 1; end end end % call scalp2d or 3d %-------------------------------------------------------------------------- spm('Pointer', 'Watch');drawnow; if strcmpi(s, '2d') spm_eeg_scalp2d_ext(D, t, handles.Tselection(1)); else % change time for james' function t=round(t/1000*D.Radc)+D.events.start+1; if length(t) == 1 d = squeeze(D.data(D.channels.eeg, t, handles.Tselection(1))); else d = squeeze(mean(D.data(D.channels.eeg, t, handles.Tselection(1)), 2)); end if strmatch(D.channels.ctf,'bdf_setup.mat') spm_eeg_scalp3d(d); else errordlg({'This can only be used for 128 channel BDF data at the moment'}); return; end end spm('Pointer', 'Arrow');drawnow;
github
spm/spm5-master
spm_eeg_select_channels.m
.m
spm5-master/spm_eeg_select_channels.m
10,356
utf_8
a742f19989b2763640c0d4fb074fcadd
function varargout = spm_eeg_select_channels(varargin) % SPM_EEG_SELECT_CHANNELS M-file for spm_eeg_select_channels.fig % SPM_EEG_SELECT_CHANNELS, by itself, creates a new SPM_EEG_SELECT_CHANNELS or raises the existing % singleton*. % % H = SPM_EEG_SELECT_CHANNELS returns the handle to a new SPM_EEG_SELECT_CHANNELS or the handle to % the existing singleton*. % % SPM_EEG_SELECT_CHANNELS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SPM_EEG_SELECT_CHANNELS.M with the given input arguments. % % SPM_EEG_SELECT_CHANNELS('Property','Value',...) creates a new SPM_EEG_SELECT_CHANNELS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before spm_eeg_select_channels_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to spm_eeg_select_channels_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 spm_eeg_select_channels % Last Modified by GUIDE v2.5 13-Jul-2005 14:18:07 %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Stefan Kiebel % $Id: spm_eeg_select_channels.m 716 2007-01-16 21:13:50Z karl $ % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @spm_eeg_select_channels_OpeningFcn, ... 'gui_OutputFcn', @spm_eeg_select_channels_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin & isstr(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 spm_eeg_select_channels is made visible. function spm_eeg_select_channels_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 spm_eeg_select_channels (see VARARGIN) % Choose default command line output for spm_eeg_select_channels handles.output = hObject; % display graph of channels D = varargin{1}; P = fullfile(spm('dir'), 'EEGtemplates', D.channels.ctf); load(P) % correct Cnames (channel template file entries can have more than one % entry per channel) for i = 1:Nchannels if iscell(Cnames{i}) Cnames{i} = Cnames{i}{1}; end end figure(handles.figure1); Xrec = [-0.01 0.01 0.01 -0.01]; Yrec = [-0.01 -0.01 0.01 0.01]; Hpatch = cell(1, Nchannels); Htext = cell(1, Nchannels); Cselect = [1 1 1]; Cdeselect = [0.5 0.5 0.5]; ind = zeros(1,length(D.channels.order)); ind(D.gfx.channels) = 1; tmp = D.channels.order; % if D.channels.order isn't replaced by this variable -> strange error in 7.04 for i = 1:length(D.channels.order) if ~ind(i) Hpatch{i} = patch(Xrec+Cpos(1,tmp(i)), Yrec+Cpos(2,tmp(i)), Cdeselect, 'EdgeColor', 'none'); else Hpatch{i} = patch(Xrec+Cpos(1,tmp(i)), Yrec+Cpos(2,tmp(i)), Cselect, 'EdgeColor', 'none'); end Hpatch{i}; xy = get(Hpatch{i}, 'Vertices'); Htext{i} = text(min(xy(:,1)), max(xy(:,2)), Cnames{D.channels.order(i)}); set(Htext{i}, 'VerticalAlignment', 'middle', 'HorizontalAlignment', 'left'); end axis square axis off % listbox set(handles.listbox1, 'String', Cnames(D.channels.order([1:length(ind)]))); set(handles.listbox1, 'Value', find(ind)); handles.D = D; handles.ind = ind; handles.Cnames = Cnames; handles.Cpos = Cpos; handles.Nchannels = Nchannels; handles.Hpatch = Hpatch; handles.Htext = Htext; handles.Cselect = Cselect; handles.Cdeselect = Cdeselect; for i = 1:length(D.gfx.channels) % callbacks for patches and text if D.gfx.channels(i) ~=0 set(Hpatch{i}, 'ButtonDownFcn', {@patch_select, handles, i}); set(Htext{i}, 'ButtonDownFcn', {@patch_select, handles, i}); end end % Update handles structure guidata(hObject, handles); % UIWAIT makes spm_eeg_select_channels wait for user response (see UIRESUME) uiwait(handles.figure1); function patch_select(obj, eventdata, handles, i, ind); s = get(handles.listbox1, 'Value'); h = handles.Hpatch{i}; if ~ismember(i, s) set(h, 'FaceColor', handles.Cselect); set(handles.listbox1, 'Value', sort([s, i])); else set(h, 'FaceColor', handles.Cdeselect); set(handles.listbox1, 'Value', setdiff(s, i)); end % --- Outputs from this function are returned to the command line. function varargout = spm_eeg_select_channels_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) varargout{1} = handles.output; close(handles.figure1); % --- 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 set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); 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 = get(hObject,'String') returns listbox1 contents as cell array % contents{get(hObject,'Value')} returns selected item from listbox1 s = get(handles.listbox1, 'Value'); for i = 1:length(handles.ind) if ismember(i, s) set(handles.Hpatch{i}, 'FaceColor', handles.Cselect); else set(handles.Hpatch{i}, 'FaceColor', handles.Cdeselect); end end % --- Executes on button press in select. function select_Callback(hObject, eventdata, handles) % hObject handle to select (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Cycle through patch elements and recolour for i = 1:length(handles.ind) set(handles.Hpatch{i}, 'FaceColor', handles.Cselect); end % set all listbox entries to selected set(handles.listbox1, 'Value', [1:length(handles.ind)]); % --- Executes on button press in deselect. function deselect_Callback(hObject, eventdata, handles) % hObject handle to deselect (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Cycle through patch elements and recolour for i = 1:length(handles.ind) set(handles.Hpatch{i}, 'FaceColor', handles.Cdeselect); end % remove all listbox entries set(handles.listbox1, 'Value', []); % --- Executes on button press in load. function load_Callback(hObject, eventdata, handles) % hObject handle to load (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [P1, P2] = uigetfile('*.mat', 'Select file to load from'); load(fullfile(P2, P1), 'Iselectedchannels'); if ~exist('Iselectedchannels', 'var') errordlg('This file doesn''t contain channel indices', 'Wrong file?'); else if max(Iselectedchannels) > length(handles.ind) errordlg('This file doesn''t channel indices for these data', 'Wrong file?'); else set(handles.listbox1, 'Value', Iselectedchannels); for i = 1:handles.Nchannels if isempty(find(Iselectedchannels == i)) set(handles.Hpatch{i}, 'FaceColor', handles.Cdeselect); else set(handles.Hpatch{i}, 'FaceColor', handles.Cselect); end end end end % --- Executes on button press in save. function save_Callback(hObject, eventdata, handles) % hObject handle to save (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) Iselectedchannels = get(handles.listbox1, 'Value'); [P1, P2] = uiputfile('*.mat', 'Choose file name to save to'); if spm_matlab_version_chk('7') >= 0 save(fullfile(P2, P1), '-V6', 'Iselectedchannels'); else save(fullfile(P2, P1), 'Iselectedchannels'); end % --- Executes on button press in ok. function ok_Callback(hObject, eventdata, handles) % hObject handle to ok (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % returns vector of channel indices that are to be displayed if isempty(get(handles.listbox1, 'Value')) h = errordlg('Must select at least one channel!', 'Selection error', 'modal'); else % return indices of selected channels handles.output = get(handles.listbox1, 'Value'); guidata(hObject, handles); uiresume; end % --- Executes on button press in removebad. function removebad_Callback(hObject, eventdata, handles) % hObject handle to removebad (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) D = handles.D; s = get(handles.listbox1, 'Value'); s = setdiff(s, D.channels.Bad); set(handles.listbox1, 'Value', s); for i = 1:handles.Nchannels if isempty(find(s == i)) set(handles.Hpatch{i}, 'FaceColor', handles.Cdeselect); else set(handles.Hpatch{i}, 'FaceColor', handles.Cselect); end end
github
spm/spm5-master
spm_eeg_spm_ui.m
.m
spm5-master/spm_eeg_spm_ui.m
6,241
utf_8
06838efc9f6f9ed245832834e9095dd7
function [SPM] = spm_eeg_spm_ui(SPM) % user interface for calling general linear model specification for EEG % data % FORMAT [SPM] = spm_eeg_spm_ui(SPM) % %_______________________________________________________________________ % % Specification of M/EEG designs %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Stefan Kiebel, Karl Friston % $Id: spm_eeg_spm_ui.m 539 2006-05-19 17:59:30Z Darren $ %-GUI setup %----------------------------------------------------------------------- [Finter, Fgraph, CmdLine] = spm('FnUIsetup', 'EEG stats model setup', 0); spm_help('!ContextHelp', mfilename) % get design matrix and/or data %======================================================================= if ~nargin str = 'specify design or data'; if spm_input(str, 1, 'b', {'design','data'}, [1 0]); % specify a design %------------------------------------------------------- if sf_abort, spm_clf(Finter), return, end % choose either normal design specification or shortcut Oanalysis = spm_input('Choose design options', 1,'m',{'all options', 'ERP/ERF'}, [0 1]); SPM.eeg.Oanalysis = Oanalysis; SPM = spm_eeg_design(SPM); return else % get design %------------------------------------------------------- load(spm_select(1,'^SPM\.mat$','Select SPM.mat')); end else % get design matrix %--------------------------------------------------------------- SPM = spm_eeg_design(SPM); end % check data are specified %----------------------------------------------------------------------- try if ~nargin % was called by GUI, i.e. user _wants_ to input data SPM.xY = rmfield(SPM.xY, 'P'); end SPM.xY.P; catch if SPM.eeg.Oanalysis == 1 % ERP analysis, only 2 factors (condition and time) Nobs = SPM.eeg.Nlevels{1}; % Nerps tmp = spm_select(Nobs, 'image', 'Select ERPs (1st frame only)'); clear q for i = 1:Nobs [p1, p2, p3] = spm_fileparts(deblank(tmp(i, :))); q{i} = fullfile(p1, [p2 p3]); % removes ,1 end P = strvcat(q); else % defaults to normal design specification % get filenames %--------------------------------------------------------------- % Number of observations of factor 1 Nobs = size(SPM.eeg.Xind{end-1}, 1); P = []; oldpwd = pwd; for i = 1:Nobs str = sprintf('Select images for '); for j = 1:SPM.eeg.Nfactors-1 str = [str sprintf('%s(%d)', SPM.eeg.factor{j}, SPM.eeg.Xind{end-1}(i, j))]; if j < SPM.eeg.Nfactors-1, str = [str ', ']; end end Nimages = sum(all(kron(ones(size(SPM.eeg.Xind{end}, 1), 1), SPM.eeg.Xind{end-1}(i, :)) == SPM.eeg.Xind{end}(:, 1:end-1), 2)); q = spm_select(Nimages, 'image', str, '', oldpwd); P = strvcat(P, q); end end % place in data field %--------------------------------------------------------------- SPM.xY.P = P; end % Assemble remaining design parameters %======================================================================= spm_help('!ContextHelp',mfilename) %======================================================================= % - C O N F I G U R E D E S I G N %======================================================================= spm_clf(Finter); spm('FigName','Configuring, please wait...',Finter,CmdLine); spm('Pointer','Watch'); % get file identifiers %======================================================================= %-Map files %----------------------------------------------------------------------- fprintf('%-40s: ','Mapping files') %-# VY = spm_vol(SPM.xY.P); fprintf('%30s\n','...done') %-# %-check internal consistency of images %----------------------------------------------------------------------- spm_check_orientations(VY); %-place in xY %----------------------------------------------------------------------- SPM.xY.VY = VY; %-Only implicit mask %======================================================================= SPM.xM = struct('T', ones(length(VY), 1),... 'TH', -inf*ones(length(VY), 1),... 'I', 0,... 'VM', {[]},... 'xs', struct('Masking','analysis threshold')); %-Design description - for saving and display %======================================================================= % SPM.xsDes = struct(... % 'Basis_functions', SPM.xBF.name,... % 'Number_of_ERPs', sprintf('%d', sum(SPM.eeg.Nsub)*SPM.eeg.Ntypes),... % 'Sampling_frequency', sprintf('%0.2f {s}',SPM.xY.RT)... % ); % %-Save SPM.mat %----------------------------------------------------------------------- fprintf('%-40s: ','Saving SPM configuration') %-# if spm_matlab_version_chk('7') >= 0 save('SPM', 'SPM', '-V6'); else save('SPM', 'SPM'); end fprintf('%30s\n','...SPM.mat saved') %-# %-Display Design report %======================================================================= fprintf('%-40s: ','Design reporting') %-# fname = cat(1,{SPM.xY.VY.fname}'); % spm_DesRep('DesMtx',SPM.xX, SPM.xY.P); fprintf('%30s\n','...done') %-# %-End: Cleanup GUI %======================================================================= spm_clf(Finter) spm('FigName','Stats: configured',Finter,CmdLine); spm('Pointer','Arrow') fprintf('\n\n') %======================================================================= %- S U B - F U N C T I O N S %======================================================================= function abort = sf_abort %======================================================================= if exist(fullfile('.','SPM.mat')) str = { 'Current directory contains existing SPM file:',... 'Continuing will overwrite existing file!'}; abort = spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename); if abort, fprintf('%-40s: %30s\n\n',... 'Abort... (existing SPM files)',spm('time')), end else abort = 0; end
github
spm/spm5-master
spm_vol_check.m
.m
spm5-master/spm_vol_check.m
1,690
utf_8
210f1146cb0cf92ed4da535629b23c27
function [samef, msg, chgf] = spm_vol_check(varargin) % FORMAT [samef, msg, chgf] = spm_vol_check(V1, V2, ...) % checks spm_vol structs are in same space % % V1, V2, etc - arrays of spm_vol structs % % samef - true if images have same dims, mats % msg - cell array containing helpful message if not % chgf - logical Nx2 array of difference flags %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Matthew Brett % $Id: spm_vol_check.m 184 2005-05-31 13:23:32Z john $ [fnames samef msg] = deal({},1,{}); if nargin < 1, return; end; for i = 1:numel(varargin), vols = varargin{i}; if ~isempty(vols), if i == 1, dims = cat(3,vols(:).dim); mats = cat(3,vols(:).mat); else, dims = cat(3,dims,vols(:).dim); mats = cat(3,mats,vols(:).mat); end; fnames = {fnames{:}, vols(:).fname}; end; end; nimgs = size(dims, 3); if nimgs < 2, return; end; labs = {'dimensions', 'orientation & voxel size'}; dimf = any(diff(dims(:,1:3,:),1,3)); matf = any(any(diff(mats,1,3))); chgf = logical([dimf(:) matf(:)]); chgi = find(any(chgf, 2)); if ~isempty(chgi), samef = 0; e1 = chgi(1); msg = {['Images don''t all have the same ' ... sepcat(labs(chgf(e1,:)),', ')],... 'First difference between image pair:',... fnames{e1},... fnames{e1+1}}; end; return; function s = sepcat(strs, sep) % returns cell array of strings as one char string, separated by sep if nargin < 2, sep = ';'; end if isempty(strs), s = ''; return; end strs = strs(:)'; strs = [strs; repmat({sep}, 1, length(strs))]; s = [strs{1:end-1}]; return;
github
spm/spm5-master
spm_eeg_rdata_CTF275.m
.m
spm5-master/spm_eeg_rdata_CTF275.m
7,267
utf_8
b651bcf377a7a29b4661c27a68df88d3
function D = spm_eeg_rdata_CTF275(S) %%%% function to read in CTF data to Matlab try timewindow = S.tw; catch timewindow = spm_input('do you want to read in all the data','+1','yes|no',[1 0]); end if timewindow ==1 timeperiod='all'; else try timeperiod=S.timeperiod; catch [Finter,Fgraph,CmdLine] = spm('FnUIsetup','MEG data conversion ',0); str = 'time window'; YPos = -1; while 1 if YPos == -1 YPos = '+1'; end [timeperiod, YPos] = spm_input(str, YPos, 'r'); if timeperiod(1) < timeperiod(2), break, end str = sprintf('window must increase with time'); end end end try pre_data = ctf_read(S.Fdata,[],timeperiod,[],0); catch error('wrong folder name') end try Fchannels = S.Fchannels; catch Fchannels = spm_select(1, '\.mat$', 'Select channel template file', {}, fullfile(spm('dir'), 'EEGtemplates')); end D.channels.ctf = spm_str_manip(Fchannels, 't'); D.channels.Bad = []; % compatibility with some preprocessing functions D.channels.heog = 0; D.channels.veog = 0; D.channels.reference = 0; I = STRMATCH('UPPT0',pre_data.sensor.label) if isempty(I) warning(sprintf('No parallel port event channel was found in the CTF file: your data will be read without events')) D.events.time=[]; D.events.code=[]; else if length(I)==1 PP1=squeeze(pre_data.data(:,I(1))); else PP1=squeeze(pre_data.data(:,I(1))); PP2=squeeze(pre_data.data(:,I(2))); end D.events.time=[]; D.events.code=[]; inds=find(diff(PP1)>0); if ~isempty(inds) if length(PP1)<inds(end)+2 inds(end)=''; end D.events.code=PP1(inds+2)'; %changed to +2 from +1 to avoid errors when changing event code without passing by zero. D.events.time=inds'+1; end if length(I)>1 inds=find(diff(PP2)<0); if ~isempty(inds) D.events.code=[D.events.code,PP2(inds+1)'+255]; D.events.time=[D.events.time,inds'+1]; end end [X,I]=sort(D.events.time); D.events.time=D.events.time(I); D.events.code=D.events.code(I); end sens=strmatch('M',pre_data.sensor.label); D.channels.name=pre_data.sensor.label(sens); D.channels.order=[1:length(sens)]; D.Nchannels=length(sens); D.channels.eeg=[1:length(sens)]; D.Radc=pre_data.setup.sample_rate; D.Nsamples=pre_data.setup.number_samples; D.Nevents=pre_data.setup.number_trials; [pathstr,name,ext,versn]=spm_fileparts(pre_data.folder); D.datatype= 'float'; D.fname=[name,'.mat']; D.path=pwd; D.fnamedat=[name,'.dat']; if D.Nevents>1 D.events.start=pre_data.setup.pretrigger_samples; D.events.stop=D.Nsamples-pre_data.setup.pretrigger_samples-1; D.events.reject=zeros(1,D.Nevents); D.events.code=ones(1,D.Nevents); D.events.types=1; D.events.Ntypes=1; end D.scale = ones(D.Nchannels, 1, D.Nevents); fpd = fopen(fullfile(D.path, D.fnamedat), 'w'); for ev=1:D.Nevents for n=1:D.Nsamples fwrite(fpd, pre_data.data(n,sens,ev).*1e15, 'float'); end end fclose(fpd); % --- Save coil/sensor positions and orientations for source reconstruction (in mm) --- % - channel locations and orientations SensLoc = []; SensOr = []; for i = 1:length(pre_data.sensor.location); if any(pre_data.sensor.location(:,i)) & pre_data.sensor.label{i}(1) == 'M' SensLoc = [SensLoc; pre_data.sensor.location(:,i)']; SensOr = [SensOr ; pre_data.sensor.orientation(:,i)']; end end SensLoc = 10*SensLoc; % convertion from cm to mm if length(SensLoc) > 275 warning(sprintf('Found more than 275 channels!\n')); end [pth,nam,ext] = fileparts(D.fname); fic_sensloc = fullfile(D.path,[nam '_sensloc.mat']); fic_sensorient = fullfile(D.path,[nam '_sensorient.mat']); save(fic_sensloc, 'SensLoc'); save(fic_sensorient, 'SensOr'); clear SensLoc % for DCM/ERF: Use fieldtrip functions to retrieve sensor location and % orientation structure hdr = read_ctf_res4(findres4file(S.Fdata)); grad = fieldtrip_ctf2grad(hdr); D.channels.grad = grad; % - coil locations (in this order - NZ:nazion , LE: left ear , RE: right ear) CurrentDir = pwd; cd(pre_data.folder); hc_files = dir('*.hc'); if isempty(hc_files) warning(sprintf('Impossible to find head coil file\n')); elseif length(hc_files) > 1 hc_file = spm_select(1, '\.hc$', 'Select head coil file'); else hc_file = fullfile(pre_data.folder,hc_files.name); end clear hc_files for coils=1:3 fid = fopen(hc_file,'r'); testlines = fgetl(fid); t=0; while t==0 if coils==1 & strmatch('measured nasion coil position relative to head (cm):',testlines); t=1; for i = 1:3 % Nazion coordinates UsedLine = fgetl(fid); UsedLine = fliplr(deblank(fliplr(UsedLine))); [A,COUNT,ERRMSG,NEXTINDEX] = sscanf(UsedLine,'%c = %f'); if ~isempty(ERRMSG) | (COUNT ~= 2) warning(sprintf('Unable to read head coil file\n')); else NZ(i) = A(2); end end end if coils==2 & strmatch('measured left ear coil position relative to head (cm):',testlines); t=1; for i = 1:3 % Nazion coordinates UsedLine = fgetl(fid); UsedLine = fliplr(deblank(fliplr(UsedLine))); [A,COUNT,ERRMSG,NEXTINDEX] = sscanf(UsedLine,'%c = %f'); if ~isempty(ERRMSG) | (COUNT ~= 2) warning(sprintf('Unable to read head coil file\n')); else LE(i) = A(2); end end end if coils==3 & strmatch('measured right ear coil position relative to head (cm):',testlines); t=1; for i = 1:3 % Nazion coordinates UsedLine = fgetl(fid); UsedLine = fliplr(deblank(fliplr(UsedLine))); [A,COUNT,ERRMSG,NEXTINDEX] = sscanf(UsedLine,'%c = %f'); if ~isempty(ERRMSG) | (COUNT ~= 2) warning(sprintf('Unable to read head coil file\n')); else RE(i) = A(2); end end end testlines = fgetl(fid); end fclose(fid); end CoiLoc = 10*[NZ ; LE ; RE]; % convertion from cm to mm cd(CurrentDir); fic_sensloc = fullfile(D.path,[nam '_fidloc_meeg.mat']); save(fic_sensloc,'CoiLoc'); clear hc_file CoiLoc UnusedLines UsedLine A COUNT ERRMSG NEXTINDEX % ------- D.modality = 'MEG'; D.units = 'femto T'; if spm_matlab_version_chk('7') >= 0 save(fullfile(D.path, D.fname), '-V6', 'D'); else save(fullfile(D.path, D.fname), 'D'); end % find file name if truncated or with uppercase extension % added by Arnaud Delorme June 15, 2004 % ------------------------------------------------------- function res4name = findres4file( folder ) res4name = dir([ folder filesep '*.res4' ]); if isempty(res4name) res4name = dir([ folder filesep '*.RES4' ]); end if isempty(res4name) error('No file with extension .res4 or .RES4 in selected folder'); else res4name = [ folder filesep res4name.name ]; end; return
github
spm/spm5-master
spm_fmri_spm_ui.m
.m
spm5-master/spm_fmri_spm_ui.m
18,967
utf_8
66b6af6d5d22fc23cfbb10e11fcf0d6f
function [SPM] = spm_fmri_spm_ui(SPM) % Setting up the general linear model for fMRI time-series % FORMAT [SPM] = spm_fmri_spm_ui(SPM) % % creates SPM with the following fields % % xY: [1x1 struct] - data stucture % nscan: [double] - vector of scans per session % xBF: [1x1 struct] - Basis function stucture (see spm_fMRI_design) % Sess: [1x1 struct] - Session stucture (see spm_fMRI_design) % xX: [1x1 struct] - Design matric stucture (see spm_fMRI_design) % xGX: [1x1 struct] - Global variate stucture % xVi: [1x1 struct] - Non-sphericity stucture % xM: [1x1 struct] - Masking stucture % xsDes: [1x1 struct] - Design description stucture % % % SPM.xY % P: [n x ? char] - filenames % VY: [n x 1 struct] - filehandles % RT: Repeat time % % SPM.xGX % % iGXcalc: {'none'|'Scaling'} - Global normalization option % sGXcalc: 'mean voxel value' - Calculation method % sGMsca: 'session specific' - Grand mean scaling % rg: [n x 1 double] - Global estimate % GM: 100 - Grand mean % gSF: [n x 1 double] - Global scaling factor % % SPM.xVi % Vi: {[n x n sparse]..} - covariance components % form: {'none'|'AR(1)'} - form of non-sphericity % % SPM.xM % T: [n x 1 double] - Masking index % TH: [n x 1 double] - Threshold % I: 0 % VM: - Mask filehandles % xs: [1x1 struct] - cellstr description % % (see also spm_spm_ui) % %____________________________________________________________________________ % % spm_fmri_spm_ui configures the design matrix, data specification and % filtering that specify the ensuing statistical analysis. These % arguments are passed to spm_spm that then performs the actual parameter % estimation. % % The design matrix defines the experimental design and the nature of % hypothesis testing to be implemented. The design matrix has one row % for each scan and one column for each effect or explanatory variable. % (e.g. regressor or stimulus function). The parameters are estimated in % a least squares sense using the general linear model. Specific profiles % within these parameters are tested using a linear compound or contrast % with the T or F statistic. The resulting statistical map constitutes % an SPM. The SPM{T}/{F} is then characterized in terms of focal or regional % differences by assuming that (under the null hypothesis) the components of % the SPM (i.e. residual fields) behave as smooth stationary Gaussian fields. % % spm_fmri_spm_ui allows you to (i) specify a statistical model in terms % of a design matrix, (ii) associate some data with a pre-specified design % [or (iii) specify both the data and design] and then proceed to estimate % the parameters of the model. % Inferences can be made about the ensuing parameter estimates (at a first % or fixed-effect level) in the results section, or they can be re-entered % into a second (random-effect) level analysis by treating the session or % subject-specific [contrasts of] parameter estimates as new summary data. % Inferences at any level obtain by specifying appropriate T or F contrasts % in the results section to produce SPMs and tables of p values and statistics. % % spm_fmri_spm calls spm_fMRI_design which allows you to configure a % design matrix in terms of events or epochs. % % spm_fMRI_design allows you to build design matrices with separable % session-specific partitions. Each partition may be the same (in which % case it is only necessary to specify it once) or different. Responses % can be either event- or epoch related, The only distinction is the duration % of the underlying input or stimulus function. Mathematically they are both % modeled by convolving a series of delta (stick) or box functions (u), % indicating the onset of an event or epoch with a set of basis % functions. These basis functions model the hemodynamic convolution, % applied by the brain, to the inputs. This convolution can be first-order % or a generalized convolution modeled to second order (if you specify the % Volterra option). [The same inputs are used by the hemodynamic model or % or dynamic causal models which model the convolution explicitly in terms of % hidden state variables (see spm_hdm_ui and spm_dcm_ui).] % Basis functions can be used to plot estimated responses to single events % once the parameters (i.e. basis function coefficients) have % been estimated. The importance of basis functions is that they provide % a graceful transition between simple fixed response models (like the % box-car) and finite impulse response (FIR) models, where there is one % basis function for each scan following an event or epoch onset. The % nice thing about basis functions, compared to FIR models, is that data % sampling and stimulus presentation does not have to be synchronized % thereby allowing a uniform and unbiased sampling of peri-stimulus time. % % Event-related designs may be stochastic or deterministic. Stochastic % designs involve one of a number of trial-types occurring with a % specified probably at successive intervals in time. These % probabilities can be fixed (stationary designs) or time-dependent % (modulated or non-stationary designs). The most efficient designs % obtain when the probabilities of every trial type are equal. % A critical issue in stochastic designs is whether to include null events % If you wish to estimate the evoke response to a specific event % type (as opposed to differential responses) then a null event must be % included (even if it is not modeled explicitly). % % The choice of basis functions depends upon the nature of the inference % sought. One important consideration is whether you want to make % inferences about compounds of parameters (i.e. contrasts). This is % the case if (i) you wish to use a SPM{T} to look separately at % activations and deactivations or (ii) you with to proceed to a second % (random-effect) level of analysis. If this is the case then (for % event-related studies) use a canonical hemodynamic response function % (HRF) and derivatives with respect to latency (and dispersion). Unlike % other bases, contrasts of these effects have a physical interpretation % and represent a parsimonious way of characterising event-related % responses. Bases such as a Fourier set require the SPM{F} for % inference. % % See spm_fMRI_design for more details about how designs are specified. % % Serial correlations in fast fMRI time-series are dealt with as % described in spm_spm. At this stage you need to specify the filtering % that will be applied to the data (and design matrix) to give a % generalized least squares (GLS) estimate of the parameters required. % This filtering is important to ensure that the GLS estimate is % efficient and that the error variance is estimated in an unbiased way. % % The serial correlations will be estimated with a ReML (restricted % maximum likelihood) algorithm using an autoregressive AR(1) model % during parameter estimation. This estimate assumes the same % correlation structure for each voxel, within each session. The ReML % estimates are then used to correct for non-sphericity during inference % by adjusting the statistics and degrees of freedom appropriately. The % discrepancy between estimated and actual intrinsic (i.e. prior to % filtering) correlations are greatest at low frequencies. Therefore % specification of the high-pass filter is particularly important. % % High-pass filtering is implemented at the level of the % filtering matrix K (as opposed to entering as confounds in the design % matrix). The default cutoff period is 128 seconds. Use 'explore design' % to ensure this cutof is not removing too much experimental variance. % Note that high-pass filtering uses a residual forming matrix (i.e. % it is not a convolution) and is simply to a way to remove confounds % without estimating their parameters explicitly. The constant term % is also incorporated into this filter matrix. % %----------------------------------------------------------------------- % Refs: % % Friston KJ, Holmes A, Poline J-B, Grasby PJ, Williams SCR, Frackowiak % RSJ & Turner R (1995) Analysis of fMRI time-series revisited. NeuroImage % 2:45-53 % % Worsley KJ and Friston KJ (1995) Analysis of fMRI time-series revisited - % again. NeuroImage 2:178-181 % % Friston KJ, Frith CD, Frackowiak RSJ, & Turner R (1995) Characterising % dynamic brain responses with fMRI: A multivariate approach NeuroImage - % 2:166-172 % % Frith CD, Turner R & Frackowiak RSJ (1995) Characterising evoked % hemodynamics with fMRI Friston KJ, NeuroImage 2:157-165 % % Josephs O, Turner R and Friston KJ (1997) Event-related fMRI, Hum. Brain % Map. 0:00-00 % %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Karl Friston, Jean-Baptiste Poline & Christian Buchel % $Id: spm_fmri_spm_ui.m 592 2006-08-14 18:36:21Z Darren $ SCCSid = '$Rev: 592 $'; %-GUI setup %----------------------------------------------------------------------- [Finter,Fgraph,CmdLine] = spm('FnUIsetup','fMRI stats model setup',0); spm_help('!ContextHelp',mfilename) global defaults % get design matrix and/or data %======================================================================= if ~nargin str = 'specify design or data'; if spm_input(str,1,'b',{'design','data'},[1 0]); % specify a design %------------------------------------------------------- if sf_abort, spm_clf(Finter), return, end SPM = spm_fMRI_design; spm_fMRI_design_show(SPM); return else % get design %------------------------------------------------------- load(spm_select(1,'^SPM\.mat$','Select SPM.mat')); end else % get design matrix %--------------------------------------------------------------- SPM = spm_fMRI_design(SPM); end % get Repeat time %----------------------------------------------------------------------- try RT = SPM.xY.RT; catch RT = spm_input('Interscan interval {secs}','+1'); SPM.xY.RT = RT; end % session and scan number %----------------------------------------------------------------------- nscan = SPM.nscan; nsess = length(nscan); % check data are specified %----------------------------------------------------------------------- try SPM.xY.P; catch % get filenames %--------------------------------------------------------------- P = []; for i = 1:nsess str = sprintf('select scans for session %0.0f',i); q = spm_select(nscan(i),'image',str); P = strvcat(P,q); end % place in data field %--------------------------------------------------------------- SPM.xY.P = P; end % Assemble remaining design parameters %======================================================================= spm_help('!ContextHelp',mfilename) SPM.SPMid = spm('FnBanner',mfilename,SCCSid); % Global normalization %----------------------------------------------------------------------- nsess = length(SPM.nscan); try SPM.xGX.iGXcalc; catch spm_input('Global intensity normalisation...',1,'d',mfilename) str = 'remove Global effects'; SPM.xGX.iGXcalc = spm_input(str,'+1','scale|none',{'Scaling' 'None'}); end SPM.xGX.sGXcalc = 'mean voxel value'; SPM.xGX.sGMsca = 'session specific'; % High-pass filtering and serial correlations %======================================================================= % low frequency confounds %----------------------------------------------------------------------- try myLastWarn = 0; HParam = [SPM.xX.K(:).HParam]; if ( length(HParam) == 1 ) HParam = HParam*ones(1,nsess); elseif ( length(HParam) ~= nsess ) % Uh Oh - somehow the number of specified HParam values and % sessions don't match. Throw an error, continue with manual HPF % specification, and alert! the user. % go to the catch block myLastWarn = 1; error; end catch % specify low frequency confounds %--------------------------------------------------------------- spm_input('Temporal autocorrelation options','+1','d',mfilename) switch spm_input('High-pass filter?','+1','b','none|specify'); case 'specify' % default 128 seconds %------------------------------------------------------- HParam = 128*ones(1,nsess); str = 'cutoff period (secs)'; HParam = spm_input(str,'+1','e',HParam,[1 nsess]); case 'none' % Inf seconds (i.e. constant term only) %------------------------------------------------------- HParam = Inf*ones(1,nsess); end % This avoids displaying the warning if we had existed the try block % at the level of accessing HParam. if myLastWarn warning('SPM:InvalidHighPassFilterSpec',... ['Different number of High-pass filter values and sessions.\n',... 'HPF filter configured manually. Design setup will proceed.']); clear myLastWarn end end % create and set filter struct %--------------------------------------------------------------- for i = 1:nsess K(i) = struct( 'HParam', HParam(i),... 'row', SPM.Sess(i).row,... 'RT', SPM.xY.RT); end SPM.xX.K = spm_filter(K); % intrinsic autocorrelations (Vi) %----------------------------------------------------------------------- try cVi = SPM.xVi.form; catch % Contruct Vi structure for non-sphericity ReML estimation %=============================================================== str = 'Correct for serial correlations?'; cVi = {'none','AR(1)'}; cVi = spm_input(str,'+1','b',cVi); end % create Vi struct %----------------------------------------------------------------------- if ~ischar(cVi) % AR coeficient[s] specified %----------------------------------------------------------------------- SPM.xVi.Vi = spm_Ce(nscan,cVi(1:3)); cVi = ['AR( ' sprintf('%0.1f ',cVi) ')']; else switch lower(cVi) case 'none' % xVi.V is i.i.d %--------------------------------------------------------------- SPM.xVi.V = speye(sum(nscan)); cVi = 'i.i.d'; otherwise % otherwise assume AR(0.2) in xVi.Vi %--------------------------------------------------------------- SPM.xVi.Vi = spm_Ce(nscan,0.2); cVi = 'AR(0.2)'; end end SPM.xVi.form = cVi; %======================================================================= % - C O N F I G U R E D E S I G N %======================================================================= spm_clf(Finter); spm('FigName','Configuring, please wait...',Finter,CmdLine); spm('Pointer','Watch'); % get file identifiers %======================================================================= %-Map files %----------------------------------------------------------------------- fprintf('%-40s: ','Mapping files') %-# VY = spm_vol(SPM.xY.P); fprintf('%30s\n','...done') %-# %-check internal consistency of images %----------------------------------------------------------------------- spm_check_orientations(VY); %-place in xY %----------------------------------------------------------------------- SPM.xY.VY = VY; %-Compute Global variate %======================================================================= GM = 100; q = length(VY); g = zeros(q,1); fprintf('%-40s: %30s','Calculating globals',' ') %-# for i = 1:q fprintf('%s%30s',repmat(sprintf('\b'),1,30),sprintf('%4d/%-4d',i,q)) %-# g(i) = spm_global(VY(i)); end fprintf('%s%30s\n',repmat(sprintf('\b'),1,30),'...done') %-# % scale if specified (otherwise session specific grand mean scaling) %----------------------------------------------------------------------- gSF = GM./g; if strcmp(lower(SPM.xGX.iGXcalc),'none') for i = 1:nsess gSF(SPM.Sess(i).row) = GM./mean(g(SPM.Sess(i).row)); end end %-Apply gSF to memory-mapped scalefactors to implement scaling %----------------------------------------------------------------------- for i = 1:q SPM.xY.VY(i).pinfo(1:2,:) = SPM.xY.VY(i).pinfo(1:2,:)*gSF(i); end %-place global variates in global structure %----------------------------------------------------------------------- SPM.xGX.rg = g; SPM.xGX.GM = GM; SPM.xGX.gSF = gSF; %-Masking structure automatically set to 80% of mean %======================================================================= try TH = g.*gSF*defaults.mask.thresh; catch TH = g.*gSF*0.8; end SPM.xM = struct( 'T', ones(q,1),... 'TH', TH,... 'I', 0,... 'VM', {[]},... 'xs', struct('Masking','analysis threshold')); %-Design description - for saving and display %======================================================================= for i = 1:nsess, ntr(i) = length(SPM.Sess(i).U); end Fstr = sprintf('[min] Cutoff period %d seconds',min(HParam)); SPM.xsDes = struct(... 'Basis_functions', SPM.xBF.name,... 'Number_of_sessions', sprintf('%d',nsess),... 'Trials_per_session', sprintf('%-3d',ntr),... 'Interscan_interval', sprintf('%0.2f {s}',SPM.xY.RT),... 'High_pass_Filter', sprintf('Cutoff: %d {s}',SPM.xX.K(1).HParam),... 'Global_calculation', SPM.xGX.sGXcalc,... 'Grand_mean_scaling', SPM.xGX.sGMsca,... 'Global_normalisation', SPM.xGX.iGXcalc); %-Save SPM.mat %----------------------------------------------------------------------- fprintf('%-40s: ','Saving SPM configuration') %-# if spm_matlab_version_chk('7') >= 0, save('SPM', 'SPM', '-V6'); else save('SPM', 'SPM'); end; fprintf('%30s\n','...SPM.mat saved') %-# %-Display Design report %======================================================================= fprintf('%-40s: ','Design reporting') %-# fname = cat(1,{SPM.xY.VY.fname}'); spm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes) fprintf('%30s\n','...done') %-# %-End: Cleanup GUI %======================================================================= spm_clf(Finter) spm('FigName','Stats: configured',Finter,CmdLine); spm('Pointer','Arrow') fprintf('\n\n') %======================================================================= %- S U B - F U N C T I O N S %======================================================================= function abort = sf_abort %======================================================================= if exist(fullfile('.','SPM.mat')) str = { 'Current directory contains existing SPM file:',... 'Continuing will overwrite existing file!'}; abort = spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename); if abort, fprintf('%-40s: %30s\n\n',... 'Abort... (existing SPM files)',spm('time')), end else abort = 0; end
github
spm/spm5-master
spm_input.m
.m
spm5-master/spm_input.m
83,619
utf_8
7a6922167daf9947097ce8acfb9902eb
function varargout = spm_input(varargin) % Comprehensive graphical and command line input function % FORMATs (given in Programmers Help) %_______________________________________________________________________ % % spm_input handles most forms of interactive user input for SPM. % (File selection is handled by spm_select.m) % % There are five types of input: String, Evaluated, Conditions, Buttons % and Menus: These prompt for string input; string input which is % evaluated to give a numerical result; selection of one item from a % set of buttons; selection of an item from a menu. % % - STRING, EVALUATED & CONDITION input - % For STRING, EVALUATED and CONDITION input types, a prompt is % displayed adjacent to an editable text entry widget (with a lilac % background!). Clicking in the entry widget allows editing, pressing % <RETURN> or <ENTER> enters the result. You must enter something, % empty answers are not accepted. A default response may be pre-specified % in the entry widget, which will then be outlined. Clicking the border % accepts the default value. % % Basic editing of the entry widget is supported *without* clicking in % the widget, provided no other graphics widget has the focus. (If a % widget has the focus, it is shown highlighted with a thin coloured % line. Clicking on the window background returns the focus to the % window, enabling keyboard accelerators.). This enables you to type % responses to a sequence of questions without having to repeatedly % click the mouse in the text widgets. Supported are BackSpace and % Delete, line kill (^U). Other standard ASCII characters are appended % to the text in the entry widget. Press <RETURN> or <ENTER> to submit % your response. % % A ContextMenu is provided (in the figure background) giving access to % relevant utilities including the facility to load input from a file % (see spm_load.m and examples given below): Click the right button on % the figure background. % % For EVALUATED input, the string submitted is evaluated in the base % MatLab workspace (see MatLab's `eval` command) to give a numerical % value. This permits the entry of numerics, matrices, expressions, % functions or workspace variables. I.e.: % i) - a number, vector or matrix e.g. "[1 2 3 4]" % "[1:4]" % "1:4" % ii) - an expression e.g. "pi^2" % "exp(-[1:36]/5.321)" % iii) - a function (that will be invoked) e.g. "spm_load('tmp.dat')" % (function must be on MATLABPATH) "input_cov(36,5.321)" % iv) - a variable from the base workspace % e.g. "tmp" % % The last three options provide a great deal of power: spm_load will % load a matrix from an ASCII data file and return the results. When % called without an argument, spm_load will pop up a file selection % dialog. Alternatively, this facility can be gained from the % ContextMenu. The second example assummes a custom funcion called % input_cov has been written which expects two arguments, for example % the following file saved as input_cov.m somewhere on the MATLABPATH % (~/matlab, the matlab subdirectory of your home area, and the current % directory, are on the MATLABPATH by default): % % function [x] = input_cov(n,decay) % % data input routine - mono-exponential covariate % % FORMAT [x] = input_cov(n,decay) % % n - number of time points % % decay - decay constant % x = exp(-[1:n]/decay); % % Although this example is trivial, specifying large vectors of % empirical data (e.g. reaction times for 72 scans) is efficient and % reliable using this device. In the last option, a variable called tmp % is picked up from the base workspace. To use this method, set the % variables in the MatLab base workspace before starting an SPM % procedure (but after starting the SPM interface). E.g. % >> tmp=exp(-[1:36]/5.321) % % Occasionally a vector of a specific length will be required: This % will be indicated in the prompt, which will start with "[#]", where % # is the length of vector(s) required. (If a matrix is entered then % at least one dimension should equal #.) % % Occasionally a specific type of number will be required. This should % be obvious from the context. If you enter a number of the wrong type, % you'll be alerted and asked to re-specify. The types are i) Real % numbers; ii) Integers; iii) Whole numbers [0,1,2,3,...] & iv) Natural % numbers [1,2,3,...] % % CONDITIONS type input is for getting indicator vectors. The features % of evaluated input described above are complimented as follows: % v) - a compressed list of digits 0-9 e.g. "12121212" % ii) - a list of indicator characters e.g. "abababab" % a-z mapped to 1-26 in alphabetical order, *except* r ("rest") % which is mapped to zero (case insensitive, [A:Z,a:z] only) % ...in addition the response is checked to ensure integer condition indices. % Occasionally a specific number of conditions will be required: This % will be indicated in the prompt, which will end with (#), where # is % the number of conditions required. % % CONTRAST type input is for getting contrast weight vectors. Enter % contrasts as row-vectors. Contrast weight vectors will be padded with % zeros to the correct length, and checked for validity. (Valid % contrasts are estimable, which are those whose weights vector is in % the row-space of the design matrix.) % % Errors in string evaluation for EVALUATED & CONDITION types are % handled gracefully, the user notified, and prompted to re-enter. % % - BUTTON input - % For Button input, the prompt is displayed adjacent to a small row of % buttons. Press the approprate button. The default button (if % available) has a dark outline. Keyboard accelerators are available % (provided no graphics widget has the focus): <RETURN> or <ENTER> % selects the default button (if available). Typing the first character % of the button label (case insensitive) "presses" that button. (If % these Keys are not unique, then the integer keys 1,2,... "press" the % appropriate button.) % % The CommandLine variant presents a simple menu of buttons and prompts % for a selection. Any default response is indicated, and accepted if % an empty line is input. % % % - MENU input - % For Menu input, the prompt is displayed in a pull down menu widget. % Using the mouse, a selection is made by pulling down the widget and % releasing the mouse on the appropriate response. The default response % (if set) is marked with an asterisk. Keyboard accelerators are % available (provided no graphic widget has the focus) as follows: 'f', % 'n' or 'd' move forward to next response down; 'b', 'p' or 'u' move % backwards to the previous response up the list; the number keys jump % to the appropriate response number; <RETURN> or <ENTER> slelects the % currently displayed response. If a default is available, then % pressing <RETURN> or <ENTER> when the prompt is displayed jumps to % the default response. % % The CommandLine variant presents a simple menu and prompts for a selection. % Any default response is indicated, and accepted if an empty line is % input. % % % - Combination BUTTON/EDIT input - % In this usage, you will be presented with a set of buttons and an % editable text widget. Click one of the buttons to choose that option, % or type your response in the edit widget. Any default response will % be shown in the edit widget. The edit widget behaves in the same way % as with the STRING/EVALUATED input, and expects a single number. % Keypresses edit the text widget (rather than "press" the buttons) % (provided no other graphics widget has the focus). A default response % can be selected with the mouse by clicking the thick border of the % edit widget. % % % - Comand line - % If YPos is 0 or global CMDLINE is true, then the command line is used. % Negative YPos overrides CMDLINE, ensuring the GUI is used, at % YPos=abs(YPos). Similarly relative YPos beginning with '!' % (E.g.YPos='!+1') ensures the GUI is used. % % spm_input uses the SPM 'Interactive' window, which is 'Tag'ged % 'Interactive'. If there is no such window, then the current figure is % used, or an 'Interactive' window created if no windows are open. % %----------------------------------------------------------------------- % Programers help is contained in the main body of spm_input.m %----------------------------------------------------------------------- % See : input.m (MatLab Reference Guide) % See also : spm_select.m (SPM file selector dialog) % : spm_input.m (Input wrapper function - handles batch mode) %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Andrew Holmes % $Id: spm_input.m 2818 2009-03-03 11:04:15Z guillaume $ %======================================================================= % - FORMAT specifications for programers %======================================================================= % generic - [p,YPos] = spm_input(Prompt,YPos,Type,...) % string - [p,YPos] = spm_input(Prompt,YPos,'s',DefStr) % string+ - [p,YPos] = spm_input(Prompt,YPos,'s+',DefStr) % evaluated - [p,YPos] = spm_input(Prompt,YPos,'e',DefStr,n) % - natural - [p,YPos] = spm_input(Prompt,YPos,'n',DefStr,n,mx) % - whole - [p,YPos] = spm_input(Prompt,YPos,'w',DefStr,n,mx) % - integer - [p,YPos] = spm_input(Prompt,YPos,'i',DefStr,n) % - real - [p,YPos] = spm_input(Prompt,YPos,'r',DefStr,n,mm) % condition - [p,YPos] = spm_input(Prompt,YPos,'c',DefStr,n,m) % contrast - [p,YPos] = spm_input(Prompt,YPos,'x',DefStr,n,X) % permutation- [p,YPos] = spm_input(Prompt,YPos,'p',DefStr,P,n) % button - [p,YPos] = spm_input(Prompt,YPos,'b',Labels,Values,DefItem) % button/edit combo's (edit for string or typed scalar evaluated input) % [p,YPos] = spm_input(Prompt,YPos,'b?1',Labels,Values,DefStr,mx) % ...where ? in b?1 specifies edit widget type as with string & eval'd input % - [p,YPos] = spm_input(Prompt,YPos,'n1',DefStr,mx) % - [p,YPos] = spm_input(Prompt,YPos,'w1',DefStr,mx) % button dialog % - [p,YPos] = spm_input(Prompt,YPos,'bd',... % Labels,Values,DefItem,Title) % menu - [p,YPos] = spm_input(Prompt,YPos,'m',Labels,Values,DefItem) % display - spm_input(Message,YPos,'d',Label) % display - (GUI only) spm_input(Alert,YPos,'d!',Label) % % yes/no - [p,YPos] = spm_input(Prompt,YPos,'y/n',Values,DefItem) % buttons (shortcut) where Labels is a bar delimited string % - [p,YPos] = spm_input(Prompt,YPos,Labels,Values,DefItem) % % NB: Natural numbers are [1:Inf), Whole numbers are [0:Inf) % % -- Parameters (input) -- % % Prompt - prompt string % - Defaults (missing or empty) to 'Enter an expression' % % YPos - (numeric) vertical position {1 - 12} % - overriden by global CMDLINE % - 0 for command line % - negative to force GUI % - (string) relative vertical position E.g. '+1' % - relative to last position used % - overriden by global CMDLINE % - YPos(1)=='!' forces GUI E.g. '!+1' % - '_' is a shortcut for the lowest GUI position % - Defaults (missing or empty) to '+1' % % Type - type of interrogation % - 's'tring % - 's+' multi-line string % - p returned as cellstr (nx1 cell array of strings) % - DefStr can be a cellstr or string matrix % - 'e'valuated string % - 'n'atural numbers % - 'w'hole numbers % - 'i'ntegers % - 'r'eals % - 'c'ondition indicator vector % - 'x' - contrast entry % - If n(2) or design matrix X is specified, then % contrast matrices are padded with zeros to have % correct length. % - if design matrix X is specified, then contrasts are % checked for validity (i.e. in the row-space of X) % (checking handled by spm_SpUtil) % - 'b'uttons % - 'bd' - button dialog: Uses MatLab's questdlg % - For up to three buttons % - Prompt can be a cellstr with a long multiline message % - CmdLine support as with 'b' type % - button/edit combo's: 'be1','bn1','bw1','bi1','br1' % - second letter of b?1 specifies type for edit widget % - 'n1' - single natural number (buttons 1,2,... & edit) % - 'w1' - single whole number (buttons 0,1,... & edit) % - 'm'enu pulldown % - 'y/n' : Yes or No buttons % (See shortcuts below) % - bar delimited string : buttons with these labels % (See shortcuts below) % - Defaults (missing or empty) to 'e' % % DefStr - Default string to be placed in entry widget for string and % evaluated types % - Defaults to '' % % n ('e', 'c' & 'p' types) % - Size of matrix requred % - NaN for 'e' type implies no checking - returns input as evaluated % - length of n(:) specifies dimension - elements specify size % - Inf implies no restriction % - Scalar n expanded to [n,1] (i.e. a column vector) % (except 'x' contrast type when it's [n,np] for np % - E.g: [n,1] & [1,n] (scalar n) prompt for an n-vector, % returned as column or row vector respectively % [1,Inf] & [Inf,1] prompt for a single vector, % returned as column or row vector respectively % [n,Inf] & [Inf,n] prompts for any number of n-vectors, % returned with row/column dimension n respectively. % [a,b] prompts for an 2D matrix with row dimension a and % column dimension b % [a,Inf,b] prompt for a 3D matrix with row dimension a, % page dimension b, and any column dimension. % - 'c' type can only deal with single vectors % - NaN for 'c' type treated as Inf % - Defaults (missing or empty) to NaN % % n ('x'type) % - Number of contrasts required by 'x' type (n(1)) % ( n(2) can be used specify length of contrast vectors if ) % ( a design matrix isn't passed ) % - Defaults (missing or empty) to 1 - vector contrast % % mx ('n', 'w', 'n1', 'w1', 'bn1' & 'bw1' types) % - Maximum value (inclusive) % % mm ('r' type) % - Maximum and minimum values (inclusive) % % m - Number of unique conditions required by 'c' type % - Inf implies no restriction % - Defaults (missing or empty) to Inf - no restriction % % P - set (vector) of numbers of which a permutation is required % % X - Design matrix for contrast checking in 'x' type % - Can be either a straight matrix or a space structure (see spm_sp) % - Column dimension of design matrix specifies length of contrast % vectors (overriding n(2) is specified). % % Title - Title for questdlg in 'bd' type % % Labels - Labels for button and menu types. % - string matrix, one label per row % - bar delimited string % E.g. 'AnCova|Scaling|None' % % Values - Return values corresponding to Labels for button and menu types % - j-th row is returned if button / menu item j is selected % (row vectors are transposed) % - Defaults (missing or empty) to - (button) Labels % - ( menu ) menu item numbers % % DefItem - Default item number, for button and menu types. % % -- Parameters (output) -- % p - results % YPos - Optional second output argument returns GUI position just used % %----------------------------------------------------------------------- % WINDOWS: % % spm_input uses the SPM 'Interactive' 'Tag'ged window. If this isn't % available and no figures are open, an 'Interactive' SPM window is % created (`spm('CreateIntWin')`). If figures are available, then the % current figure is used *unless* it is 'Tag'ged. % %----------------------------------------------------------------------- % SHORTCUTS: % % Buttons SHORTCUT - If the Type parameter is a bar delimited string, then % the Type is taken as 'b' with the specified labels, and the next parameter % (if specified) is taken for the Values. % % Yes/No question shortcut - p = spm_input(Prompt,YPos,'y/n') expands % to p = spm_input(Prompt,YPos,'b','yes|no',...), enabling easy use of % spm_input for yes/no dialogue. Values defaults to 'yn', so 'y' or 'n' % is returned as appropriate. % %----------------------------------------------------------------------- % EXAMPLES: % ( Specified YPos is overriden if global CMDLINE is ) % ( true, when the command line versions are used. ) % % p = spm_input % Command line input of an evaluated string, default prompt. % p = spm_input('Enter a value',1) % Evaluated string input, prompted by 'Enter a value', in % position 1 of the dialog figure. % p = spm_input(str,'+1','e',0.001) % Evaluated string input, prompted by contents of string str, % in next position of the dialog figure. % Default value of 0.001 offered. % p = spm_input(str,2,'e',[],5) % Evaluated string input, prompted by contents of string str, % in second position of the dialog figure. % Vector of length 5 required - returned as column vector % p = spm_input(str,2,'e',[],[Inf,5]) % ...as above, but can enter multiple 5-vectors in a matrix, % returned with 5-vectors in rows % p = spm_input(str,0,'c','ababab') % Condition string input, prompted by contents of string str % Uses command line interface. % Default string of 'ababab' offered. % p = spm_input(str,0,'c','010101') % As above, but default string of '010101' offered. % [p,YPos] = spm_input(str,'0','s','Image') % String input, same position as last used, prompted by str, % default of 'Image' offered. YPos returns GUI position used. % p = spm_input(str,'-1','y/n') % Yes/No buttons for question with prompt str, in position one % before the last used Returns 'y' or 'n'. % p = spm_input(str,'-1','y/n',[1,0],2) % As above, but returns 1 for yes response, 0 for no, % with 'no' as the default response % p = spm_input(str,4,'AnCova|Scaling') % Presents two buttons labelled 'AnCova' & 'Scaling', with % prompt str, in position 4 of the dialog figure. Returns the % string on the depresed button, where buttons can be pressed % with the mouse or by the respective keyboard accelerators % 'a' & 's' (or 'A' & 'S'). % p = spm_input(str,-4,'b','AnCova|Scaling',[],2) % As above, but makes "Scaling" the default response, and % overrides global CMDLINE % p = spm_input(str,0,'b','AnCova|Scaling|None',[1,2,3]) % Prompts for [A]ncova / [S]caling / [N]one in MatLab command % window, returns 1, 2, or 3 according to the first character % of the entered string as one of 'a', 's', or 'n' (case % insensitive). % p = spm_input(str,1,'b','AnCova',1) % Since there's only one button, this just displays the response % in GUI position 1 (or on the command line if global CMDLINE % is true), and returns 1. % p = spm_input(str,'+0','br1','None|Mask',[-Inf,NaN],0.8) % Presents two buttons labelled "None" & "Mask" (which return % -Inf & NaN if clicked), together with an editable text widget % for entry of a single real number. The default of 0.8 is % initially presented in the edit window, and can be selected by % pressing return. % Uses the previous GUI position, unless global CMDLINE is true, % in which case a command-line equivalent is used. % p = spm_input(str,'+0','w1') % Prompts for a single whole number using a combination of % buttons and edit widget, using the previous GUI position, % or the command line if global CMDLINE is true. % p = spm_input(str,'!0','m','Single Subject|Multi Subject|Multi Study') % Prints the prompt str in a pull down menu containing items % 'Single Subject', 'Multi Subject' & 'Multi Study'. When OK is % clicked p is returned as the index of the choice, 1,2, or 3 % respectively. Uses last used position in GUI, irrespective of % global CMDLINE % p = spm_input(str,5,'m',... % 'Single Subject|Multi Subject|Multi Study',... % ['SS';'MS';'SP'],2) % As above, but returns strings 'SS', 'MS', or 'SP' according to % the respective choice, with 'MS; as the default response. % p = spm_input(str,0,'m',... % 'Single Subject|Multi Subject|Multi Study',... % ['SS';'MS';'SP'],2) % As above, but the menu is presented in the command window % as a numbered list. % spm_input('AnCova, GrandMean scaling',0,'d') % Displays message in a box in the MatLab command window % [null,YPos]=spm_input('Session 1','+1','d!','fMRI') % Displays 'fMRI: Session 1' in next GUI position of the % 'Interactive' window. If CMDLINE is 1, then nothing is done. % Position used is returned in YPos. % %----------------------------------------------------------------------- % FORMAT h = spm_input(Prompt,YPos,'m!',Labels,cb,UD,XCB); % GUI PullDown menu utility - creates a pulldown menu in the Interactive window % FORMAT H = spm_input(Prompt,YPos,'b!',Labels,cb,UD,XCB); % GUI Buttons utility - creates GUI buttons in the Interactive window % % Prompt, YPos, Labels - as with 'm'enu/'b'utton types % cb - CallBack string % UD - UserData % XCB - Extended CallBack handling - allows different CallBack for each item, % and use of UD in CallBack strings. [Defaults to 1 for PullDown type % when multiple CallBacks specified, 0 o/w.] % H - Handle of 'PullDown' uicontrol / 'Button's % % In "normal" mode (when XCB is false), this is essentially a utility % to create a PullDown menu widget or set of buttons in the SPM % 'Interactive' figure, using positioning and Label definition % conveniences of the spm_input 'm'enu & 'b'utton types. If Prompt is % not empty, then the PullDown/Buttons appears on the right, with the % Prompt on the left, otherwise the PullDown/Buttons use the whole % width of the Interactive figure. The PopUp's CallBack string is % specified in cb, and [optional] UserData may be passed as UD. % % For buttons, a separate callback can be specified for each button, by % passing the callbacks corresponding to the Labels as rows of a % cellstr or string matrix. % % This "different CallBacks" facility can also be extended to the % PullDown type, using the "extended callback" mode (when XCB is % true). % In addition, in "extended callback", you can use UD to % refer to the UserData argument in the CallBack strings. (What happens % is this: The cb & UD are stored as fields in the PopUp's UserData % structure, and the PopUp's callback is set to spm_input('!m_cb'), % which reads UD into the functions workspace and eval's the % appropriate CallBack string. Note that this means that base % workspace variables are inaccessible (put what you need in UD), and % that any return arguments from CallBack functions are not passed back % to the base workspace). % % %----------------------------------------------------------------------- % UTILITY FUNCTIONS: % % FORMAT colour = spm_input('!Colour') % Returns colour for input widgets, as specified in COLOUR parameter at % start of code. % colour - [r,g,b] colour triple % % FORMAT [iCond,msg] = spm_input('!iCond',str,n,m) % Parser for special 'c'ondition type: Handles digit strings and % strings of indicator chars. % str - input string % n - length of condition vector required [defaut Inf - no restriction] % m - number of conditions required [default Inf - no restrictions] % iCond - Integer condition indicator vector % msg - status message % % FORMAT hM = spm_input('!InptConMen',Finter,H) % Sets a basic Input ContextMenu for the figure % Finter - figure to set menu in % H - handles of objects to delete on "crash out" option % hM - handle of UIContextMenu % % FORMAT [CmdLine,YPos] = spm_input('!CmdLine',YPos) % Sorts out whether to use CmdLine or not & canonicalises YPos % CmdLine - Binary flag % YPos - Position index % % FORMAT Finter = spm_input('!GetWin',F) % Locates (or creates) figure to work in % F - Interactive Figure, defaults to 'Interactive' % Finter - Handle of figure to use % % FORMAT [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp) % Raise window & jump pointer over question % RRec - Response rectangle of current question % F - Interactive Figure, Defaults to 'Interactive' % XDisp - X-displacement of cursor relative to RRec % PLoc - Pointer location before jumping % cF - Current figure before making F current. % % FORMAT [PLoc,cF] = spm_input('!PointerJumpBack',PLoc,cF) % Replace pointer and reset CurrentFigure back % PLoc - Pointer location before jumping % cF - Previous current figure % % FORMAT spm_input('!PrntPrmpt',Prompt,TipStr,Title) % Print prompt for CmdLine questioning % Prompt - prompt string, callstr, or string matrix % TipStr - tip string % Title - title string % % FORMAT [Frec,QRec,PRec,RRec] = spm_input('!InputRects',YPos,rec,F) % Returns rectangles (pixels) used in GUI % YPos - Position index % rec - Rectangle specifier: String, one of 'Frec','QRec','PRec','RRec' % Defaults to '', which returns them all. % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % FRec - Position of interactive window % QRec - Position of entire question % PRec - Position of prompt % RRec - Position of response % % FORMAT spm_input('!DeleteInputObj',F) % Deltes input objects (only) from figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % % FORMAT [CPos,hCPos] = spm_input('!CurrentPos',F) % Returns currently used GUI question positions & their handles % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % CPos - Vector of position indices % hCPos - (n x CPos) matrix of object handles % % FORMAT h = spm_input('!FindInputObj',F) % Returns handles of input GUI objects in figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % h - vector of object handles % % FORMAT [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine) % Returns next position index, specified by YPos % YPos - Absolute (integer) or relative (string) position index % Defaults to '+1' % F - Interactive Figure, defaults to spm_figure('FindWin','Interactive') % CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos) % NPos - Next position index % CPos & hCPos - as for !CurrentPos % % FORMAT NPos = spm_input('!SetNextPos',YPos,F,CmdLine) % Sets up for input at next position index, specified by YPos. This utility % function can be used stand-alone to implicitly set the next position % by clearing positions NPos and greater. % YPos - Absolute (integer) or relative (string) position index % Defaults to '+1' % F - Interactive Figure, defaults to spm_figure('FindWin','Interactive') % CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos) % NPos - Next position index % % FORMAT MPos = spm_input('!MaxPos',F,FRec3) % Returns maximum position index for figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % Not required if FRec3 is specified % FRec3 - Length of interactive figure in pixels % % FORMAT spm_input('!EditableKeyPressFcn',h,ch) % KeyPress callback for GUI string / eval input % % FORMAT spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch) % KeyPress callback for GUI buttons % % FORMAT spm_input('!PullDownKeyPressFcn',h,ch,DefItem) % KeyPress callback for GUI pulldown menus % % FORMAT spm_input('!m_cb') % Extended CallBack handler for 'p' PullDown utility type % % FORMAT spm_input('!dScroll',h,str) % Scroll text string in object h % h - handle of text object % Prompt - Text to scroll (Defaults to 'UserData' of h) % %----------------------------------------------------------------------- % SUBFUNCTIONS: % % FORMAT [Keys,Labs] = sf_labkeys(Labels) % Make unique character keys for the Labels, ignoring case. % Used with 'b'utton types. % % FORMAT [p,msg] = sf_eEval(str,Type,n,m) % Common code for evaluating various input types. % % FORMAT str = sf_SzStr(n,l) % Common code to construct prompt strings for pre-specified vector/matrix sizes % % FORMAT [p,msg] = sf_SzChk(p,n,msg) % Common code to check (& canonicalise) sizes of input vectors/matrices % %_______________________________________________________________________ % @(#)spm_input.m 2.8 Andrew Holmes 03/03/04 %-Parameters %======================================================================= COLOUR = get(0,'defaultUicontrolBackgroundColor'); PJump = 1; %-Jumping of pointer to question? TTips = 1; %-Use ToolTipStrings? (which can be annoying!) ConCrash = 1; %-Add "crash out" option to 'Interactive'fig.ContextMenu %-Condition arguments %======================================================================= if nargin<1|isempty(varargin{1}), Prompt=''; else, Prompt=varargin{1}; end if ~isempty(Prompt) & ischar(Prompt) & Prompt(1)=='!' %-Utility functions have Prompt string starting with '!' Type = Prompt; else %-Should be an input request: get Type & YPos if nargin<3|isempty(varargin{3}), Type='e'; else, Type=varargin{3}; end if any(Type=='|'), Type='b|'; end if nargin<2|isempty(varargin{2}), YPos='+1'; else, YPos=varargin{2}; end [CmdLine,YPos] = spm_input('!CmdLine',YPos); if ~CmdLine %-Setup for GUI use %-Locate (or create) figure to work in Finter = spm_input('!GetWin'); %-Find out which Y-position to use, setup for use YPos = spm_input('!SetNextPos',YPos,Finter,CmdLine); %-Determine position of objects [FRec,QRec,PRec,RRec]=spm_input('!InputRects',YPos,'',Finter); end end switch lower(Type) case {'s','s+','e','n','w','i','r','c','x','p'} %-String and evaluated input %======================================================================= %-Condition arguments if nargin<6|isempty(varargin{6}), m=[]; else, m=varargin{6}; end if nargin<5|isempty(varargin{5}), n=[]; else, n=varargin{5}; end if nargin<4, DefStr=''; else, DefStr=varargin{4}; end if strcmp(lower(Type),'s+') %-DefStr should be a cellstr for 's+' type. if isempty(DefStr), DefStr = {}; else, DefStr = cellstr(DefStr); end DefStr = DefStr(:); else %-DefStr needs to be a string if ~ischar(DefStr), DefStr=num2str(DefStr); end DefStr = DefStr(:)'; end strM=''; switch lower(Type) %-Type specific defaults/setup case 's', TTstr='enter string'; case 's+',TTstr='enter string - multi-line'; case 'e', TTstr='enter expression to evaluate'; case 'n', TTstr='enter expression - natural number(s)'; if ~isempty(m), strM=sprintf(' (in [1,%d])',m); TTstr=[TTstr,strM]; end case 'w', TTstr='enter expression - whole number(s)'; if ~isempty(m), strM=sprintf(' (in [0,%d])',m); TTstr=[TTstr,strM]; end case 'i', TTstr='enter expression - integer(s)'; case 'r', TTstr='enter expression - real number(s)'; if ~isempty(m), TTstr=[TTstr,sprintf(' in [%g,%g]',min(m),max(m))]; end case 'c', TTstr='enter indicator vector e.g. 0101... or abab...'; if ~isempty(m) & isfinite(m), strM=sprintf(' (%d)',m); end case 'x', TTstr='enter contrast matrix'; case 'p', if isempty(n), error('permutation of what?'), else, P=n(:)'; end if isempty(m), n = [1,length(P)]; end m = P; if ~length(setxor(m,[1:max(m)])) TTstr=['enter permutation of [1:',num2str(max(m)),']']; else TTstr=['enter permutation of [',num2str(m),']']; end otherwise, TTstr='enter expression'; end strN = sf_SzStr(n); if CmdLine %-Use CmdLine to get answer %----------------------------------------------------------------------- spm_input('!PrntPrmpt',[Prompt,strN,strM],TTstr) %-Do Eval Types in Base workspace, catch errors switch lower(Type), case 's' if ~isempty(DefStr) Prompt=[Prompt,' (Default: ',DefStr,' )']; end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end while isempty(str) spm('Beep') fprintf('! %s : enter something!\n',mfilename) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end end p = str; msg = ''; case 's+' fprintf(['Multi-line input: Type ''.'' on a line',... ' of its own to terminate input.\n']) if ~isempty(DefStr) fprintf('Default : (press return to accept)\n') fprintf(' : %s\n',DefStr{:}) end fprintf('\n') str = input('l001 : ','s'); while (isempty(str) | strcmp(str,'.')) & isempty(DefStr) spm('Beep') fprintf('! %s : enter something!\n',mfilename) str = input('l001 : ','s'); end if isempty(str) %-Accept default p = DefStr; else %-Got some input, allow entry of additional lines p = {str}; str = input(sprintf('l%03u : ',length(p)+1),'s'); while ~strcmp(str,'.') p = [p;{str}]; str = input(sprintf('l%03u : ',length(p)+1),'s'); end end msg = ''; otherwise if ~isempty(DefStr) Prompt=[Prompt,' (Default: ',DefStr,' )']; end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type,n,m); while ischar(p) spm('Beep'), fprintf('! %s : %s\n',mfilename,msg) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type,n,m); end end if ~isempty(msg), fprintf('\t%s\n',msg), end else %-Use GUI to get answer %----------------------------------------------------------------------- %-Create text and edit control objects %--------------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',[strN,Prompt,strM],... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData','',... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); %-Default button surrounding edit widget (if a DefStr given) %-Callback sets hPrmpt UserData, and EditWidget string, to DefStr % (Buttons UserData holds handles [hPrmpt,hEditWidget], set later) cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',... 'get(gcbo,''String'')),',... 'set(get(gcbo,''UserData'')*[0;1],''String'',',... 'get(gcbo,''String''))']; if ~isempty(DefStr) if iscellstr(DefStr), str=[DefStr{1},'...']; else, str=DefStr; end hDef = uicontrol(Finter,'Style','PushButton',... 'String',DefStr,... 'ToolTipString',... ['Click on border to accept default: ' str],... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',[],... 'BackgroundColor',COLOUR,... 'CallBack',cb,... 'Position',RRec+[-2,-2,+4,+4]); else hDef = []; end %-Edit widget: Callback puts string into hPrompts UserData cb = 'set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))'; h = uicontrol(Finter,'Style','Edit',... 'String',DefStr,... 'Max',strcmp(lower(Type),'s+')+1,... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',hPrmpt,... 'CallBack',cb,... 'Horizontalalignment','Left',... 'BackgroundColor','w',... 'Position',RRec); set(hDef,'UserData',[hPrmpt,h]) uifocus(h); if TTips, set(h,'ToolTipString',TTstr), end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,hDef,h]); cb = [ 'set(get(gcbo,''UserData''),''String'',',... '[''spm_load('''''',spm_select(1),'''''')'']), ',... 'set(get(get(gcbo,''UserData''),''UserData''),''UserData'',',... 'get(get(gcbo,''UserData''),''String''))']; uimenu(hM,'Label','load from text file','Separator','on',... 'CallBack',cb,'UserData',h) %-Bring window to fore & jump pointer to edit widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); %-Setup FigureKeyPressFcn for editing of entry widget without clicking set(Finter,'KeyPressFcn',[... 'spm_input(''!EditableKeyPressFcn'',',... 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',... '''Style'',''edit''),',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for edit, do eval Types in Base workspace, catch errors %--------------------------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input window cleared whilst waiting ',... 'for response: Bailing out!']), end str = get(hPrmpt,'UserData'); switch lower(Type), case 's' p = str; msg = ''; case 's+' p = cellstr(str); msg = ''; otherwise [p,msg] = sf_eEval(str,Type,n,m); while ischar(p) set(h,'Style','Text',... 'String',msg,'HorizontalAlignment','Center',... 'ForegroundColor','r') spm('Beep'), pause(2) set(h,'Style','Edit',... 'String',str,... 'HorizontalAlignment','Left',... 'ForegroundColor','k') %set(hPrmpt,'UserData',''); waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input window cleared ',... 'whilst waiting for response: Bailing out!']),end str = get(hPrmpt,'UserData'); [p,msg] = sf_eEval(str,Type,n,m); end end %-Fix edit window, clean up, reposition pointer, set CurrentFig back delete([hM,hDef]), set(Finter,'KeyPressFcn','') set(h,'Style','Text','HorizontalAlignment','Center',... 'ToolTipString',msg,... 'BackgroundColor',COLOUR) spm_input('!PointerJumpBack',PLoc,cF) drawnow end % (if CmdLine) %-Return response %----------------------------------------------------------------------- varargout = {p,YPos}; case {'b','bd','b|','y/n','be1','bn1','bw1','bi1','br1',... '-n1','n1','-w1','w1','m'} %-'b'utton & 'm'enu Types %======================================================================= %-Condition arguments switch lower(Type), case {'b','be1','bi1','br1','m'} m = []; Title = ''; if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=''; else, Labels =varargin{4}; end case 'bd' if nargin<7, Title=''; else, Title =varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=''; else, Labels =varargin{4}; end case 'y/n' Title = ''; if nargin<5, DefItem=[]; else, DefItem=varargin{5}; end if nargin<4, Values=[]; else, Values =varargin{4}; end if isempty(Values), Values='yn'; end Labels = {'yes','no'}; case 'b|' Title = ''; if nargin<5, DefItem=[]; else, DefItem=varargin{5}; end if nargin<4, Values=[]; else, Values =varargin{4}; end Labels = varargin{3}; case 'bn1' if nargin<7, m=[]; else, m=varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=[1:5]'; Values=[1:5]; Type='-n1'; else, Labels=varargin{4}; end case 'bw1' if nargin<7, m=[]; else, m=varargin{7}; end if nargin<6, DefItem=[]; else, DefItem=varargin{6}; end if nargin<5, Values=[]; else, Values =varargin{5}; end if nargin<4, Labels=[0:4]'; Values=[0:4]; Type='-w1'; else, Labels=varargin{4}; end case {'-n1','n1','-w1','w1'} if nargin<5, m=[]; else, m=varargin{5}; end if nargin<4, DefItem=[]; else, DefItem=varargin{4}; end switch lower(Type) case {'n1','-n1'}, Labels=[1:min([5,m])]'; Values=Labels'; Type='-n1'; case {'w1','-w1'}, Labels=[0:min([4,m])]'; Values=Labels'; Type='-w1'; end end %-Check some labels were specified if isempty(Labels), error('No Labels specified'), end if iscellstr(Labels), Labels=char(Labels); end %-Convert Labels "option" string to string matrix if required if ischar(Labels) & any(Labels=='|') OptStr=Labels; BarPos=find([OptStr=='|',1]); Labels=OptStr(1:BarPos(1)-1); for Bar = 2:sum(OptStr=='|')+1 Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1)); end end %-Set default Values for the Labels if isempty(Values) if strcmp(lower(Type),'m') Values=[1:size(Labels,1)]'; else Values=Labels; end else %-Make sure Values are in rows if size(Labels,1)>1 & size(Values,1)==1, Values = Values'; end %-Check numbers of Labels and Values match if (size(Labels,1)~=size(Values,1)) error('Labels & Values incompatible sizes'), end end %-Numeric Labels to strings if isnumeric(Labels) tmp = Labels; Labels = cell(size(tmp,1),1); for i=1:prod(size(tmp)), Labels{i}=num2str(tmp(i,:)); end Labels=char(Labels); end switch lower(Type), case {'b','bd','b|','y/n'} %-Process button types %======================================================================= %-Make unique character keys for the Labels, sort DefItem %--------------------------------------------------------------- nLabels = size(Labels,1); [Keys,Labs] = sf_labkeys(Labels); if ~isempty(DefItem) & any(DefItem==[1:nLabels]) DefKey = Keys(DefItem); else DefItem = 0; DefKey = ''; end if CmdLine %-Display question prompt spm_input('!PrntPrmpt',Prompt,'',Title) %-Build prompt %------------------------------------------------------- if ~isempty(Labs) Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' ']; for i = 2:nLabels Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' ']; end else Prmpt = ['[',Keys(1),'] ']; for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end end if DefItem Prmpt = [Prmpt,... ' (Default: ',deblank(Labels(DefItem,:)),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels) else str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end while isempty(str) | ~any(lower(Keys)==lower(str(1))) if ~isempty(str),fprintf('%c\t!Out of range\n',7),end str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end end k = find(lower(Keys)==lower(str(1))); end fprintf('\n') p = Values(k,:); if ischar(p), p=deblank(p); end elseif strcmp(lower(Type),'bd') if nLabels>3, error('at most 3 labels for GUI ''db'' type'), end tmp = cellstr(Labels); if DefItem tmp = [tmp; tmp(DefItem)]; Prompt = cellstr(Prompt); Prompt=Prompt(:); Prompt = [Prompt;{' '};... {['[default: ',tmp{DefItem},']']}]; else tmp = [tmp; tmp(1)]; end k = min(find(strcmp(tmp,... questdlg(Prompt,sprintf('%s%s: %s...',spm('ver'),... spm('GetUser',' (%s)'),Title),tmp{:})))); p = Values(k,:); if ischar(p), p=deblank(p); end else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets %-Create text and edit control objects %-'UserData' of prompt contains answer %------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',Prompt,... 'Tag',Tag,... 'UserData',[],... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); if nLabels==1 %-Only one choice - auto-pick k = 1; else %-Draw buttons and process response dX = RRec(3)/nLabels; if TTips, str = ['select with mouse or use kbd: ',... sprintf('%c/',Keys(1:end-1)),Keys(end)]; else, str=''; end %-Store button # in buttons 'UserData' property %-Store handle of prompt string in buttons 'Max' property %-Button callback sets UserData of prompt string to % number of pressed button cb = ['set(get(gcbo,''Max''),''UserData'',',... 'get(gcbo,''UserData''))']; H = []; XDisp = []; for i=1:nLabels if i==DefItem %-Default button, outline it h = uicontrol(Finter,'Style','Frame',... 'BackGroundColor','k',... 'ForeGroundColor','k',... 'Tag',Tag,... 'Position',... [RRec(1)+(i-1)*dX ... RRec(2)-1 dX RRec(4)+2]); XDisp = (i-1/3)*dX; H = [H,h]; end h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'ToolTipString',str,... 'Tag',Tag,... 'Max',hPrmpt,... 'UserData',i,... 'BackgroundColor',COLOUR,... 'Callback',cb,... 'Position',[RRec(1)+(i-1)*dX+1 ... RRec(2) dX-2 RRec(4)]); if i == DefItem, uifocus(h); end H = [H,h]; end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,H]); %-Bring window to fore & jump pointer to default button [PLoc,cF]=spm_input('!PointerJump',RRec,Finter,XDisp); %-Callback for KeyPress, to store valid button # in % UserData of Prompt, DefItem if (DefItem~=0) % & return (ASCII-13) is pressed set(Finter,'KeyPressFcn',... ['spm_input(''!ButtonKeyPressFcn'',',... 'findobj(gcf,''Tag'',''',Tag,''',',... '''Style'',''text''),',... '''',lower(Keys),''',',num2str(DefItem),',',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for button press, process results %----------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt) error(['Input objects cleared whilst ',... 'waiting for response: Bailing out!']) end k = get(hPrmpt,'UserData'); %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') spm_input('!PointerJumpBack',PLoc,cF) end %-Display answer uicontrol(Finter,'Style','Text',... 'String',deblank(Labels(k,:)),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',RRec); drawnow p = Values(k,:); if ischar(p), p=deblank(p); end end case {'be1','bn1','bw1','bi1','br1','-n1','-w1'} %-Process button/entry combo types %======================================================================= if ischar(DefItem), DefStr=DefItem; else, DefStr=num2str(DefItem); end if isempty(m), strM=''; else, strM=sprintf(' (<=%d)',m); end if CmdLine %-Process default item %--------------------------------------------------------------- if ~isempty(DefItem) [DefVal,msg] = sf_eEval(DefStr,Type(2),1); if ischar(DefVal), error(['Invalid DefItem: ',msg]), end Labels = strvcat(Labels,DefStr); Values = [Values;DefVal]; DefItem = size(Labels,1); end %-Add option to specify... Labels = strvcat(Labels,'specify...'); %-Process options nLabels = size(Labels,1); [Keys,Labs] = sf_labkeys(Labels); if ~isempty(DefItem), DefKey = Keys(DefItem); else, DefKey = ''; end %-Print banner prompt %--------------------------------------------------------------- spm_input('!PrntPrmpt',Prompt) %-Display question prompt if Type(1)=='-' %-No special buttons - go straight to input k = size(Labels,1); else %-Offer buttons, default or "specify..." %-Build prompt %------------------------------------------------------- if ~isempty(Labs) Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' ']; for i = 2:nLabels Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' ']; end else Prmpt = ['[',Keys(1),'] ']; for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end end if DefItem, Prmpt = [Prmpt,... ' (Default: ',deblank(Labels(DefItem,:)),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels) else str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end while isempty(str) | ~any(lower(Keys)==lower(str(1))) if ~isempty(str),fprintf('%c\t!Invalid response\n',7),end str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end end k = find(lower(Keys)==lower(str(1))); end fprintf('\n') end %-Process response: prompt for value if "specify..." option chosen %=============================================================== if k<size(Labels,1) p = Values(k,:); if ischar(p), p=deblank(p); end else %-"specify option chosen: ask user to specify %------------------------------------------------------- switch lower(Type(2)) case 's', tstr=' string'; case 'e', tstr='n expression'; case 'n', tstr=' natural number';case 'w', tstr=' whole number'; case 'i', tstr='n integer'; case 'r', tstr=' real number'; otherwise, tstr=''; end Prompt = sprintf('%s (a%s%s)',Prompt,tstr,strM); if ~isempty(DefStr) Prompt=sprintf('%s\b, default %s)',Prompt,DefStr); end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end %-Eval in Base workspace, catch errors [p,msg] = sf_eEval(str,Type(2),1,m); while ischar(p) spm('Beep'), fprintf('! %s : %s\n',mfilename,msg) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type(2),1,m); end end else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets nLabels = size(Labels,1); %-#buttons %-Create text and edit control objects %-'UserData' of prompt contains answer %--------------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',[Prompt,strM],... 'Tag',Tag,... 'UserData',[],... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); %-Draw buttons & entry widget, & process response dX = RRec(3)*(2/3)/nLabels; %-Store button # in buttons 'UserData' %-Store handle of prompt string in buttons 'Max' property %-Callback sets UserData of prompt string to button number. cb = ['set(get(gcbo,''Max''),''UserData'',get(gcbo,''UserData''))']; if TTips, str=sprintf('select by mouse or enter value in text widget'); else, str=''; end H = []; for i=1:nLabels h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'Max',hPrmpt,... 'ToolTipString',str,... 'Tag',Tag,... 'UserData',i,... 'BackgroundColor',COLOUR,... 'Callback',cb,... 'Position',[RRec(1)+(i-1)*dX+1 RRec(2) dX-2 RRec(4)]); H = [H,h]; end %-Default button surrounding edit widget (if a DefStr given) %-Callback sets hPrmpt UserData, and EditWidget string, to DefStr % (Buttons UserData holds handles [hPrmpt,hEditWidget], set later) cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',... 'get(gcbo,''String'')),',... 'set(get(gcbo,''UserData'')*[0;1],''String'',',... 'get(gcbo,''String''))']; if ~isempty(DefStr) hDef = uicontrol(Finter,'Style','PushButton',... 'String',DefStr,... 'ToolTipString',['Click on border to accept ',... 'default: ' DefStr],... 'Tag',Tag,... 'UserData',[],... 'CallBack',cb,... 'BackgroundColor',COLOUR,... 'Position',... [RRec(1)+RRec(3)*(2/3) RRec(2)-2 RRec(3)/3+2 RRec(4)+4]); H = [H,hDef]; else hDef = []; end %-Edit widget: Callback puts string into hPrompts UserData cb = ['set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))']; h = uicontrol(Finter,'Style','Edit',... 'String',DefStr,... 'ToolTipString',str,... 'Tag',Tag,... 'UserData',hPrmpt,... 'CallBack',cb,... 'Horizontalalignment','Center',... 'BackgroundColor','w',... 'Position',... [RRec(1)+RRec(3)*(2/3)+2 RRec(2) RRec(3)/3-2 RRec(4)]); set(hDef,'UserData',[hPrmpt,h]) uifocus(h); H = [H,h]; %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,H]); %-Bring window to fore & jump pointer to default button [PLoc,cF] = spm_input('!PointerJump',RRec,Finter,RRec(3)*0.95); %-Setup FigureKeyPressFcn for editing of entry widget without clicking set(Finter,'KeyPressFcn',[... 'spm_input(''!EditableKeyPressFcn'',',... 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',... '''Style'',''edit''),',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for button press, process results %--------------------------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input objects cleared whilst waiting ',... 'for response: Bailing out!']), end p = get(hPrmpt,'UserData'); if ~ischar(p) k = p; p = Values(k,:); if ischar(p), p=deblank(p); end else Labels = strvcat(Labels,'specify...'); k = size(Labels,1); [p,msg] = sf_eEval(p,Type(2),1,m); while ischar(p) set(H,'Visible','off') h = uicontrol('Style','Text','String',msg,... 'Horizontalalignment','Center',... 'ForegroundColor','r',... 'BackgroundColor',COLOUR,... 'Tag',Tag,'Position',RRec); spm('Beep') pause(2), delete(h), set(H,'Visible','on') set(hPrmpt,'UserData','') waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input objects cleared ',... 'whilst waiting for response: Bailing out!']),end p = get(hPrmpt,'UserData'); if ischar(p), [p,msg] = sf_eEval(p,Type(2),1,m); end end end %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') spm_input('!PointerJumpBack',PLoc,cF) %-Display answer uicontrol(Finter,'Style','Text',... 'String',num2str(p),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',RRec); drawnow end % (if CmdLine) case 'm' %-Process menu type %======================================================================= nLabels = size(Labels,1); if ~isempty(DefItem) & ~any(DefItem==[1:nLabels]), DefItem=[]; end %-Process pull down menu type if CmdLine spm_input('!PrntPrmpt',Prompt) nLabels = size(Labels,1); for i = 1:nLabels, fprintf('\t%2d : %s\n',i,Labels(i,:)), end Prmpt = ['Menu choice (1-',int2str(nLabels),')']; if DefItem Prmpt=[Prmpt,' (Default: ',num2str(DefItem),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('Menu choice: 1 - %s\t(only option)',Labels) else k = input([Prmpt,' ? ']); if DefItem & isempty(k), k=DefItem; end while isempty(k) | ~any([1:nLabels]==k) if ~isempty(k),fprintf('%c\t!Out of range\n',7),end k = input([Prmpt,' ? ']); if DefItem & isempty(k), k=DefItem; end end end fprintf('\n') else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets if nLabels==1 %-Only one choice - auto-pick k = 1; else Labs=[repmat(' ',nLabels,2),Labels]; if DefItem Labs(DefItem,1)='*'; H = uicontrol(Finter,'Style','Frame',... 'BackGroundColor','k',... 'ForeGroundColor','k',... 'Position',QRec+[-1,-1,+2,+2]); else H = []; end cb = ['if (get(gcbo,''Value'')>1),',... 'set(gcbo,''UserData'',''Selected''), end']; hPopUp = uicontrol(Finter,'Style','PopUp',... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'String',strvcat([Prompt,'...'],Labs),... 'Tag',Tag,... 'UserData',DefItem,... 'CallBack',cb,... 'Position',QRec); if TTips, set(hPopUp,'ToolTipString',['select with ',... 'mouse or type option number (1-',... num2str(nLabels),') & press return']), end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPopUp,H]); %-Bring window to fore & jump pointer to menu widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); %-Callback for KeyPresses cb=['spm_input(''!PullDownKeyPressFcn'',',... 'findobj(gcf,''Tag'',''',Tag,'''),',... 'get(gcf,''CurrentCharacter''))']; set(Finter,'KeyPressFcn',cb) %-Wait for menu selection %----------------------------------------------- waitfor(hPopUp,'UserData') if ~ishandle(hPopUp), error(['Input object cleared ',... 'whilst waiting for response: Bailing out!']),end k = get(hPopUp,'Value')-1; %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') set(hPopUp,'Style','Text',... 'Horizontalalignment','Center',... 'String',deblank(Labels(k,:)),... 'BackgroundColor',COLOUR) spm_input('!PointerJumpBack',PLoc,cF) end %-Display answer uicontrol(Finter,'Style','Text',... 'String',deblank(Labels(k,:)),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',QRec); drawnow end p = Values(k,:); if ischar(p), p=deblank(p); end otherwise, error('unrecognised type') end % (switch lower(Type) within case {'b','b|','y/n'}) %-Log the transaction & return response %----------------------------------------------------------------------- if exist('spm_log')==2 if iscellstr(Prompt), Prompt=Prompt{1}; end spm_log([mfilename,' : ',Prompt,': (',deblank(Labels(k,:)),')'],p); end varargout = {p,YPos}; case {'m!','b!'} %-GUI PullDown/Buttons utility %======================================================================= % H = spm_input(Prompt,YPos,'p',Labels,cb,UD,XCB) %-Condition arguments if nargin<7, XCB = 0; else, XCB = varargin{7}; end if nargin<6, UD = []; else, UD = varargin{6}; end if nargin<5, cb = ''; else, cb = varargin{5}; end if nargin<4, Labels = []; else, Labels = varargin{4}; end if CmdLine, error('Can''t do CmdLine GUI utilities!'), end if isempty(cb), cb = 'disp(''(CallBack not set)'')'; end if ischar(cb), cb = cellstr(cb); end if length(cb)>1 & strcmp(lower(Type),'m!'), XCB=1; end if iscellstr(Labels), Labels=char(Labels); end %-Convert Labels "option" string to string matrix if required if any(Labels=='|') OptStr=Labels; BarPos=find([OptStr=='|',1]); Labels=OptStr(1:BarPos(1)-1); for Bar = 2:sum(OptStr=='|')+1 Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1)); end end %-Check #CallBacks if ~( length(cb)==1 | (length(cb)==size(Labels,1)) ) error('Labels & Callbacks size mismatch'), end %-Draw Prompt %----------------------------------------------------------------------- Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets if ~isempty(Prompt) uicontrol(Finter,'Style','Text',... 'String',Prompt,... 'Tag',Tag,... 'HorizontalAlignment','Right',... 'BackgroundColor',COLOUR,... 'Position',PRec) Rec = RRec; else Rec = QRec; end %-Sort out UserData for extended callbacks (handled by spm_input('!m_cb') %----------------------------------------------------------------------- if XCB, if iscell(UD), UD={UD}; end, UD = struct('UD',UD,'cb',{cb}); end %-Draw PullDown or Buttons %----------------------------------------------------------------------- switch lower(Type), case 'm!' if XCB, UD.cb=cb; cb = {'spm_input(''!m_cb'')'}; end H = uicontrol(Finter,'Style','PopUp',... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'String',Labels,... 'Tag',Tag,... 'UserData',UD,... 'CallBack',char(cb),... 'Position',Rec); case 'b!' nLabels = size(Labels,1); dX = Rec(3)/nLabels; H = []; for i=1:nLabels if length(cb)>1, tcb=cb(i); else, tcb=cb; end if XCB, UD.cb=tcb; tcb = {'spm_input(''!m_cb'')'}; end h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'ToolTipString','',... 'Tag',Tag,... 'UserData',UD,... 'BackgroundColor',COLOUR,... 'Callback',char(tcb),... 'Position',[Rec(1)+(i-1)*dX+1 ... Rec(2) dX-2 Rec(4)]); H = [H,h]; end end %-Bring window to fore & jump pointer to menu widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); varargout = {H}; case {'d','d!'} %-Display message %======================================================================= %-Condition arguments if nargin<4, Label=''; else, Label=varargin{4}; end if CmdLine & strcmp(lower(Type),'d') fprintf('\n +-%s%s+',Label,repmat('-',1,57-length(Label))) Prompt = [Prompt,' ']; while length(Prompt)>0 tmp = length(Prompt); if tmp>56, tmp=min([max(find(Prompt(1:56)==' ')),56]); end fprintf('\n | %s%s |',Prompt(1:tmp),repmat(' ',1,56-tmp)) Prompt(1:tmp)=[]; end fprintf('\n +-%s+\n',repmat('-',1,57)) elseif ~CmdLine if ~isempty(Label), Prompt = [Label,': ',Prompt]; end figure(Finter) %-Create text axes and edit control objects %--------------------------------------------------------------- h = uicontrol(Finter,'Style','Text',... 'String',Prompt(1:min(length(Prompt),56)),... 'FontWeight','bold',... 'Tag',['GUIinput_',int2str(YPos)],... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'UserData',Prompt,... 'Position',QRec); if length(Prompt)>56 pause(1) set(h,'ToolTipString',Prompt) spm_input('!dScroll',h) uicontrol(Finter,'Style','PushButton','String','>',... 'ToolTipString','press to scroll message',... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',h,... 'CallBack',[... 'set(gcbo,''Visible'',''off''),',... 'spm_input(''!dScroll'',get(gcbo,''UserData'')),',... 'set(gcbo,''Visible'',''on'')'],... 'BackgroundColor',COLOUR,... 'Position',[QRec(1)+QRec(3)-10,QRec(2),15,QRec(4)]); end end if nargout>0, varargout={[],YPos}; end %======================================================================= % U T I L I T Y F U N C T I O N S %======================================================================= case '!colour' %======================================================================= % colour = spm_input('!Colour') varargout = {COLOUR}; case '!icond' %======================================================================= % [iCond,msg] = spm_input('!iCond',str,n,m) % Parse condition indicator spec strings: % '2 3 2 3', '0 1 0 1', '2323', '0101', 'abab', 'R A R A' if nargin<4, m=Inf; else, m=varargin{4}; end if nargin<3, n=NaN; else, n=varargin{3}; end if any(isnan(n(:))) n=Inf; elseif (length(n(:))==2 & ~any(n==1)) | length(n(:))>2 error('condition input can only do vectors') end if nargin<2, i=''; else, i=varargin{2}; end if isempty(i), varargout={[],'empty input'}; return, end msg = ''; i=i(:)'; if ischar(i) if i(1)=='0' & all(ismember(unique(i(:)),setstr(abs('0'):abs('9')))) %-Leading zeros in a digit list msg = sprintf('%s expanded',i); z = min(find([diff(i=='0'),1])); i = [zeros(1,z), spm_input('!iCond',i(z+1:end))']; else %-Try an eval, for functions & string #s i = evalin('base',['[',i,']'],'i'); end end if ischar(i) %-Evaluation error from above: see if it's an 'abab' or 'a b a b' type: [c,null,i] = unique(lower(i(~isspace(i)))); if all(ismember(c,setstr(abs('a'):abs('z')))) %-Map characters a-z to 1-26, but let 'r' be zero (rest) tmp = c-'a'+1; tmp(tmp=='r'-'a'+1)=0; i = tmp(i); msg = [sprintf('[%s] mapped to [',c),... sprintf('%d,',tmp(1:end-1)),... sprintf('%d',tmp(end)),']']; else i = '!'; msg = 'evaluation error'; end elseif ~all(floor(i(:))==i(:)) i = '!'; msg = 'must be integers'; elseif length(i)==1 & prod(n)>1 msg = sprintf('%d expanded',i); i = floor(i./10.^[floor(log10(i)+eps):-1:0]); i = i-[0,10*i(1:end-1)]; end %-Check size of i & #conditions if ~ischar(i), [i,msg] = sf_SzChk(i,n,msg); end if ~ischar(i) & isfinite(m) & length(unique(i))~=m i = '!'; msg = sprintf('%d conditions required',m); end varargout = {i,msg}; case '!inptconmen' %======================================================================= % hM = spm_input('!InptConMen',Finter,H) if nargin<3, H=[]; else, H=varargin{3}; end if nargin<2, varargout={[]}; else, Finter=varargin{2}; end hM = uicontextmenu('Parent',Finter); uimenu(hM,'Label','help on spm_input',... 'CallBack','spm_help(''spm_input.m'')') if ConCrash uimenu(hM,'Label','crash out','Separator','on',... 'CallBack','delete(get(gcbo,''UserData''))',... 'UserData',[hM,H]) end set(Finter,'UIContextMenu',hM) varargout={hM}; case '!cmdline' %======================================================================= % [CmdLine,YPos] = spm_input('!CmdLine',YPos) %-Sorts out whether to use CmdLine or not & canonicalises YPos if nargin<2, YPos=''; else, YPos=varargin{2}; end if isempty(YPos), YPos='+1'; end CmdLine = []; %-Special YPos specifications if ischar(YPos) if(YPos(1)=='!'), CmdLine=0; YPos(1)=[]; end elseif YPos==0 CmdLine=1; elseif YPos<0 CmdLine=0; YPos=-YPos; end CmdLine = spm('CmdLine',CmdLine); if CmdLine, YPos=0; end varargout = {CmdLine,YPos}; case '!getwin' %======================================================================= % Finter = spm_input('!GetWin',F) %-Locate (or create) figure to work in (Don't use 'Tag'ged figs) if nargin<2, F='Interactive'; else, F=varargin{2}; end Finter = spm_figure('FindWin',F); if isempty(Finter) if any(get(0,'Children')) if isempty(get(gcf,'Tag')), Finter = gcf; else, Finter = spm('CreateIntWin'); end else, Finter = spm('CreateIntWin'); end end varargout = {Finter}; case '!pointerjump' %======================================================================= % [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp) %-Raise window & jump pointer over question if nargin<4, XDisp=[]; else, XDisp=varargin{4}; end if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, error('Insufficient arguments'), else, RRec=varargin{2}; end F = spm_figure('FindWin',F); PLoc = get(0,'PointerLocation'); cF = get(0,'CurrentFigure'); if ~isempty(F) figure(F) FRec = get(F,'Position'); if isempty(XDisp), XDisp=RRec(3)*4/5; end if PJump, set(0,'PointerLocation',... floor([(FRec(1)+RRec(1)+XDisp), (FRec(2)+RRec(2)+RRec(4)/3)])); end end varargout = {PLoc,cF}; case '!pointerjumpback' %======================================================================= % spm_input('!PointerJumpBack',PLoc,cF) %-Replace pointer and reset CurrentFigure back if nargin<4, cF=[]; else, F=varargin{3}; end if nargin<2, error('Insufficient arguments'), else, PLoc=varargin{2}; end if PJump, set(0,'PointerLocation',PLoc), end cF = spm_figure('FindWin',cF); if ~isempty(cF), set(0,'CurrentFigure',cF); end case '!prntprmpt' %======================================================================= % spm_input('!PrntPrmpt',Prompt,TipStr,Title) %-Print prompt for CmdLine questioning if nargin<4, Title = ''; else, Title = varargin{4}; end if nargin<3, TipStr = ''; else, TipStr = varargin{3}; end if nargin<2, Prompt = ''; else, Prompt = varargin{2}; end if isempty(Prompt), Prompt='Enter an expression'; end Prompt = cellstr(Prompt); if ~isempty(TipStr) tmp = 8 + length(Prompt{end}) + length(TipStr); if tmp < 62 TipStr = sprintf('%s(%s)',repmat(' ',1,70-tmp),TipStr); else TipStr = sprintf('\n%s(%s)',repmat(' ',1,max(0,70-length(TipStr))),TipStr); end end if isempty(Title) fprintf('\n%s\n',repmat('~',1,72)) else fprintf('\n= %s %s\n',Title,repmat('~',1,72-length(Title)-3)) end fprintf('\t%s',Prompt{1}) for i=2:prod(size(Prompt)), fprintf('\n\t%s',Prompt{i}), end fprintf('%s\n%s\n',TipStr,repmat('~',1,72)) case '!inputrects' %======================================================================= % [Frec,QRec,PRec,RRec,Sz,Se] = spm_input('!InputRects',YPos,rec,F) if nargin<4, F='Interactive'; else, F=varargin{4}; end if nargin<3, rec=''; else, rec=varargin{3}; end if nargin<2, YPos=1; else, YPos=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('Figure not found'), end Units = get(F,'Units'); set(F,'Units','pixels') FRec = get(F,'Position'); set(F,'Units',Units); Xdim = FRec(3); Ydim = FRec(4); WS = spm('WinScale'); Sz = round(22*min(WS)); %-Height Pd = Sz/2; %-Pad Se = 2*round(25*min(WS)/2); %-Seperation Yo = round(2*min(WS)); %-Y offset for responses a = 5.5/10; y = Ydim - Se*YPos; QRec = [Pd y Xdim-2*Pd Sz]; %-Question PRec = [Pd y floor(a*Xdim)-2*Pd Sz]; %-Prompt RRec = [ceil(a*Xdim) y+Yo floor((1-a)*Xdim)-Pd Sz]; %-Response % MRec = [010 y Xdim-50 Sz]; %-Menu PullDown % BRec = MRec + [Xdim-50+1, 0+1, 50-Xdim+30, 0]; %-Menu PullDown OK butt if ~isempty(rec) varargout = {eval(rec)}; else varargout = {FRec,QRec,PRec,RRec,Sz,Se}; end case '!deleteinputobj' %======================================================================= % spm_input('!DeleteInputObj',F) if nargin<2, F='Interactive'; else, F=varargin{2}; end h = spm_input('!FindInputObj',F); delete(h(h>0)) case {'!currentpos','!findinputobj'} %======================================================================= % [CPos,hCPos] = spm_input('!CurrentPos',F) % h = spm_input('!FindInputObj',F) % hPos contains handles: Columns contain handles corresponding to Pos if nargin<2, F='Interactive'; else, F=varargin{2}; end F = spm_figure('FindWin',F); %-Find tags and YPos positions of 'GUIinput_' 'Tag'ged objects H = []; YPos = []; for h = get(F,'Children')' tmp = get(h,'Tag'); if ~isempty(tmp) if strcmp(tmp(1:min(length(tmp),9)),'GUIinput_') H = [H, h]; YPos = [YPos, eval(tmp(10:end))]; end end end switch lower(Type), case '!findinputobj' varargout = {H}; case '!currentpos' if nargout<2 varargout = {max(YPos),[]}; elseif isempty(H) varargout = {[],[]}; else %-Sort out tmp = sort(YPos); CPos = tmp(find([1,diff(tmp)])); nPos = length(CPos); nPerPos = diff(find([1,diff(tmp),1])); hCPos = zeros(max(nPerPos),nPos); for i = 1:nPos hCPos(1:nPerPos(i),i) = H(YPos==CPos(i))'; end varargout = {CPos,hCPos}; end end case '!nextpos' %======================================================================= % [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine) %-Return next position to use if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, YPos='+1'; else, YPos=varargin{2}; end if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos); else, CmdLine=varargin{4}; end F = spm_figure('FindWin',F); %-Get current positions if nargout<3 CPos = spm_input('!CurrentPos',F); hCPos = []; else [CPos,hCPos] = spm_input('!CurrentPos',F); end if CmdLine NPos = 0; else MPos = spm_input('!MaxPos',F); if ischar(YPos) %-Relative YPos %-Strip any '!' prefix from YPos if(YPos(1)=='!'), YPos(1)=[]; end if strncmp(YPos,'_',1) %-YPos='_' means bottom YPos=eval(['MPos+',YPos(2:end)],'MPos'); else YPos = max([0,CPos])+eval(YPos); end else %-Absolute YPos YPos=abs(YPos); end NPos = min(max(1,YPos),MPos); end varargout = {NPos,CPos,hCPos}; case '!setnextpos' %======================================================================= % NPos = spm_input('!SetNextPos',YPos,F,CmdLine) %-Set next position to use if nargin<3, F='Interactive'; else, F=varargin{3}; end if nargin<2, YPos='+1'; else, YPos=varargin{2}; end if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos); else, CmdLine=varargin{4}; end %-Find out which Y-position to use [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine); %-Delete any previous inputs using positions NPos and after if any(CPos>=NPos), h=hCPos(:,CPos>=NPos); delete(h(h>0)), end varargout = {NPos}; case '!maxpos' %======================================================================= % MPos = spm_input('!MaxPos',F,FRec3) % if nargin<3 if nargin<2, F='Interactive'; else, F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F) FRec3=spm('WinSize','Interactive')*[0;0;0;1]; else %-Get figure size Units = get(F,'Units'); set(F,'Units','pixels') FRec3 = get(F,'Position')*[0;0;0;1]; set(F,'Units',Units); end end Se = round(25*min(spm('WinScale'))); MPos = floor((FRec3-5)/Se); varargout = {MPos}; case '!editablekeypressfcn' %======================================================================= % spm_input('!EditableKeyPressFcn',h,ch,hPrmpt) if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcbf,'KeyPressFcn','','UserData',[]), return, end if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else, ch=varargin{3};end if nargin<4, hPrmpt=get(h,'UserData'); else, hPrmpt=varargin{4}; end tmp = get(h,'String'); if isempty(tmp), tmp=''; end if iscellstr(tmp) & length(tmp)==1; tmp=tmp{:}; end if isempty(ch) %- shift / control / &c. pressed return elseif any(abs(ch)==[32:126]) %-Character if iscellstr(tmp), return, end tmp = [tmp, ch]; elseif abs(ch)==21 %- ^U - kill tmp = ''; elseif any(abs(ch)==[8,127]) %-BackSpace or Delete if iscellstr(tmp), return, end if length(tmp), tmp(length(tmp))=''; end elseif abs(ch)==13 %-Return pressed if ~isempty(tmp) set(hPrmpt,'UserData',get(h,'String')) end return else %-Illegal character return end set(h,'String',tmp) case '!buttonkeypressfcn' %======================================================================= % spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch) %-Callback for KeyPress, to store valid button # in UserData of Prompt, % DefItem if (DefItem~=0) & return (ASCII-13) is pressed %-Condition arguments if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcf,'KeyPressFcn','','UserData',[]), return, end if nargin<3, error('Insufficient arguments'); else, Keys=varargin{3}; end if nargin<4, DefItem=0; else, DefItem=varargin{4}; end if nargin<5, ch=get(gcf,'CurrentCharacter'); else, ch=varargin{5}; end if isempty(ch) %- shift / control / &c. pressed return elseif (DefItem & ch==13) But = DefItem; else But = find(lower(ch)==lower(Keys)); end if ~isempty(But), set(h,'UserData',But), end case '!pulldownkeypressfcn' %======================================================================= % spm_input('!PullDownKeyPressFcn',h,ch,DefItem) if nargin<2, error('Insufficient arguments'), else, h=varargin{2}; end if isempty(h), set(gcf,'KeyPressFcn',''), return, end if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else, ch=varargin{3};end if nargin<4, DefItem=get(h,'UserData'); else, ch=varargin{4}; end Pmax = get(h,'Max'); Pval = get(h,'Value'); if Pmax==1, return, end if isempty(ch) %- shift / control / &c. pressed return elseif abs(ch)==13 if Pval==1 if DefItem, set(h,'Value',max(2,min(DefItem+1,Pmax))), end else set(h,'UserData','Selected') end elseif any(ch=='bpu') %-Move "b"ack "u"p to "p"revious entry set(h,'Value',max(2,Pval-1)) elseif any(ch=='fnd') %-Move "f"orward "d"own to "n"ext entry set(h,'Value',min(Pval+1,Pmax)) elseif any(ch=='123456789') %-Move to entry n set(h,'Value',max(2,min(eval(ch)+1,Pmax))) else %-Illegal character end case '!m_cb' %-CallBack handler for extended CallBack 'p'ullDown type %======================================================================= % spm_input('!m_cb') %-Get PopUp handle and value h = gcbo; n = get(h,'Value'); %-Get PopUp's UserData, check cb and UD fields exist, extract cb & UD tmp = get(h,'UserData'); if ~(isfield(tmp,'cb') & isfield(tmp,'UD')) error('Invalid UserData structure for spm_input extended callback') end cb = tmp.cb; UD = tmp.UD; %-Evaluate appropriate CallBack string (ignoring any return arguments) % NB: Using varargout={eval(cb{n})}; gives an error if the CallBack % has no return arguments! if length(cb)==1, eval(char(cb)); else, eval(cb{n}); end case '!dscroll' %======================================================================= % spm_input('!dScroll',h,Prompt) %-Scroll text in object h if nargin<2, return, else, h=varargin{2}; end if nargin<3, Prompt = get(h,'UserData'); else, Prompt=varargin{3}; end tmp = Prompt; if length(Prompt)>56 while length(tmp)>56 tic, while(toc<0.1), pause(0.05), end tmp(1)=[]; set(h,'String',tmp(1:min(length(tmp),56))) end pause(1) set(h,'String',Prompt(1:min(length(Prompt),56))) end otherwise %======================================================================= error(['Invalid type/action: ',Type]) %======================================================================= end % (case lower(Type)) %======================================================================= %- S U B - F U N C T I O N S %======================================================================= function [Keys,Labs] = sf_labkeys(Labels) %======================================================================= %-Make unique character keys for the Labels, ignoring case if nargin<1, error('insufficient arguments'), end if iscellstr(Labels), Labels = char(Labels); end if isempty(Labels), Keys=''; Labs=''; return, end Keys=Labels(:,1)'; nLabels = size(Labels,1); if any(~diff(abs(sort(lower(Keys))))) if nLabels<10 Keys = sprintf('%d',[1:nLabels]); elseif nLabels<=26 Keys = sprintf('%c',abs('a')+[0:nLabels-1]); else error('Too many buttons!') end Labs = Labels; else Labs = Labels(:,2:end); end function [p,msg] = sf_eEval(str,Type,n,m) %======================================================================= %-Evaluation and error trapping of typed input if nargin<4, m=[]; end if nargin<3, n=[]; end if nargin<2, Type='e'; end if nargin<1, str=''; end if isempty(str), p='!'; msg='empty input'; return, end switch lower(Type) case 's' p = str; msg = ''; case 'e' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; else [p,msg] = sf_SzChk(p,n); end case 'n' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:)|p(:)<1)|~isreal(p) p='!'; msg='natural number(s) required'; elseif ~isempty(m) & any(p(:)>m) p='!'; msg=['max value is ',num2str(m)]; else [p,msg] = sf_SzChk(p,n); end case 'w' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:)|p(:)<0)|~isreal(p) p='!'; msg='whole number(s) required'; elseif ~isempty(m) & any(p(:)>m) p='!'; msg=['max value is ',num2str(m)]; else [p,msg] = sf_SzChk(p,n); end case 'i' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:))|~isreal(p) p='!'; msg='integer(s) required'; else [p,msg] = sf_SzChk(p,n); end case 'p' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif length(setxor(p(:)',m)) p='!'; msg='invalid permutation'; else [p,msg] = sf_SzChk(p,n); end case 'r' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif ~isreal(p) p='!'; msg='real number(s) required'; elseif ~isempty(m) & ( max(p)>max(m) | min(p)<min(m) ) p='!'; msg=sprintf('real(s) in [%g,%g] required',min(m),max(m)); else [p,msg] = sf_SzChk(p,n); end case 'c' if isempty(m), m=Inf; end [p,msg] = spm_input('!iCond',str,n,m); case 'x' X = m; %-Design matrix/space-structure if isempty(n), n=1; end %-Sort out contrast matrix dimensions (contrast vectors in rows) if length(n)==1, n=[n,Inf]; else, n=reshape(n(1:2),1,2); end if ~isempty(X) % - override n(2) w/ design column dimension n(2) = spm_SpUtil('size',X,2); end p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; else if isfinite(n(2)) & size(p,2)<n(2) tmp = n(2) -size(p,2); p = [p, zeros(size(p,1),tmp)]; if size(p,1)>1, str=' columns'; else, str='s'; end msg = sprintf('right padded with %d zero%s',tmp,str); else msg = ''; end if size(p,2)>n(2) p='!'; msg=sprintf('too long - only %d prams',n(2)); elseif isfinite(n(1)) & size(p,1)~=n(1) p='!'; if n(1)==1, msg='vector required'; else, msg=sprintf('%d contrasts required',n(1)); end elseif ~isempty(X) & ~spm_SpUtil('allCon',X,p') p='!'; msg='invalid contrast'; end end otherwise error('unrecognised type'); end function str = sf_SzStr(n,l) %======================================================================= %-Size info string constuction if nargin<2, l=0; else, l=1; end if nargin<1, error('insufficient arguments'), end if isempty(n), n=NaN; end n=n(:); if length(n)==1, n=[n,1]; end, dn=length(n); if any(isnan(n)) | (prod(n)==1 & dn<=2) | (dn==2 & min(n)==1 & isinf(max(n))) str = ''; lstr = ''; elseif dn==2 & min(n)==1 str = sprintf('[%d]',max(n)); lstr = [str,'-vector']; elseif dn==2 & sum(isinf(n))==1 str = sprintf('[%d]',min(n)); lstr = [str,'-vector(s)']; else str=''; for i = 1:dn if isfinite(n(i)), str = sprintf('%s,%d',str,n(i)); else, str = sprintf('%s,*',str); end end str = ['[',str(2:end),']']; lstr = [str,'-matrix']; end if l, str=sprintf('\t%s',lstr); else, str=[str,' ']; end function [p,msg] = sf_SzChk(p,n,msg) %======================================================================= %-Size checking if nargin<3, msg=''; end if nargin<2, n=[]; end, if isempty(n), n=NaN; else, n=n(:)'; end if nargin<1, error('insufficient arguments'), end if ischar(p) | any(isnan(n(:))), return, end if length(n)==1, n=[n,1]; end dn = length(n); sp = size(p); dp = ndims(p); if dn==2 & min(n)==1 %-[1,1], [1,n], [n,1], [1,Inf], [Inf,1] - vector - allow transpose %--------------------------------------------------------------- i = min(find(n==max(n))); if n(i)==1 & max(sp)>1 p='!'; msg='scalar required'; elseif ndims(p)~=2 | ~any(sp==1) | ( isfinite(n(i)) & max(sp)~=n(i) ) %-error: Not2D | not vector | not right length if isfinite(n(i)), str=sprintf('%d-',n(i)); else, str=''; end p='!'; msg=[str,'vector required']; elseif sp(i)==1 & n(i)~=1 p=p'; msg=[msg,' (input transposed)']; end elseif dn==2 & sum(isinf(n))==1 %-[n,Inf], [Inf,n] - n vector(s) required - allow transposing %--------------------------------------------------------------- i = find(isfinite(n)); if ndims(p)~=2 | ~any(sp==n(i)) p='!'; msg=sprintf('%d-vector(s) required',min(n)); elseif sp(i)~=n p=p'; msg=[msg,' (input transposed)']; end else %-multi-dimensional matrix required - check dimensions %--------------------------------------------------------------- if ndims(p)~=dn | ~all( size(p)==n | isinf(n) ) p = '!'; msg=''; for i = 1:dn if isfinite(n(i)), msg = sprintf('%s,%d',msg,n(i)); else, msg = sprintf('%s,*',msg); end end msg = ['[',msg(2:end),']-matrix required']; end end function uifocus(h) %======================================================================= % Matlab r14 no longer keeps focus on the uicontrol, unless it is % explicitly specified, otherwise control is given to the figure's % keypress function. therefore we must explicitly set the focus to % a uicontrol or the user is forced to click into the control to % enter data or press a button. Matlab 7 has extended the functionality % of the uicontrol function. uicontrol(handle) sets the focus % to the designated uiontrol's handle. try if spm_matlab_version_chk('7') >= 0 if strcmpi(get(h, 'Style'), 'PushButton') == 1 uicontrol(gcbo); else uicontrol(h); end end end
github
spm/spm5-master
spm_config_minc.m
.m
spm5-master/spm_config_minc.m
2,505
utf_8
47d6e77ccd421f13aeb57fc2941eccb1
function opts = spm_config_minc % Configuration file for minc import jobs %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_config_minc.m 1032 2007-12-20 14:45:55Z john $ %_______________________________________________________________________ data.type = 'files'; data.name = 'MINC files'; data.tag = 'data'; data.filter = 'mnc'; data.num = Inf; data.help = {'Select the MINC files to convert.'}; dtype.type = 'menu'; dtype.name = 'Data Type'; dtype.tag = 'dtype'; dtype.labels = {'UINT8 - unsigned char','INT16 - signed short','INT32 - signed int','FLOAT - single prec. float','DOUBLE - double prec. float'}; dtype.values = {spm_type('uint8'),spm_type('int16'),spm_type('int32'),spm_type('float32'),spm_type('float64')}; dtype.val = {spm_type('int16')}; dtype.help = {[... 'Data-type of output images. '... 'Note that the number of bits used determines '... 'the accuracy, and the amount of disk space needed.']}; ext.type = 'menu'; ext.name = 'NIFTI Type'; ext.tag = 'ext'; ext.labels = {'.nii only','.img + .hdr'}; ext.values = {'.nii','.img'}; ext.val = {'.img'}; ext.help = {[... 'Output files can be written as .img + .hdr, ',... 'or the two can be combined into a .nii file.']}; op1.type = 'branch'; op1.name = 'Options'; op1.tag = 'opts'; op1.val = {dtype,ext}; op1.help = {'Conversion options'}; opts.type = 'branch'; opts.name = 'MINC Import'; opts.tag = 'minc'; opts.val = {data,op1}; opts.prog = @convert_minc; opts.vfiles = @vfiles; opts.help = {[... 'MINC Conversion. MINC is the image data format used for exchanging data '... 'within the ICBM community, and the format used by the MNI software tools. '... 'It is based on NetCDF, but due to be superceded by a new version relatively soon. '... 'MINC is no longer supported for reading images into SPM, so MINC files need to '... 'be converted to NIFTI format in order to use them. '... 'See http://www.bic.mni.mcgill.ca/software/ for more information.']}; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function convert_minc(job) for i=1:length(job.data), spm_mnc2nifti(job.data{i},job.opts); end; return; function vf = vfiles(job) vf = cell(size(job.data)); for i=1:numel(job.data), [pth,nam,ext,num] = spm_fileparts(job.data{i}); vf{i} = fullfile(pth,[nam job.opts.ext num]); end;
github
spm/spm5-master
spm_realign.m
.m
spm5-master/spm_realign.m
17,190
utf_8
4b1e430488a8aa45f21f252c19f49b04
function P = spm_realign(P,flags) % Estimation of within modality rigid body movement parameters % FORMAT P = spm_realign(P,flags) % % P - matrix of filenames {one string per row} % All operations are performed relative to the first image. % ie. Coregistration is to the first image, and resampling % of images is into the space of the first image. % For multiple sessions, P should be a cell array, where each % cell should be a matrix of filenames. % % flags - a structure containing various options. The fields are: % quality - Quality versus speed trade-off. Highest quality % (1) gives most precise results, whereas lower % qualities gives faster realignment. % The idea is that some voxels contribute little to % the estimation of the realignment parameters. % This parameter is involved in selecting the number % of voxels that are used. % % fwhm - The FWHM of the Gaussian smoothing kernel (mm) % applied to the images before estimating the % realignment parameters. % % sep - the default separation (mm) to sample the images. % % rtm - Register to mean. If field exists then a two pass % procedure is to be used in order to register the % images to the mean of the images after the first % realignment. % % PW - a filename of a weighting image (reciprocal of % standard deviation). If field does not exist, then % no weighting is done. % % interp - B-spline degree used for interpolation % %__________________________________________________________________________ % % Inputs % A series of *.img conforming to SPM data format (see 'Data Format'). % % Outputs % If no output argument, then an updated voxel to world matrix is written % to the headers of the images (a .mat file is created for 4D images). % The details of the transformation are displayed in the % results window as plots of translation and rotation. % A set of realignment parameters are saved for each session, named: % rp_*.txt. %__________________________________________________________________________ % % The voxel to world mappings. % % These are simply 4x4 affine transformation matrices represented in the % NIFTI headers (see http://nifti.nimh.nih.gov/nifti-1 ). % These are normally modified by the `realignment' and `coregistration' % modules. What these matrixes represent is a mapping from % the voxel coordinates (x0,y0,z0) (where the first voxel is at coordinate % (1,1,1)), to coordinates in millimeters (x1,y1,z1). % % x1 = M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4) % y1 = M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4) % z1 = M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4) % % Assuming that image1 has a transformation matrix M1, and image2 has a % transformation matrix M2, the mapping from image1 to image2 is: M2\M1 % (ie. from the coordinate system of image1 into millimeters, followed % by a mapping from millimeters into the space of image2). % % These matrices allow several realignment or coregistration steps to be % combined into a single operation (without the necessity of resampling the % images several times). The `.mat' files are also used by the spatial % normalisation module. %__________________________________________________________________________ % Ref: % Friston KJ, Ashburner J, Frith CD, Poline J-B, Heather JD & Frackowiak % RSJ (1995) Spatial registration and normalization of images Hum. Brain % Map. 2:165-189 %__________________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_realign.m 1030 2007-12-20 11:43:12Z john $ if nargin==0, return; end; def_flags = struct('quality',1,'fwhm',5,'sep',4,'interp',2,'wrap',[0 0 0],'rtm',0,'PW','','graphics',1,'lkp',1:6); if nargin < 2, flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end; end; end; if ~iscell(P), tmp = cell(1); tmp{1} = P; P = tmp; end; for i=1:length(P), if ischar(P{i}), P{i} = spm_vol(P{i}); end; end; if ~isempty(flags.PW) && ischar(flags.PW), flags.PW = spm_vol(flags.PW); end; % Remove empty cells PN = {}; j = 1; for i=1:length(P), if ~isempty(P{i}), PN{j} = P{i}; j = j+1; end; end; P = PN; if isempty(P), warning('Nothing to do'); return; end; if length(P)==1, P{1} = realign_series(P{1},flags); if nargout==0, save_parameters(P{1}); end; else Ptmp = P{1}(1); for s=2:numel(P), Ptmp = [Ptmp ; P{s}(1)]; end; Ptmp = realign_series(Ptmp,flags); for s=1:numel(P), M = Ptmp(s).mat*inv(P{s}(1).mat); for i=1:numel(P{s}), P{s}(i).mat = M*P{s}(i).mat; end; end; for s=1:numel(P), P{s} = realign_series(P{s},flags); if nargout==0, save_parameters(P{s}); end; end; end; if nargout==0, % Save Realignment Parameters %--------------------------------------------------------------------------- for s=1:numel(P), for i=1:numel(P{s}), spm_get_space([P{s}(i).fname ',' num2str(P{s}(i).n)], P{s}(i).mat); end; end; end; if flags.graphics, plot_parameters(P); end; if length(P)==1, P=P{1}; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function P = realign_series(P,flags) % Realign a time series of 3D images to the first of the series. % FORMAT P = realign_series(P,flags) % P - a vector of volumes (see spm_vol) %----------------------------------------------------------------------- % P(i).mat is modified to reflect the modified position of the image i. % The scaling (and offset) parameters are also set to contain the % optimum scaling required to match the images. %_______________________________________________________________________ if numel(P)<2, return; end; skip = sqrt(sum(P(1).mat(1:3,1:3).^2)).^(-1)*flags.sep; d = P(1).dim(1:3); lkp = flags.lkp; rand('state',0); % want the results to be consistant. if d(3) < 3, lkp = [1 2 6]; [x1,x2,x3] = ndgrid(1:skip(1):d(1)-.5, 1:skip(2):d(2)-.5, 1:skip(3):d(3)); x1 = x1 + rand(size(x1))*0.5; x2 = x2 + rand(size(x2))*0.5; else [x1,x2,x3]=ndgrid(1:skip(1):d(1)-.5, 1:skip(2):d(2)-.5, 1:skip(3):d(3)-.5); x1 = x1 + rand(size(x1))*0.5; x2 = x2 + rand(size(x2))*0.5; x3 = x3 + rand(size(x3))*0.5; end; x1 = x1(:); x2 = x2(:); x3 = x3(:); % Possibly mask an area of the sample volume. %----------------------------------------------------------------------- if ~isempty(flags.PW), [y1,y2,y3]=coords([0 0 0 0 0 0],P(1).mat,flags.PW.mat,x1,x2,x3); wt = spm_sample_vol(flags.PW,y1,y2,y3,1); msk = find(wt>0.01); x1 = x1(msk); x2 = x2(msk); x3 = x3(msk); wt = wt(msk); else wt = []; end; % Compute rate of change of chi2 w.r.t changes in parameters (matrix A) %----------------------------------------------------------------------- V = smooth_vol(P(1),flags.interp,flags.wrap,flags.fwhm); deg = [flags.interp*[1 1 1]' flags.wrap(:)]; [G,dG1,dG2,dG3] = spm_bsplins(V,x1,x2,x3,deg); clear V A0 = make_A(P(1).mat,x1,x2,x3,dG1,dG2,dG3,wt,lkp); b = G; if ~isempty(wt), b = b.*wt; end; %----------------------------------------------------------------------- if numel(P) > 2, % Remove voxels that contribute very little to the final estimate. % Simulated annealing or something similar could be used to % eliminate a better choice of voxels - but this way will do for % now. It basically involves removing the voxels that contribute % least to the determinant of the inverse covariance matrix. spm_chi2_plot('Init','Eliminating Unimportant Voxels',... 'Relative quality','Iteration'); Alpha = spm_atranspa([A0 b]); det0 = det(Alpha); det1 = det0; spm_chi2_plot('Set',det1/det0); while det1/det0 > flags.quality, dets = zeros(size(A0,1),1); for i=1:size(A0,1), dets(i) = det(Alpha - spm_atranspa([A0(i,:) b(i)])); end; [junk,msk] = sort(det1-dets); msk = msk(1:round(length(dets)/10)); A0(msk,:) = []; b(msk,:) = []; G(msk,:) = []; x1(msk,:) = []; x2(msk,:) = []; x3(msk,:) = []; dG1(msk,:) = []; dG2(msk,:) = []; dG3(msk,:) = []; if ~isempty(wt), wt(msk,:) = []; end; Alpha = spm_atranspa([A0 b]); det1 = det(Alpha); spm_chi2_plot('Set',single(det1/det0)); end; spm_chi2_plot('Clear'); end; %----------------------------------------------------------------------- if flags.rtm, count = ones(size(b)); ave = G; grad1 = dG1; grad2 = dG2; grad3 = dG3; end; spm_progress_bar('Init',length(P)-1,'Registering Images'); % Loop over images %----------------------------------------------------------------------- for i=2:length(P), V = smooth_vol(P(i),flags.interp,flags.wrap,flags.fwhm); d = [size(V) 1 1]; d = d(1:3); ss = Inf; countdown = -1; for iter=1:64, [y1,y2,y3] = coords([0 0 0 0 0 0],P(1).mat,P(i).mat,x1,x2,x3); msk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3))); if length(msk)<32, error_message(P(i)); end; F = spm_bsplins(V, y1(msk),y2(msk),y3(msk),deg); if ~isempty(wt), F = F.*wt(msk); end; A = A0(msk,:); b1 = b(msk); sc = sum(b1)/sum(F); b1 = b1-F*sc; soln = spm_atranspa(A)\(A'*b1); p = [0 0 0 0 0 0 1 1 1 0 0 0]; p(lkp) = p(lkp) + soln'; P(i).mat = inv(spm_matrix(p))*P(i).mat; pss = ss; ss = sum(b1.^2)/length(b1); if (pss-ss)/pss < 1e-8 && countdown == -1, % Stopped converging. countdown = 2; end; if countdown ~= -1, if countdown==0, break; end; countdown = countdown -1; end; end; if flags.rtm, % Generate mean and derivatives of mean tiny = 5e-2; % From spm_vol_utils.c msk = find((y1>=(1-tiny) & y1<=(d(1)+tiny) &... y2>=(1-tiny) & y2<=(d(2)+tiny) &... y3>=(1-tiny) & y3<=(d(3)+tiny))); count(msk) = count(msk) + 1; [G,dG1,dG2,dG3] = spm_bsplins(V,y1(msk),y2(msk),y3(msk),deg); ave(msk) = ave(msk) + G*sc; grad1(msk) = grad1(msk) + dG1*sc; grad2(msk) = grad2(msk) + dG2*sc; grad3(msk) = grad3(msk) + dG3*sc; end; spm_progress_bar('Set',i-1); end; spm_progress_bar('Clear'); if ~flags.rtm, return; end; %_______________________________________________________________________ M=P(1).mat; A0 = make_A(M,x1,x2,x3,grad1./count,grad2./count,grad3./count,wt,lkp); if ~isempty(wt), b = (ave./count).*wt; else b = (ave./count); end clear ave grad1 grad2 grad3 % Loop over images %----------------------------------------------------------------------- spm_progress_bar('Init',length(P),'Registering Images to Mean'); for i=1:length(P), V = smooth_vol(P(i),flags.interp,flags.wrap,flags.fwhm); d = [size(V) 1 1 1]; ss = Inf; countdown = -1; for iter=1:64, [y1,y2,y3] = coords([0 0 0 0 0 0],M,P(i).mat,x1,x2,x3); msk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3))); if length(msk)<32, error_message(P(i)); end; F = spm_bsplins(V, y1(msk),y2(msk),y3(msk),deg); if ~isempty(wt), F = F.*wt(msk); end; A = A0(msk,:); b1 = b(msk); sc = sum(b1)/sum(F); b1 = b1-F*sc; soln = spm_atranspa(A)\(A'*b1); p = [0 0 0 0 0 0 1 1 1 0 0 0]; p(lkp) = p(lkp) + soln'; P(i).mat = inv(spm_matrix(p))*P(i).mat; pss = ss; ss = sum(b1.^2)/length(b1); if (pss-ss)/pss < 1e-8 && countdown == -1 % Stopped converging. % Do three final iterations to finish off with countdown = 2; end; if countdown ~= -1 if countdown==0, break; end; countdown = countdown -1; end; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); % Since we are supposed to be aligning everything to the first % image, then we had better do so %----------------------------------------------------------------------- M = M/P(1).mat; for i=1:length(P) P(i).mat = M*P(i).mat; end return; %_______________________________________________________________________ %_______________________________________________________________________ function [y1,y2,y3]=coords(p,M1,M2,x1,x2,x3) % Rigid body transformation of a set of coordinates. M = (inv(M2)*inv(spm_matrix(p))*M1); y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4); y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4); y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4); return; %_______________________________________________________________________ %_______________________________________________________________________ function V = smooth_vol(P,hld,wrp,fwhm) % Convolve the volume in memory. s = sqrt(sum(P.mat(1:3,1:3).^2)).^(-1)*(fwhm/sqrt(8*log(2))); x = round(6*s(1)); x = -x:x; y = round(6*s(2)); y = -y:y; z = round(6*s(3)); z = -z:z; x = exp(-(x).^2/(2*(s(1)).^2)); y = exp(-(y).^2/(2*(s(2)).^2)); z = exp(-(z).^2/(2*(s(3)).^2)); x = x/sum(x); y = y/sum(y); z = z/sum(z); i = (length(x) - 1)/2; j = (length(y) - 1)/2; k = (length(z) - 1)/2; d = [hld*[1 1 1]' wrp(:)]; V = spm_bsplinc(P,d); spm_conv_vol(V,V,x,y,z,-[i j k]); return; %_______________________________________________________________________ %_______________________________________________________________________ function A = make_A(M,x1,x2,x3,dG1,dG2,dG3,wt,lkp) % Matrix of rate of change of weighted difference w.r.t. parameter changes p0 = [0 0 0 0 0 0 1 1 1 0 0 0]; A = zeros(numel(x1),length(lkp)); for i=1:length(lkp) pt = p0; pt(lkp(i)) = pt(i)+1e-6; [y1,y2,y3] = coords(pt,M,M,x1,x2,x3); tmp = sum([y1-x1 y2-x2 y3-x3].*[dG1 dG2 dG3],2)/(-1e-6); if ~isempty(wt), A(:,i) = tmp.*wt; else A(:,i) = tmp; end end return; %_______________________________________________________________________ %_______________________________________________________________________ function error_message(P) str = { 'There is not enough overlap in the images',... 'to obtain a solution.',... ' ',... 'Offending image:',... P.fname,... ' ',... 'Please check that your header information is OK.',... 'The Check Reg utility will show you the initial',... 'alignment between the images, which must be',... 'within about 4cm and about 15 degrees in order',... 'for SPM to find the optimal solution.'}; spm('alert*',str,mfilename,sqrt(-1)); error('insufficient image overlap') %_______________________________________________________________________ %_______________________________________________________________________ function plot_parameters(P) fg=spm_figure('FindWin','Graphics'); if ~isempty(fg), P = cat(1,P{:}); if length(P)<2, return; end; Params = zeros(numel(P),12); for i=1:numel(P), Params(i,:) = spm_imatrix(P(i).mat/P(1).mat); end % display results % translation and rotation over time series %------------------------------------------------------------------- spm_figure('Clear','Graphics'); ax=axes('Position',[0.1 0.65 0.8 0.2],'Parent',fg,'Visible','off'); set(get(ax,'Title'),'String','Image realignment','FontSize',16,'FontWeight','Bold','Visible','on'); x = 0.1; y = 0.9; for i = 1:min([numel(P) 12]) text(x,y,[sprintf('%-4.0f',i) P(i).fname],'FontSize',10,'Interpreter','none','Parent',ax); y = y - 0.08; end if numel(P) > 12 text(x,y,'................ etc','FontSize',10,'Parent',ax); end ax=axes('Position',[0.1 0.35 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on'); plot(Params(:,1:3),'Parent',ax) s = ['x translation';'y translation';'z translation']; %text([2 2 2], Params(2, 1:3), s, 'Fontsize',10,'Parent',ax) legend(ax, s, 0) set(get(ax,'Title'),'String','translation','FontSize',16,'FontWeight','Bold'); set(get(ax,'Xlabel'),'String','image'); set(get(ax,'Ylabel'),'String','mm'); ax=axes('Position',[0.1 0.05 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on'); plot(Params(:,4:6)*180/pi,'Parent',ax) s = ['pitch';'roll ';'yaw ']; %text([2 2 2], Params(2, 4:6)*180/pi, s, 'Fontsize',10,'Parent',ax) legend(ax, s, 0) set(get(ax,'Title'),'String','rotation','FontSize',16,'FontWeight','Bold'); set(get(ax,'Xlabel'),'String','image'); set(get(ax,'Ylabel'),'String','degrees'); % print realigment parameters spm_print end return; %_______________________________________________________________________ %_______________________________________________________________________ function save_parameters(V) fname = [spm_str_manip(prepend(V(1).fname,'rp_'),'s') '.txt']; n = length(V); Q = zeros(n,6); for j=1:n, qq = spm_imatrix(V(j).mat/V(1).mat); Q(j,:) = qq(1:6); end; save(fname,'Q','-ascii'); return; %_______________________________________________________________________ %_______________________________________________________________________ function PO = prepend(PI,pre) [pth,nm,xt,vr] = spm_fileparts(deblank(PI)); PO = fullfile(pth,[pre nm xt vr]); return; %_______________________________________________________________________
github
spm/spm5-master
spm_config_realign_and_unwarp.m
.m
spm5-master/spm_config_realign_and_unwarp.m
35,460
utf_8
fbec3386cd1dc0e8d8a2121f0e5d0359
function opts = spm_config_realign_and_unwarp % Configuration file for realign and unwarping jobs %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Darren R. Gitelman % $Id: spm_config_realign_and_unwarp.m 1032 2007-12-20 14:45:55Z john $ %_______________________________________________________________________ quality.type = 'entry'; quality.name = 'Quality'; quality.tag = 'quality'; quality.strtype = 'r'; quality.num = [1 1]; quality.def = 'realign.estimate.quality'; quality.extras = [0 1]; quality.help = {[... 'Quality versus speed trade-off. Highest quality (1) gives most ',... 'precise results, whereas lower qualities gives faster realignment. ',... 'The idea is that some voxels contribute little to the estimation of ',... 'the realignment parameters. This parameter is involved in selecting ',... 'the number of voxels that are used.']}; %------------------------------------------------------------------------ weight.type = 'files'; weight.name = 'Weighting'; weight.tag = 'weight'; weight.filter = 'image'; weight.num = [0 1]; weight.val = {{}}; weight.help = {[... 'The option of providing a weighting image to weight each voxel ',... 'of the reference image differently when estimating the realignment ',... 'parameters. The weights are proportional to the inverses of the ',... 'standard deviations. ',... 'For example, when there is a lot of extra-brain motion - e.g., during ',... 'speech, or when there are serious artifacts in a particular region of ',... 'the images.']}; %------------------------------------------------------------------------ einterp.type = 'menu'; einterp.name = 'Interpolation'; einterp.tag = 'einterp'; einterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline ',... '3rd Degree B-Spline','4th Degree B-Spline','5th Degree B-Spline ',... '6th Degree B-Spline','7th Degree B-Spline'}; einterp.values = {0,1,2,3,4,5,6,7}; einterp.def = 'realign.estimate.interp'; einterp.help = {... ['The method by which the images are sampled when being written in a ',... 'different space. '],... [' Nearest Neighbour ',... ' - Fastest, but not normally recommended. '],... [' Bilinear Interpolation ',... ' - OK for PET, or realigned fMRI. '],... [' B-spline Interpolation/* \cite{thevenaz00a} ',... ' - Better quality (but slower) interpolation, especially ',... ' with higher degree splines. Do not use B-splines when ',... ' there is any region of NaN or Inf in the images. ']}; %------------------------------------------------------------------------ ewrap.type = 'menu'; ewrap.name = 'Wrapping'; ewrap.tag = 'ewrap'; ewrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z ',... 'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'}; ewrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]}; ewrap.def = 'realign.estimate.wrap'; ewrap.help = {... 'These are typically: ',... ' No wrapping - for images that have already ',... ' been spatially transformed. ',... ' Wrap in Y - for (un-resliced) MRI where phase encoding ',... ' is in the Y direction (voxel space).'}; %------------------------------------------------------------------------ fwhm.type = 'entry'; fwhm.name = 'Smoothing (FWHM)'; fwhm.tag = 'fwhm'; fwhm.num = [1 1]; fwhm.strtype = 'e'; p1 = [... 'The FWHM of the Gaussian smoothing kernel (mm) applied to the ',... 'images before estimating the realignment parameters.']; p2 = ' * PET images typically use a 7 mm kernel.'; p3 = ' * MRI images typically use a 5 mm kernel.'; fwhm.help = {p1,'',p2,'',p3}; %------------------------------------------------------------------------ sep.type = 'entry'; sep.name = 'Separation'; sep.tag = 'sep'; sep.num = [1 1]; sep.strtype = 'e'; sep.val = {4}; sep.help = {[... 'The separation (in mm) between the points sampled in the ',... 'reference image. Smaller sampling distances gives more accurate ',... 'results, but will be slower.']}; %------------------------------------------------------------------------ rtm.type = 'menu'; rtm.name = 'Num Passes'; rtm.tag = 'rtm'; rtm.labels = {'Register to first','Register to mean'}; rtm.values = {0,1}; p1 = [... 'Register to first: Images are registered to the first image in the series. ',... 'Register to mean: A two pass procedure is used in order to register the ',... 'images to the mean of the images after the first realignment.']; p2 = ' * PET images are typically registered to the mean.'; p3 = ' * MRI images are typically registered to the first image.'; rtm.help = {p1,'',p2,'',p3}; %------------------------------------------------------------------------ basfcn.type = 'menu'; basfcn.name = 'Basis Functions'; basfcn.tag = 'basfcn'; basfcn.labels = {'8x8x*','10x10x*','12x12x*','14x14x*'}; basfcn.values = {[8 8],[10 10],[12 12],[14 14]}; basfcn.def = 'unwarp.estimate.basfcn'; basfcn.help = {[... 'Number of basis functions to use for each dimension. ',... 'If the third dimension is left out, the order for that ',... 'dimension is calculated to yield a roughly equal spatial ',... 'cut-off in all directions. Default: [12 12 *]']}; %------------------------------------------------------------------------ regorder.type = 'menu'; regorder.name = 'Regularisation'; regorder.tag = 'regorder'; regorder.labels = {'0','1','2','3'}; regorder.values = {0,1,2,3}; regorder.def = 'unwarp.estimate.regorder'; regorder.help = {[... 'Unwarp looks for the solution that maximises the likelihood ',... '(minimises the variance) while simultaneously maximising the ',... 'smoothness of the estimated field (c.f. Lagrange multipliers). ',... 'This parameter determines how to balance the compromise between ',... 'these (i.e. the value of the multiplier). Test it on your own ',... 'data (if you can be bothered) or go with the defaults. '],... '',[... 'Regularisation of derivative fields is based on the regorder''th ',... '(spatial) derivative of the field. The choices are ',... '0, 1, 2, or 3. Default: 1']}; %------------------------------------------------------------------------ lambda.type = 'menu'; lambda.name = 'Reg. Factor'; lambda.tag = 'lambda'; lambda.labels = {'A little','Medium','A lot'}; lambda.values = {1e4, 1e5, 1e6,}; lambda.def = 'unwarp.estimate.regwgt'; lambda.help = {'Regularisation factor. Default: Medium.'}; %------------------------------------------------------------------------ rem.type = 'menu'; rem.name = 'Re-estimate movement params'; rem.tag = 'rem'; rem.labels = {'Yes','No'}; rem.values = {1 0}; rem.def = 'unwarp.estimate.rem'; rem.help = {[... 'Re-estimation means that movement-parameters should be re-estimated ',... 'at each unwarping iteration. Default: Yes.']}; %------------------------------------------------------------------------ jm.type = 'menu'; jm.name = 'Jacobian deformations'; jm.tag = 'jm'; jm.labels = {'Yes','No'}; jm.values = {1 0}; jm.def = 'unwarp.estimate.jm'; jm.help = {[... 'In the defaults there is also an option to include Jacobian ',... 'intensity modulation when estimating the fields. "Jacobian ',... 'intensity modulation" refers to the dilution/concentration ',... 'of intensity that ensue as a consequence of the distortions. ',... 'Think of a semi-transparent coloured rubber sheet that you ',... 'hold against a white background. If you stretch a part of ',... 'the sheet (induce distortions) you will see the colour fading ',... 'in that particular area. In theory it is a brilliant idea to ',... 'include also these effects when estimating the field (see e.g. ',... 'Andersson et al, NeuroImage 20:870-888). In practice for this ',... 'specific problem it is NOT a good idea. Default: No']}; %------------------------------------------------------------------------ fot.type = 'entry'; fot.name = 'First-order effects'; fot.tag = 'fot'; fot.strtype = 'e'; fot.num = [1 Inf]; fot.val = {[4 5]}; p1 = [... 'Theoretically (ignoring effects of shimming) one would expect the ',... 'field to depend only on subject out-of-plane rotations. Hence the ',... 'default choice ("Pitch and Roll", i.e., [4 5]). Go with that unless you have very ',... 'good reasons to do otherwise']; p2 = [... 'Vector of first order effects to model. Movements to be modelled ',... 'are referred to by number. 1= x translation; 2= y translation; 3= z translation ',... '4 = x rotation, 5 = y rotation and 6 = z rotation.']; p3 = 'To model pitch & roll enter: [4 5]'; p4 = 'To model all movements enter: [1:6]'; p5 = 'Otherwise enter a customised set of movements to model'; fot.help = {p1,'',p2,'',p3,'',p4,'',p5}; %------------------------------------------------------------------------ sot.type = 'entry'; sot.name = 'Second-order effects'; sot.tag = 'sot'; sot.strtype = 'e'; sot.num = [1 Inf]; sot.val = {[]}; p1 = [... 'List of second order terms to model second derivatives of. This is entered ',... 'as a vector of movement parameters similar to first order effects, or leave blank for NONE']; p2 = 'Movements to be modelled are referred to by number:'; p3 = [... '1= x translation; 2= y translation; 3= z translation ',... '4 = x rotation, 5 = y rotation and 6 = z rotation.']; p4 = 'To model the interaction of pitch & roll enter: [4 5]'; p5 = 'To model all movements enter: [1:6]'; p6 = [... 'The vector will be expanded into an n x 2 matrix of effects. For example ',... '[4 5] will be expanded to:']; p7 = '[ 4 4'; p8 = ' 4 5'; p9 = ' 5 5 ]'; sot.help = {p1,'',p2,'',p3,'',p4,'',p5,'',p6,'',p7,'',p8,'',p9}; % put the expression in the context of the base workspace. % assignin('base','soe',@SOE) %---------------------------------------------------------------------- uwfwhm.type = 'entry'; uwfwhm.name = 'Smoothing for unwarp (FWHM)'; uwfwhm.tag = 'uwfwhm'; uwfwhm.num = [1 1]; uwfwhm.strtype = 'r'; uwfwhm.def = 'unwarp.estimate.fwhm'; uwfwhm.help = {... 'FWHM (mm) of smoothing filter applied to images prior to estimation of deformation fields.'}; %---------------------------------------------------------------------- noi.type = 'entry'; noi.name = 'Number of Iterations'; noi.tag = 'noi'; noi.num = [1 1]; noi.strtype = 'n'; noi.def = 'unwarp.estimate.noi'; noi.help = {'Maximum number of iterations. Default: 5.'}; %---------------------------------------------------------------------- expround.type = 'menu'; expround.name = 'Taylor expansion point'; expround.tag = 'expround'; expround.labels = {'Average','First','Last'}; expround.values = {'Average','First','Last'}; expround.def = 'unwarp.estimate.expround'; expround.help = {[... 'Point in position space to perform Taylor-expansion around. ',... 'Choices are (''First'', ''Last'' or ''Average''). ''Average'' should ',... '(in principle) give the best variance reduction. If a field-map acquired ',... 'before the time-series is supplied then expansion around the ''First'' ',... 'MIGHT give a slightly better average geometric fidelity.']}; %---------------------------------------------------------------------- %---------------------------------------------------------------------- unnecessary.type = 'const'; unnecessary.tag = 'unnecessary'; unnecessary.val = {[]}; unnecessary.name = 'No Phase Maps'; unnecessary.help = {'Precalculated phase maps not included in unwarping.'}; %---------------------------------------------------------------------- global defaults if ~isempty(defaults) && isfield(defaults,'modality') ... && strcmpi(defaults.modality,'pet'), fwhm.val = {7}; rtm.val = {1}; else fwhm.val = {5}; rtm.val = {0}; end; eoptions.type = 'branch'; eoptions.name = 'Estimation Options'; eoptions.tag = 'eoptions'; eoptions.val = {quality,sep,fwhm,rtm,einterp,ewrap,weight}; eoptions.help = {['Various registration options that could be modified to improve the results. ',... 'Whenever possible, the authors of SPM try to choose reasonable settings, but sometimes they can be improved.']}; %------------------------------------------------------------------------ which.type = 'menu'; which.name = 'Resliced images'; which.tag = 'which'; which.labels = {' All Images (1..n)',' Images 2..n ',... ' All Images + Mean Image',' Mean Image Only'}; which.values = {[2 0],[1 0],[2 1],[0 1]}; which.val = {[2 1]}; which.help = {... 'All Images (1..n) ',... [' This reslices all the images - including the first image selected '... ' - which will remain in its original position. '],... ' ',... 'Images 2..n ',... [' Reslices images 2..n only. Useful for if you wish to reslice ',... ' (for example) a PET image to fit a structural MRI, without ',... ' creating a second identical MRI volume. '],... ' ',... 'All Images + Mean Image ',... [' In addition to reslicing the images, it also creates a mean of the ',... ' resliced image. '],... ' ',... 'Mean Image Only ',... ' Creates the mean image only.'}; %------------------------------------------------------------------------ uwwhich.type = 'menu'; uwwhich.name = 'Reslices images (unwarp)?'; uwwhich.tag = 'uwwhich'; uwwhich.labels = {' All Images (1..n)',' All Images + Mean Image'}; uwwhich.values = {[2 0],[2 1]}; uwwhich.val = {[2 1]}; uwwhich.help = {... 'All Images (1..n) ',... ' This reslices and unwarps all the images. ',... ' ',... 'All Images + Mean Image ',... [' In addition to reslicing the images, it also creates a mean ',... ' of the resliced images.']}; %------------------------------------------------------------------------ rinterp.type = 'menu'; rinterp.name = 'Interpolation'; rinterp.tag = 'rinterp'; rinterp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline ',... '3rd Degree B-Spline','4th Degree B-Spline','5th Degree B-Spline ',... '6th Degree B-Spline','7th Degree B-Spline'}; rinterp.values = {0,1,2,3,4,5,6,7}; rinterp.def = 'realign.write.interp'; rinterp.help = {... ['The method by which the images are sampled when being written in a ',... 'different space. '],... [' Nearest Neighbour ',... ' - Fastest, but not normally recommended.'],... [' Bilinear Interpolation ',... ' - OK for PET, or realigned fMRI. ',... ' B-spline Interpolation/*\cite{thevenaz00a}*/'],... [' - Better quality (but slower) interpolation, especially ',... ' with higher degree splines. Do not use B-splines when ',... ' there is any region of NaN or Inf in the images. ']}; %------------------------------------------------------------------------ wrap.type = 'menu'; wrap.name = 'Wrapping'; wrap.tag = 'wrap'; wrap.labels = {'No wrap','Wrap X','Wrap Y','Wrap X & Y','Wrap Z ',... 'Wrap X & Z','Wrap Y & Z','Wrap X, Y & Z'}; wrap.values = {[0 0 0],[1 0 0],[0 1 0],[1 1 0],[0 0 1],[1 0 1],[0 1 1],[1 1 1]}; wrap.def = 'realign.write.wrap'; wrap.help = {... 'These are typically: ',... [' No wrapping - for PET or images that have already ',... ' been spatially transformed. '],... [' Wrap in Y - for (un-resliced) MRI where phase encoding ',... ' is in the Y direction (voxel space).']}; %------------------------------------------------------------------------ mask.type = 'menu'; mask.name = 'Masking'; mask.tag = 'mask'; mask.labels = {'Mask images','Dont mask images'}; mask.values = {1,0}; mask.def = 'realign.write.mask'; mask.help = {[... 'Because of subject motion, different images are likely to have different ',... 'patterns of zeros from where it was not possible to sample data. ',... 'With masking enabled, the program searches through the whole time series ',... 'looking for voxels which need to be sampled from outside the original ',... 'images. Where this occurs, that voxel is set to zero for the whole set ',... 'of images (unless the image format can represent NaN, in which case ',... 'NaNs are used where possible).']}; %------------------------------------------------------------------------ uweoptions.type = 'branch'; uweoptions.name = 'Unwarp Estimation Options'; uweoptions.tag = 'uweoptions'; uweoptions.val = {basfcn,regorder,lambda,jm,fot,sot,uwfwhm,rem,noi,expround}; uweoptions.help = {'Various registration & unwarping estimation options.'}; %------------------------------------------------------------------------ uwroptions.type = 'branch'; uwroptions.name = 'Unwarp Reslicing Options'; uwroptions.tag = 'uwroptions'; uwroptions.val = {uwwhich,rinterp,wrap,mask}; uwroptions.help = {'Various registration & unwarping estimation options.'}; %------------------------------------------------------------------------ scans.type = 'files'; scans.name = 'Images'; scans.tag = 'scans'; scans.num = [1 Inf]; scans.filter = 'image'; scans.help = {... 'Select scans for this session. ',[... 'In the coregistration step, the sessions are first realigned to ',... 'each other, by aligning the first scan from each session to the ',... 'first scan of the first session. Then the images within each session ',... 'are aligned to the first image of the session. ',... 'The parameter estimation is performed this way because it is assumed ',... '(rightly or not) that there may be systematic differences ',... 'in the images between sessions.']}; %------------------------------------------------------------------------ pmscan.type = 'files'; pmscan.name = 'Phase map (vdm* file)'; pmscan.tag = 'pmscan'; pmscan.num = [0 1]; pmscan.val = {{}}; pmscan.filter = 'image'; pmscan.ufilter = '^vdm5_.*'; pmscan.help = {[... 'Select pre-calculated phase map, or leave empty for no phase correction. ',... 'The vdm* file is assumed to be already in alignment with the first scan ',... 'of the first session.']}; %---------------------------------------------------------------------- data.type = 'branch'; data.name = 'Session'; data.tag = 'data'; data.val = {scans, pmscan}; p2 = [... 'Only add similar session data to a realign+unwarp branch, i.e., ',... 'choose Data or Data+phase map for all sessions, but don''t use them ',... 'interchangeably.']; p3 = [... 'In the coregistration step, the sessions are first realigned to ',... 'each other, by aligning the first scan from each session to the ',... 'first scan of the first session. Then the images within each session ',... 'are aligned to the first image of the session. ',... 'The parameter estimation is performed this way because it is assumed ',... '(rightly or not) that there may be systematic differences ',... 'in the images between sessions.']; data.help = {p2,'',p3}; %------------------------------------------------------------------------ ruwdata.type = 'repeat'; ruwdata.name = 'Data'; ruwdata.tag = 'ruwdata'; ruwdata.values = {data}; ruwdata.num = [1 Inf]; ruwdata.help = {'Data sessions to unwarp.'}; %------------------------------------------------------------------------ opts.type = 'branch'; opts.name = 'Realign & Unwarp'; opts.tag = 'realignunwarp'; opts.val = {ruwdata,eoptions,uweoptions,uwroptions}; opts.prog = @realunwarp; opts.vfiles = @vfiles_rureslice; opts.modality = {'PET','FMRI','VBM'}; opts.help = {... 'Within-subject registration and unwarping of time series.',... '',... [... 'The realignment part of this routine realigns a time-series of images ',... 'acquired from the same subject using a least squares approach and a ',... '6 parameter (rigid body) spatial transformation. The first image in ',... 'the list specified by the user is used as a reference to which all ',... 'subsequent scans are realigned. The reference scan does not have to ',... 'the the first chronologically and it may be wise to chose a ',... '"representative scan" in this role.'],... '',... [... 'The aim is primarily to remove movement artefact in fMRI and PET ',... 'time-series (or more generally longitudinal studies). ',... '".mat" files are written for each of the input images. ',... 'The details of the transformation are displayed in the results window ',... 'as plots of translation and rotation. ',... 'A set of realignment parameters are saved for each session, named ',... 'rp_*.txt.'],... '',... [... 'In the coregistration step, the sessions are first realigned to ',... 'each other, by aligning the first scan from each session to the ',... 'first scan of the first session. Then the images within each session ',... 'are aligned to the first image of the session. ',... 'The parameter estimation is performed this way because it is assumed ',... '(rightly or not) that there may be systematic differences ',... 'in the images between sessions.'],... [... 'The paper/* \cite{ja_geometric}*/ is unfortunately a bit old now and describes none of ',... 'the newer features. Hopefully we''ll have a second paper out any ',... 'decade now.'],... '',... [... 'See also spm_uw_estimate.m for a detailed description of the ',... 'implementation. ',... 'Even after realignment there is considerable variance in fMRI time ',... 'series that covary with, and is most probably caused by, subject ',... 'movements/* \cite{ja_geometric}*/. It is also the case that this variance is typically ',... 'large compared to experimentally induced variance. Anyone interested ',... 'can include the estimated movement parameters as covariates in the ',... 'design matrix, and take a look at an F-contrast encompassing those ',... 'columns. It is quite dramatic. The result is loss of sensitivity, ',... 'and if movements are correlated to task specificity. I.e. we may ',... 'mistake movement induced variance for true activations. ',... 'The problem is well known, and several solutions have been suggested. ',... 'A quite pragmatic (and conservative) solution is to include the ',... 'estimated movement parameters (and possibly squared) as covariates ',... 'in the design matrix. Since we typically have loads of degrees of ',... 'freedom in fMRI we can usually afford this. The problems occur when ',... 'movements are correlated with the task, since the strategy above ',... 'will discard "good" and "bad" variance alike (i.e. remove also "true" ',... 'activations.'],... '',... [... 'The "covariate" strategy described above was predicated on a model ',... 'where variance was assumed to be caused by "spin history" effects, ',... 'but will work pretty much equally good/bad regardless of what the ',... 'true underlying cause is. Others have assumed that the residual variance ',... 'is caused mainly by errors introduced by the interpolation kernel in the ',... 'resampling step of the realignment. One has tried to solve this through ',... 'higher order resampling (huge Sinc kernels, or k-space resampling). ',... 'Unwarp is based on a different hypothesis regarding the residual ',... 'variance. EPI images are not particularly faithful reproductions of ',... 'the object, and in particular there are severe geometric distortions ',... 'in regions where there is an air-tissue interface (e.g. orbitofrontal ',... 'cortex and the anterior medial temporal lobes). In these areas in ',... 'particular the observed image is a severely warped version of reality, ',... 'much like a funny mirror at a fair ground. When one moves in front of ',... 'such a mirror ones image will distort in different ways and ones head ',... 'may change from very elongated to seriously flattened. If we were to ',... 'take digital snapshots of the reflection at these different positions ',... 'it is rather obvious that realignment will not suffice to bring them ',... 'into a common space.'],... '',... [... 'The situation is similar with EPI images, and an image collected for ',... 'a given subject position will not be identical to that collected at ',... 'another. We call this effect susceptibility-by-movement interaction. ',... 'Unwarp is predicated on the assumption that the susceptibility-by- ',... 'movement interaction is responsible for a sizable part of residual ',... 'movement related variance.'],... '',... [... 'Assume that we know how the deformations change when the subject ',... 'changes position (i.e. we know the derivatives of the deformations ',... 'with respect to subject position). That means that for a given time ',... 'series and a given set of subject movements we should be able to ',... 'predict the "shape changes" in the object and the ensuing variance ',... 'in the time series. It also means that, in principle, we should be ',... 'able to formulate the inverse problem, i.e. given the observed ',... 'variance (after realignment) and known (estimated) movements we should ',... 'be able to estimate how deformations change with subject movement. ',... 'We have made an attempt at formulating such an inverse model, and at ',... 'solving for the "derivative fields". A deformation field can be ',... 'thought of as little vectors at each position in space showing how ',... 'that particular location has been deflected. A "derivative field" ',... 'is then the rate of change of those vectors with respect to subject ',... 'movement. Given these "derivative fields" we should be able to remove ',... 'the variance caused by the susceptibility-by-movement interaction. ',... 'Since the underlying model is so restricted we would also expect ',... 'experimentally induced variance to be preserved. Our experiments ',... 'have also shown this to be true.'],... '',... [... 'In theory it should be possible to estimate also the "static" ',... 'deformation field, yielding an unwarped (to some true geometry) ',... 'version of the time series. In practise that doesn''t really seem to ',... 'work. Hence, the method deals only with residual movement related ',... 'variance induced by the susceptibility-by-movement interaction. ',... 'This means that the time-series will be undistorted to some ',... '"average distortion" state rather than to the true geometry. ',... 'If one wants additionally to address the issue of anatomical ',... 'fidelity one should combine Unwarp with a measured fieldmap.'],... '',... [... 'The description above can be thought of in terms of a Taylor ',... 'expansion of the field as a function of subject movement. Unwarp ',... 'alone will estimate the first (and optionally second, see below) ',... 'order terms of this expansion. It cannot estimate the zeroth ',... 'order term (the distortions common to all scans in the time ',... 'series) since that doesn''t introduce (almost) any variance in ',... 'the time series. The measured fieldmap takes the role of the ',... 'zeroth order term. Refer to the FieldMap toolbox and the ',... 'documents FieldMap.man and FieldMap_principles.man for a ',... 'description of how to obtain fieldmaps in the format expected ',... 'by Unwarp.'],... '',... [... 'If we think of the field as a function of subject movement it ',... 'should in principle be a function of six variables since rigid ',... 'body movement has six degrees of freedom. However, the physics ',... 'of the problem tells us that the field should not depend on ',... 'translations nor on rotation in a plane perpendicular to the ',... 'magnetic flux. Hence it should in principle be sufficient to ',... 'model the field as a function of out-of-plane rotations (i.e. ',... 'pitch and roll). One can object to this in terms of the effects ',... 'of shimming (object no longer immersed in a homogenous field) ',... 'that introduces a dependence on all movement parameters. In ',... 'addition SPM/Unwarp cannot really tell if the transversal ',... 'slices it is being passed are really perpendicular to the flux ',... 'or not. In practice it turns out thought that it is never (at ',... 'least we haven''t seen any case) necessary to include more ',... 'than Pitch and Roll. This is probably because the individual ',... 'movement parameters are typically highly correlated anyway, ',... 'which in turn is probably because most heads that we scan ',... 'are attached to a neck around which rotations occur. ',... 'On the subject of Taylor expansion we should mention that there ',... 'is the option to use a second-order expansion (through the ',... 'defaults) interface. This implies estimating also the ',... 'rate-of-change w.r.t. to some movement parameter of ',... 'the rate-of-change of the field w.r.t. some movement parameter ',... '(colloquially known as a second derivative). It can be quite ',... 'interesting to watch (and it is amazing that it is possible) ',... 'but rarely helpful/necessary.'],... '',... [... 'In the defaults there is also an option to include Jacobian ',... 'intensity modulation when estimating the fields. "Jacobian ',... 'intensity modulation" refers to the dilution/concentration ',... 'of intensity that ensue as a consequence of the distortions. ',... 'Think of a semi-transparent coloured rubber sheet that you ',... 'hold against a white background. If you stretch a part of ',... 'the sheet (induce distortions) you will see the colour fading ',... 'in that particular area. In theory it is a brilliant idea to ',... 'include also these effects when estimating the field (see e.g. ',... 'Andersson et al, NeuroImage 20:870-888). In practice for this ',... 'specific problem it is NOT a good idea.'],... '',... [... 'It should be noted that this is a method intended to correct ',... 'data afflicted by a particular problem. If there is little ',... 'movement in your data to begin with this method will do you little ',... 'good. If on the other hand there is appreciable movement in your ',... 'data (>1deg) it will remove some of that unwanted variance. If, ',... 'in addition, movements are task related it will do so without ',... 'removing all your "true" activations. ',... 'The method attempts to minimise total (across the image volume) ',... 'variance in the data set. It should be realised that while ',... '(for small movements) a rather limited portion of the total ',... 'variance is removed, the susceptibility-by-movement interaction ',... 'effects are quite localised to "problem" areas. Hence, for a ',... 'subset of voxels in e.g. frontal-medial and orbitofrontal cortices ',... 'and parts of the temporal lobes the reduction can be quite dramatic ',... '(>90). ',... 'The advantages of using Unwarp will also depend strongly on the ',... 'specifics of the scanner and sequence by which your data has been ',... 'acquired. When using the latest generation scanners distortions ',... 'are typically quite small, and distortion-by-movement interactions ',... 'consequently even smaller. A small check list in terms of ',... 'distortions is '],... 'a) Fast gradients->short read-out time->small distortions ',... 'b) Low field (i.e. <3T)->small field changes->small distortions ',... 'c) Low res (64x64)->short read-out time->small distortions ',... 'd) SENSE/SMASH->short read-out time->small distortions ',[... 'If you can tick off all points above chances are you have minimal ',... 'distortions to begin with and you can say "sod Unwarp" (but not ',... 'to our faces!).']};... %------------------------------------------------------------------------ %------------------------------------------------------------------------ return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function realunwarp(varargin) job = varargin{1}; % assemble flags %----------------------------------------------------------------------- % assemble realignment estimation flags. flags.quality = job.eoptions.quality; flags.fwhm = job.eoptions.fwhm; flags.sep = job.eoptions.sep; flags.rtm = job.eoptions.rtm; flags.PW = strvcat(job.eoptions.weight); flags.interp = job.eoptions.einterp; flags.wrap = job.eoptions.ewrap; uweflags.order = job.uweoptions.basfcn; uweflags.regorder = job.uweoptions.regorder; uweflags.lambda = job.uweoptions.lambda; uweflags.jm = job.uweoptions.jm; uweflags.fot = job.uweoptions.fot; if ~isempty(job.uweoptions.sot) cnt = 1; for i=1:size(job.uweoptions.sot,2) for j=i:size(job.uweoptions.sot,2) sotmat(cnt,1) = job.uweoptions.sot(i); sotmat(cnt,2) = job.uweoptions.sot(j); cnt = cnt+1; end end else sotmat = []; end uweflags.sot = sotmat; uweflags.fwhm = job.uweoptions.uwfwhm; uweflags.rem = job.uweoptions.rem; uweflags.noi = job.uweoptions.noi; uweflags.exp_round = job.uweoptions.expround; uwrflags.interp = job.uwroptions.rinterp; uwrflags.wrap = job.uwroptions.wrap; uwrflags.mask = job.uwroptions.mask; uwrflags.which = job.uwroptions.uwwhich(1); uwrflags.mean = job.uwroptions.uwwhich(2); if uweflags.jm == 1 uwrflags.udc = 2; else uwrflags.udc = 1; end %--------------------------------------------------------------------- % assemble files %--------------------------------------------------------------------- P = {}; for i = 1:numel(job.data) P{i} = strvcat(job.data(i).scans{:}); if ~isempty(job.data(i).pmscan) sfP{i} = job.data(i).pmscan{1}; else sfP{i} = []; end end % realign %---------------------------------------------------------------- spm_realign(P,flags); for i = 1:numel(P) uweflags.sfP = sfP{i}; % unwarp estimate %---------------------------------------------------------------- tmpP = spm_vol(P{i}(1,:)); uweflags.M = tmpP.mat; ds = spm_uw_estimate(P{i},uweflags); ads(i) = ds; [path,name] = fileparts(P{i}(1,:)); pefile = fullfile(path,[name '_uw.mat']); if spm_matlab_version_chk('7') >= 0 save(pefile,'-V6','ds'); else save(pefile,'ds'); end; end; % unwarp write - done at the single subject level since Batch % forwards one subjects data at a time for analysis, assuming % that subjects should be grouped as new spatial nodes. Sessions % should be within subjects. %---------------------------------------------------------------- spm_uw_apply(ads,uwrflags); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function vf = vfiles_rureslice(job) P = job.data; if numel(P)>0 && iscell(P(1).scans), P = cat(1,P(:).scans); end; switch job.uwroptions.uwwhich(1), case 0, vf = {}; case 2, vf = cell(numel(P),1); for i=1:length(vf), [pth,nam,ext,num] = spm_fileparts(P{i}); vf{i} = fullfile(pth,['u', nam, ext, num]); end; end; if job.uwroptions.uwwhich(2), [pth,nam,ext,num] = spm_fileparts(P{1}); vf = {vf{:}, fullfile(pth,['meanu', nam, ext, num])}; end;
github
spm/spm5-master
spm_surf.m
.m
spm5-master/spm_surf.m
9,530
utf_8
10f87454cf682a1c4a3bac82b13549a0
function spm_surf(P,mode,thresh) % Surface extraction. % FORMAT spm_surf % % This surface extraction is not particularly sophisticated. It simply % smooths the data slightly and extracts the surface at a threshold of % 0.5. Optionally, a vector of thresholds can be supplied and a surface % will be extracted for each threshold. This does only work for extracted % surfaces, not for renderings. % % Inputs: % c1xxx.img & c2xxx.img - grey and white matter segments created % using the segmentation routine. These can be manually cleaned up % first using e.g., MRIcro. % % Outputs: % A "render_xxx.mat" file can be produced that can be used for % rendering activations on to. % % A "surf_xxx.mat" file can also be written, which is created using % Matlab's isosurface function. % This extracted brain surface can be viewed using code something % like: % FV = load(spm_select(1,'^surf_.*\.mat$','Select surface data')); % fg = spm_figure('GetWin','Graphics'); % ax = axes('Parent',fg); % p = patch(FV, 'Parent',ax,... % 'FaceColor', [0.8 0.7 0.7], 'FaceVertexCData', [],... % 'EdgeColor', 'none',... % 'FaceLighting', 'phong',... % 'SpecularStrength' ,0.7, 'AmbientStrength', 0.1,... % 'DiffuseStrength', 0.7, 'SpecularExponent', 10); % set(0,'CurrentFigure',fg); % set(fg,'CurrentAxes',ax); % l = camlight(-40, 20); % axis image; % rotate3d on; % % % The surface can also be save as OBJ format, as used by Alias|Wavefront. % See e.g. http://www.nada.kth.se/~asa/Ray/matlabobj.html %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_surf.m 660 2006-10-20 12:22:05Z volkmar $ if nargin==0, [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Surface'); SPMid = spm('FnBanner',mfilename,'$Rev: 660 $'); spm_help('!ContextHelp',mfilename); P = spm_select([1 Inf],'image','Select images'); mode = spm_input('Save','+1','m',... ['Save Rendering|Save Extracted Surface|'... 'Save Rendering and Surface|Save Surface as OBJ format'],[1 2 3 4],3); else CmdLine = 0; Finter = spm_figure('GetWin','Interactive'); end; if nargin < 3 thresh = .5; end; spm('FigName','Surface: working',Finter,CmdLine); do_it(P,mode,thresh); spm('FigName','Surface: done',Finter,CmdLine); return; %_______________________________________________________________________ %_______________________________________________________________________ function do_it(P,mode,thresh) spm('Pointer','Watch') V = spm_vol(P); br = zeros(V(1).dim(1:3)); for i=1:V(1).dim(3), B = spm_matrix([0 0 i]); tmp = spm_slice_vol(V(1),B,V(1).dim(1:2),1); for j=2:length(V), M = V(j).mat\V(1).mat*B; tmp = tmp + spm_slice_vol(V(j),M,V(1).dim(1:2),1); end; br(:,:,i) = tmp; end; % Build a 3x3x3 seperable smoothing kernel and smooth %----------------------------------------------------------------------- kx=[0.75 1 0.75]; ky=[0.75 1 0.75]; kz=[0.75 1 0.75]; sm=sum(kron(kron(kz,ky),kx))^(1/3); kx=kx/sm; ky=ky/sm; kz=kz/sm; spm_conv_vol(br,br,kx,ky,kz,-[1 1 1]); [pth,nam,ext] = fileparts(V(1).fname); if any(mode==[1 3]), % Produce rendering %----------------------------------------------------------------------- matname = fullfile(pth,['render_' nam '.mat']); tmp = struct('dat',br,'dim',size(br),'mat',V(1).mat); renviews(tmp,matname); end; if any(mode==[2 3 4]), % Produce extracted surface %----------------------------------------------------------------------- tmp = struct('dat',br,'dim',size(br),'mat',V(1).mat); for k=1:numel(thresh) [faces,vertices] = isosurface(br,thresh(k)); % Swap around x and y because isosurface does for some % wierd and wonderful reason. Mat = V(1).mat(1:3,:)*[0 1 0 0;1 0 0 0;0 0 1 0; 0 0 0 1]; vertices = (Mat*[vertices' ; ones(1,size(vertices,1))])'; if numel(thresh)==1 nam1 = nam; else nam1 = sprintf('%s-%d',nam,k); end; if any(mode==[2 3]), matname = fullfile(pth,['surf_' nam1 '.mat']); if spm_matlab_version_chk('7.0') >=0, save(matname,'-V6','faces','vertices'); else save(matname,'faces','vertices'); end; end; if any(mode==[4]), fname = fullfile(pth,[nam1 '.obj']); fid = fopen(fname,'w'); fprintf(fid,'# Created with SPM5 (%s v %s) on %s\n', mfilename,'$Rev: 660 $',date); fprintf(fid,'v %.3f %.3f %.3f\n',vertices'); fprintf(fid,'g Cortex\n'); % Group Cortex fprintf(fid,'f %d %d %d\n',faces'); fprintf(fid,'g\n'); fclose(fid); end; end; end; spm('Pointer') return; %_______________________________________________________________________ %_______________________________________________________________________ function renviews(V,oname) % Produce images for rendering activations to % % FORMAT renviews(V,oname) % V - mapped image to render, or alternatively % a structure of: % V.dat - 3D array % V.dim - size of 3D array % V.mat - affine mapping from voxels to millimeters % oname - the name of the render.mat file. %_______________________________________________________________________ % % Produces a matrix file "render_xxx.mat" which contains everything that % "spm_render" is likely to need. % % Ideally, the input image should contain values in the range of zero % and one, and be smoothed slightly. A threshold of 0.5 is used to % distinguish brain from non-brain. %_______________________________________________________________________ linfun = inline('fprintf([''%-30s%s''],x,[repmat(sprintf(''\b''),1,30)])','x'); linfun('Rendering: '); linfun('Rendering: Transverse 1..'); rend{1} = make_struct(V,[pi 0 pi/2]); linfun('Rendering: Transverse 2..'); rend{2} = make_struct(V,[0 0 pi/2]); linfun('Rendering: Saggital 1..'); rend{3} = make_struct(V,[0 pi/2 pi]); linfun('Rendering: Saggital 2..'); rend{4} = make_struct(V,[0 pi/2 0]); linfun('Rendering: Coronal 1..'); rend{5} = make_struct(V,[pi/2 pi/2 0]); linfun('Rendering: Coronal 2..'); rend{6} = make_struct(V,[pi/2 pi/2 pi]); linfun('Rendering: Save..'); if spm_matlab_version_chk('7') >=0 save(oname,'-V6','rend'); else save(oname,'rend'); end; linfun(' '); disp_renderings(rend); spm_print; return; %_______________________________________________________________________ %_______________________________________________________________________ function str = make_struct(V,thetas) [D,M] = matdim(V.dim(1:3),V.mat,thetas); [ren,dep] = make_pic(V,M*V.mat,D); str = struct('M',M,'ren',ren,'dep',dep); return; %_______________________________________________________________________ %_______________________________________________________________________ function [ren,zbuf]=make_pic(V,M,D) % A bit of a hack to try and make spm_render_vol produce some slightly % prettier output. It kind of works... if isfield(V,'dat'), vv = V.dat; else, vv = V; end; [REN, zbuf, X, Y, Z] = spm_render_vol(vv, M, D, [0.5 1]); fw = max(sqrt(sum(M(1:3,1:3).^2))); msk = find(zbuf==1024); brn = ones(size(X)); brn(msk) = 0; brn = spm_conv(brn,fw); X(msk) = 0; Y(msk) = 0; Z(msk) = 0; msk = find(brn<0.5); tmp = brn; tmp(msk) = 100000; sX = spm_conv(X,fw)./tmp; sY = spm_conv(Y,fw)./tmp; sZ = spm_conv(Z,fw)./tmp; zbuf = spm_conv(zbuf,fw)./tmp; zbuf(msk) = 1024; vec = [-1 1 3]; % The direction of the lighting. vec = vec/norm(vec); [t,dx,dy,dz] = spm_sample_vol(vv,sX,sY,sZ,3); IM = inv(diag([0.5 0.5 1])*M(1:3,1:3))'; ren = IM(1:3,1:3)*[dx(:)' ; dy(:)' ; dz(:)']; len = sqrt(sum(ren.^2,1))+eps; ren = [ren(1,:)./len ; ren(2,:)./len ; ren(3,:)./len]; ren = reshape(vec*ren,[size(dx) 1]); ren(find(ren<0)) = 0; ren(msk) = ren(msk)-0.2; ren = ren*0.8+0.2; mx = max(ren(:)); ren = ren/mx; return; %_______________________________________________________________________ %_______________________________________________________________________ function disp_renderings(rend) Fgraph = spm_figure('GetWin','Graphics'); spm_results_ui('Clear',Fgraph); hght = 0.95; nrow = ceil(length(rend)/2); ax=axes('Parent',Fgraph,'units','normalized','Position',[0, 0, 1, hght],'Visible','off'); image(0,'Parent',ax); set(ax,'YTick',[],'XTick',[]); for i=1:length(rend), ren = rend{i}.ren; ax=axes('Parent',Fgraph,'units','normalized',... 'Position',[rem(i-1,2)*0.5, floor((i-1)/2)*hght/nrow, 0.5, hght/nrow],... 'Visible','off'); image(ren*64,'Parent',ax); set(ax,'DataAspectRatio',[1 1 1], ... 'PlotBoxAspectRatioMode','auto',... 'YTick',[],'XTick',[],'XDir','normal','YDir','normal'); end; drawnow; return; %_______________________________________________________________________ function [d,M] = matdim(dim,mat,thetas) R = spm_matrix([0 0 0 thetas]); bb = [[1 1 1];dim(1:3)]; c = [ bb(1,1) bb(1,2) bb(1,3) 1 bb(1,1) bb(1,2) bb(2,3) 1 bb(1,1) bb(2,2) bb(1,3) 1 bb(1,1) bb(2,2) bb(2,3) 1 bb(2,1) bb(1,2) bb(1,3) 1 bb(2,1) bb(1,2) bb(2,3) 1 bb(2,1) bb(2,2) bb(1,3) 1 bb(2,1) bb(2,2) bb(2,3) 1]'; tc = diag([2 2 1 1])*R*mat*c; tc = tc(1:3,:)'; mx = max(tc); mn = min(tc); M = spm_matrix(-mn(1:2))*diag([2 2 1 1])*R; d = ceil(abs(mx(1:2)-mn(1:2)))+1; return;
github
spm/spm5-master
spm_write_sn.m
.m
spm5-master/spm_write_sn.m
20,095
utf_8
165d7e8750b57d3108a160ea233ec808
function VO = spm_write_sn(V,prm,flags,extras) % Write Out Warped Images. % FORMAT VO = spm_write_sn(V,matname,flags,msk) % V - Images to transform (filenames or volume structure). % matname - Transformation information (filename or structure). % flags - flags structure, with fields... % interp - interpolation method (0-7) % wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences) % vox - voxel sizes (3 element vector - in mm) % Non-finite values mean use template vox. % bb - bounding box (2x3 matrix - in mm) % Non-finite values mean use template bb. % preserve - either 0 or 1. A value of 1 will "modulate" % the spatially normalised images so that total % units are preserved, rather than just % concentrations. % msk - An optional cell array for masking the spatially % normalised images (see below). % % Warped images are written prefixed by "w". % % Non-finite vox or bounding box suggests that values should be derived % from the template image. % % Don't use interpolation methods greater than one for data containing % NaNs. % _______________________________________________________________________ % % FORMAT msk = spm_write_sn(V,matname,flags,'mask') % V - Images to transform (filenames or volume structure). % matname - Transformation information (filename or structure). % flags - flags structure, with fields... % wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences) % vox - voxel sizes (3 element vector - in mm) % Non-finite values mean use template vox. % bb - bounding box (2x3 matrix - in mm) % Non-finite values mean use template bb. % msk - a cell array for masking a series of spatially normalised % images. % % % _______________________________________________________________________ % % FORMAT VO = spm_write_sn(V,prm,'modulate') % V - Spatially normalised images to modulate (filenames or % volume structure). % prm - Transformation information (filename or structure). % % After nonlinear spatial normalization, the relative volumes of some % brain structures will have decreased, whereas others will increase. % The resampling of the images preserves the concentration of pixel % units in the images, so the total counts from structures that have % reduced volumes after spatial normalization will be reduced by an % amount proportional to the volume reduction. % % This routine rescales images after spatial normalization, so that % the total counts from any structure are preserved. It was written % as an optional step in performing voxel based morphometry. % %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_write_sn.m 1020 2007-12-06 20:20:31Z john $ if isempty(V), return; end; if ischar(prm), prm = load(prm); end; if ischar(V), V = spm_vol(V); end; if nargin==3 && ischar(flags) && strcmpi(flags,'modulate'), if nargout==0, modulate(V,prm); else VO = modulate(V,prm); end; return; end; def_flags = struct('interp',1,'vox',NaN,'bb',NaN,'wrap',[0 0 0],'preserve',0); [def_flags.bb, def_flags.vox] = bbvox_from_V(prm.VG(1)); if nargin < 3, flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end; end; end; if ~all(isfinite(flags.vox(:))), flags.vox = def_flags.vox; end; if ~all(isfinite(flags.bb(:))), flags.bb = def_flags.bb; end; [x,y,z,mat] = get_xyzmat(prm,flags.bb,flags.vox); if nargin==4, if ischar(extras) && strcmpi(extras,'mask'), VO = get_snmask(V,prm,x,y,z,flags.wrap); return; end; if iscell(extras), msk = extras; end; end; if nargout>0 && length(V)>8, error('Too many images to save in memory'); end; if ~exist('msk','var') msk = get_snmask(V,prm,x,y,z,flags.wrap); end; if nargout==0, if isempty(prm.Tr), affine_transform(V,prm,x,y,z,mat,flags,msk); else nonlin_transform(V,prm,x,y,z,mat,flags,msk); end; else if isempty(prm.Tr), VO = affine_transform(V,prm,x,y,z,mat,flags,msk); else VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = affine_transform(V,prm,x,y,z,mat,flags,msk) [X,Y] = ndgrid(x,y); d = [flags.interp*[1 1 1]' flags.wrap(:)]; spm_progress_bar('Init',numel(V),'Resampling','volumes completed'); for i=1:numel(V), VO = make_hdr_struct(V(i),x,y,z,mat); if flags.preserve VO.fname = prepend(VO.fname,'m'); end detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat); if flags.preserve, VO.pinfo(1:2,:) = VO.pinfo(1:2,:)/detAff; end; %Dat= zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; C = spm_bsplinc(V(i),d); for j=1:length(z), % Cycle over planes [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF.mat*prm.Affine); dat = spm_bsplins(C,X2,Y2,Z2,d); if flags.preserve, dat = dat*detAff; end; dat(msk{j}) = NaN; Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; if nargout~=0, VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; else spm_write_vol(VO, Dat); end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk) [X,Y] = ndgrid(x,y); Tr = prm.Tr; BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); if flags.preserve, DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); end; d = [flags.interp*[1 1 1]' flags.wrap(:)]; spm_progress_bar('Init',numel(V),'Resampling','volumes completed'); for i=1:numel(V), VO = make_hdr_struct(V(i),x,y,z,mat); if flags.preserve VO.fname = prepend(VO.fname,'m'); end detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat); % Accumulate data %Dat= zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; C = spm_bsplinc(V(i),d); for j=1:length(z), % Cycle over planes % Nonlinear deformations %---------------------------------------------------------------------------- tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); X1 = X + BX*tx*BY'; Y1 = Y + BX*ty*BY'; Z1 = z(j) + BX*tz*BY'; [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF.mat*prm.Affine); dat = spm_bsplins(C,X2,Y2,Z2,d); dat(msk{j}) = NaN; if ~flags.preserve, Dat(:,:,j) = single(dat); else j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes. %------------------------------------------------------------------ dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); end; if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; if nargout==0, if flags.preserve, VO = rmfield(VO,'pinfo'); end VO = spm_write_vol(VO,Dat); else VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = modulate(V,prm) spm_progress_bar('Init',numel(V),'Modulating','volumes completed'); for i=1:numel(V), VO = V(i); VO = rmfield(VO,'pinfo'); VO.fname = prepend(VO.fname,'m'); detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat); %Dat = zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; [bb, vox] = bbvox_from_V(VO); [x,y,z,mat] = get_xyzmat(prm,bb,vox); if sum((mat(:)-VO.mat(:)).^2)>1e-7, error('Orientations not compatible'); end; Tr = prm.Tr; if isempty(Tr), for j=1:length(z), % Cycle over planes dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0); Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; else BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); for j=1:length(z), % Cycle over planes tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes. %------------------------------------------------------------------ dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0); dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; end; if nargout==0, VO = spm_write_vol(VO,Dat); else VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = make_hdr_struct(V,x,y,z,mat) VO = V; VO.fname = prepend(V.fname,'w'); VO.mat = mat; VO.dim(1:3) = [length(x) length(y) length(z)]; VO.pinfo = V.pinfo; VO.descrip = 'spm - 3D normalized'; return; %_______________________________________________________________________ %_______________________________________________________________________ function T2 = get_2Dtrans(T3,B,j) d = [size(T3) 1 1 1]; tmp = reshape(T3,d(1)*d(2),d(3)); T2 = reshape(tmp*B(j,:)',d(1),d(2)); return; %_______________________________________________________________________ %_______________________________________________________________________ function PO = prepend(PI,pre) [pth,nm,xt,vr] = spm_fileparts(deblank(PI)); PO = fullfile(pth,[pre nm xt vr]); return; %_______________________________________________________________________ %_______________________________________________________________________ function Mask = getmask(X,Y,Z,dim,wrp) % Find range of slice tiny = 5e-2; Mask = true(size(X)); if ~wrp(1), Mask = Mask & (X >= (1-tiny) & X <= (dim(1)+tiny)); end; if ~wrp(2), Mask = Mask & (Y >= (1-tiny) & Y <= (dim(2)+tiny)); end; if ~wrp(3), Mask = Mask & (Z >= (1-tiny) & Z <= (dim(3)+tiny)); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [X2,Y2,Z2] = mmult(X1,Y1,Z1,Mult) if length(Z1) == 1, X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + (Mult(1,3)*Z1 + Mult(1,4)); Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + (Mult(2,3)*Z1 + Mult(2,4)); Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + (Mult(3,3)*Z1 + Mult(3,4)); else X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4); Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4); Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [bb,vx] = bbvox_from_V(V) vx = sqrt(sum(V.mat(1:3,1:3).^2)); if det(V.mat(1:3,1:3))<0, vx(1) = -vx(1); end; o = V.mat\[0 0 0 1]'; o = o(1:3)'; bb = [-vx.*(o-1) ; vx.*(V.dim(1:3)-o)]; return; %_______________________________________________________________________ %_______________________________________________________________________ function msk = get_snmask(V,prm,x,y,z,wrap) % Generate a mask for where there is data for all images %----------------------------------------------------------------------- msk = cell(length(z),1); t1 = cat(3,V.mat); t2 = cat(1,V.dim); t = [reshape(t1,[16 length(V)])' t2(:,1:3)]; Tr = prm.Tr; [X,Y] = ndgrid(x,y); BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); if numel(V)>1 && any(any(diff(t,1,1))), spm_progress_bar('Init',length(z),'Computing available voxels','planes completed'); for j=1:length(z), % Cycle over planes Count = zeros(length(x),length(y)); if isempty(Tr), % Generate a mask for where there is data for all images %---------------------------------------------------------------------------- for i=1:numel(V), [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF.mat*prm.Affine); Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap); end; else % Nonlinear deformations %---------------------------------------------------------------------------- X1 = X + BX*get_2Dtrans(Tr(:,:,:,1),BZ,j)*BY'; Y1 = Y + BX*get_2Dtrans(Tr(:,:,:,2),BZ,j)*BY'; Z1 = z(j) + BX*get_2Dtrans(Tr(:,:,:,3),BZ,j)*BY'; % Generate a mask for where there is data for all images %---------------------------------------------------------------------------- for i=1:numel(V), [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF.mat*prm.Affine); Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap); end; end; msk{j} = uint32(find(Count ~= numel(V))); spm_progress_bar('Set',j); end; spm_progress_bar('Clear'); else for j=1:length(z), msk{j} = uint32([]); end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [x,y,z,mat] = get_xyzmat(prm,bb,vox) % The old voxel size and origin notation is used here. % This requires that the position and orientation % of the template is transverse. It would not be % straitforward to account for templates that are % in different orientations because the basis functions % would no longer be seperable. The seperable basis % functions mean that computing the deformation field % from the parameters is much faster. % bb = sort(bb); % vox = abs(vox); msk = find(vox<0); bb = sort(bb); bb(:,msk) = flipud(bb(:,msk)); % Adjust bounding box slightly - so it rounds to closest voxel. % Comment out if not needed. I chose not to change it because % it would lead to being bombarded by questions about spatially % normalised images not having the same dimensions. bb(:,1) = round(bb(:,1)/vox(1))*vox(1); bb(:,2) = round(bb(:,2)/vox(2))*vox(2); bb(:,3) = round(bb(:,3)/vox(3))*vox(3); M = prm.VG(1).mat; vxg = sqrt(sum(M(1:3,1:3).^2)); if det(M(1:3,1:3))<0, vxg(1) = -vxg(1); end; ogn = M\[0 0 0 1]'; ogn = ogn(1:3)'; % Convert range into range of voxels within template image x = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1); y = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2); z = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3); og = -vxg.*ogn; % Again, chose whether to round to closest voxel. of = -vox.*(round(-bb(1,:)./vox)+1); %of = bb(1,:)-vox; M1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1]; M2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1]; mat = prm.VG(1).mat*inv(M1)*M2; LEFTHANDED = true; if (LEFTHANDED && det(mat(1:3,1:3))>0) || (~LEFTHANDED && det(mat(1:3,1:3))<0), Flp = [-1 0 0 (length(x)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1]; mat = mat*Flp; x = flipud(x(:))'; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = write_dets(P,bb,vox) if nargin==1, job = P; P = job.P; bb = job.bb; vox = job.vox; end; spm_progress_bar('Init',numel(P),'Writing','volumes completed'); for i=1:numel(V), prm = load(deblank(P{i})); [x,y,z,mat] = get_xyzmat(prm,bb,vox); Tr = prm.Tr; BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); [pth,nam,ext,nm] = spm_fileparts(P{i}); VO = struct('fname',fullfile(pth,['jy_' nam ext nm]),... 'dim',[numel(x),numel(y),numel(z)],... 'dt',[spm_type('float32') spm_platform('bigend')],... 'pinfo',[1 0 0]',... 'mat',mat,... 'n',1,... 'descrip','Jacobian determinants'); VO = spm_create_vol(VO); detAff = det(prm.VF.mat*prm.Affine/prm.VG(1).mat); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; for j=1:length(z), % Cycle over planes % Nonlinear deformations tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); %---------------------------------------------------------------------------- j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes. %------------------------------------------------------------------ dat = (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); if numel(P)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; VO = spm_write_vol(VO,Dat); spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________
github
spm/spm5-master
spm_DesMtx.m
.m
spm5-master/spm_DesMtx.m
30,975
utf_8
fbbb25a149ba004e3f50c2089f236004
function [X,Pnames,Index,idx,jdx,kdx]=spm_DesMtx(varargin); % Design matrix construction from factor level and covariate vectors % FORMAT [X,Pnames] = spm_DesMtx(<FCLevels-Constraint-FCnames> list) % FORMAT [X,Pnames,Index,idx,jdx,kdx] = spm_DesMtx(FCLevels,Constraint,FCnames) % % <FCLevels-Constraints-FCnames> % - set of arguments specifying a portion of design matrix (see below) % - FCnames parameter, or Constraint and FCnames parameters, are optional % - a list of multiple <FCLevels-Constraint-FCnames> triples can be % specified, where FCnames or Constraint-FCnames may be omitted % within any triple. The program then works recursively. % % X - design matrix % Pnames - paramater names as (constructed from FCnames) - a cellstr % Index - integer index of factor levels % - only returned when computing a single design matrix partition % % idx,jdx,kdx - reference vectors mapping I & Index (described below) % - only returned when computing a single design matrix partition % for unconstrained factor effects ('-' or '~') % % ---------------- % - Utilities: % % FORMAT i = spm_DesMtx('pds',v,m,n) % Patterned data setting function - inspired by MINITAB's "SET" command % v - base pattern vector % m - (scalar natural number) #replications of elements of v [default 1] % n - (scalar natural number) #repeats of pattern [default 1] % i - resultant pattern vector, with v's elements replicated m times, % the resulting vector repeated n times. % % FORMAT [nX,nPnames] = spm_DesMtx('sca',X1,Pnames1,X2,Pnames2,...) % Produces a scaled design matrix nX with max(abs(nX(:))<=1, suitable % for imaging with: image((nX+1)*32) % X1,X2,... - Design matrix partitions % Pnames1, Pnames2,... - Corresponding parameter name string mtx/cellstr (opt) % nX - Scaled design matrix % nPnames - Concatenated parameter names for columns of nX % % FORMAT Fnames = spm_DesMtx('Fnames',Pnames) % Converts parameter names into suitable filenames % Pnames - string mtx/cellstr containing parameter names % Fnames - filenames derived from Pnames. (cellstr) % % FORMAT TPnames = spm_DesMtx('TeXnames',Pnames) % Removes '*'s and '@'s from Pnames, so TPnames suitable for TeX interpretation % Pnames - string mtx/cellstr containing parameter names % TPnames - TeX-ified parameter names % % FORMAT Map = spm_DesMtx('ParMap',aMap) % Returns Nx2 cellstr mapping (greek TeX) parameters to English names, % using the notation established in the SPMcourse notes. % aMap - (optional) Mx2 cellstr of additional or over-ride mappings % Map - cellstr of parameter names (col1) and corresponding English names (col2) % % FORMAT EPnames = spm_DesMtx('ETeXnames',Pnames,aMap) % Translates greek (TeX) parameter names into English using mapping given by % spm_DesMtx('ParMap',aMap) % Pnames - string mtx/cellstr containing parameter names % aMap - (optional) Mx2 cellstr of additional or over-ride mappings % EPnames - cellstr of converted parameter names %_______________________________________________________________________ % % Returns design matrix corresponding to given vectors containing % levels of a factor; two way interactions; covariates (n vectors); % ready-made sections of design matrix; and factor by covariate % interactions. % % The specification for the design matrix is passed in sets of arguments, % each set corresponding to a particular Factor/Covariate/&c., specifying % a section of the design matrix. The set of arguments consists of the % FCLevels matrix (Factor/Covariate levels), an optional constraint string, % and an optional (string) name matrix containing the names of the % Factor/Covariate/&c. % % MAIN EFFECTS: For a main effect, or single factor, the FCLevels % matrix is an integer vector whose values represent the levels of the % factor. The integer factor levels need not be positive, nor in % order. In the '~' constraint types (below), a factor level of zero % is ignored (treated as no effect), and no corresponding column of % design matrix is created. Effects for the factor levels are entered % into the design matrix *in increasing order* of the factor levels. % Check Pnames to find out which columns correspond to which levels of % the factor. % % TWO WAY INTERACTIONS: For a two way interaction effect between two % factors, the FCLevels matrix is an nx2 integer matrix whose columns % indicate the levels of the two factors. An effect is included for % each unique combination of the levels of the two factors. Again, % factor levels must be integer, though not necessarily positive. % Zero levels are ignored in the '~' constraint types described below. % % CONSTRAINTS: Each FactorLevels vector/matrix may be followed by an % (optional) ConstraintString. % % ConstraintStrings for main effects are: % '-' - No Constraint % '~' - Ignore zero level of factor % (I.e. cornerPoint constraint on zero level, % (same as '.0', except zero level is always ignored, % (even if factor only has zero level, in which case % (an empty DesMtx results and a warning is given % '+0' - sum-to-zero constraint % '+0m' - Implicit sum-to-zero constraint % '.' - CornerPoint constraint % '.0' - CornerPoint constraint applied to zero factor level % (warns if there is no zero factor level) % Constraints for two way interaction effects are % '-' - No Constraints % '~' - Ignore zero level of any factor % (I.e. cornerPoint constraint on zero level, % (same as '.ij0', except zero levels are always ignored % '+i0','+j0','+ij0' - sum-to-zero constraints % '.i', '.j', '.ij' - CornerPoint constraints % '.i0','.j0','.ij0' - CornerPoint constraints applied to zero factor level % (warns if there is no zero factor level) % '+i0m', '+j0m' - Implicit sum-to-zero constraints % % With the exception of the "ignore zero" '~' constraint, constraints % are only applied if there are sufficient factor levels. CornerPoint % and explicit sum-to-zero Constraints are applied to the last level of % the factor. % % The implicit sum-to-zero constraints "mean correct" appropriate rows % of the relevant design matrix block. For a main effect, constraint % '+0m' "mean corrects" the main effect block across columns, % corresponding to factor effects B_i, where B_i = B'_i - mean(B'_i) : % The B'_i are the fitted parameters, effectively *relative* factor % parameters, relative to their mean. This leads to a rank deficient % design matrix block. If Matlab's pinv, which implements a % Moore-Penrose pseudoinverse, is used to solve the least squares % problem, then the solution with smallest L2 norm is found, which has % mean(B'_i)=0 provided the remainder of the design is unique (design % matrix blocks of full rank). In this case therefore the B_i are % identically the B'_i - the mean correction imposes the constraint. % % % COVARIATES: The FCLevels matrix here is an nxc matrix whose columns % contain the covariate values. An effect is included for each covariate. % Covariates are identified by ConstraintString 'C'. % % % PRE-SPECIFIED DESIGN BLOCKS: ConstraintString 'X' identifies a % ready-made bit of design matrix - the effect is the same as 'C'. % % % FACTOR BY COVARIATE INTERACTIONS: are identified by ConstraintString % 'FxC'. The last column is understood to contain the covariate. Other % columns are taken to contain integer FactorLevels vectors. The % (unconstrained) interaction of the factors is interacted with the % covariate. Zero factor levels are ignored if ConstraintString '~FxC' % is used. % % % NAMES: Each Factor/Covariate can be 'named', by passing a name % string. Pass a string matrix, or cell array (vector) of strings, % with rows (cells) naming the factors/covariates in the respective % columns of the FCLevels matrix. These names default to <Fac>, <Cov>, % <Fac1>, <Fac2> &c., and are used in the construction of the Pnames % parameter names. % E.g. for an interaction, spm_DesMtx([F1,F2],'+ij0',['subj';'cond']) % giving parameter names such as subj*cond_{1,2} etc... % % Pnames returns a string matrix whose successive rows describe the % effects parameterised in the corresponding columns of the design % matrix. `Fac1*Fac2_{2,3}' would refer to the parameter for the % interaction of the two factors Fac1 & Fac2, at the 2nd level of the % former and the 3rd level of the latter. Other forms are % - Simple main effect (level 1) : <Fac>_{1} % - Three way interaction (level 1,2,3) : <Fac1>*<Fac2>*<Fac3>_{1,2,3} % - Two way factor interaction by covariate interaction : % : <Cov>@<Fac1>*<Fac2>_{1,1} % - Column 3 of prespecified DesMtx block (if unnamed) % : <X> [1] % The special characters `_*()[]{}' are recognised by the scaling % function (spm_DesMtx('sca',...), and should therefore be avoided % when naming effects and covariates. % % % INDEX: An Integer Index matrix is returned if only a single block of % design matrix is being computed (single set of parameters). It % indexes the actual order of the effect levels in the design matrix block. % (Factor levels are introduced in order, regardless of order of % appearence in the factor index matrices, so that the parameters % vector has a sensible order.) This is used to aid recursion. % % Similarly idx,jdx & kdx are indexes returned for a single block of % design matrix consisting of unconstrained factor effects ('-' or '~'). % These indexes map I and Index (in a similar fashion to the `unique` % function) as follows: % - idx & jdx are such that I = Index(:,jdx)' and Index = I(idx,:)' % where vector I is given as a column vector % - If the "ignore zeros" constraint '~' is used, then kdx indexes the % non-zero (combinations) of factor levels, such that % I(kdx,:) = Index(:,jdx)' and Index == I(kdx(idx),:)' % % ---------------- % % The "patterned data setting" (spm_DesMtx('pds'...) is a simple % utility for setting patterned indicator vectors, inspired by % MINITAB's "SET" command. % % The vector v has it's elements replicated m times, and the resulting % vector is itself repeated n times, giving a resultant vector i of % length n*m*length(v) % % Examples: % spm_DesMtx('pds',1:3) % = [1,2,3] % spm_DesMtx('pds',1:3,2) % = [1,1,2,2,3,3] % spm_DesMtx('pds',1:3,2,3) % = [1,1,2,2,3,3,1,1,2,2,3,3,1,1,2,2,3,3] % NB: MINITAB's "SET" command has syntax n(v)m: % % ---------------- % % The design matrix scaling feature is designed to return a scaled % version of a design matrix, with values in [-1,1], suitable for % visualisation. Special care is taken to apply the same normalisation % to blocks of design matrix reflecting a single effect, to preserve % appropriate relationships between columns. Identification of effects % corresponding to columns of design matrix portions is via the parameter % names matrices. The design matrix may be passed in any number of % parts, provided the corresponding parameter names are given. It is % assummed that the block representing an effect is contained within a % single partition. Partitions supplied without corresponding parameter % names are scaled on a column by column basis, the parameters labelled as % <UnSpec> in the returned nPnames matrix. % % Effects are identified using the special characters `_*()[]{}' used in % parameter naming as follows: (here ? is a wildcard) % - ?(?) - general block (column normalised) % - ?[?] - specific block (block normalised) % - ?_{?} - main effect or interaction of main effects % - ?@?_{?} - factor by covariate interaction % Blocks are identified by looking for runs of parameters of the same type % with the same names: E.g. a block of main effects for factor 'Fac1' % would have names like Fac1_{?}. % % Scaling is as follows: % * fMRI blocks are scaled around zero to lie in [-1,1] % * No scaling is carried out if max(abs(tX(:))) is in [.4,1] % This protects dummy variables from normalisation, even if % using implicit sum-to-zero constraints. % * If the block has a single value, it's replaced by 1's % * FxC blocks are normalised so the covariate values cover [-1,1] % but leaving zeros as zero. % * Otherwise, block is scaled to cover [-1,1]. % %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Andrew Holmes % $Id: spm_DesMtx.m 112 2005-05-04 18:20:52Z john $ %-Parse arguments for recursive construction of design matrices %======================================================================= if nargin==0 error('Insufficient arguments'), end if ischar(varargin{1}) %-Non-recursive action string usage Constraint=varargin{1}; elseif nargin>=2 & ~(ischar(varargin{2}) | iscell(varargin{2})) [X1,Pnames1]=spm_DesMtx(varargin{1}); [X2,Pnames2]=spm_DesMtx(varargin{2:end}); X=[X1,X2]; Pnames=[Pnames1;Pnames2]; return elseif nargin>=3 & ~(ischar(varargin{3}) | iscell(varargin{3})) [X1,Pnames1]=spm_DesMtx(varargin{1:2}); [X2,Pnames2]=spm_DesMtx(varargin{3:end}); X=[X1,X2]; Pnames=[Pnames1;Pnames2]; return elseif nargin>=4 [X1,Pnames1]=spm_DesMtx(varargin{1:3}); [X2,Pnames2]=spm_DesMtx(varargin{4:end}); X=[X1,X2]; Pnames=[Pnames1;Pnames2]; return else %-If I is a vector, make it a column vector I=varargin{1}; if size(I,1)==1, I=I'; end %-Sort out constraint and Factor/Covariate name parameters if nargin<2, Constraint='-'; else, Constraint=varargin{2}; end if isempty(I), Constraint='mt'; end if nargin<3, FCnames={}; else, FCnames=varargin{3}; end if char(FCnames), FCnames=cellstr(FCnames); end end switch Constraint, case 'mt' %-Empty I case %======================================================================= X = []; Pnames = {}; Index = []; case {'C','X'} %-Covariate effect, or ready-made design matrix %======================================================================= %-I contains a covariate (C), or is to be inserted "as is" (X) X = I; %-Construct parameter name index %----------------------------------------------------------------------- if isempty(FCnames) if strcmp(Constraint,'C'), FCnames={'<Cov>'}; else, FCnames={'<X>'}; end end if length(FCnames)==1 & size(X,2)>1 Pnames = cell(size(X,2),1); for i=1:size(X,2) Pnames{i} = sprintf('%s [%d]',FCnames{1},i); end elseif length(FCnames)~=size(X,2) error('FCnames doesn''t match covariate/X matrix') else Pnames = FCnames; end case {'-(1)','~(1)'} %-Simple main effect ('~' ignores zero levels) %======================================================================= %-Sort out arguments %----------------------------------------------------------------------- if size(I,2)>1, error('Simple main effect requires vector index'), end if any(I~=floor(I)), error('Non-integer indicator vector'), end if isempty(FCnames), FCnames = {'<Fac>'}; elseif length(FCnames)>1, error('Too many FCnames'), end nXrows = size(I,1); % Sort out unique factor levels - ignore zero level in '~(1)' usage %----------------------------------------------------------------------- if Constraint(1)~='~' [Index,idx,jdx] = unique(I'); kdx = [1:nXrows]; else [Index,idx,jdx] = unique(I(I~=0)'); kdx = find(I~=0)'; if isempty(Index) X=[]; Pnames={}; Index=[]; warning(['factor has only zero level - ',... 'returning empty DesMtx partition']) return end end %-Set up unconstrained X matrix & construct parameter name index %----------------------------------------------------------------------- nXcols = length(Index); %-Columns in ascending order of corresponding factor level X = zeros(nXrows,nXcols); Pnames = cell(nXcols,1); for ii=1:nXcols %-ii indexes i in Index X(:,ii) = I==Index(ii); %-Can't use: for i=Index, X(:,i) = I==i; end % in case Index has holes &/or doesn't start at 1! Pnames{ii} = sprintf('%s_{%d}',FCnames{1},Index(ii)); end %-Don't append effect level if only one level if nXcols==1, Pnames=FCnames; end case {'-','~'} %-Main effect / interaction ('~' ignores zero levels) %======================================================================= if size(I,2)==1 %-Main effect - process directly [X,Pnames,Index,idx,jdx,kdx] = spm_DesMtx(I,[Constraint,'(1)'],FCnames); return end if any((I(:))~=floor(I(:))), error('Non-integer indicator vector'), end % Sort out unique factor level combinations & build design matrix %----------------------------------------------------------------------- %-Make "raw" index to unique effects nI = I - ones(size(I,1),1)*min(I); tmp = max(I)-min(I)+1; tmp = [fliplr(cumprod(tmp(end:-1:2))),1]; rIndex = sum(nI.*(ones(size(I,1),1)*tmp),2)+1; %-Ignore combinations where any factor has level zero in '~' usage if Constraint(1)=='~' rIndex(any(I==0,2))=0; if all(rIndex==0) X=[]; Pnames={}; Index=[]; warning(['no non-zero factor level combinations - ',... 'returning empty DesMtx partition']) return end end %-Build design matrix based on unique factor combinations [X,null,sIndex,idx,jdx,kdx]=spm_DesMtx(rIndex,[Constraint,'(1)']); %-Sort out Index matrix Index = I(kdx(idx),:)'; %-Construct parameter name index %----------------------------------------------------------------------- if isempty(FCnames) tmp = ['<Fac1>',sprintf('*<Fac%d>',2:size(I,2))]; elseif length(FCnames)==size(I,2) tmp = [FCnames{1},sprintf('*%s',FCnames{2:end})]; else error('#FCnames mismatches #Factors in interaction') end Pnames = cell(size(Index,2),1); for c = 1:size(Index,2) Pnames{c} = ... [sprintf('%s_{%d',tmp,Index(1,c)),sprintf(',%d',Index(2:end,c)),'}']; end case {'FxC','-FxC','~FxC'} %-Factor dependent covariate effect % ('~' ignores zero factor levels) %======================================================================= %-Check %----------------------------------------------------------------------- if size(I,2)==1, error('FxC requires multi-column I'), end F = I(:,1:end-1); C = I(:,end); if ~all(all(F==floor(F),1),2) error('non-integer indicies in F partition of FxC'), end if isempty(FCnames) Fnames = ''; Cnames = '<Cov>'; elseif length(FCnames)==size(I,2) Fnames = FCnames(1:end-1); Cnames = FCnames{end}; else error('#FCnames mismatches #Factors+#Cov in FxC') end %-Set up design matrix X & names matrix - ignore zero levels if '~FxC' use %----------------------------------------------------------------------- if Constraint(1)~='~', [X,Pnames,Index] = spm_DesMtx(F,'-',Fnames); else, [X,Pnames,Index] = spm_DesMtx(F,'~',Fnames); end X = X.*(C*ones(1,size(X,2))); Pnames = cellstr([repmat([Cnames,'@'],size(Index,2),1),char(Pnames)]); case {'.','.0','+0','+0m'} %-Constrained simple main effect %======================================================================= if size(I,2)~=1, error('Simple main effect requires vector index'), end [X,Pnames,Index] = spm_DesMtx(I,'-(1)',FCnames); %-Impose constraint if more than one effect %----------------------------------------------------------------------- %-Apply uniqueness constraints ('.' & '+0') to last effect, which is % in last column, since column i corresponds to level Index(i) %-'.0' corner point constraint is applied to zero factor level only nXcols = size(X,2); zCol = find(Index==0); if nXcols==1 & ~strcmp(Constraint,'.0') error('only one level: can''t constrain') elseif strcmp(Constraint,'.') X(:,nXcols)=[]; Pnames(nXcols)=[]; Index(nXcols)=[]; elseif strcmp(Constraint,'.0') zCol = find(Index==0); if isempty(zCol), warning('no zero level to constrain') elseif nXcols==1, error('only one level: can''t constrain'), end X(:,zCol)=[]; Pnames(zCol)=[]; Index(zCol)=[]; elseif strcmp(Constraint,'+0') X(find(X(:,nXcols)),:)=-1; X(:,nXcols)=[]; Pnames(nXcols)=[]; Index(nXcols)=[]; elseif strcmp(Constraint,'+0m') X = X - 1/nXcols; end case {'.i','.i0','.j','.j0','.ij','.ij0','+i0','+j0','+ij0','+i0m','+j0m'} %-Two way interaction effects %======================================================================= if size(I,2)~=2, error('Two way interaction requires Nx2 index'), end [X,Pnames,Index] = spm_DesMtx(I,'-',FCnames); %-Implicit sum to zero %----------------------------------------------------------------------- if any(strcmp(Constraint,{'+i0m','+j0m'})) SumIToZero = strcmp(Constraint,'+i0m'); SumJToZero = strcmp(Constraint,'+j0m'); if SumIToZero %-impose implicit SumIToZero constraints Js = sort(Index(2,:)); Js = Js([1,1+find(diff(Js))]); for j = Js rows = find(I(:,2)==j); cols = find(Index(2,:)==j); if length(cols)==1 error('Only one level: Can''t constrain') end X(rows,cols) = X(rows,cols) - 1/length(cols); end end if SumJToZero %-impose implicit SumJToZero constraints Is = sort(Index(1,:)); Is = Is([1,1+find(diff(Is))]); for i = Is rows = find(I(:,1)==i); cols = find(Index(1,:)==i); if length(cols)==1 error('Only one level: Can''t constrain') end X(rows,cols) = X(rows,cols) - 1/length(cols); end end %-Explicit sum to zero %----------------------------------------------------------------------- elseif any(strcmp(Constraint,{'+i0','+j0','+ij0'})) SumIToZero = any(strcmp(Constraint,{'+i0','+ij0'})); SumJToZero = any(strcmp(Constraint,{'+j0','+ij0'})); if SumIToZero %-impose explicit SumIToZero constraints i = max(Index(1,:)); if i==min(Index(1,:)) error('Only one i level: Can''t constrain'), end cols = find(Index(1,:)==i); %-columns to delete for c=cols j=Index(2,c); t_cols=find(Index(2,:)==j); t_rows=find(X(:,c)); %-This ij equals -sum(ij) over other i % (j fixed for this col c). %-So subtract weight of this ij factor from % weights for all other ij factors for this j % to impose the constraint. X(t_rows,t_cols) = X(t_rows,t_cols)... -X(t_rows,c)*ones(1,length(t_cols)); %-( Next line would do it, but only first time round, when all ) % ( weights are 1, and only one weight per row for this j. ) % X(t_rows,t_cols)=-1*ones(length(t_rows),length(t_cols)); end %-delete columns X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[]; end if SumJToZero %-impose explicit SumJToZero constraints j = max(Index(2,:)); if j==min(Index(2,:)) error('Only one j level: Can''t constrain'), end cols=find(Index(2,:)==j); for c=cols i=Index(1,c); t_cols=find(Index(1,:)==i); t_rows=find(X(:,c)); X(t_rows,t_cols) = X(t_rows,t_cols)... -X(t_rows,c)*ones(1,length(t_cols)); end %-delete columns X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[]; end %-Corner point constraints %----------------------------------------------------------------------- elseif any(strcmp(Constraint,{'.i','.i0','.j','.j0','.ij','.ij0'})) CornerPointI = any(strcmp(Constraint,{'.i','.i0','.ij','.ij0'})); CornerPointJ = any(strcmp(Constraint,{'.j','.j0','.ij','.ij0'})); if CornerPointI %-impose CornerPointI constraints if Constraint(end)~='0', i = max(Index(1,:)); else, i = 0; end cols=find(Index(1,:)==i); %-columns to delete if isempty(cols) warning('no zero i level to constrain') elseif all(Index(1,:)==i) error('only one i level: can''t constrain') end %-delete columns X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[]; end if CornerPointJ %-impose CornerPointJ constraints if Constraint(end)~='0', j = max(Index(2,:)); else, j = 0; end cols=find(Index(2,:)==j); if isempty(cols) warning('no zero j level to constrain') elseif all(Index(2,:)==j) error('only one j level: can''t constrain') end X(:,cols)=[]; Pnames(cols)=[]; Index(:,cols)=[]; end end case {'PDS','pds'} %-Patterned data set utility %======================================================================= % i = spm_DesMtx('pds',v,m,n) if nargin<4, n=1; else, n=varargin{4}; end if nargin<3, m=1; else, m=varargin{3}; end if nargin<2, varargout={[]}, return, else, v=varargin{2}; end if any([size(n),size(m)])>1, error('n & m must be scalars'), end if any(([m,n]~=floor([m,n]))|([m,n]<1)) error('n & m must be natural numbers'), end if sum(size(v)>1)>1, error('v must be a vector'), end %-Computation %----------------------------------------------------------------------- si = ones(1,ndims(v)); si(find(size(v)>1))=n*m*length(v); X = reshape(repmat(v(:)',m,n),si); case {'Sca','sca'} %-Scale DesMtx for imaging %======================================================================= nX = []; nPnames = {}; Carg = 2; %-Loop through the arguments accumulating scaled design matrix nX %----------------------------------------------------------------------- while(Carg <= nargin) rX = varargin{Carg}; Carg=Carg+1; if Carg<=nargin & ~isempty(varargin{Carg}) & ... (ischar(varargin{Carg}) | iscellstr(varargin{Carg})) rPnames = char(varargin{Carg}); Carg=Carg+1; else %-No names to work out blocks from - normalise by column rPnames = repmat('<UnSpec>',size(rX,2),1); end %-Pad out rPnames with 20 spaces to permit looking past line ends rPnames = [rPnames,repmat(' ',size(rPnames,1),20)]; while(~isempty(rX)) if size(rX,2)>1 & max([1,find(rPnames(1,:)=='(')]) < ... max([0,find(rPnames(1,:)==')')]) %-Non-specific block: find the rest & column normalise round zero %=============================================================== c1 = max(find(rPnames(1,:)=='(')); d = any(diff(abs(rPnames(:,1:c1))),2)... | ~any(rPnames(2:end,c1+1:end)==')',2); t = min(find([d;1])); %-Normalise columns of block around zero %------------------------------------------------------- tmp = size(nX,2); nX = [nX, zeros(size(rX,1),t)]; for i=1:t, nX(:,tmp+i) = rX(:,i)/max(abs(rX(:,i))); end nPnames = [nPnames; cellstr(rPnames(1:t,:))]; rX(:,1:t) = []; rPnames(1:t,:)=[]; elseif size(rX,2)>1 & max([1,find(rPnames(1,:)=='[')]) < ... max([0,find(rPnames(1,:)==']')]) %-Block: find the rest & normalise together %=============================================================== c1 = max(find(rPnames(1,:)=='[')); d = any(diff(abs(rPnames(:,1:c1))),2)... | ~any(rPnames(2:end,c1+1:end)==']',2); t = min(find([d;1])); %-Normalise block %------------------------------------------------------- nX = [nX,sf_tXsca(rX(:,1:t))]; nPnames = [nPnames; cellstr(rPnames(1:t,:))]; rX(:,1:t) = []; rPnames(1:t,:)=[]; elseif size(rX,2)>1 & max([1,findstr(rPnames(1,:),'_{')]) < ... max([0,find(rPnames(1,:)=='}')]) %-Factor, interaction of factors, or FxC: find the rest... %=============================================================== c1 = max(findstr(rPnames(1,:),'_{')); d = any(diff(abs(rPnames(:,1:c1+1))),2)... | ~any(rPnames(2:end,c1+2:end)=='}',2); t = min(find([d;1])); %-Normalise block %------------------------------------------------------- tX = rX(:,1:t); if any(rPnames(1,1:c1)=='@') %-FxC interaction C = tX(tX~=0); tX(tX~=0) = 2*(C-min(C))/max(C-min(C))-1; nX = [nX,tX]; else %-Straight interaction nX = [nX,sf_tXsca(tX)]; end nPnames = [nPnames; cellstr(rPnames(1:t,:))]; rX(:,1:t) = []; rPnames(1:t,:)=[]; else %-Dunno! Just column normalise %=============================================================== nX = [nX,sf_tXsca(rX(:,1))]; nPnames = [nPnames; cellstr(rPnames(1,:))]; rX(:,1) = []; rPnames(1,:)=[]; end end end X = nX; Pnames = nPnames; case {'Fnames','fnames'} %-Turn parameter names into valid filenames %======================================================================= % Fnames = spm_DesMtx('FNames',Pnames) if nargin<2, varargout={''}; return, end Fnames = varargin{2}; for i=1:prod(size(Fnames)) str = Fnames{i}; str(str==',')='x'; %-',' to 'x' str(str=='*')='-'; %-'*' to '-' str(str=='@')='-'; %-'@' to '-' str(str==' ')='_'; %-' ' to '_' str(str=='/')=''; %- delete '/' str(str=='.')=''; %- delete '.' Fnames{i} = str; end Fnames = spm_str_manip(Fnames,'v'); %- retain only legal characters X = Fnames; case {'TeXnames','texnames'} %-Remove '@' & '*' for TeX interpretation %======================================================================= % TPnames = spm_DesMtx('TeXnames',Pnames) if nargin<2, varargout={''}; return, end TPnames = varargin{2}; for i=1:prod(size(TPnames)) str = TPnames{i}; str(str=='*')=''; %- delete '*' str(str=='@')=''; %- delete '@' TPnames{i} = str; end X = TPnames; case {'ParMap','parmap'} %-Parameter mappings: greek to english %======================================================================= % Map = spm_DesMtx('ParMap',aMap) Map = { '\mu', 'const';... '\theta', 'repl';... '\alpha', 'cond';... '\gamma', 'subj';... '\rho', 'covint';... '\zeta', 'global';... '\epsilon', 'error'}; if nargin<2, aMap={}; else, aMap = varargin{2}; end if isempty(aMap), X=Map; return, end if ~(iscellstr(aMap) & ndims(aMap)==2), error('aMap must be an nx2 cellstr'), end for i=1:size(aMap,1) j = find(strcmp(aMap{i,1},Map(:,1))); if isempty(j) Map=[aMap(i,:); Map]; else Map(j,2) = aMap(i,2); end end X = Map; case {'ETeXNames','etexnames'} %-Search & replace: for Englishifying TeX %======================================================================= % EPnames = spm_DesMtx('TeXnames',Pnames,aMap) if nargin<2, varargout={''}; return, end if nargin<3, aMap={}; else, aMap = varargin{3}; end Map = spm_DesMtx('ParMap',aMap); EPnames = varargin{2}; for i=1:size(Map,1) EPnames = strrep(EPnames,Map{i,1},Map{i,2}); end X = EPnames; otherwise %-Mis-specified arguments - ERROR %======================================================================= if ischar(varargin{1}) error('unrecognised action string') else error('unrecognised constraint type') end %======================================================================= end %======================================================================= % - S U B F U N C T I O N S %======================================================================= function nX = sf_tXsca(tX) if nargin==0, nX=[]; return, end if abs(max(abs(tX(:)))-0.7)<(.3+1e-10) nX = tX; elseif all(tX(:)==tX(1)) nX = ones(size(tX)); elseif max(abs(tX(:)))<1e-10 nX = zeros(size(tX)); else nX = 2*(tX-min(tX(:)))/max(tX(:)-min(tX(:)))-1; end
github
spm/spm5-master
spm_eeg_average_TF.m
.m
spm5-master/spm_eeg_average_TF.m
2,660
utf_8
8918d10a4b4307e86b50c10c90c4de8a
function D=spm_eeg_average_TF(S) %%% function to average induced TF data if standard average does not work because of out of memeory issues % James Kilner % $Id$ try D = S.D; catch D = spm_select(1, '.*\.mat$', 'Select EEG mat file'); end P = spm_str_manip(D, 'H'); try D = spm_eeg_ldata(D); catch error(sprintf('Trouble reading file %s', D)); end try c = S.c; catch % if there is no S.c, assume that user wants default average within % trial type c = eye(D.events.Ntypes); end c1=size(D.data,1); c2=size(D.data,2); c3=size(D.data,3); D=rmfield(D,'data'); pack; d=zeros(c1,c2,c3,D.events.Ntypes); fh=fopen(fullfile(D.path,D.fnamedat),'r'); ni=zeros(1,D.events.Ntypes); for n=1:D.Nevents if D.events.reject(n)== 0 [m,i]=find(D.events.types==D.events.code(n)); data=fread(fh,[1,c1*c2*c3],'short'); data=reshape(data,c1,c2,c3,1); data=data.*repmat(D.scale(:,1,1,n),[1,D.Nfrequencies, D.Nsamples]); d(:,:,:,i)=d(:,:,:,i)+data; end end D.fnamedat = ['m' D.fnamedat]; fpd = fopen(fullfile(P, D.fnamedat), 'w'); D.scale = zeros(D.Nchannels, 1, 1, D.events.Ntypes); for n=1:D.events.Ntypes dat=squeeze(d(:,:,:,n)./length(find(D.events.code==D.events.types(n) & ~D.events.reject))); ni(n)=length(find(D.events.code==D.events.types(n) & ~D.events.reject)); D.scale(:, 1, 1, n) = max(max(squeeze(abs(dat)), [], 3), [], 2)./32767; dat = int16(dat./repmat(D.scale(:, 1, 1, n), [1, D.Nfrequencies, D.Nsamples])); fwrite(fpd, dat, 'int16'); end fclose (fh) ; fclose(fpd); D.Nevents = size(c, 2); D.events.repl = ni; disp(sprintf('%s: Number of replications per contrast:', D.fname)) s = []; for i = 1:D.events.Ntypes s = [s sprintf('average %d: %d trials', D.events.types(i), D.events.repl(i))]; if i < D.events.Ntypes s = [s sprintf(', ')]; else s = [s '\n']; end end disp(sprintf(s)) % labeling of resulting contrasts, take care to keep numbers of old trial % types % check this again: can be problematic, when user mixes within-trialtype % and over-trial type contrasts D.events.code = size(1, size(c, 2)); for i = 1:size(c, 2) if sum(c(:, i)) == 1 & sum(~c(:, i)) == size(c, 1)-1 D.events.code(i) = find(c(:, i)); else D.events.code(i) = i; end end D.events.time = []; D.events.types = D.events.code; D.events.Ntypes = length(D.events.types); D.data = []; D.events.reject = zeros(1, D.Nevents); D.events.blinks = zeros(1, D.Nevents); D.fname = ['m' D.fname]; if spm_matlab_version_chk('7') >= 0 save(fullfile(P, D.fname), '-V6', 'D'); else save(fullfile(P, D.fname), 'D'); end
github
spm/spm5-master
spm_config_imcalc.m
.m
spm5-master/spm_config_imcalc.m
6,138
utf_8
165df05c2186b3308b46e82029d2c079
function opts = spm_config_imcalc % Configuration file for image calculator %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_config_imcalc.m 1032 2007-12-20 14:45:55Z john $ %_______________________________________________________________________ inpt.type = 'files'; inpt.name = 'Input Images'; inpt.tag = 'input'; inpt.filter = 'image'; inpt.num = [1 Inf]; inpt.help = {[... 'These are the images that are used by the calculator. They ',... 'are referred to as i1, i2, i3, etc in the order that they are ',... 'specified.']}; outpt.type = 'entry'; outpt.name = 'Output Filename'; outpt.tag = 'output'; outpt.strtype = 's'; outpt.num = [1 Inf]; outpt.val = {'output.img'}; outpt.help = {[... 'The output image is written to current working directory ',... 'unless a valid full pathname is given. If a path name is given here, the ',... 'output directory setting will be ignored.']}; outdir.type = 'files'; outdir.name = 'Output Directory'; outdir.tag = 'outdir'; outdir.filter = 'dir'; outdir.num = [0 1]; outdir.val = {''}; outdir.help = {['Files produced by this function will be written into this ' ... 'output directory. If no directory is given, images will be' ... ' written to current working directory. If both output' ... ' filename and output directory contain a directory, then '... 'output filename takes precedence.']}; expr.type = 'entry'; expr.name = 'Expression'; expr.tag = 'expression'; expr.strtype = 's'; expr.num = [2 Inf]; expr.val = {'i1'}; expr.help = {... 'Example expressions (f):',... ' * Mean of six images (select six images)',... ' f = ''(i1+i2+i3+i4+i5+i6)/6''',... ' * Make a binary mask image at threshold of 100',... ' f = ''i1>100''',... ' * Make a mask from one image and apply to another',... ' f = ''i2.*(i1>100)''',[... ' - here the first image is used to make the mask, which is applied to the second image'],... ' * Sum of n images',... ' f = ''i1 + i2 + i3 + i4 + i5 + ...''',... ' * Sum of n images (when reading data into a data-matrix - use dmtx arg)',... ' f = ''sum(X)'''}; dmtx.type = 'menu'; dmtx.name = 'Data Matrix'; dmtx.tag = 'dmtx'; dmtx.labels = {'No - don''t read images into data matrix','Yes - read images into data matrix'}; dmtx.values = {0,1}; dmtx.def = 'imcalc.dmtx'; %dmtx.val = {0}; dmtx.help = {[... 'If the dmtx flag is set, then images are read into a data matrix X ',... '(rather than into separate variables i1, i2, i3,...). The data matrix ',... ' should be referred to as X, and contains images in rows. ',... 'Computation is plane by plane, so in data-matrix mode, X is a NxK ',... 'matrix, where N is the number of input images [prod(size(Vi))], and K ',... 'is the number of voxels per plane [prod(Vi(1).dim(1:2))].']}; mask.type = 'menu'; mask.name = 'Masking'; mask.tag = 'mask'; mask.labels = {'No implicit zero mask','Implicit zero mask','NaNs should be zeroed'}; mask.values = {0,1,-1}; mask.def = 'imcalc.mask'; %mask.val = {0}; mask.help = {[... 'For data types without a representation of NaN, implicit zero masking ',... 'assumes that all zero voxels are to be treated as missing, and ',... 'treats them as NaN. NaN''s are written as zero (by spm_write_plane), ',... 'for data types without a representation of NaN.']}; intrp.type = 'menu'; intrp.name = 'Interpolation'; intrp.tag = 'interp'; intrp.labels = {'Nearest neighbour','Trilinear','2nd Degree Sinc',... '3rd Degree Sinc','4th Degree Sinc','5th Degree Sinc',... '6th Degree Sinc','7th Degree Sinc'}; intrp.values = {0,1,-2,-3,-4,-5,-6,-7}; intrp.def = 'imcalc.interp'; %intrp.val = {1}; h1 = [... 'With images of different sizes and orientations, the size and ',... 'orientation of the first is used for the output image. A warning is ',... 'given in this situation. Images are sampled into this orientation ',... 'using the interpolation specified by the hold parameter.']; intrp.help = {h1,'',[... 'The method by which the images are sampled when being written in a ',... 'different space.'],... ' Nearest Neighbour',... ' - Fastest, but not normally recommended.',... ' Bilinear Interpolation',... ' - OK for PET, or realigned fMRI.',... ' Sinc Interpolation',... ' - Better quality (but slower) interpolation, especially',... ' with higher degrees.'... }; dtype.type = 'menu'; dtype.name = 'Data Type'; dtype.tag = 'dtype'; dtype.labels = {'UINT8 - unsigned char','INT16 - signed short','INT32 - signed int','FLOAT - single prec. float','DOUBLE - double prec. float'}; dtype.values = {spm_type('uint8'),spm_type('int16'),spm_type('int32'),spm_type('float32'),spm_type('float64')}; dtype.def = 'imcalc.dtype'; %dtype.val = {spm_type('int16')}; dtype.help = {'Data-type of output image'}; options.type = 'branch'; options.name = 'Options'; options.tag = 'options'; options.val = {dmtx,mask,intrp,dtype}; options.help = {'Options for image calculator'}; opts.type = 'branch'; opts.name = 'Image Calculator'; opts.tag = 'imcalc'; opts.val = {inpt,outpt,outdir,expr,options}; opts.prog = @fun; opts.vfiles = @vfiles; opts.help = {[... 'The image calculator is for performing user-specified ',... 'algebraic manipulations on a set of images, with the result being ',... 'written out as an image. The user is prompted to supply images to ',... 'work on, a filename for the output image, and the expression to ',... 'evaluate. The expression should be a standard MATLAB expression, ',... 'within which the images should be referred to as i1, i2, i3,... etc.']}; return; function fun(opt) flags = {opt.options.dmtx, opt.options.mask, opt.options.dtype, opt.options.interp}; outfile = vfiles(opt); spm_imcalc_ui(strvcat(opt.input{:}),outfile{1},opt.expression,flags); return; function vf = vfiles(job) [p,nam,ext,num] = spm_fileparts(job.output); if isempty(p) if isempty(job.outdir{1}) p=pwd; else p = job.outdir{1}; end; end; if isempty(strfind(ext,',')) ext=[ext ',1']; end; vf{1} = fullfile(p,[nam ext num]); return;
github
spm/spm5-master
spm_imatrix.m
.m
spm5-master/spm_imatrix.m
1,535
utf_8
e1e622d4cffa69aa616e536b77f85d66
function P = spm_imatrix(M) % returns the parameters for creating an affine transformation % FORMAT P = spm_imatrix(M) % M - Affine transformation matrix % P - Parameters (see spm_matrix for definitions) %___________________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner & Stefan Kiebel % $Id: spm_imatrix.m 184 2005-05-31 13:23:32Z john $ % Translations and zooms %----------------------------------------------------------------------- R = M(1:3,1:3); C = chol(R'*R); P = [M(1:3,4)' 0 0 0 diag(C)' 0 0 0]; if det(R)<0, P(7)=-P(7);end % Fix for -ve determinants % Shears %----------------------------------------------------------------------- C = diag(diag(C))\C; P(10:12) = C([4 7 8]); R0 = spm_matrix([0 0 0 0 0 0 P(7:12)]); R0 = R0(1:3,1:3); R1 = R/R0; % This just leaves rotations in matrix R1 %----------------------------------------------------------------------- %[ c5*c6, c5*s6, s5] %[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5] %[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5] P(5) = asin(rang(R1(1,3))); if (abs(P(5))-pi/2)^2 < 1e-9, P(4) = 0; P(6) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3))); else c = cos(P(5)); P(4) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c)); P(6) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c)); end; return; % There may be slight rounding errors making b>1 or b<-1. function a = rang(b) a = min(max(b, -1), 1); return;
github
spm/spm5-master
ctf_folder.m
.m
spm5-master/ctf_folder.m
2,949
utf_8
4e051b8e8a1e6ec08c6b7a53e6b37340
function [ctf] = ctf_folder(folder,ctf); % ctf_folder - get and check CTF .ds folder name % % [ctf] = ctf_folder( [folder], [ctf] ); % % folder: The .ds directory of the dataset. It should be a complete path % or given relative to the current working directory (given by pwd). The % returned value will ensure the complete path is identified. If this % argument is empty or not given, a graphical prompt for the folder % appears. % % eg, % ctf = ctf_folder; % % ctf.folder is returned (as a complete path). % % <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> % % < > % % < DISCLAIMER: > % % < > % % < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. > % % < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR > % % < OFFICIAL USE. > % % < > % % <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<> % % % $Revision: 1.7 $ $Date: 2005/01/21 02:07:36 $ % Copyright (C) 2004 Darren L. Weber % % 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % Modified: 01/2004, Darren.Weber_at_radiology.ucsf.edu %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('folder','var'), folder = []; end if ~exist('ctf','var'), ctf = []; end if isempty(folder), if isfield(ctf,'folder'), folder = ctf.folder; else folder = []; end end if exist(folder) ~= 7, fprintf('...folder inputs are invalid\n'); folder = getfolder; end ctf.folder = folder; % ensure we get the folder path current_dir = pwd; cd(ctf.folder); cd .. folderPath = pwd; cd(current_dir); % check whether the folder path is in the folder already [path,file] = fileparts(ctf.folder); % if findstr(folderPath,ctf.folder), % OK the path is already in the folder % else if isempty(path) % Add the folderPath ctf.folder = fullfile(folderPath,ctf.folder); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function folder = getfolder, folder = uigetdir(pwd,'locate CTF .ds folder'); if ~folder, error('no folder specified'); end return
github
spm/spm5-master
spm_affreg.m
.m
spm5-master/spm_affreg.m
18,881
utf_8
75ec9b5af8f8965af695dc0eb74ed73c
function [M,scal] = spm_affreg(VG,VF,flags,M,scal) % Affine registration using least squares. % FORMAT [M,scal] = spm_affreg(VG,VF,flags,M0,scal0) % % VG - Vector of template volumes. % VF - Source volume. % flags - a structure containing various options. The fields are: % WG - Weighting volume for template image(s). % WF - Weighting volume for source image % Default to []. % sep - Approximate spacing between sampled points (mm). % Defaults to 5. % regtype - regularisation type. Options are: % 'none' - no regularisation % 'rigid' - almost rigid body % 'subj' - inter-subject registration (default). % 'mni' - registration to ICBM templates % globnorm - Global normalisation flag (1) % M0 - (optional) starting estimate. Defaults to eye(4). % scal0 - (optional) starting estimate. % % M - affine transform, such that voxels in VF map to those in % VG by VG.mat\M*VF.mat % scal - scaling factors for VG % % When only one template is used, then the cost function is approximately % symmetric, although a linear combination of templates can be used. % Regularisation is based on assuming a multi-normal distribution for the % elements of the Henckey Tensor. See: % "Non-linear Elastic Deformations". R. W. Ogden (Dover), 1984. % Weighting for the regularisation is determined approximately according % to: % "Incorporating Prior Knowledge into Image Registration" % J. Ashburner, P. Neelin, D. L. Collins, A. C. Evans & K. J. Friston. % NeuroImage 6:344-352 (1997). % %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_affreg.m 1160 2008-02-20 18:04:09Z john $ if nargin<5, scal = ones(length(VG),1); end; if nargin<4, M = eye(4); end; def_flags = struct('sep',5, 'regtype','subj','WG',[],'WF',[],'globnorm',1,'debug',0); if nargin < 2 || ~isstruct(flags), flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end; end; end; % Check to ensure inputs are valid... % --------------------------------------------------------------- if length(VF)>1, error('Can not use more than one source image'); end; if ~isempty(flags.WF), if length(flags.WF)>1, error('Can only use one source weighting image'); end; if any(any((VF.mat-flags.WF.mat).^2>1e-8)), error('Source and its weighting image must have same orientation'); end; if any(any(VF.dim(1:3)-flags.WF.dim(1:3))), error('Source and its weighting image must have same dimensions'); end; end; if ~isempty(flags.WG), if length(flags.WG)>1, error('Can only use one template weighting image'); end; tmp = reshape(cat(3,VG(:).mat,flags.WG.mat),16,length(VG)+length(flags.WG)); else tmp = reshape(cat(3,VG(:).mat),16,length(VG)); end; if any(any(diff(tmp,1,2).^2>1e-8)), error('Reference images must all have the same orientation'); end; if ~isempty(flags.WG), tmp = cat(1,VG(:).dim,flags.WG.dim); else tmp = cat(1,VG(:).dim); end; if any(any(diff(tmp(:,1:3),1,1))), error('Reference images must all have the same dimensions'); end; % --------------------------------------------------------------- % Generate points to sample from, adding some jitter in order to % make the cost function smoother. % --------------------------------------------------------------- rand('state',0); % want the results to be consistant. dg = VG(1).dim(1:3); df = VF(1).dim(1:3); if length(VG)==1, skip = sqrt(sum(VG(1).mat(1:3,1:3).^2)).^(-1)*flags.sep; [x1,x2,x3]=ndgrid(1:skip(1):dg(1)-.5, 1:skip(2):dg(2)-.5, 1:skip(3):dg(3)-.5); x1 = x1 + rand(size(x1))*0.5; x1 = x1(:); x2 = x2 + rand(size(x2))*0.5; x2 = x2(:); x3 = x3 + rand(size(x3))*0.5; x3 = x3(:); end; skip = sqrt(sum(VF(1).mat(1:3,1:3).^2)).^(-1)*flags.sep; [y1,y2,y3]=ndgrid(1:skip(1):df(1)-.5, 1:skip(2):df(2)-.5, 1:skip(3):df(3)-.5); y1 = y1 + rand(size(y1))*0.5; y1 = y1(:); y2 = y2 + rand(size(y2))*0.5; y2 = y2(:); y3 = y3 + rand(size(y3))*0.5; y3 = y3(:); % --------------------------------------------------------------- if flags.globnorm, % Scale all images approximately equally % --------------------------------------------------------------- for i=1:length(VG), VG(i).pinfo(1:2,:) = VG(i).pinfo(1:2,:)/spm_global(VG(i)); end; VF(1).pinfo(1:2,:) = VF(1).pinfo(1:2,:)/spm_global(VF(1)); end; % --------------------------------------------------------------- if length(VG)==1, [G,dG1,dG2,dG3] = spm_sample_vol(VG(1),x1,x2,x3,1); if ~isempty(flags.WG), WG = abs(spm_sample_vol(flags.WG,x1,x2,x3,1))+eps; WG(~isfinite(WG)) = 1; end; end; [F,dF1,dF2,dF3] = spm_sample_vol(VF(1),y1,y2,y3,1); if ~isempty(flags.WF), WF = abs(spm_sample_vol(flags.WF,y1,y2,y3,1))+eps; WF(~isfinite(WF)) = 1; end; % --------------------------------------------------------------- n_main_its = 0; ss = Inf; W = [Inf Inf Inf]; est_smo = 1; % --------------------------------------------------------------- for iter=1:256, pss = ss; p0 = [0 0 0 0 0 0 1 1 1 0 0 0]; % Initialise the cost function and its 1st and second derivatives % --------------------------------------------------------------- n = 0; ss = 0; Beta = zeros(12+length(VG),1); Alpha = zeros(12+length(VG)); if length(VG)==1, % Make the cost function symmetric % --------------------------------------------------------------- % Build a matrix to rotate the derivatives by, converting from % derivatives w.r.t. changes in the overall affine transformation % matrix, to derivatives w.r.t. the parameters p. % --------------------------------------------------------------- dt = 0.0001; R = eye(13); MM0 = inv(VG.mat)*inv(spm_matrix(p0))*VG.mat; for i1=1:12, p1 = p0; p1(i1) = p1(i1)+dt; MM1 = (inv(VG.mat)*inv(spm_matrix(p1))*(VG.mat)); R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1); end; % --------------------------------------------------------------- [t1,t2,t3] = coords((M*VF(1).mat)\VG(1).mat,x1,x2,x3); msk = find((t1>=1 & t1<=df(1) & t2>=1 & t2<=df(2) & t3>=1 & t3<=df(3))); if length(msk)<32, error_message; end; t1 = t1(msk); t2 = t2(msk); t3 = t3(msk); t = spm_sample_vol(VF(1), t1,t2,t3,1); % Get weights % --------------------------------------------------------------- if ~isempty(flags.WF) || ~isempty(flags.WG), if isempty(flags.WF), wt = WG(msk); else wt = spm_sample_vol(flags.WF(1), t1,t2,t3,1)+eps; wt(~isfinite(wt)) = 1; if ~isempty(flags.WG), wt = 1./(1./wt + 1./WG(msk)); end; end; wt = sparse(1:length(wt),1:length(wt),wt); else % wt = speye(length(msk)); wt = []; end; % --------------------------------------------------------------- clear t1 t2 t3 % Update the cost function and its 1st and second derivatives. % --------------------------------------------------------------- [AA,Ab,ss1,n1] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,scal^(-2)*t,G(msk)-(1/scal)*t,wt); Alpha = Alpha + R'*AA*R; Beta = Beta + R'*Ab; ss = ss + ss1; n = n + n1; % t = G(msk) - (1/scal)*t; end; if 1, % Build a matrix to rotate the derivatives by, converting from % derivatives w.r.t. changes in the overall affine transformation % matrix, to derivatives w.r.t. the parameters p. % --------------------------------------------------------------- dt = 0.0001; R = eye(12+length(VG)); MM0 = inv(M*VF.mat)*spm_matrix(p0)*M*VF.mat; for i1=1:12, p1 = p0; p1(i1) = p1(i1)+dt; MM1 = (inv(M*VF.mat)*spm_matrix(p1)*M*VF.mat); R(1:12,i1) = reshape((MM1(1:3,:)-MM0(1:3,:))/dt,12,1); end; % --------------------------------------------------------------- [t1,t2,t3] = coords(VG(1).mat\M*VF(1).mat,y1,y2,y3); msk = find((t1>=1 & t1<=dg(1) & t2>=1 & t2<=dg(2) & t3>=1 & t3<=dg(3))); if length(msk)<32, error_message; end; if length(msk)<32, error_message; end; t1 = t1(msk); t2 = t2(msk); t3 = t3(msk); t = zeros(length(t1),length(VG)); % Get weights % --------------------------------------------------------------- if ~isempty(flags.WF) || ~isempty(flags.WG), if isempty(flags.WG), wt = WF(msk); else wt = spm_sample_vol(flags.WG(1), t1,t2,t3,1)+eps; wt(~isfinite(wt)) = 1; if ~isempty(flags.WF), wt = 1./(1./wt + 1./WF(msk)); end; end; wt = sparse(1:length(wt),1:length(wt),wt); else wt = speye(length(msk)); end; % --------------------------------------------------------------- if est_smo, % Compute derivatives of residuals in the space of F % --------------------------------------------------------------- [ds1,ds2,ds3] = transform_derivs(VG(1).mat\M*VF(1).mat,dF1(msk),dF2(msk),dF3(msk)); for i=1:length(VG), [t(:,i),dt1,dt2,dt3] = spm_sample_vol(VG(i), t1,t2,t3,1); ds1 = ds1 - dt1*scal(i); clear dt1 ds2 = ds2 - dt2*scal(i); clear dt2 ds3 = ds3 - dt3*scal(i); clear dt3 end; dss = [ds1'*wt*ds1 ds2'*wt*ds2 ds3'*wt*ds3]; clear ds1 ds2 ds3 else for i=1:length(VG), t(:,i)= spm_sample_vol(VG(i), t1,t2,t3,1); end; end; clear t1 t2 t3 % Update the cost function and its 1st and second derivatives. % --------------------------------------------------------------- [AA,Ab,ss2,n2] = costfun(y1,y2,y3,dF1,dF2,dF3,msk,-t,F(msk)-t*scal,wt); Alpha = Alpha + R'*AA*R; Beta = Beta + R'*Ab; ss = ss + ss2; n = n + n2; end; if est_smo, % Compute a smoothness correction from the residuals and their % derivatives. This is analagous to the one used in: % "Analysis of fMRI Time Series Revisited" % Friston KJ, Holmes AP, Poline JB, Grasby PJ, Williams SCR, % Frackowiak RSJ, Turner R. Neuroimage 2:45-53 (1995). % --------------------------------------------------------------- vx = sqrt(sum(VG(1).mat(1:3,1:3).^2)); pW = W; W = (2*dss/ss2).^(-.5).*vx; W = min(pW,W); if flags.debug, fprintf('\nSmoothness FWHM: %.3g x %.3g x %.3g mm\n', W*sqrt(8*log(2))); end; if length(VG)==1, dens=2; else dens=1; end; smo = prod(min(dens*flags.sep/sqrt(2*pi)./W,[1 1 1])); est_smo=0; n_main_its = n_main_its + 1; end; % Update the parameter estimates % --------------------------------------------------------------- nu = n*smo; sig2 = ss/nu; [d1,d2] = reg(M,12+length(VG),flags.regtype); soln = (Alpha/sig2+d2)\(Beta/sig2-d1); scal = scal - soln(13:end); M = spm_matrix(p0 + soln(1:12)')*M; if flags.debug, fprintf('%d\t%g\n', iter, ss/n); piccies(VF,VG,M,scal); end; % If cost function stops decreasing, then re-estimate smoothness % and try again. Repeat a few times. % --------------------------------------------------------------- ss = ss/n; if iter>1, spm_chi2_plot('Set',ss); end; if (pss-ss)/pss < 1e-6, est_smo = 1; end; if n_main_its>3, break; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [X1,Y1,Z1] = transform_derivs(Mat,X,Y,Z) % Given the derivatives of a scalar function, return those of the % affine transformed function %_______________________________________________________________________ t1 = Mat(1:3,1:3); t2 = eye(3); if sum((t1(:)-t2(:)).^2) < 1e-12, X1 = X;Y1 = Y; Z1 = Z; else X1 = Mat(1,1)*X + Mat(1,2)*Y + Mat(1,3)*Z; Y1 = Mat(2,1)*X + Mat(2,2)*Y + Mat(2,3)*Z; Z1 = Mat(3,1)*X + Mat(3,2)*Y + Mat(3,3)*Z; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [d1,d2] = reg(M,n,typ) % Analytically compute the first and second derivatives of a penalty % function w.r.t. changes in parameters. if nargin<3, typ = 'subj'; end; if nargin<2, n = 13; end; [mu,isig] = priors(typ); ds = 0.000001; d1 = zeros(n,1); d2 = zeros(n); p0 = [0 0 0 0 0 0 1 1 1 0 0 0]; h0 = penalty(p0,M,mu,isig); for i=7:12, % derivatives are zero w.r.t. rotations and translations p1 = p0; p1(i) = p1(i)+ds; h1 = penalty(p1,M,mu,isig); d1(i) = (h1-h0)/ds; % First derivative for j=7:12, p2 = p0; p2(j) = p2(j)+ds; h2 = penalty(p2,M,mu,isig); p3 = p1; p3(j) = p3(j)+ds; h3 = penalty(p3,M,mu,isig); d2(i,j) = ((h3-h2)/ds-(h1-h0)/ds)/ds; % Second derivative end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function h = penalty(p,M,mu,isig) % Return a penalty based on the elements of an affine transformation, % which is given by: % spm_matrix(p)*M % % The penalty is based on the 6 unique elements of the Hencky tensor % elements being multinormally distributed. %_______________________________________________________________________ % Unique elements of symmetric 3x3 matrix. els = [1 2 3 5 6 9]; T = spm_matrix(p)*M; T = T(1:3,1:3); T = 0.5*logm(T'*T); T = T(els)' - mu; h = T'*isig*T; return; %_______________________________________________________________________ %_______________________________________________________________________ function [mu,isig] = priors(typ) % The parameters for this distribution were derived empirically from 227 % scans, that were matched to the ICBM space. %_______________________________________________________________________ mu = zeros(6,1); isig = zeros(6); switch deblank(lower(typ)), case 'mni', % For registering with MNI templates... mu = [0.0667 0.0039 0.0008 0.0333 0.0071 0.1071]'; isig = 1e4 * [ 0.0902 -0.0345 -0.0106 -0.0025 -0.0005 -0.0163 -0.0345 0.7901 0.3883 0.0041 -0.0103 -0.0116 -0.0106 0.3883 2.2599 0.0113 0.0396 -0.0060 -0.0025 0.0041 0.0113 0.0925 0.0471 -0.0440 -0.0005 -0.0103 0.0396 0.0471 0.2964 -0.0062 -0.0163 -0.0116 -0.0060 -0.0440 -0.0062 0.1144]; case 'rigid', % Constrained to be almost rigid... mu = zeros(6,1); isig = eye(6)*1e9; case 'isochoric', % Volume preserving... error('Not implemented'); case 'isotropic', % Isotropic zoom in all directions... error('Not implemented'); case 'subj', % For inter-subject registration... mu = zeros(6,1); isig = 1e3 * [ 0.8876 0.0784 0.0784 -0.1749 0.0784 -0.1749 0.0784 5.3894 0.2655 0.0784 0.2655 0.0784 0.0784 0.2655 5.3894 0.0784 0.2655 0.0784 -0.1749 0.0784 0.0784 0.8876 0.0784 -0.1749 0.0784 0.2655 0.2655 0.0784 5.3894 0.0784 -0.1749 0.0784 0.0784 -0.1749 0.0784 0.8876]; case 'none', % No regularisation... mu = zeros(6,1); isig = zeros(6); otherwise, error(['"' typ '" not recognised as type of regularisation.']); end; return; %_______________________________________________________________________ function [y1,y2,y3]=coords(M,x1,x2,x3) % Affine transformation of a set of coordinates. %_______________________________________________________________________ y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4); y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4); y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4); return; %_______________________________________________________________________ %_______________________________________________________________________ function A = make_A(x1,x2,x3,dG1,dG2,dG3,t) % Generate part of a design matrix using the chain rule... % df/dm = df/dy * dy/dm % where % df/dm is the rate of change of intensity w.r.t. affine parameters % df/dy is the gradient of the image f % dy/dm crange of position w.r.t. change of parameters %_______________________________________________________________________ A = [x1.*dG1 x1.*dG2 x1.*dG3 ... x2.*dG1 x2.*dG2 x2.*dG3 ... x3.*dG1 x3.*dG2 x3.*dG3 ... dG1 dG2 dG3 t]; return; %_______________________________________________________________________ %_______________________________________________________________________ function [AA,Ab,ss,n] = costfun(x1,x2,x3,dG1,dG2,dG3,msk,lastcols,b,wt) chunk = 10240; lm = length(msk); AA = zeros(12+size(lastcols,2)); Ab = zeros(12+size(lastcols,2),1); ss = 0; n = 0; for i=1:ceil(lm/chunk), ind = (((i-1)*chunk+1):min(i*chunk,lm))'; msk1 = msk(ind); A1 = make_A(x1(msk1),x2(msk1),x3(msk1),dG1(msk1),dG2(msk1),dG3(msk1),lastcols(ind,:)); b1 = b(ind); if ~isempty(wt), wt1 = wt(ind,ind); AA = AA + A1'*wt1*A1; %Ab = Ab + A1'*wt1*b1; Ab = Ab + (b1'*wt1*A1)'; ss = ss + b1'*wt1*b1; n = n + trace(wt1); clear wt1 else AA = AA + spm_atranspa(A1); %Ab = Ab + A1'*b1; Ab = Ab + (b1'*A1)'; ss = ss + b1'*b1; n = n + length(msk1); end; clear A1 b1 msk1 ind end; return; %_______________________________________________________________________ %_______________________________________________________________________ function error_message % Display an error message for when things go wrong. str = { 'There is not enough overlap in the images',... 'to obtain a solution.',... ' ',... 'Please check that your header information is OK.',... 'The Check Reg utility will show you the initial',... 'alignment between the images, which must be',... 'within about 4cm and about 15 degrees in order',... 'for SPM to find the optimal solution.'}; spm('alert*',str,mfilename,sqrt(-1)); error('insufficient image overlap') %_______________________________________________________________________ %_______________________________________________________________________ function piccies(VF,VG,M,scal) % This is for debugging purposes. % It shows the linear combination of template images, the affine % transformed source image, the residual image and a histogram of the % residuals. %_______________________________________________________________________ figure(2); Mt = spm_matrix([0 0 (VG(1).dim(3)+1)/2]); M = (M*VF(1).mat)\VG(1).mat; t = zeros(VG(1).dim(1:2)); for i=1:length(VG); t = t + spm_slice_vol(VG(i), Mt,VG(1).dim(1:2),1)*scal(i); end; u = spm_slice_vol(VF(1),M*Mt,VG(1).dim(1:2),1); subplot(2,2,1);imagesc(t');axis image xy off subplot(2,2,2);imagesc(u');axis image xy off subplot(2,2,3);imagesc(u'-t');axis image xy off %subplot(2,2,4);hist(b,50); % Entropy of residuals may be a nice cost function? drawnow; return; %_______________________________________________________________________
github
spm/spm5-master
spm_loaduint8.m
.m
spm5-master/spm_loaduint8.m
1,375
utf_8
c323020909cc93a83057b28b65305214
function udat = spm_loaduint8(V) % Load data from file indicated by V into an array of unsigned bytes. if size(V.pinfo,2)==1 && V.pinfo(1) == 2, mx = 255*V.pinfo(1) + V.pinfo(2); mn = V.pinfo(2); else, spm_progress_bar('Init',V.dim(3),... ['Computing max/min of ' spm_str_manip(V.fname,'t')],... 'Planes complete'); mx = -Inf; mn = Inf; for p=1:V.dim(3), img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1); mx = max([max(img(:))+paccuracy(V,p) mx]); mn = min([min(img(:)) mn]); spm_progress_bar('Set',p); end; end; spm_progress_bar('Init',V.dim(3),... ['Loading ' spm_str_manip(V.fname,'t')],... 'Planes loaded'); udat = uint8(0); udat(V.dim(1),V.dim(2),V.dim(3))=0; rand('state',100); for p=1:V.dim(3), img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1); acc = paccuracy(V,p); if acc==0, udat(:,:,p) = uint8(round((img-mn)*(255/(mx-mn)))); else, % Add random numbers before rounding to reduce aliasing artifact r = rand(size(img))*acc; udat(:,:,p) = uint8(round((img+r-mn)*(255/(mx-mn)))); end; spm_progress_bar('Set',p); end; spm_progress_bar('Clear'); return; function acc = paccuracy(V,p) % if ~spm_type(V.dim(4),'intt'), if ~spm_type(V.dt(1),'intt'), acc = 0; else, if size(V.pinfo,2)==1, acc = abs(V.pinfo(1,1)); else, acc = abs(V.pinfo(1,p)); end; end;
github
spm/spm5-master
savexml.m
.m
spm5-master/savexml.m
4,312
utf_8
753fabe9a2ec52f53e55248f54e10df9
function savexml(filename, varargin) %SAVEXML Save workspace variables to disk in XML. % SAVEXML FILENAME saves all workspace variables to the XML-file % named FILENAME.xml. The data may be retrieved with LOADXML. if % FILENAME has no extension, .xml is assumed. % % SAVE, by itself, creates the XML-file named 'matlab.xml'. It is % an error if 'matlab.xml' is not writable. % % SAVE FILENAME X saves only X. % SAVE FILENAME X Y Z saves X, Y, and Z. The wildcard '*' can be % used to save only those variables that match a pattern. % % SAVE ... -APPEND adds the variables to an existing file. % % Use the functional form of SAVE, such as SAVE(filename','var1','var2'), % when the filename or variable names are stored in strings. % % See also SAVE, MAT2XML, XMLTREE. % Copyright 2003 Guillaume Flandin. % $Revision: 112 $ $Date: 2003/07/10 13:50 $ % $Id: savexml.m 112 2005-05-04 18:20:52Z john $ if nargin == 0 filename = 'matlab.xml'; fprintf('\nSaving to: %s\n\n',filename); else if ~ischar(filename) error('[SAVEXML] Argument must contain a string.'); end [pathstr,name,ext] = fileparts(filename); if isempty(ext) filename = [filename '.xml']; end end if nargin <= 1, varargin = {'*'}; end if nargout > 0 error('[SAVEXML] Too many output arguments.'); end if strcmpi(varargin{end},'-append') if length(varargin) > 1 varargin = varargin(1:end-1); else varargin = {'*'}; end if exist(filename,'file') % TODO % No need to parse the whole tree ? detect duplicate variables ? t = xmltree(filename); else error(sprintf(... '[SAVEXML] Unable to write file %s: file does not exist.',filename)); end else t = xmltree('<matfile/>'); end for i=1:length(varargin) v = evalin('caller',['whos(''' varargin{i} ''')']); if isempty(v) error(['[SAVEXML] Variable ''' varargin{i} ''' not found.']); end for j=1:length(v) [t, uid] = add(t,root(t),'element',v(j).name); t = attributes(t,'add',uid,'type',v(j).class); t = attributes(t,'add',uid,'size',xml_num2str(v(j).size)); t = xml_var2xml(t,evalin('caller',v(j).name),uid); end end save(t,filename); %======================================================================= function t = xml_var2xml(t,v,uid) switch class(v) case 'double' t = add(t,uid,'chardata',xml_num2str(v)); case 'sparse' [i,j,s] = find(v); [t, uid2] = add(t,uid,'element','row'); t = attributes(t,'add',uid2,'size',xml_num2str(size(i))); t = add(t,uid2,'chardata',xml_num2str(i)); [t, uid2] = add(t,uid,'element','col'); t = attributes(t,'add',uid2,'size',xml_num2str(size(j))); t = add(t,uid2,'chardata',xml_num2str(j)); [t, uid2] = add(t,uid,'element','val'); t = attributes(t,'add',uid2,'size',xml_num2str(size(s))); t = add(t,uid2,'chardata',xml_num2str(s)); case 'struct' names = fieldnames(v); for j=1:prod(size(v)) for i=1:length(names) [t, uid2] = add(t,uid,'element',names{i}); t = attributes(t,'add',uid2,'index',num2str(j)); t = attributes(t,'add',uid2,'type',... class(getfield(v(j),names{i}))); t = attributes(t,'add',uid2,'size', ... xml_num2str(size(getfield(v(j),names{i})))); t = xml_var2xml(t,getfield(v(j),names{i}),uid2); end end case 'cell' for i=1:prod(size(v)) [t, uid2] = add(t,uid,'element','cell'); % TODO % special handling of cellstr ? t = attributes(t,'add',uid2,'index',num2str(i)); t = attributes(t,'add',uid2,'type',class(v{i})); t = attributes(t,'add',uid2,'size',xml_num2str(size(v{i}))); t = xml_var2xml(t,v{i},uid2); end case 'char' % TODO % char values should be in CData t = add(t,uid,'chardata',v); case {'int8','uint8','int16','uint16','int32','uint32'} [t, uid] = add(t,uid,'element',class(v)); % TODO % Handle integer formats (cannot use sprintf or num2str) otherwise if ismember('serialize',methods(class(v))) % TODO % is CData necessary for class output ? t = add(t,uid,'cdata',serialize(v)); else warning(sprintf(... '[SAVEXML] Cannot convert from %s to XML.',class(v))); end end %======================================================================= function s = xml_num2str(n) % TODO % use format ? if isempty(n) s = '[]'; else s = ['[' sprintf('%g ',n(1:end-1))]; s = [s num2str(n(end)) ']']; end
github
spm/spm5-master
spm_eeg_inv_electrset.m
.m
spm5-master/spm_eeg_inv_electrset.m
16,739
utf_8
16af7781a5ed0427df06e69cbafc0d66
function [el_sphc,el_name] = spm_eeg_inv_electrset(el_set) %------------------------------------------------------------------------ % FORMAT [el_sphc,el_name] = spm_eeg_inv_electrset(el_set) ; % or % FORMAT [set_Nel,set_name] = spm_eeg_inv_electrset ; % % Creates the electrode set on a sphere, set type is defined by 'el_set'. % or return the name of the sets available, and the number of electrodes. % Electrode coordinates generated are on a unit sphere, with : % - nasion at [0 1 0] % - left/right ear at [-1 0 0]/[1 0 0] % - inion at [0 -1 0] % - and Cz at [0 0 1] % So the coordinates need to be adapted for any (semi-)realistic head % model! %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Christophe Phillips, % $Id$ set_name = strvcat('10-20 system with 23 electrodes.', ... '10-20 system with 19 electrodes.', ... '61 Equidistant electrodes.', ... '148 electrodes, Pascual-Marqui''s set.', ... '31 electrodes, Rik''s set.', ... '10-20 system with 21 electrodes.', ... '10-20 system with 29 electrodes.', ... '62 electrodes on ext. 10-20 system.', ... 'Select BDF from EEGtemplates.', ... 'Select CTF from EEGtemplates'); Nr_electr = [23 19 61 148 31 21 29 62 -1]; if nargin < 1 el_sphc = Nr_electr; el_name = set_name; else try switch el_set case 1 fprintf(['\n',set_name(el_set,:),'\n\n']); [el_sphc,el_name] = sys1020_23 ; case 2 fprintf(['\n',set_name(el_set,:),'\n\n']); [el_sphc,el_name] = sys1020_19 ; case 3 fprintf(['\n',set_name(el_set,:),'\n\n']); [el_sphc,el_name] = sys61 ; case 4 fprintf(['\n',set_name(el_set,:),'\n\n']); [el_sphc,el_name] = sys148 ; case 5 fprintf(['\n',set_name(el_set,:),'\n\n']); el_rik = [59 1 14 50 48 33 19 47 31 17 ... 46 30 29 44 36 9 22 38 11 24 ... 39 26 25 40 42 53 37 49 41 45 8]; % Subset of electrodes for Rik's expe. [el_sphc,el_name] = sys61 ; el_sphc = el_sphc(:,el_rik) ; el_name = el_name(el_rik,:) ; case 6 fprintf(['\n',set_name(el_set,:),'\n\n']); el_not_21 = [2 22]; el_21 = 1:23; el_21(el_not_21) = []; [el_sphc,el_name] = sys1020_23 ; el_sphc = el_sphc(:,el_21) ; el_name = el_name(el_21,:) ; case 7 fprintf(['\n',set_name(el_set,:),'\n\n']); [el_sphc,el_name] = sys1020_29 ; case 8 fprintf(['\n',set_name(el_set,:),'\n\n']); [el_sphc,el_name] = sys1020_62 ; case 9 Fchannels = spm_select(1, '\.mat$', 'Select channel template file', ... {}, fullfile(spm('dir'), 'EEGtemplates')); [Fpath,Fname] = fileparts(Fchannels); elec = load(Fchannels); el_sphc = elec.pos(:,1:3)'; el_name = elec.allelecs; case 10 Fchannels = spm_select(1, '\.mat$', 'Select channel template file', ... {}, fullfile(spm('dir'), 'EEGtemplates')); [Fpath,Fname] = fileparts(Fchannels); elec = load(Fchannels); try [el_sphc,el_name] = treatCTF(elec,Fname); catch el_sphc = elec.pos3D; el_name = elec.Cnames; end otherwise warning('Unknown electrodes set !!!') el_sphc = []; el_name = []; end if ~iscell(el_name) el_name = cellstr(el_name); end catch error(['Provide the electrode set number : from 1 to ',num2str(length(Nr_electr))]) end end return %________________________________________________________________________ % % Subfunctions defining the electrode sets % %________________________________________________________________________ % FORMAT el_sphc = sysXXXX ; % % Genrates a set of electrode coordinates on a sphere. % Other sets can be added here, as long as the format is respected : % el_sphc : 3xNel coordinates on a radius 1 sphere % Nel : nr of electrodes %------------------------------------------------------------------------ function [el_sphc,el_name] = sys1020_23 ; % Classic 10-20 system with 23 usefull electrodes % The mastoid electrodes (A1-A2) are located on the hemispheric plane d2r=pi/180; % converts degrees to radian Fpz = [ 0 sin(72*d2r) cos(72*d2r) ] ; Fp1 = [ -sin(72*d2r)*sin(18*d2r) sin(72*d2r)*cos(18*d2r) cos(72*d2r) ] ; F7 = [ -sin(72*d2r)*sin(54*d2r) sin(72*d2r)*cos(54*d2r) cos(72*d2r) ] ; T3 = [ -sin(72*d2r) 0 cos(72*d2r) ] ; C3 = [ -sin(36*d2r) 0 cos(36*d2r) ] ; Cz = [ 0 0 1 ] ; Fz = [ 0 sin(36*d2r) cos(36*d2r) ] ; temp=Fz+F7 ; F3=temp/norm(temp); el_sphc=[ Fp1 ; % Fp1 Fpz % Fpz -Fp1(1) Fp1(2) Fp1(3) ; % Fp2 F7 ; % F7 F3 ; % F3 Fz ; % Fz -F3(1) F3(2) F3(3) ; % F4 -F7(1) F7(2) F7(3) ; % F8 -1 0 0 ; % A1 T3 ; % T3 C3 ; % C3 Cz ; % Cz -C3(1) C3(2) C3(3) ; % C4 -T3(1) T3(2) T3(3) ; % T4 1 0 0 ; % A2 F7(1) -F7(2) F7(3) ; % T5 F3(1) -F3(2) F3(3) ; % P3 Fz(1) -Fz(2) Fz(3) ; % Pz -F3(1) -F3(2) F3(3) ; % P4 -F7(1) -F7(2) F7(3) ; % T6 Fp1(1) -Fp1(2) Fp1(3) ; % O1 Fpz(1) -Fpz(2) Fpz(3) ; % Oz -Fp1(1) -Fp1(2) Fp1(3) ]' ; % O2 el_name = str2mat('Fp1','Fpz','Fp2', ... 'F7','F3','Fz','F4','F8', ... 'A1','T3','C3','Cz','C4','T4','A2', ... 'T5','P3','Pz','P4','T6', ... 'O1','Oz','O2') ; return %------------------------------------------------------------------------ function [el_sphc,el_name] = sys1020_19 ; % Classic 10-20 system with 19 usefull electrodes % The mastoid electrodes (A1-A2) would be located on the hemispheric plane % Compared with the previous set, electrodes Fpz, A1, A2 & Oz are removed d2r=pi/180; % converts degrees to radian Fpz = [ 0 sin(72*d2r) cos(72*d2r) ] ; Fp1 = [ -sin(72*d2r)*sin(18*d2r) sin(72*d2r)*cos(18*d2r) cos(72*d2r) ] ; F7 = [ -sin(72*d2r)*sin(54*d2r) sin(72*d2r)*cos(54*d2r) cos(72*d2r) ] ; T3 = [ -sin(72*d2r) 0 cos(72*d2r) ] ; C3 = [ -sin(36*d2r) 0 cos(36*d2r) ] ; Cz = [ 0 0 1 ] ; Fz = [ 0 sin(36*d2r) cos(36*d2r) ] ; temp=Fz+F7 ; F3=temp/norm(temp); el_sphc=[ Fp1 ; % Fp1 -Fp1(1) Fp1(2) Fp1(3) ; % Fp2 F7 ; % F7 F3 ; % F3 Fz ; % Fz -F3(1) F3(2) F3(3) ; % F4 -F7(1) F7(2) F7(3) ; % F8 T3 ; % T3 C3 ; % C3 Cz ; % Cz -C3(1) C3(2) C3(3) ; % C4 -T3(1) T3(2) T3(3) ; % T4 F7(1) -F7(2) F7(3) ; % T5 F3(1) -F3(2) F3(3) ; % P3 Fz(1) -Fz(2) Fz(3) ; % Pz -F3(1) -F3(2) F3(3) ; % P4 -F7(1) -F7(2) F7(3) ; % T6 Fp1(1) -Fp1(2) Fp1(3) ; % O1 -Fp1(1) -Fp1(2) Fp1(3) ]' ; % O2 el_name = str2mat('Fp1','Fp2', ... 'F7','F3','Fz','F4','F8', ... 'T3','C3','Cz','C4','T4', ... 'T5','P3','Pz','P4','T6', ... 'O1','O2') ; return %------------------------------------------------------------------------ function [el_sphc,el_name] = sys1020_29 ; % Classic 10-20 system with 29 useful electrodes % The mastoid electrodes (A1-A2) are located on the hemispheric plane % Intermediate locations at 10% are used here, hence a few "classic" % electrodes have different names (EG. T8=T4, P8=T6, T7=T3, P7=T5 d2r=pi/180; % converts degrees to radian Fpz = [ 0 sin(72*d2r) cos(72*d2r) ] ; Fp1 = [ -sin(72*d2r)*sin(18*d2r) sin(72*d2r)*cos(18*d2r) cos(72*d2r) ] ; F7 = [ -sin(72*d2r)*sin(54*d2r) sin(72*d2r)*cos(54*d2r) cos(72*d2r) ] ; T3 = [ -sin(72*d2r) 0 cos(72*d2r) ] ; C3 = [ -sin(36*d2r) 0 cos(36*d2r) ] ; Cz = [ 0 0 1 ] ; Fz = [ 0 sin(36*d2r) cos(36*d2r) ] ; F3 = Fz+F7 ;F3 = F3/norm(F3); Fc5 = F7+F3+T3+C3; Fc5 = Fc5/norm(Fc5); Fc1 = F3+Fz+C3+Cz; Fc1 = Fc1/norm(Fc1); el_sphc=[ 1 0 0 ; % A2 -F7(1) F7(2) F7(3) ; % F8 -T3(1) T3(2) T3(3) ; % T8=T4 or flipped T3 -F7(1) -F7(2) F7(3) ; % P8=T6 -Fc5(1) Fc5(2) Fc5(3) ; % Fc6 -Fc5(1) -Fc5(2) Fc5(3) ; % Cp6 -Fp1(1) Fp1(2) Fp1(3) ; % Fp2 -F3(1) F3(2) F3(3) ; % F4 -C3(1) C3(2) C3(3) ; % C4 -F3(1) -F3(2) F3(3) ; % P4 -Fp1(1) -Fp1(2) Fp1(3) ; % O2 -Fc1(1) Fc1(2) Fc1(3) ; % Fc2 -Fc1(1) -Fc1(2) Fc1(3) ; % Cp2 Fz ; % Fz Cz ; % Cz Fz(1) -Fz(2) Fz(3) ; % Pz Fc1 % Fc1 Fc1(1) -Fc1(2) Fc1(3) ; % Cp1 Fp1 ; % Fp1 F3 ; % F3 C3 ; % C3 F3(1) -F3(2) F3(3) ; % P3 Fp1(1) -Fp1(2) Fp1(3) ; % O1 Fc5 ; % Fc5 Fc5(1) -Fc5(2) Fc5(3) ; % Cp5 F7 ; % F7 T3 ; % T7=T3 F7(1) -F7(2) F7(3) ; % P7=T5 -1 0 0 ]' ; % A1 el_name = strvcat('A2','F8','T8','P8','Fc6','Cp6', ... 'Fp2','F4','C4','P4','O2','Fc2','Cp2', ... 'Fz','Cz','Pz','Fc1','Cp1', ... 'Fp1','F3','C3','P3','O1','Fc5','Cp5', ... 'F7','T7','P7','A1') ; return %------------------------------------------------------------------------ function [el_sphc,el_name] = sys61 ; % 61 quasi-equidistant electrodes, as used on the easycap. % d2r = pi/180 ; Ne_pr = [ 6 12 15 16 14 ] ; % Number of electrodes per "ring", from top to bottom % Cz is assumed to be perfectly on top [0 0 1] N_r = length(Ne_pr) ; dth = 90 * d2r / N_r ; el_sphc = [0 0 1] ; for i=1:N_r thet = i * dth ; sth = sin(thet) ; cth = cos(thet) ; l_phi = (90:-360/Ne_pr(i):-269)*d2r ; for phi=l_phi el_sphc = [ el_sphc ; sth*cos(phi) sth*sin(phi) cth ] ; end end % remove 3 frontal electrodes at the level of eyes. el_sphc([51 52 64],:) = [] ; el_sphc = el_sphc'; el_name = num2str((1:61)'); %figure,plot3(el_sphc(1,:),el_sphc(2,:),el_sphc(3,:),'*');axis vis3d;rotate3d on return %------------------------------------------------------------------------ function [el_sphc,el_name] = sys148 ; % 148 electrodes spread as in the paper by Pascual-Marqui et al. % This si not suitable for a realist head model, as the location of the eyes % is ignored... warning('This electrode set is not suitable for realistic head model !'); d2r = pi/180 ; Ne_pr = [ 6 12 17 21 23 24 23 21 ] ; el_sphc = [0 0 1] ; N_r = length(Ne_pr) ; dth = 90 * d2r / (1+length(find(diff(Ne_pr)>0))) ; % Number of electrodes per "ring", from top to bottom % The nr of electr per ring decreases under the hemispheric line % Cz is assumed to be perfectly on top [0 0 1] for i=1:N_r thet = i * dth ; sth = sin(thet) ; cth = cos(thet) ; dphi = - 360 / Ne_pr(i) * d2r ; phi0 = (1-rem(i,2)) * dphi / 2 ; for j=1:Ne_pr(i) phi = phi0 + (j-1)*dphi ; el_sphc = [ el_sphc ; -sth*sin(phi) sth*cos(phi) cth ] ; end end el_sphc = el_sphc'; el_name = num2str((1:148)'); %figure,plot3(el_sphc(1,:),el_sphc(2,:),el_sphc(3,:),'*');axis vis3d;rotate3d on return %------------------------------------------------------------------------ function [el_sphc,el_name] = sys1020_62 ; % Classic 10-20 system with 62 useful electrodes % The mastoid electrodes (A1-A2) are located on the hemispheric plane % Intermediate locations at 10% are used here, hence a few "classic" % electrodes have different names (eg. T8=T4, P8=T6, T7=T3, P7=T5 d2r=pi/180; % converts degrees to radian % Electrodes on the front left quarter %------------------------------------- % Main electrodes FPz = [ 0 sin(72*d2r) cos(72*d2r) ] ; FP1 = [ -sin(72*d2r)*sin(18*d2r) sin(72*d2r)*cos(18*d2r) cos(72*d2r) ] ; AF7 = [ -sin(72*d2r)*sin(36*d2r) sin(72*d2r)*cos(36*d2r) cos(72*d2r) ] ; F7 = [ -sin(72*d2r)*sin(54*d2r) sin(72*d2r)*cos(54*d2r) cos(72*d2r) ] ; FT7 = [ -sin(72*d2r)*sin(72*d2r) sin(72*d2r)*cos(72*d2r) cos(72*d2r) ] ; T7 = [ -sin(72*d2r) 0 cos(72*d2r) ] ; C5 = [ -sin(54*d2r) 0 cos(54*d2r) ] ; C3 = [ -sin(36*d2r) 0 cos(36*d2r) ] ; C1 = [ -sin(18*d2r) 0 cos(18*d2r) ] ; AFz = [ 0 sin(54*d2r) cos(54*d2r) ] ; Fz = [ 0 sin(36*d2r) cos(36*d2r) ] ; Ref = [ 0 sin(18*d2r) cos(18*d2r) ] ; Cz = [ 0 0 1 ] ; TP9 = [ -sin(108*d2r) cos(108*d2r) 0 ] ; % Intermediate electrodes AF3 = AF7+AFz ; AF3 = AF3/norm(AF3); F3 = Fz+F7 ; F3 = F3 /norm(F3); FC3 = FT7+Ref ; FC3 = FC3/norm(FC3); F5 = F7+F3 ; F5 = F5 /norm(F5); F1 = Fz+F3 ; F1 = F1 /norm(F1); FC5 = FT7+FC3 ; FC5 = FC5/norm(FC5); FC1 = Ref+FC3 ; FC1 = FC1/norm(FC1); % Note, there is no A1/A2 inthis montage but TP9 and TP10 el_sphc=[ FP1 ; % Fp1 FPz ; % Fpz -FP1(1) FP1(2) FP1(3) ; % Fp2 AF7 ; % AF7 AF3 ; % AF3 AFz ; % AFz -AF3(1) AF3(2) AF3(3) ; % AF4 -AF7(1) AF7(2) AF7(3) ; % AF8 F7 ; % F7 F5 ; % F5 F3 ; % F3 F1 ; % F1 Fz ; % Fz -F1(1) F1(2) F1(3) ; % F2 -F3(1) F3(2) F3(3) ; % F4 -F5(1) F5(2) F5(3) ; % F6 -F7(1) F7(2) F7(3) ; % F8 FT7 ; % FT7 FC5 ; % FC5 FC3 ; % FC3 FC1 ; % FC1 -FC1(1) FC1(2) FC1(3) ; % FC2 -FC3(1) FC3(2) FC3(3) ; % FC4 -FC5(1) FC5(2) FC5(3) ; % FC6 -FT7(1) FT7(2) FT7(3) ; % FT8 T7 ; % T7 C5 ; % C5 C3 ; % C3 C1 ; % C1 Cz ; % Cz -C1(1) C1(2) C1(3) ; % C2 -C3(1) C3(2) C3(3) ; % C4 -C5(1) C5(2) C5(3) ; % C6 -T7(1) T7(2) T7(3) ; % T8 Start posteririor part TP9 ; % TP9 FT7(1) -FT7(2) FT7(3) ; % TP7 FC5(1) -FC5(2) FC5(3) ; % CP5 FC3(1) -FC3(2) FC3(3) ; % CP3 FC1(1) -FC1(2) FC1(3) ; % CP1 Ref(1) -Ref(2) Ref(3) ; % Cpz -FC1(1) -FC1(2) FC1(3) ; % CP2 -FC3(1) -FC3(2) FC3(3) ; % CP3 -FC5(1) -FC5(2) FC5(3) ; % CP6 -FT7(1) -FT7(2) FT7(3) ; % TP8 -TP9(1) TP9(2) TP9(3) ; % TP10 F7(1) -F7(2) F7(3) ; % P7 F5(1) -F5(2) F5(3) ; % P5 F3(1) -F3(2) F3(3) ; % P3 F1(1) -F1(2) F1(3) ; % P1 Fz(1) -Fz(2) Fz(3) ; % Pz -F1(1) -F1(2) F1(3) ; % P2 -F3(1) -F3(2) F3(3) ; % P4 -F5(1) -F5(2) F5(3) ; % P6 -F7(1) -F7(2) F7(3) ; % P8 AF7(1) -AF7(2) AF7(3) ; % PO7 AF3(1) -AF3(2) AF3(3) ; % PO3 AFz(1) -AFz(2) AFz(3) ; % POz -AF3(1) -AF3(2) AF3(3) ; % PO4 -AF7(1) -AF7(2) AF7(3) ; % PO8 FP1(1) -FP1(2) FP1(3) ; % O1 FPz(1) -FPz(2) FPz(3) ; % Oz -FP1(1) -FP1(2) FP1(3) ]'; % O2 el_name = strvcat('FP1','FPz','FP2','AF7','AF3','AFz','AF4','AF8', ... 'F7','F5','F3','F1','Fz','F2','F4','F6','F8', ... 'FT7','FC5','FC3','FC1','FC2','FC4','FC6','FT8', ... 'T7','C5','C3','C1','Cz','C2','C4','C6','T8', ... 'TP9','TP7','CP5','CP3','CP1','CPz','CP2','CP4','CP6','TP8','TP10', ... 'P7','P5','P3','P1','Pz','P2','P4','P6','P8', ... 'PO7','PO3','POz','PO4','PO8','O1','Oz','O2'); return %________________________________________________________________________ % % A few other subfunctions %________________________________________________________________________ function [el_sphc,el_name] = treatCTF(elec,Fname); % Takes the info from the CTF and creates the standard 3D electrode set % from the 2D map. switch lower(Fname) case 'ctf275_setup' xf = elec.Cpos(1,:)-.45; yf = elec.Cpos(2,:)-.55; rf = sqrt(xf.^2+yf.^2); xf = xf./max(rf)*pi/2; yf = yf./max(rf)*pi/2; chan_to_remove = [] ; % HEOG & VEOG case '61channels' xf = elec.Cpos(1,:)-.5; yf = elec.Cpos(2,:)-.5; rf = sqrt(xf.^2+yf.^2); xf = xf./max(rf)*pi/2; yf = yf./max(rf)*pi/2; chan_to_remove = [1 2] ; % HEOG & VEOG otherwise error('Unknown CTF') end [ x, y, z ] = FlatToCart(xf, yf); el_sphc = [x;y;z]; el_sphc(:,chan_to_remove) = []; el_name = elec.Cnames; el_name(chan_to_remove) = []; return %________________________________________________________________________ function [ x, y, z ] = FlatToCart(xf, yf) % Convert 2D Cartesian Flat Map coordinates into Cartesian % coordinates on surface of unit sphere theta = atan2(yf,xf); phi = xf./cos(theta); z = sqrt(1./(1+tan(phi).^2)); rh = sqrt(1-z.^2); x = rh.*cos(theta); y = rh.*sin(theta); return
github
spm/spm5-master
spm_bilinear.m
.m
spm5-master/spm_bilinear.m
3,613
utf_8
7f238feffb3fabfd9fb371f41cf46a02
function [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt) % returns global Volterra kernels for a MIMO Bilinear system % FORMAT [H0,H1,H2] = spm_bilinear(A,B,C,D,x0,N,dt) % A - (n x n) df(x(0),0)/dx - n states % B - (n x n x m) d2f(x(0),0)/dxdu - m inputs % C - (n x m) df(x(0),0)/du - d2f(x(0),0)/dxdu*x(0) % D - (n x 1) f(x(0).0) - df(x(0),0)/dx*x(0) % x0 - (n x 1) x(0) % N - kernel depth {intervals} % dt - interval {seconds} % % Volterra kernels: % % H0 - (n) = h0(t) = y(t) % H1 - (N x n x m) = h1i(t,s1) = dy(t)/dui(t - s1) % H2 - (N x N x n x m x m) = h2ij(t,s1,s2) = d2y(t)/dui(t - s1)duj(t - s2) % % where n = p if modes are specified %___________________________________________________________________________ % Returns Volterra kernels for bilinear systems of the form % % dx/dt = f(x,u) = A*x + B1*x*u1 + ... Bm*x*um + C1u1 + ... Cmum + D % y(t) = x(t) % %--------------------------------------------------------------------------- % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Karl Friston % $Id: spm_bilinear.m 112 2005-05-04 18:20:52Z john $ % Volterra kernels for bilinear systems %=========================================================================== % parameters %--------------------------------------------------------------------------- n = size(A,1); % state variables m = size(C,2); % inputs A = full(A); B = full(B); C = full(C); D = full(D); % eignvector solution {to reduce M0 to leading diagonal form} %--------------------------------------------------------------------------- M0 = [0 zeros(1,n); D A]; [U J] = eig(M0); V = pinv(U); % Lie operator {M0} %--------------------------------------------------------------------------- M0 = sparse(J); X0 = V*[1; x0]; % 0th order kernel %--------------------------------------------------------------------------- H0 = ex(N*dt*M0)*X0; % 1st order kernel %--------------------------------------------------------------------------- if nargout > 1 % Lie operator {M1} %------------------------------------------------------------------- for i = 1:m M1(:,:,i) = V*[0 zeros(1,n); C(:,i) B(:,:,i)]*U; end % 1st order kernel %------------------------------------------------------------------- H1 = zeros(N,n + 1,m); for p = 1:m for i = 1:N u1 = N - i + 1; H1(u1,:,p) = ex(u1*dt*M0)*M1(:,:,p)*ex(-u1*dt*M0)*H0; end end end % 2nd order kernels %--------------------------------------------------------------------------- if nargout > 2 H2 = zeros(N,N,n + 1,m,m); for p = 1:m for q = 1:m for j = 1:N u2 = N - j + 1; u1 = N - [1:j] + 1; H = ex(u2*dt*M0)*M1(:,:,q)*ex(-u2*dt*M0)*H1(u1,:,p)'; H2(u2,u1,:,q,p) = H'; H2(u1,u2,:,p,q) = H'; end end end end % project to state space and remove kernels associated with the constant %--------------------------------------------------------------------------- if nargout > 0 H0 = real(U*H0); H0 = H0([1:n] + 1); end if nargout > 1 for p = 1:m H1(:,:,p) = real(H1(:,:,p)*U.'); end H1 = H1(:,[1:n] + 1,:); end if nargout > 1 for p = 1:m for q = 1:m for j = 1:N H2(j,:,:,p,q) = real(squeeze(H2(j,:,:,p,q))*U.'); end end end H2 = H2(:,:,[1:n] + 1,:,:); end return % matrix exponential function (for diagonal matrices) %--------------------------------------------------------------------------- function y = ex(x) n = length(x); y = spdiags(exp(diag(x)),0,n,n); return
github
spm/spm5-master
spm_powell.m
.m
spm5-master/spm_powell.m
7,978
utf_8
063a0beec40aebe20cbadf483220393b
function [p,f] = spm_powell(p,xi,tolsc,func,varargin) % Powell optimisation method % FORMAT [p,f] = spm_powell(p,xi,tolsc,func,varargin) % p - Starting parameter values % xi - columns containing directions in which to begin % searching. % tolsc - stopping criteria % - optimisation stops when % sqrt(sum(((p-p_prev)./tolsc).^2))<1 % func - name of evaluated function % varargin - remaining arguments to func (after p) % % p - final parameter estimates % f - function value at minimum % %_______________________________________________________________________ % Method is based on Powell's optimisation method described in % Numerical Recipes (Press, Flannery, Teukolsky & Vetterling). %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_powell.m 691 2006-11-22 17:44:19Z john $ p = p(:); f = feval(func,p,varargin{:}); for iter=1:512, if numel(p)>1, fprintf('iteration %d...\n', iter); end; ibig = numel(p); pp = p; fp = f; del = 0; for i=1:length(p), ft = f; [p,junk,f] = min1d(p,xi(:,i),func,f,tolsc,varargin{:}); if abs(ft-f) > del, del = abs(ft-f); ibig = i; end; end; if numel(p)==1 || sqrt(sum(((p(:)-pp(:))./tolsc(:)).^2))<1, return; end; ft = feval(func,2.0*p-pp,varargin{:}); if ft < f, [p,xi(:,ibig),f] = min1d(p,p-pp,func,f,tolsc,varargin{:}); end; end; warning('Too many optimisation iterations'); return; %_______________________________________________________________________ %_______________________________________________________________________ function [p,pi,f] = min1d(p,pi,func,f,tolsc,varargin) % Line search for minimum. global lnm % used in funeval lnm = struct('p',p,'pi',pi,'func',func,'args',[]); lnm.args = varargin; min1d_plot('Init', 'Line Minimisation','Function','Parameter Value'); min1d_plot('Set', 0, f); tol = 1/sqrt(sum((pi(:)./tolsc(:)).^2)); t = bracket(f); [f,pmin] = search(t,tol); pi = pi*pmin; p = p + pi; for i=1:length(p), fprintf('%-8.4g ', p(i)); end; fprintf('| %.5g\n', f); min1d_plot('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function f = funeval(p) % Reconstruct parameters and evaluate. global lnm % defined in min1d pt = lnm.p+p.*lnm.pi; f = feval(lnm.func,pt,lnm.args{:}); min1d_plot('Set',p,f); return; %_______________________________________________________________________ %_______________________________________________________________________ function t = bracket(f) % Bracket the minimum (t(2)) between t(1) and t(3) gold = (1+sqrt(5))/2; % Golden ratio t(1) = struct('p',0,'f',f); t(2).p = 1; t(2).f = funeval(t(2).p); % if t(2) not better than t(1) then swap if t(2).f > t(1).f, t(3) = t(1); t(1) = t(2); t(2) = t(3); end; t(3).p = t(2).p + gold*(t(2).p-t(1).p); t(3).f = funeval(t(3).p); while t(2).f > t(3).f, % fit a polynomial to t tmp = cat(1,t.p)-t(2).p; pol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f); % minimum is when gradient of polynomial is zero % sign of pol(3) (the 2nd deriv) should be +ve if pol(3)>0, % minimum is when gradient of polynomial is zero d = -pol(2)/(2*pol(3)+eps); % A very conservative constraint on the displacement if d > (1+gold)*(t(3).p-t(2).p), d = (1+gold)*(t(3).p-t(2).p); end; u.p = t(2).p+d; else, % sign of pol(3) (the 2nd deriv) is not +ve % so extend out by golden ratio instead u.p = t(3).p+gold*(t(3).p-t(2).p); end; % FUNCTION EVALUATION u.f = funeval(u.p); if (t(2).p < u.p) == (u.p < t(3).p), % u is between t(2) and t(3) if u.f < t(3).f, % minimum between t(2) and t(3) - done t(1) = t(2); t(2) = u; return; elseif u.f > t(2).f, % minimum between t(1) and u - done t(3) = u; return; end; end; % Move all 3 points along t(1) = t(2); t(2) = t(3); t(3) = u; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function [f,p] = search(t, tol) % Brent's method for line searching - given that minimum is bracketed gold1 = 1-(sqrt(5)-1)/2; % Current and previous displacements d = Inf; pd = Inf; % sort t into best first order [junk,ind] = sort(cat(1,t.f)); t = t(ind); brk = [min(cat(1,t.p)) max(cat(1,t.p))]; for iter=1:128, % check stopping criterion if abs(t(1).p - 0.5*(brk(1)+brk(2)))+0.5*(brk(2)-brk(1)) <= 2*tol, p = t(1).p; f = t(1).f; return; end; % keep last two displacents ppd = pd; pd = d; % fit a polynomial to t tmp = cat(1,t.p)-t(1).p; pol = pinv([ones(3,1) tmp tmp.^2])*cat(1,t.f); % minimum is when gradient of polynomial is zero d = -pol(2)/(2*pol(3)+eps); u.p = t(1).p+d; % check so that displacement is less than the last but two, % that the displaced point is between the brackets % and that the solution is a minimum rather than a maximum eps2 = 2*eps*abs(t(1).p)+eps; if abs(d) > abs(ppd)/2 | u.p < brk(1)+eps2 | u.p > brk(2)-eps2 | pol(3)<=0, % if criteria are not met, then golden search into the larger part if t(1).p >= 0.5*(brk(1)+brk(2)), d = gold1*(brk(1)-t(1).p); else, d = gold1*(brk(2)-t(1).p); end; u.p = t(1).p+d; end; % FUNCTION EVALUATION u.f = funeval(u.p); % Insert the new point into the appropriate position and update % the brackets if necessary if u.f <= t(1).f, if u.p >= t(1).p, brk(1)=t(1).p; else, brk(2)=t(1).p; end; t(3) = t(2); t(2) = t(1); t(1) = u; else, if u.p < t(1).p, brk(1)=u.p; else, brk(2)=u.p; end; if u.f <= t(2).f, t(3) = t(2); t(2) = u; elseif u.f <= t(3).f, t(3) = u; end; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function min1d_plot(action,arg1,arg2,arg3,arg4) % Visual output for line minimisation persistent min1dplot %----------------------------------------------------------------------- if (nargin == 0) min1d_plot('Init'); else % initialize %--------------------------------------------------------------- if (strcmp(lower(action),'init')) if (nargin<4) arg3 = 'Function'; if (nargin<3) arg2 = 'Value'; if (nargin<2) arg1 = 'Line minimisation'; end end end fg = spm_figure('FindWin','Interactive'); if ~isempty(fg) min1dplot = struct('pointer',get(fg,'Pointer'),'name',get(fg,'Name'),'ax',[]); min1d_plot('Clear'); set(fg,'Pointer','watch'); % set(fg,'Name',arg1); min1dplot.ax = axes('Position', [0.15 0.1 0.8 0.75],... 'Box', 'on','Parent',fg); lab = get(min1dplot.ax,'Xlabel'); set(lab,'string',arg3,'FontSize',10); lab = get(min1dplot.ax,'Ylabel'); set(lab,'string',arg2,'FontSize',10); lab = get(min1dplot.ax,'Title'); set(lab,'string',arg1); line('Xdata',[], 'Ydata',[],... 'LineWidth',2,'Tag','LinMinPlot','Parent',min1dplot.ax,... 'LineStyle','-','Marker','o'); drawnow; end % reset %--------------------------------------------------------------- elseif (strcmp(lower(action),'set')) F = spm_figure('FindWin','Interactive'); br = findobj(F,'Tag','LinMinPlot'); if (~isempty(br)) [xd,indx] = sort([get(br,'Xdata') arg1]); yd = [get(br,'Ydata') arg2]; yd = yd(indx); set(br,'Ydata',yd,'Xdata',xd); drawnow; end % clear %--------------------------------------------------------------- elseif (strcmp(lower(action),'clear')) fg = spm_figure('FindWin','Interactive'); if isstruct(min1dplot), if ishandle(min1dplot.ax), delete(min1dplot.ax); end; set(fg,'Pointer',min1dplot.pointer); set(fg,'Name',min1dplot.name); end; spm_figure('Clear',fg); drawnow; end; end %_______________________________________________________________________
github
spm/spm5-master
spm_vol.m
.m
spm5-master/spm_vol.m
5,542
utf_8
eb6c5a42448d73ffcb5701c148093c4f
function V = spm_vol(P) % Get header information etc for images. % FORMAT V = spm_vol(P) % P - a matrix of filenames. % V - a vector of structures containing image volume information. % The elements of the structures are: % V.fname - the filename of the image. % V.dim - the x, y and z dimensions of the volume % V.dt - A 1x2 array. First element is datatype (see spm_type). % The second is 1 or 0 depending on the endian-ness. % V.mat - a 4x4 affine transformation matrix mapping from % voxel coordinates to real world coordinates. % V.pinfo - plane info for each plane of the volume. % V.pinfo(1,:) - scale for each plane % V.pinfo(2,:) - offset for each plane % The true voxel intensities of the jth image are given % by: val*V.pinfo(1,j) + V.pinfo(2,j) % V.pinfo(3,:) - offset into image (in bytes). % If the size of pinfo is 3x1, then the volume is assumed % to be contiguous and each plane has the same scalefactor % and offset. %____________________________________________________________________________ % % The fields listed above are essential for the mex routines, but other % fields can also be incorporated into the structure. % % The images are not memory mapped at this step, but are mapped when % the mex routines using the volume information are called. % % Note that spm_vol can also be applied to the filename(s) of 4-dim % volumes. In that case, the elements of V will point to a series of 3-dim % images. % % This is a replacement for the spm_map_vol and spm_unmap_vol stuff of % MatLab4 SPMs (SPM94-97), which is now obsolete. %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_vol.m 982 2007-10-26 14:01:54Z john $ if nargin==0, V = struct('fname', {},... 'dim', {},... 'dt', {},... 'pinfo', {},... 'mat', {},... 'n', {},... 'descrip', {},... 'private',{}); return; end; % If is already a vol structure then just return; if isstruct(P), V = P; return; end; V = subfunc2(P); return; %_______________________________________________________________________ %_______________________________________________________________________ function V = subfunc2(P) if iscell(P), V = cell(size(P)); for j=1:numel(P), if iscell(P{j}), V{j} = subfunc2(P{j}); else V{j} = subfunc1(P{j}); end; end; else V = subfunc1(P); end; return; %_______________________________________________________________________ %_______________________________________________________________________ function V = subfunc1(P) if isempty(P), V = []; return; end; counter = 0; for i=1:size(P,1), v = subfunc(P(i,:)); [V(counter+1:counter+size(v, 2),1).fname] = deal(''); [V(counter+1:counter+size(v, 2),1).mat] = deal([0 0 0 0]); [V(counter+1:counter+size(v, 2),1).mat] = deal(eye(4)); [V(counter+1:counter+size(v, 2),1).mat] = deal([1 0 0]'); if isempty(v), hread_error_message(P(i,:)); error(['Can''t get volume information for ''' P(i,:) '''']); end f = fieldnames(v); for j=1:size(f,1) eval(['[V(counter+1:counter+size(v,2),1).' f{j} '] = deal(v.' f{j} ');']); end counter = counter + size(v,2); end return; %_______________________________________________________________________ %_______________________________________________________________________ function V = subfunc(p) [pth,nam,ext,n1] = spm_fileparts(deblank(p)); p = fullfile(pth,[nam ext]); n = str2num(n1); if ~exist(p,'file'), existance_error_message(p); error('File "%s" does not exist.', p); end switch ext, case {'.nii','.NII'}, % Do nothing case {'.img','.IMG'}, if ~exist(fullfile(pth,[nam '.hdr']),'file') && ~exist(fullfile(pth,[nam '.HDR']),'file'), existance_error_message(fullfile(pth,[nam '.hdr'])), error('File "%s" does not exist.', fullfile(pth,[nam '.hdr'])); end case {'.hdr','.HDR'}, ext = '.img'; p = fullfile(pth,[nam ext]); if ~exist(p,'file'), existance_error_message(p), error('File "%s" does not exist.', p); end otherwise, error('File "%s" is not of a recognised type.', p); end if isempty(n), V = spm_vol_nifti(p); else V = spm_vol_nifti(p,n); end; if isempty(n) && length(V.private.dat.dim) > 3 V0(1) = V; for i = 2:V.private.dat.dim(4) V0(i) = spm_vol_nifti(p, i); end V = V0; end if ~isempty(V), return; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function hread_error_message(q) str = {... 'Error reading information on:',... [' ',spm_str_manip(q,'k40d')],... ' ',... 'Please check that it is in the correct format.'}; spm('alert*',str,mfilename,sqrt(-1)); return; %_______________________________________________________________________ function existance_error_message(q) str = {... 'Unable to find file:',... [' ',spm_str_manip(q,'k40d')],... ' ',... 'Please check that it exists.'}; spm('alert*',str,mfilename,sqrt(-1)); return;
github
spm/spm5-master
spm_jobman.m
.m
spm5-master/spm_jobman.m
97,869
utf_8
1db2d5463418dcdf0a80c81d7cb7705a
function varargout = spm_jobman(varargin) % UI/Batching stuff %_______________________________________________________________________ % This code is based on an earlier version by Philippe Ciuciu and % Guillaume Flandin of Orsay, France. % % FORMAT spm_jobman % spm_jobman('interactive') % spm_jobman('interactive',job) % spm_jobman('interactive',job,node) % spm_jobman('interactive','',node) % Runs the user interface in interactive mode. % % FORMAT spm_jobman('serial') % spm_jobman('serial',job) % spm_jobman('serial',job,node) % spm_jobman('serial','',node) % Runs the user interface in serial mode. % % FORMAT spm_jobman('run',job) % Runs a job. % % FORMAT spm_jobman('run_nogui',job) % Runs a job without X11 (as long as there is no graphics output from the % job itself). % % FORMAT spm_jobman('help',node) % spm_jobman('help',node,width) % Creates a cell array containing help information. This is justified % to be 'width' characters wide. e.g. % h = spm_jobman('help','jobs.spatial.coreg.estimate'); % for i=1:numel(h),fprintf('%s\n',h{i}); end; % % FORMAT spm_jobman('jobhelp') % Creates a cell array containing help information specific for a certain % job. Help is only printed for items where job specific help is % present. This can be used together with spm_jobman('help') to create a % job specific manual. This feature is available only on MATLAB R14SP2 % and higher. % % node - indicates which part of the configuration is to be used. % For example, it could be 'jobs.spatial.coreg'. % % job - can be the name of a jobfile (as a .mat or a .xml), or a % 'jobs' variable loaded from a jobfile. % % FORMAT spm_jobman('defaults') % Runs the interactive defaults editor. % % FORMAT spm_jobman('pulldown') % Creates a pulldown 'TASKS' menu in the Graphics window. % % FORMAT spm_jobman('chmod') % Changes the modality for the TASKS pulldown. % % FORMAT [tag, jobs, typ, jobhelps] = spm_jobman('harvest',c) % Take a data structure, and extract what is needed to save it % as a batch job (for experts only). If c is omitted, use the currently % displayed job tree as source. %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_jobman.m 1862 2008-06-30 14:12:49Z volkmar $ if nargin==0 setup_ui; else switch lower(varargin{1}) case {'interactive'} if nargin>=2 setup_ui(varargin{2:nargin}); else setup_ui; end; case {'serial'} if nargin>=2, serial(varargin{2:nargin}); else serial; end; case {'run'} if nargin<2 error('Nothing to run'); end; run_job(varargin{2}); case {'run_nogui'} if nargin<2 error('Nothing to run'); end; run_job(varargin{2},0); case {'defaults'}, setup_ui('defaults'); case {'pulldown'} pulldown; case {'chmod'} if nargin>1, chmod(varargin{2}); end; case {'help'} if nargin>=2, varargout{1} = showdoc(varargin{2:nargin}); else varargout{1} = showdoc; end; case {'jobhelp'} varargout{1} = showjobhelp; case {'harvest'} if nargin == 1 args{1} = get(batch_box,'Userdata'); else args = varargin(2:nargin); end; [varargout{1:nargout}] = harvest(args{:}); case {'initcfg'} otherwise error(['"' varargin{1} '" - unknown option']); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function defaults_edit(varargin) setup_ui('defaults'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function interactive(varargin) ud = get(varargin{1},'UserData'); if iscell(ud) setup_ui(ud{:}); else setup_ui; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function setup_ui(varargin) % Configure the user interface fg = clearwin; fs = getdef('ui.fs'); if numel(fs)~=1 || ~isnumeric(fs{1}) || numel(fs{1})~=1, fs = 12; else fs = fs{1}; end; col1 = getdef('ui.colour1'); if numel(col1)~=1 || ~isnumeric(col1{1}) || numel(col1{1})~=3, col1 = [0.8 0.8 1]; else col1 = col1{1}; end; col2 = getdef('ui.colour2'); if numel(col2)~=1 || ~isnumeric(col2{1}) || numel(col2{1})~=3, col2 = [1 1 0.8]; else col2 = col2{1}; end; col3 = getdef('ui.colour3'); if numel(col3)~=1 || ~isnumeric(col3{1}) || numel(col3{1})~=3, col3 = [0 0 0]; else col3 = col3{1}; end; t=uicontrol(fg,... 'Style','listbox',... 'Units','normalized',... 'Position',[0.02 0.31 0.48 0.67],... 'Callback',@click_batch_box,... 'Tag','batch_box',... 'ForegroundColor', col3,... 'BackgroundColor',col1,... 'FontSize',fs,... 'Value',1); c0 = cntxtmnu(t); c1 = uimenu('Label','Exp/Con All', 'Parent',c0); uimenu('Label','Expand All', 'Parent',c1,'Callback',@expandall); uimenu('Label','Contract All', 'Parent',c1,'Callback',@contractall); uimenu('Label','Expand All Undefined Inputs', 'Parent',c1,'Callback',@expandallopen); t=uicontrol(fg,... 'Style','listbox',... 'ListBoxTop',1,... 'Units','normalized',... 'Position',[0.02 0.02 0.96 0.25],... 'Tag','help_box',... 'FontName','fixedwidth',... 'FontSize',fs,... 'ForegroundColor', col3,... 'BackgroundColor',col2); set(t,'Value',[], 'Enable', 'inactive', 'Max',2, 'Min',0); workaround(t); cntxtmnu(t); if spm_matlab_version_chk('7.1')>=0 t=uibuttongroup('parent',fg,... 'units','normalized', ... 'position',[.02 .27 .5 .03],... 'tag','help_box_switch', ... 'SelectionChangeFcn',@click_batch_box); t1=uicontrol('parent',t,... 'style','radio',... 'string','General help', ... 'units','normalized',... 'position',[0 .05 .5 .95]); l2=uicontrol('parent',t,... 'style','radio',... 'string','Job specific help', ... 'units','normalized',... 'position',[.5 .05 .5 .95]); end; t=uicontrol(fg,... 'Style','listbox',... 'Units','normalized',... 'Position',[0.51 0.74 0.47 0.24],... 'ForegroundColor', col3,... 'BackgroundColor',col1,... 'FontSize',fs,... 'Tag','opts_box'); cntxtmnu(t); t=uicontrol(fg,... 'Style','listbox',... 'Units','normalized',... 'Position',[0.51 0.49 0.47 0.24],... 'Tag','val_box',... 'ForegroundColor', col3,... 'BackgroundColor',col2,... 'Enable', 'inactive',... 'Value',[],... 'FontSize',fs,... 'Max',2, 'Min',0); set(t,'Value',[], 'Enable', 'on', 'Max',2, 'Min',0,'ListBoxTop',1); cntxtmnu(t); t=uicontrol(fg,... 'Style','listbox',... 'Units','normalized',... 'Position',[0.51 0.38 0.47 0.10],... 'Tag','msg_box',... 'ForegroundColor', col3,... 'BackgroundColor',col2,... 'Enable', 'inactive',... 'Value',[],... 'FontSize',fs,... 'Max',2, 'Min',0); cntxtmnu(t); if ~(nargin==1 && ischar(varargin{1}) && strcmp(varargin{1},'defaults')), t=uicontrol(fg,... 'style','pushbutton',... 'units','normalized',... 'Position',[0.51 0.31 0.15 0.06],... 'ForegroundColor', col3,... 'BackgroundColor',col1,... 'String','Save',... 'Callback',@save_job,... 'FontSize',fs,... 'Tag','save'); cntxtmnu(t); t=uicontrol(fg,... 'style','pushbutton',... 'units','normalized',... 'Position',[0.67 0.31 0.15 0.06],... 'ForegroundColor', col3,... 'BackgroundColor',col1,... 'String','Load',... 'Callback',@load_job,... 'FontSize',fs,... 'Tag','load'); cntxtmnu(t); t=uicontrol(fg,... 'style','pushbutton',... 'units','normalized',... 'Position',[0.83 0.31 0.15 0.06],... 'ForegroundColor', col3,... 'BackgroundColor',col1,... 'String','Run',... 'Callback',@run_struct,... 'Tag','run',... 'FontSize',fs,... 'Enable', 'off'); cntxtmnu(t); if nargin>0 initialise(varargin{:}); else initialise; end; else t=uicontrol(fg,... 'style','pushbutton',... 'units','normalized',... 'Position',[0.51 0.31 0.15 0.06],... 'ForegroundColor', col3,... 'BackgroundColor',col1,... 'String','OK',... 'FontSize',fs,... 'Callback',@ok_defaults); cntxtmnu(t); t=uicontrol(fg,... 'style','pushbutton',... 'units','normalized',... 'Position',[0.67 0.31 0.15 0.06],... 'ForegroundColor', col3,... 'BackgroundColor',col1,... 'String','Reset',... 'FontSize',fs,... 'Callback',@reset_defaults); cntxtmnu(t); t=uicontrol(fg,... 'style','pushbutton',... 'units','normalized',... 'Position',[0.83 0.31 0.15 0.06],... 'ForegroundColor', col3,... 'BackgroundColor',col1,... 'String','Cancel',... 'FontSize',fs,... 'Callback',@clearwin); cntxtmnu(t); initialise('defaults'); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function ok_defaults(varargin) harvest_def(get(batch_box,'UserData')); clearwin; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function reset_defaults(varargin) global defaults modality = []; if isfield(defaults,'modality'), modality = defaults.modality; end; spm_defaults; if ~isfield(defaults,'modality') && ~isempty(modality), defaults.modality = modality; end; pulldown; clearwin; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function fg = clearwin(varargin) fg = spm_figure('findwin','Graphics'); if isempty(fg), fg = spm_figure('Create','Graphics'); end; delete(findobj(fg,'Parent',fg)); delete(batch_box); delete(opts_box); spm('Pointer'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function expandall(varargin) c = expcon(get(batch_box,'UserData'),1); str = get_strings(c); val = min(get(batch_box,'Value'),length(str)); set(batch_box,'String',str,'Value',val,'UserData',c); update_ui; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function contractall(varargin) c = expcon(get(batch_box,'UserData'),0); str = get_strings(c); val = min(get(batch_box,'Value'),length(str)); set(batch_box,'String',str,'Value',val,'UserData',c); update_ui; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function expandallopen(varargin) c = expopen(get(batch_box,'UserData')); str = get_strings(c); fop = Inf; % find 1st open input for k=1:numel(str) op = strfind(str{k},'<-X'); if ~isempty(op) fop=k; break; end; end; if isinf(fop) val = min(get(batch_box,'Value'),length(str)); else val = fop; end; set(batch_box,'String',str,'Value',val,'UserData',c); update_ui; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,sts] = expopen(c) sts = 0; if ~isstruct(c)||~isfield(c,'type') return; end; sts=~all_set(c); if isfield(c,'val'), for i=1:length(c.val), [c.val{i} sts1] = expopen(c.val{i}); sts = sts||sts1; end; end; if isfield(c,'expanded') c.expanded = sts; end; sts = sts||isfield(c,'prog'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = expcon(c,val) if isfield(c,'expanded'), c.expanded = val; end; if isfield(c,'val'), for i=1:length(c.val), c.val{i} = expcon(c.val{i},val); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function initialise(job,node) % load the config file, possibly adding a job % to it, and generally tidy it up. The batch box % is updated to contain the current structure. files_select_list('init'); if nargin<1, job = ''; end; if nargin<2, node = 'jobs'; end; c = initialise_struct(job); set(batch_box,'UserData',start_node(c,node)); expandallopen; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function run_job(job,gui) % Run a job. This function is not called via the UI. if nargin ==1, gui = 1; end c = initialise_struct(job); if all_set(c), run_struct1(c,gui); else error('This job is not ready yet'); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function click_batch_box(varargin) % Called when the batch box is clicked remove_string_box; if strcmp(get(get(varargin{1},'Parent'),'SelectionType'),'open') run_in_current_node(@expand_contract,false); str = get_strings(get(batch_box,'UserData')); val = min(get(batch_box,'Value'),length(str)); set(batch_box,'String',str,'Value',val); else run_in_current_node(@click_batch_box_fun,false); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function update_ui [str,sts] = get_strings(get(batch_box,'UserData')); val = min(get(batch_box,'Value'),length(str)); set(batch_box,'String',str,'Value',val); run_in_current_node(@click_batch_box_fun,false); run_but = findobj(0,'Tag','run'); if sts set(run_but,'Enable', 'on'); else set(run_but,'Enable', 'off'); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [str,sts] = get_strings(c) [unused,str,sts] = start_node(c,@get_strings1,0); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,str,sts] = get_strings1(c,l) % Return the cell vector of strings displayed in the batch % box, and also whether the job is runable. This is a recursive % function that a branch of the data structure is passed to. if isfield(c,'hidden'), sts = 1; str = ''; return; end; sts = 1; mrk = ' '; nam = ''; if isfield(c,'datacheck') && ~isempty(c.datacheck), mrk = ' <-@'; sts = 0; end; if isfield(c,'name'), nam = c.name; end; if isfield(c,'expanded') % && isfield(c,'val') && ~isempty(c.val) if strcmp(c.type,'repeat') && isfield(c,'num') sts = (length(c.val) >= c.num(1)) &&... (length(c.val) <= c.num(2)); if ~sts mrk = ' <-X'; end; end; if c.expanded if numel(c.val) == 0 premark = ''; else premark = '-'; end str = {[repmat('. ',1,l) premark nam]}; for i=1:length(c.val) [c.val{i},str1,sts1] = get_strings1(c.val{i},l+1); sts = sts && sts1; if ~isempty(str1), str = {str{:},str1{:}}; end; end; else if numel(c.val) == 0 premark = ''; else premark = '+'; end str = {[repmat('. ',1,l) premark nam]}; for i=1:length(c.val) [c.val{i},unused,sts1] = get_strings1(c.val{i},l+1); sts = sts && sts1; end; if ~sts, mrk = ' <-X'; end; end; str{1} = [str{1} mrk]; else switch c.type case 'files' % If files are selected via "Input to/Output from" shortcuts, % there is no guarantee that an allowed number of files is % specified. This is checked here. cn = c.num; if (numel(cn) == 1) if isfinite(cn) cn = [cn cn]; else cn = [0 cn]; end; end; if isempty(c.val) || (numel(c.val{1}) < cn(1)) || ... (numel(c.val{1}) > cn(2)) mrk = ' <-X'; sts = 0; end; case {'menu','entry','const','choice'} if isempty(c.val) mrk = ' <-X'; sts = 0; end; case 'repeat' % don't know, whether this ever gets executed if isfield(c,'num') sts = (length(c.val) >= c.num(1)) &&... (length(c.val) <= c.num(2)); if ~sts mrk = ' <-X'; end; end; end; str = {[repmat('. ',1,l) ' ' nam mrk]}; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function ok = all_set(c) % Return whether all the necessary fields have been filled in. % This is a recursive function that a branch of the data structure % is passed to. if isfield(c,'hidden'), ok = true; return; end; ok = true; switch c.type case {'files','menu','entry','const','choice'} if isempty(c.val) ok = false; end; case {'branch','repeat'} if strcmp(c.type,'repeat') && isfield(c,'num') ok = ok && (length(c.val) >= c.num(1)) && ... (length(c.val) <= c.num(2)); end; if ok, for i=1:length(c.val), ok1 = all_set(c.val{i}); ok = ok && ok1; if ~ok, break; end; end; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function click_options_box(varargin) % The function called when the options box is clicked dat = get(opts_box,'UserData'); if ~isempty(dat) fun = dat{get(opts_box,'Value')}; run_in_current_node(fun.fun,true,fun.args{:}); if fun.redraw, update_ui; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function varargout = run_in_current_node(varargin) % Get the current node, and run a job in it varargout = {}; c = get(batch_box,'UserData'); n = get(batch_box,'Value'); show_msg(''); va = {c,@run_in_current_node1,n,varargin{:}}; [c,unused,varargout{:}] = start_node(va{:}); set(batch_box,'UserData',c); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,varargout] = start_node(c,fun,varargin) persistent node; if isempty(node) node = {'jobs'}; end; varargout = {}; if nargin==2 tmp = [0 find([fun '.']=='.')]; node = {}; for i=1:length(tmp)-1 node = {node{:},fun((tmp(i)+1):(tmp(i+1)-1))}; end; c = make_nodes(c,node); return; end; va = {c,node,fun,varargin{:}}; [c,unused,varargout{1:nargout-1}] = start_node1(va{:}); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = make_nodes(c,node) if isfield(c,'tag') && ~strcmp(gettag(c),node{1}) return; end; if isfield(c,'tag') node = {node{2:end}}; if isempty(node), return; end; end; if isfield(c,'values') && (~isfield(c,'val') ||... isempty(c.val) || ~iscell(c.val) ||... ~strcmp(gettag(c.val{1}),node{1})) for i=1:length(c.values) if strcmp(gettag(c.values{i}),node{1}) c.val = {c.values{i}}; c.val{1} = make_nodes(c.val{1},node); end; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,sts,varargout] = start_node1(c,node,fun,varargin) varargout = {}; if nargin<4, varargin = {}; end; if isfield(c,'tag') && ~strcmp(gettag(c),node{1}) varargout = cell(1,nargout-2); sts = 0; return; end; if isfield(c,'tag'), node = {node{2:end}}; end; if isempty(node) [c,varargout{1:nargout-2}] = feval(fun,c,varargin{:}); sts = 1; return; end; if isfield(c,'val'), for i=1:length(c.val) [c.val{i},sts,varargout{1:nargout-2}] = start_node1(c.val{i},node,fun,varargin{:}); if sts, return; end; end; end; keyboard error('No such node'); % Should never execute %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,n,varargout] = run_in_current_node1(c,n,fun,modify,varargin) % Satellite for run_in_current_node varargout = {}; if nargin<5, varargin = {}; end; if isfield(c,'hidden'), return; end; n = n-1; if n<0, return; end; if n==0, % if ~isfield(c,'datacheck'), % show_msg(''); % else % show_msg(c.datacheck); % end; [c,varargout{:}] = feval(fun,c,varargin{:}); end; if isfield(c,'expanded') && ~isempty(c.val) if c.expanded, val = c.val; c.val = {}; for i=1:length(val) [tmp,n,varargout{:}] = run_in_current_node1(val{i},n,fun,modify,varargin{:}); if ~isempty(tmp) if iscell(tmp) c.val = {c.val{:}, tmp{:}}; else c.val = {c.val{:}, tmp}; end; end; end; end; end; if modify && isfield(c,'check'), if all_set(c), [unused,val] = harvest(c); c.datacheck = feval(c.check,val); end; end; if isfield(c,'datacheck') && ~isempty(c.datacheck), show_msg(c.datacheck); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = click_batch_box_fun(c,unused) % Mostly set up the options box, but also update the help and value boxes if ~isempty(opts_box) dat = {}; str = {}; switch c.type case {'const'} % do nothing case {'files'} spm('pointer','watch'); str = {str{:}, 'Specify Files'}; dat = {dat{:}, struct('fun',@file_select,'args',{{}},'redraw',1)}; addvfiles(c.id,[],c); addinfiles(c); [filestr filedat] = files_select_list('listall'); str = {str{:}, filestr{:}}; dat = {dat{:}, filedat{:}}; spm('pointer','arrow'); case {'menu'} str = {str{:}, 'Specify Menu Item'}; dat = {dat{:}, struct('fun',@menu_entry,'args',{{}},'redraw',0)}; case {'entry'} str = {str{:}, 'Specify Text'}; dat = {dat{:}, struct('fun',@text_entry,'args',{{}},'redraw',1)}; case {'branch','choice','repeat'} if strcmp(c.type,'repeat') for i=1:length(c.values) if ~isfield(c.values{i},'hidden'), str = {str{:},['New "' c.values{i}.name '"']}; dat = {dat{:}, struct('fun',@series,'args',{{c.values{i}}},'redraw',1)}; end; end; elseif strcmp(c.type,'choice') for i=1:length(c.values) if ~isfield(c.values{i},'hidden'), str = {str{:},['Choose "' c.values{i}.name '"']}; dat = {dat{:}, struct('fun',@choose,'args',{{c.values{i}}},'redraw',1)}; end; end; end; end; if isfield(c,'removable') str = {str{:},['Remove Item "' c.name '"'],['Replicate Item "' c.name '"']}; dat = {dat{:}, struct('fun',@remove,'args',{{}},'redraw',1),... struct('fun',@replicate,'args',{{}},'redraw',1)}; end; if ~same(get(opts_box,'String')',str) val = 1; else val = get(opts_box,'Value'); end; val = max(min(length(str),val),min(1,length(str))); set(opts_box,'String',str,'UserData',dat,'Callback',@click_options_box,'Value',val); end; show_value(c); % Update help txt = ''; hs=findobj(0, 'tag','help_box_switch'); cntxt=get(findobj(0,'tag','help_box'),'UIContextMenu'); if isempty(hs)||strcmp(c.type, 'repeat')||strcmp(c.type, 'choice') % No help box switch created, or node type without context help set(hs, 'Visible','Off'); help_box_switch = 2; else set(hs, 'Visible','On'); hc=get(get(hs,'children')); help_box_switch = find(cat(1,hc.Value)); end; switch help_box_switch case 2, if isfield(c,'help'), txt = c.help; end; set(findobj(cntxt,'tag','cntxt_edit_jobhelp'),'Visible','off'); case 1, if isfield(c,'jobhelp'), txt = c.jobhelp; end; if isempty(findobj(cntxt,'tag','cntxt_edit_jobhelp')) cedit=uimenu('parent',cntxt,... 'Label','Edit help',... 'Callback',@edit_jobhelp,... 'Tag','cntxt_edit_jobhelp'); else set(findobj(cntxt,'tag','cntxt_edit_jobhelp'),'Visible','on'); end; end; help_box = findobj(0,'tag','help_box'); if ~isempty(help_box) set(help_box,'String',' '); workaround(help_box); ext = get(help_box,'Extent'); pos = get(help_box,'position'); pw = floor(pos(3)/ext(3)*21-4); set(help_box,'String',spm_justify(help_box,txt)); workaround(help_box); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = expand_contract(c,unused) % Expand/contract a node (for visualisation) if isfield(c,'expanded') && ~isempty(c.val) if c.expanded c.expanded = false; else c.expanded = true; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = menu_entry(c,unused) % Setup opts box for menu entry if isfield(c,'labels') && isfield(c,'values') str = {}; dat = {}; if ~isempty(c.val) val = c.val{1}; else val = '<UNDEFINED>'; end; dv = 1; for i=1:length(c.values) if ~(ischar(val) && strcmp(val,'<UNDEFINED>')) && same(c.values{i},val) str{i} = ['* ' c.labels{i}]; dv = i; else str{i} = [' ' c.labels{i}]; end; dat{i} = struct('fun',@menuval,'args',{{c.values{i}}},'redraw',1); end; set(opts_box,'String',str,'UserData',dat,'Callback',@click_options_box,'Value',dv); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c] = file_select(c) % Select files try set(batch_box,'Enable', 'inactive'); set(opts_box, 'Enable', 'inactive'); if ~isempty(c.val), sel = c.val{1}; else sel = ''; end; if isfield(c,'dir'), dr = c.dir; else dr = pwd; end; if isfield(c,'ufilter') uf = c.ufilter; else uf = '.*'; end; [s,ok] = spm_select(c.num,c.filter,c.name,sel,dr,uf); if ok, c.val{1} = cellstr(s); end; files_select_list('addinfiles', sprintf('Input to "%s"', c.name), ... c.val{1}, c.id); catch end; spm_select('clearvfiles'); set(batch_box,'Enable', 'on'); set(opts_box, 'Enable', 'on'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = text_entry(c) % Create a string box and prompt, while hiding the opts box opts_box = findobj(gcf,'tag','opts_box'); pos = get(opts_box,'Position'); set(opts_box,'Visible','off'); fs = get(opts_box,'FontSize'); fa = get(opts_box,'FontAngle'); fw = get(opts_box,'FontWeight'); clf = get(opts_box,'ForegroundColor'); clb = get(opts_box,'BackgroundColor'); n = []; m = []; if isfield(c,'num'), n = c.num; end; if isfield(c,'extras'), m = c.extras; end; newstring = uicontrol(gcf,... 'Style','edit',... 'Units','normalized',... 'Position',[pos(1:3) pos(4)/2],... 'Tag','string_box',... 'HorizontalAlignment','left',... 'FontSize',fs,... 'FontAngle',fa,... 'FontWeight',fw,... 'ForegroundColor',clf,... 'BackgroundColor',clb,... 'Callback',@accept_string); cntxtmnu(newstring); strM=''; switch lower(c.strtype) case 's', TTstr='enter string'; case 'e', TTstr='enter expression - evaluated'; case 'n', TTstr='enter expression - natural number(s)'; if ~isempty(m), strM=sprintf(' (in [1,%d])',m); TTstr=[TTstr,strM]; end case 'w', TTstr='enter expression - whole number(s)'; if ~isempty(m), strM=sprintf(' (in [0,%d])',m); TTstr=[TTstr,strM]; end case 'i', TTstr='enter expression - integer(s)'; case 'r', TTstr='enter expression - real number(s)'; if ~isempty(m), TTstr=[TTstr,sprintf(' in [%g,%g]',min(m),max(m))]; end case 'c', TTstr='enter indicator vector e.g. 0101... or abab...'; if ~isempty(m) && isfinite(m), strM=sprintf(' (%d)',m); end otherwise, TTstr='enter expression'; end if isempty(n), n=NaN; end n=n(:); if length(n)==1, n=[n,1]; end; dn=length(n); if any(isnan(n)) || (prod(n)==1 && dn<=2) || (dn==2 && min(n)==1 && isinf(max(n))) str = ''; lstr = ''; elseif dn==2 && min(n)==1 str = sprintf('[%d]',max(n)); lstr = [str,'-vector: ']; elseif dn==2 && sum(isinf(n))==1 str = sprintf('[%d]',min(n)); lstr = [str,'-vector(s): ']; else str=''; for i = 1:dn, if isfinite(n(i)), str = sprintf('%s,%d',str,n(i)); else str = sprintf('%s,*',str); end end str = ['[',str(2:end),']']; lstr = [str,'-matrix: ']; end strN = sprintf('%s',lstr); col = get(gcf,'Color'); uicontrol(gcf,'Style','text',... 'Units','normalized',... 'BackgroundColor',col,... 'String',[strN,strM,TTstr],... 'Tag','string_prompt',... 'HorizontalAlignment','Left',... 'FontSize',fs,... 'FontAngle',fa,... 'FontWeight',fw,... 'Position',[pos(1:3)+[0 pos(4)/2 0] pos(4)/2]); if isfield(c,'val') && ~isempty(c.val) val = c.val{1}; if ischar(val) tmp = val'; tmp = tmp(:)'; set(newstring,'String',tmp); elseif isnumeric(val) if ndims(val)>2, set(newstring,'String',['reshape([', num2str(val(:)'), '],[' num2str(size(val)) '])']); else if size(val,1)==1, set(newstring,'String',num2str(val(:)')); elseif size(val,2)==1, set(newstring,'String',['[' num2str(val(:)') ']''']); else str = ''; for i=1:size(val,1), str = [str ' ' num2str(val(i,:)) ';']; end; set(newstring,'String',str); end; end; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function accept_string(varargin) % Accept a typed in string? run_in_current_node(@stringval,true,get(varargin{1},'String')); update_ui; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function remove_string_box % Delete the string box and prompt, making the opts box % visible again delete(findobj(0,'Tag','string_box')); delete(findobj(0,'Tag','string_prompt')); set(opts_box,'Visible','on'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function show_value(c) % Update the value box valtxt = {'<UNDEFINED>'}; % col = [1 0 0]; switch c.type case {'menu'} if isfield(c,'val') && ~isempty(c.val) if isfield(c,'labels') && isfield(c,'values') val = c.val{1}; for i=1:length(c.values) if same(c.values{i},val) valtxt = c.labels{i}; % col = [0 0 0]; break; end; end; end; end; case {'const','entry'} if isfield(c,'val') && ~isempty(c.val) val = c.val{1}; if isempty(val) valtxt = '<Empty>'; else if isnumeric(val) sz = size(val); if length(sz)>2 valtxt = sprintf('%dx',sz); valtxt = [valtxt(1:(end-1)) ' Numeric Array']; else valtxt = cell(size(val,1),1); for i=1:size(val,1) valtxt{i} = sprintf('%14.8g ',val(i,:)); end; end; elseif(ischar(val)) valtxt = val; else valtxt = 'Can not display'; end; end; % col = [0 0 0]; end; case {'files'} if isfield(c,'val') && ~isempty(c.val) if isempty(c.val{1}) || isempty(c.val{1}{1}) valtxt = '<None>'; else valtxt = c.val{1}; end; % col = [0 0 0]; end; case {'choice'} if isfield(c,'val') && length(c.val)==1 valtxt = {'A choice, where',['"' c.val{1}.name '"'], 'is selected.'}; % col = [0.5 0.5 0.5]; else valtxt = {'A choice, with', 'nothing selected.'}; % col = [0.5 0.5 0.5]; end; case {'repeat'} ln = length(c.val); s = 's'; if ln==1, s = ''; end; valtxt = ['A series containing ' num2str(length(c.val)) ' item' s '.']; % col = [0.5 0.5 0.5]; case {'branch'} ln = length(c.val); s = 's'; if ln==1, s = ''; end; valtxt = {['A branch holding ' num2str(length(c.val)) ' item' s '.']}; if isfield(c,'prog'), valtxt = {valtxt{:}, '', ' User specified values',... ' from this branch will be',... ' collected and passed to',... ' an executable function',... ' when the job is run.'}; end; % col = [0.5 0.5 0.5]; otherwise valtxt = 'What on earth is this???'; end; val_box = findobj(0,'tag','val_box'); if ~isempty(val_box) % set(val_box,'String',valtxt,'ForegroundColor',col); set(val_box,'String',valtxt); workaround(val_box); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = remove(c,varargin) % Remove node c if strcmp(questdlg(['Remove "' c.name '"?'],'Confirm','Yes','No','Yes'),'Yes'), c = {}; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = replicate(c,varargin) % Replicate node c c = {c,uniq_id(c)}; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = choose(c,val) % Specify the value of c to be val c.val{1} = uniq_id(val); c.expanded = true; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = menuval(c,val) % Specify the value of c to be val c.val{1} = val; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = stringval(c,val) % Accept (or not) a typed in string msg = 'SUCCESS: Values accepted'; switch c.strtype case {'s'} c.val{1} = val; show_value(c); remove_string_box; case {'s+'} msg = 'FAILURE: Cant do s+ yet'; beep; remove_string_box; otherwise n = Inf; if isfield(c,'num') n = c.num; end; if isfield(c,'extras') [val,msg] = spm_eeval(val,c.strtype,n,c.extras); else [val,msg] = spm_eeval(val,c.strtype,n); end; if ischar(val) beep; msg = ['FAILURE: ' msg]; else c.val{1} = val; show_value(c); remove_string_box; msg = ['SUCCESS: ' msg]; end; end; show_msg(msg); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = series(c,new) % Add a new repeat c.expanded = true; new.removable = true; if isfield(c,'val') c.val = {c.val{:},uniq_id(new)}; else c.val = {uniq_id(new)}; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function setdef(strin,val) global defaults if isempty(defaults), spm_defaults; end; if ischar(val) && strcmp(val,'<UNDEFINED>'), return; end; o = find(strin=='.'); df = cell(1,length(o)+1); prev = 1; for i=1:length(o), df{i} = strin(prev:(o(i)-1)); prev = o(i)+1; end; df{end} = strin(prev:end); defaults = setdef_sub(defaults,df,val); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function d = setdef_sub(d,df,val) if isempty(df), d = val; else if ~isfield(d,df{1}),d.(df{1}) = []; end; d.(df{1}) = setdef_sub(d.(df{1}),df(2:end),val); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function val = getdef(strin) % Get value of one of the SPM defaults global defaults val = getdef_sub(defaults,strin); if ischar(val) && strcmp(val,'<UNDEFINED>') val = {}; else val = {val}; end; %fprintf('%s\n',strin); %disp(val) %disp('----'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = getdef_sub(defs,field) % Satellite function for getdef o = find(field=='.'); if isempty(o) if isfield(defs,field) c = defs.(field); else c = '<UNDEFINED>'; end; return; end; if isfield(defs,field(1:(o-1))) c = getdef_sub(defs.(field(1:(o-1))),field((o+1):end)); else c = '<UNDEFINED>'; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function t = same(a,b) % Are two data structures identical? % Innocent until proven guilty t = true; % Check the dimensions if isempty(a) && isempty(b) t = true; return; end; sa = size(a); sb = size(b); if length(sa) ~= length(sb) t = false; return; end; if ~all(sa==sb) t = false; return; end; % Check the classes ca = class(a); if ~strcmp(ca,class(b)), t = false; return; end; % Recurse through data structure switch ca case {'double','single','sparse','char','int8','uint8',... 'int16','uint16','int32','uint32','logical'} msk = ((a==b) | (isnan(a)&isnan(b))); if ~all(msk(:)), t = false; return; end; case {'struct'} fa = fieldnames(a); fb = fieldnames(b); if length(fa) ~= length(fb), t = false; return; end; for i=1:length(fa) if ~strcmp(fa{i},fb{i}), t = false; return; end; for j=1:length(a) if ~same(a(j).(fa{i}),b(j).(fb{i})) t = false; return; end; end; end; case {'cell'} for j=1:length(a(:)) if ~same(a{j},b{j}), t = false; return; end; end; case {'function_handle'} if ~strcmp(func2str(a),func2str(b)) t = false; return; end; otherwise warning(['Unknown class "' ca '"']); t = false; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function t = batch_box t = findobj(0,'tag','batch_box'); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function t = opts_box t = findobj(0,'tag','opts_box'); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function save_job(varargin) % Save a batch job % if job has been loaded from somewhere, cd into this directory for file selection ljobs = get(findobj(0,'tag','load'),'Userdata'); cll = {'*.mat','Matlab .mat file';'*.m','Matlab script file';'*.xml','XML file'}; if ~isempty(ljobs) && ischar(ljobs) [spwd unused defext] = fileparts(ljobs(1,:)); ccll = false(1,size(cll,1)); for k = 1:size(cll,1), ccll(k) = ~isempty(strfind(cll{k,1},defext)); end; cll = [cll(ccll,:); cll(~ccll,:)]; else spwd = pwd; end; opwd = pwd; cd(spwd); [filename, pathname, FilterIndex] = uiputfile(cll,'Save job as'); cd(opwd); if ischar(filename) spm('Pointer','Watch'); c = get(batch_box,'UserData'); [unused,jobs,unused,jobhelps] = harvest(c); %eval([tag '=val;']); [unused,unused,ext] = fileparts(filename); if isempty(ext) ext = cll{FilterIndex}(2:end); filename = [filename ext]; end switch ext case '.xml', savexml(fullfile(pathname,filename),'jobs','jobhelps'); case '.mat', if spm_matlab_version_chk('7') >= 0, save(fullfile(pathname,filename),'-V6','jobs','jobhelps'); else save(fullfile(pathname,filename),'jobs','jobhelps'); end; case '.m', treelist('jobs','jobhelps',struct('exps',1, 'dval',2, 'fname', ... fullfile(pathname,filename))); otherwise questdlg(['Unknown extension (' ext ')'],'Nothing saved','OK','OK'); end; end; spm('Pointer'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function load_job(varargin) % Load a set of batch jobs and possibly merge it ljobs = get(findobj(0,'tag','load'),'Userdata'); if ~isempty(ljobs) && ischar(ljobs) spwd = fileparts(ljobs(1,:)); else spwd = pwd; end; [jobfiles sts] = spm_select([1 Inf], 'batch', 'Load job file(s)',[],spwd); if sts spm('Pointer','Watch'); initialise(jobfiles); set(gcbo,'Userdata',jobfiles); spm('Pointer'); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function run_struct(varargin,gui) % Get data structure from handle, and run it % If an error occured, then return to user interface if nargin ==1, gui = 1; end c = get(batch_box,'UserData'); [unused,job] = harvest(c); try run_struct1(c,gui); catch l = lasterror; fprintf('\nError running job: %s\n', l.message); if isfield(l,'stack'), % Does not always exist for k = 1:numel(l.stack), % Don't blame jobman if some other code crashes if strcmp(l.stack(k).name,'run_struct1'), break; end; try, fp = fopen(l.stack(k).file,'r'); str = fread(fp,Inf,'*uchar'); fclose(fp); str = char(str(:)'); re = regexp(str,'\$Id: \w+\.\w+ ([0-9]+) [0-9][0-9][0-9][0-9].*\$','tokens'); if numel(re)>0 && numel(re{1})>0, id = [' (v', re{1}{1}, ')']; else id = ' (???)'; end catch, id = ''; end fprintf('In file "%s"%s, function "%s" at line %d.\n', ... l.stack(k).file, id, l.stack(k).name, l.stack(k).line); end end setup_ui(job); %if spm_matlab_version_chk('7') >= 0 % rethrow(l); %else % disp(lasterr); %end end; disp('--------------------------'); disp('Done.'); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function run_struct1(c,gui) % Run a batch job from a data structure if nargin ==1, gui = 1; end if isfield(c,'prog') prog = c.prog; [unused,val] = harvest(c); disp('--------------------------'); disp(['Running "' c.name '"']); if gui [Finter,unused,CmdLine] = spm('FnUIsetup',c.name); spm('Pointer','Watch'); spm('FigName',[c.name ': running'],Finter,CmdLine); end if 0 try feval(prog,val); if gui spm('FigName',[c.name ': done'],Finter,CmdLine); end catch disp(['An error occurred when running "' c.name '"']); disp( '--------------------------------'); disp(lasterr); disp( '--------------------------------'); if gui spm('FigName',[c.name ': failed'],Finter,CmdLine); end errordlg({['An error occurred when running "' c.name '"'],lasterr},'SPM Jobs'); end; if gui, spm('Pointer'); end else feval(prog,val); if gui spm('FigName',[c.name ': done'],Finter,CmdLine); spm('Pointer'); end end; else if isfield(c,'val') for i=1:length(c.val) run_struct1(c.val{i},gui); end; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function harvest_def(c) switch c.type, case{'const','menu','files','entry'}, if isfield(c,'def') && numel(c.val)==1, setdef(c.def,c.val{1}); end; otherwise for i=1:length(c.val), harvest_def(c.val{i}); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [tag,val,typ,jobhelp] = harvest(c) % Take a data structure, and extract what is needed to save it % as a batch job tag = 'unknown'; val = []; typ = c.type; if isfield(c,'jobhelp') jobhelp.jobhelp = c.jobhelp; else jobhelp = []; end; switch(typ) case {'const','menu','files','entry'} tag = gettag(c); if ~isempty(c.val) val = c.val{1}; else val = '<UNDEFINED>'; end; if isfield(c,'jobhelp') jobhelp = c.jobhelp; end; case {'branch'} tag = gettag(c); if isfield(c,'val') val = []; for i=1:length(c.val) [tag1,val1,unused,jobhelp1] = harvest(c.val{i}); val.(tag1) = val1; jobhelp.(tag1) = jobhelp1; end; end; case {'repeat'} tag = gettag(c); if length(c.values)==1 && strcmp(c.values{1}.type,'branch'), cargs = {}; for i=1:numel(c.values{1}.val), cargs = {cargs{:},gettag(c.values{1}.val{i}),{}}; end; val = struct(cargs{:}); jobhelp = struct(cargs{:}); if isfield(c,'val') for i=1:length(c.val), [tag1,val1,typ1,jobhelp1] = harvest(c.val{i}); val(i) = val1; jobhelp(i) = jobhelp1; end; end; else val = {}; jobhelp = {}; if isfield(c,'val') for i=1:length(c.val), [tag1,val1,typ1,jobhelp1] = harvest(c.val{i}); if length(c.values)>1, if iscell(val1) val1 = struct(tag1,{val1}); else val1 = struct(tag1,val1); end; if iscell(jobhelp1) jobhelp1 = struct(tag1,{jobhelp1}); else jobhelp1 = struct(tag1,jobhelp1); end; end; val = {val{:}, val1}; jobhelp = {jobhelp{:}, jobhelp1}; end; end; end; case {'choice'} if isfield(c,'tag'), tag = gettag(c); end; [tag1,val1,unused,jobhelp1] = harvest(c.val{1}); if iscell(val1) val = struct(tag1,{val1}); else val = struct(tag1,val1); end; if iscell(jobhelp1) jobhelp = struct(tag1,{jobhelp1}); else jobhelp = struct(tag1,jobhelp1); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function tag = gettag(c) % Get a tag field - possibly from one of the kids if (strcmp(c.type,'repeat') || strcmp(c.type,'choice')) && numel(c.values)>0 tag = gettag(c.values{1}); for i=2:length(c.values) if ~strcmp(tag,gettag(c.values{i})) tag = c.tag; return; end; end; else tag = c.tag; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c0 = cntxtmnu(ob) c0 = uicontextmenu('Parent',get(ob,'Parent')); set(ob,'uicontextmenu',c0); c1 = uimenu('Label','Font', 'Parent',c0); uimenu('Label','Plain', 'Parent',c1,'Callback','set(gco,''FontWeight'',''normal'',''FontAngle'',''normal'');'); uimenu('Label','Bold', 'Parent',c1,'Callback','set(gco,''FontWeight'',''bold'', ''FontAngle'',''normal'');'); uimenu('Label','Italic', 'Parent',c1,'Callback','set(gco,''FontWeight'',''normal'',''FontAngle'',''italic'');'); uimenu('Label','Bold-Italic','Parent',c1,'Callback','set(gco,''FontWeight'',''bold'', ''FontAngle'',''italic'');'); c1 = uimenu('Label','Fontsize','Parent',c0); fs = [8 9 10 12 14 16 18]; % [20 24 28 32 36 44 48 54 60 66 72 80 88 96]; for i=fs, uimenu('Label',sprintf('%-3d',i),'Parent',c1,'Callback',@fszoom,'UserData',i); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function workaround(t) set(t,'Value',[], 'Enable', 'on', 'Max',2, 'Min',0,'ListBoxTop',1); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function addvfiles(id,c,c0) if (nargin<2)||isempty(c), c = get(batch_box,'UserData'); end; if nargin<3 c0 = []; end; files_select_list('clearvfiles'); vf =addvfiles1(c,id,{},c0); spm_select('clearvfiles'); spm_select('addvfiles',vf); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [vf,sts]=addvfiles1(c,id,vf,c0) sts = 0; if ~isstruct(c) || ~isfield(c,'type'), return; end; if isfield(c,'vfiles'), if ~find_id(c,id), [c,unused,ok] = get_strings1(c,0); if ok, [unused,job] = harvest(c); vf1 = feval(c.vfiles,job); if ~isempty(c0) files = filter_files(c0, vf1); else files = vf1; end; if ~isempty(files) files_select_list('addvfiles', sprintf('Output from "%s"', ... c.name), ... files, c.id); end; vf = {vf{:}, vf1{:}}; end; else sts = 1; end; return; end; switch c.type, case {'repeat','choice','branch'}, for i=1:length(c.val), [vf,sts]=addvfiles1(c.val{i},id,vf,c0); if sts, return; end; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function addinfiles(c0,c) id = c0.id; if nargin<2, c = get(batch_box,'UserData'); end; files_select_list('clearinfiles'); addinfiles1(c,id,'',c0); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function sts=addinfiles1(c,id,progname,c0) sts = 0; if ~isstruct(c) || ~isfield(c,'type'), return; end; if find_id(c,id), sts = 1; end; switch c.type, case 'files' if ~isempty(c.val) && ~isempty(c.val{1}) files = filter_files(c0,c.val{1}); if ~isempty(files) files_select_list('addinfiles', ... sprintf('Input to "%s->%s"', ... progname, c.name), ... files, c.id); end; end; case {'repeat','choice','branch'}, if isfield(c,'prog') progname = c.name; oldin = files_select_list('getinnum'); end; for i=1:length(c.val), sts=addinfiles1(c.val{i},id,progname,c0); if sts, return; end; end; if isfield(c,'prog') newin = files_select_list('getinnum'); if (newin-oldin > 1) files_select_list('allinfiles', ... sprintf('All inputs to %s',progname),... oldin+1, newin); end; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function ffiles = filter_files(c,files) if strcmp(c.filter, 'image')||strcmp(c.filter,'dir') filter = ['ext' c.filter]; else filter = c.filter; end; if isfield(c,'ufilter') uf = c.ufilter; if uf(1) == '^' % This will not work with full pathnames uf=uf(2:end); end; else uf = '.*'; end; ffiles = spm_select('filter', files, ... filter, uf); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function varargout = files_select_list(c,varargin) persistent vfstr; persistent vfdat; persistent vffiles; persistent vfid; persistent instr; persistent indat; persistent infiles; persistent inid; if isstruct(c) switch lower(varargin{1}) case 'getvf' c.val{1} = vffiles{varargin{2}}; case 'getin' c.val{1} = infiles{varargin{2}}; end; varargout{1} = c; return; end; if ~iscell(vfstr) && ~strcmp(lower(c),'init') files_select_list('init'); end; switch lower(c) case 'init' vfstr = {}; vfdat = {}; vffiles = {}; vfid = []; instr = {}; indat = {}; infiles = {}; inid = []; case 'clearvfiles' vfstr = {}; vfdat = {}; vffiles = {}; vfid = []; case 'clearinfiles' instr = {}; indat = {}; infiles = {}; inid = []; case 'addvfiles' nvfind = numel(vfstr)+1; vfid(nvfind) = varargin{3}; vfstr{nvfind} = varargin{1}; vfdat{nvfind} = struct('fun',@files_select_list,'args',{{'getvf', nvfind}}, ... 'redraw',1); vffiles{nvfind} = varargin{2}(:); case 'addinfiles' ninind = numel(instr)+1; inid(ninind) = varargin{3}; instr{ninind} = varargin{1}; indat{ninind} = struct('fun',@files_select_list,'args',{{'getin', ninind}}, ... 'redraw',1); infiles{ninind} = varargin{2}(:); case 'allinfiles' ninind = numel(instr)+1; inid(ninind) = -1; instr{ninind} = varargin{1}; indat{ninind} = struct('fun',@files_select_list,'args',{{'getin', ninind}}, ... 'redraw',1); infiles{ninind} = cat(1,infiles{varargin{2}:varargin{3}}); case 'getinnum' varargout{1} = numel(instr); case 'listall' varargout{1} = {vfstr{:} instr{:}}; varargout{2} = {vfdat{:} indat{:}}; end return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function ok = find_id(c,id) ok = 0; if ~isstruct(c) || ~isfield(c,'type'), return; end; if c.id==id, ok = 1; return; end; if isfield(c,'val'), for i=1:length(c.val), ok = find_id(c.val{i},id); if ok, return; end; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = uniq_id(c) if ~isstruct(c) || ~isfield(c,'type'), return; end; c.id = rand(1); if isfield(c,'val'), for i=1:length(c.val), c.val{i} = uniq_id(c.val{i}); end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function show_msg(txt) lb = findobj('tag','msg_box'); if isempty(txt), set(lb,'String',{}); else msg = get(lb,'String'); if iscell(txt), msg = {msg{:} txt{:}}; else msg = {msg{:} txt}; end; set(lb,'String',msg); end; drawnow; %------------------------------------------------------------------------ %------------------------------------------------------------------------ %function beep %fprintf('%c',7); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function pulldown % Create a pulldown for individual jobs c = initialise_struct; fg = spm_figure('findwin','Graphics'); if isempty(fg), return; end; set(0,'ShowHiddenHandles','on'); delete(findobj(fg,'tag','jobs')); set(0,'ShowHiddenHandles','off'); f0 = uimenu(fg,'Label','TASKS','HandleVisibility','off','tag','jobs'); pulldown1(f0,c,c.tag); uimenu(f0,'Label','Batch','CallBack',@interactive,'Separator','on'); uimenu(f0,'Label','Defaults','CallBack',@defaults_edit,'Separator','off'); f1 = uimenu(f0,'Label','Sequential'); pulldown2(f1,c,c.tag); if 0, % Currently unused f1 = uimenu(f0,'Label','Modality'); modalities = {'FMRI','PET','EEG'}; for i=1:length(modalities) tmp = modalities{i}; if strcmp(tmp,getdef('modality')), tmp = ['*' tmp]; else tmp = [' ' tmp]; end; uimenu(f1,'Label',tmp,'CallBack',@chmod); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function pulldown1(f0,c0,tag0) if ~isfield(c0,'values'), return; end; for i=1:length(c0.values), c1 = c0.values{i}; if isstruct(c1) && ~isfield(c1,'hidden'), tag1 = tag0; if isfield(c1,'tag'), tag1 = [tag1 '.' c1.tag]; end; if isfield(c1,'prog'), uimenu(f0,'Label',c1.name,'CallBack',@interactive,'UserData',{'',tag1}); else f1 = uimenu(f0,'Label',c1.name); pulldown1(f1,c1,tag1); end; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function pulldown2(f0,c0,tag0) if ~isfield(c0,'values'), return; end; for i=1:length(c0.values), c1 = c0.values{i}; if isstruct(c1) && ~isfield(c1,'hidden'), tag1 = tag0; if isfield(c1,'tag'), tag1 = [tag1 '.' c1.tag]; end; if isfield(c1,'prog'), if findcheck(c1), uimenu(f0,'Label',c1.name,'Enable','off'); else uimenu(f0,'Label',c1.name,'CallBack',@run_serial,'UserData',{'',tag1}); end; else f1 = uimenu(f0,'Label',c1.name); pulldown2(f1,c1,tag1); end; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function hascheck = findcheck(c) hascheck = false; if ~isstruct(c) || ~isfield(c,'type'), return; end; if isfield(c,'check'), hascheck = true; return; end; if isfield(c,'values'), for i=1:numel(c.values), hascheck = findcheck(c.values{i}); if hascheck, return; end; end; end; if isfield(c,'val'), for i=1:numel(c.val), hascheck = findcheck(c.val{i}); if hascheck, return; end; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function chmod(mod,varargin) global defaults if isempty(defaults), spm_defaults; end; if ischar(mod), %if strcmpi(defaults.modality,mod), % spm('ChMod',mod); %end; defaults.modality = mod; else tmp = get(mod,'Label'); defaults.modality = tmp(2:end); end; pulldown; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function fszoom(varargin) fs = sscanf(get(varargin{1},'Label'),'%d'); set(gco,'FontSize',fs); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function run_serial(varargin) ud = get(varargin{1},'UserData'); if iscell(ud) serial(ud{:}); else serial; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function serial(job,node) if nargin<2, node = 'jobs'; end; fg = spm_figure('FindWin','Interactive'); if isempty(fg), fg = spm('CreateIntWin'); end; delete(findobj(fg,'Parent',fg)); t=uicontrol(fg,... 'Style','listbox',... 'Units','normalized',... 'Position',[0.02 0.02 0.96 0.62],... 'Tag','help_box2',... 'FontName','fixedwidth',... 'FontSize',12,... 'BackgroundColor',[1 1 1]); set(t,'Value',[], 'Enable', 'inactive', 'Max',2, 'Min',0); workaround(t); cntxtmnu(t); spm('Pointer'); drawnow; if nargin>0, c = initialise_struct(job); else c = initialise_struct; end; c = start_node(c,node); c = start_node(c,@run_ui,{}); spm_input('!DeleteInputObj'); delete(findobj(fg,'Parent',fg)); [unused,jobs] = harvest(c); %savexml('job_last.xml','jobs'); run_job(jobs); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = run_ui(c,varargin) nnod=1; while(1), nod = nnod; [ci,unused,hlp] = get_node(c,nod); if isempty(ci), break; end; help_box = findobj(0,'tag','help_box2'); if ~isempty(help_box), set(help_box,'String',' '); workaround(help_box); ext = get(help_box,'Extent'); pos = get(help_box,'position'); pw = floor(pos(3)/ext(3)*21-4); set(help_box,'String',spm_justify(pw,hlp)); workaround(help_box); if isfield(c,'prog'), try set(help_box,'HandleVisibility','off'); [Finter,unused,CmdLine] = spm('FnUIsetup',c.name); spm('FigName',[c.name ': setup'],Finter,CmdLine); catch end; set(help_box,'HandleVisibility','on'); end; end; pos = 1; switch ci.type, case {'const','files','menu','entry'} nnod = nod + 1; vl = {'<UNDEFINED>'}; if isfield(ci,'def'), vl = getdef(ci.def); end; if numel(vl)~=0 && (~ischar(vl{1}) || ~strcmp(vl{1},'<UNDEFINED>')), getit = 0; if ~isfield(ci,'val') || ~iscell(ci.val) || isempty(ci.val), ci.val = vl; end; else getit = 1; end; switch ci.type, case {'const'} case {'files'} num = ci.num; if getit, if ~isempty(ci.val), sel = ci.val{1}; else sel = ''; end; addvfiles(ci.id,c); if isfield(ci,'dir'), dr = ci.dir; else dr = pwd; end; if isfield(ci,'ufilter') uf = ci.ufilter; else uf = '.*'; end; [ci.val{1},ok] = spm_select(num,ci.filter,ci.name,sel,dr,uf); if ~ok, error('File Selector was deleted.'); end; spm_select('clearvfiles'); ci.val{1} = cellstr(ci.val{1}); end; case {'menu'} dv = []; if getit, if isfield(ci,'val') && ~isempty(ci.val), for i=1:length(ci.values) if same(ci.values{i},ci.val{1}) dv = i; end; end; end; lab = ci.labels{1}; for i=2:length(ci.values), lab = [lab '|' ci.labels{i}]; end; if isempty(dv), ind = spm_input(ci.name,pos,'m',lab,1:length(ci.values)); else ind = spm_input(ci.name,pos,'m',lab,1:length(ci.values),dv); end; ci.val = {ci.values{ind}}; end; case {'entry'} n1 = Inf; if isfield(ci,'num'), n1 = ci.num; end; if getit, val = ''; if isfield(ci,'val') && ~isempty(ci.val) && ~strcmp(ci.val{1},'<UNDEFINED>'), val = ci.val{1}; end; if isfield(ci,'extras') val = spm_input(ci.name,pos,ci.strtype,val,n1,ci.extras); else val = spm_input(ci.name,pos,ci.strtype,val,n1); end; ci.val{1} = val; end; end; case {'repeat'}, lab = 'Done'; for i=1:length(ci.values) lab = [lab '|New "' ci.values{i}.name '"']; end; tmp = spm_input(ci.name,pos,'m',lab,0:length(ci.values)); if tmp, ci.val = {ci.val{:}, uniq_id(ci.values{tmp})}; nnod = nod; else nnod = nod + 1; end; case {'choice'} nnod = nod + 1; lab = ci.values{1}.name; for i=2:length(ci.values) lab = [lab '|' ci.values{i}.name]; end; tmp = spm_input(ci.name,pos,'m',lab,1:length(ci.values)); ci.val = {uniq_id(ci.values{tmp})}; otherwise error('This should not happen.'); end; c = set_node(c,nod,ci); end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [ci,n,hlp] = get_node(c,n) ci = []; hlp = ''; switch c.type, case {'const','files','menu','entry'} n = n-1; if n==0, ci = c; hlp = {['* ' upper(c.name)],c.help{:},'',''}; return; end; case 'choice' n = n-1; if n==0, ci = c; hlp = {['* ' upper(c.name)],c.help{:},'',''}; return; end; [ci,n,hlp] = get_node(c.val{1},n); if ~isempty(ci), hlp = {hlp{:},repmat('=',1,20),'',['* ' upper(c.name)],c.help{:},'',''}; return; end; case 'branch', for i=1:numel(c.val), [ci,n,hlp] = get_node(c.val{i},n); if ~isempty(ci), hlp = {hlp{:},repmat('=',1,20),'',['* ' upper(c.name)],c.help{:},'',''}; return; end; end; case 'repeat', for i=1:numel(c.val), [ci,n,hlp] = get_node(c.val{i},n); if ~isempty(ci), hlp = {hlp{:},repmat('=',1,20),'',['* ' upper(c.name)],c.help{:},'',''}; return; end; end; n = n-1; if n==0, ci = c; hlp = {['* ' upper(c.name)],c.help{:},'',''}; return; end; otherwise error('This should not happen'); end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,n] = set_node(c,n,ci) switch c.type, case {'const','files','menu','entry'} n = n-1; if n==0, c = ci; return; end; case 'choice' n = n-1; if n==0, c = ci; return; end; [c.val{1},n] = set_node(c.val{1},n,ci); if n<0,return; end; case 'branch', for i=1:numel(c.val), [c.val{i},n] = set_node(c.val{i},n,ci); if n<0,return; end; end; case 'repeat', for i=1:numel(c.val), [c.val{i},n] = set_node(c.val{i},n,ci); if n<0,return; end; end; n = n-1; if n==0, c = ci; return; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = initialise_struct(job) % load the config file, possibly adding a job % to it, and generally tidy it up. The batch box % is updated to contain the current structure. persistent c0 if isempty(c0), c0 = spm_config; c0 = tidy_struct(c0); end; c = insert_defs(c0); if nargin==1 && ischar(job) && strcmp(job,'defaults'), c = defsub(c,{}); c.name = 'SPM Defaults'; else c = hide_null_jobs(c); if nargin>0 && ~isempty(job), if ischar(job)||iscellstr(job) % only call fromfile if job(s) are identified by strings [job,jobhelp] = fromfile(job); else % job structure given, we therefore don't have jobhelp jobhelp = []; end; c = job_to_struct(c,job,jobhelp,'jobs'); c = uniq_id(c); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,defused] = defsub(c,defused) if nargin<2, defused = {}; end; if isfield(c,'prog'), c = rmfield(c,'prog'); end; switch c.type, case {'const'} c = []; case {'menu','entry','files'} if ~isfield(c,'def') || any(strcmp(c.def,defused)), c = []; else defused = {defused{:},c.def}; end; case {'branch'} msk = true(1,length(c.val)); for i=1:length(c.val), [c.val{i},defused] = defsub(c.val{i},defused); msk(i) = ~isempty(c.val{i}); end; c.val = c.val(msk); if isempty(c.val), c = []; end; case {'choice','repeat'} c.type = 'branch'; c.val = c.values; c = rmfield(c,'values'); [c,defused] = defsub(c,defused); end; if isfield(c,'vfiles'), c = rmfield(c,'vfiles'); end; if isfield(c,'check'), c = rmfield(c,'check'); end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = insert_defs(c) % Recursively descend through the tree structure, % and assigning default values. if ~isstruct(c) || ~isfield(c,'type'), return; end; switch c.type case {'menu','entry','files'} if isfield(c,'def') c.val = getdef(c.def); if strcmp(c.type,'files') && ~isempty(c.val) if ~isempty(c.val{1}) c.val = {cellstr(c.val{1})}; else c.val = {{}}; end; end; end; case {'repeat','choice'}, if isfield(c,'values') for i=1:numel(c.values) c.values{i} = insert_defs(c.values{i}); end; end; end; if isfield(c,'val') for i=1:numel(c.val) c.val{i} = insert_defs(c.val{i}); end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = tidy_struct(c) % Recursively descend through the tree structure, cleaning up % fields that may be missing and adding an 'expanded' field % where necessary. if ~isstruct(c) || ~isfield(c,'name') || ~isfield(c,'type') return; end; c.id = rand(1); if ~isfield(c,'help'), c.help = {}; end; if ischar(c.help), c.help = {c.help}; end; switch c.type case {'const'} if ~isfield(c,'tag') disp(c); warning(['No tag field for "' c.name '"']); c.tag = 'unknown'; end; if ~isfield(c,'val') disp(c); warning(['No val field for "' c.name '"']); c.val = {'<UNDEFINED>'}; end; case {'menu'} if ~isfield(c,'tag') disp(c); warning(['No tag field for "' c.name '"']); c.tag = 'unknown'; end; if ~isfield(c,'labels') || ~isfield(c,'values') disp(c); warning(['No labels and values field for "' c.name '"']); c.labels = {}; c.values = {}; end; if length(c.labels) ~= length(c.values) disp(c); warning(['Labels and values fields incompatible for "' c.name '"']); c.labels = {}; c.values = {}; end; if ~isfield(c,'help'), c.help = {'Option selection by menu'}; end; case {'entry'} if ~isfield(c,'tag') disp(c); warning(['No tag field for "' c.name '"']); c.tag = 'unknown'; end; if ~isfield(c,'strtype') disp(c); warning(['No strtype field for "' c.name '"']); c.strtype = 'e'; end; if ~isfield(c,'num') disp(c); warning(['No num field for "' c.name '"']); c.num = [1 1]; end; if length(c.num)~=2 disp(c); warning(['Num field for "' c.name '" is wrong length']); c.num = [Inf 1]; end; if ~isfield(c,'help'), c.help = {'Option selection by text entry'}; end; case {'files'} if ~isfield(c,'tag') disp(c); warning(['No tag field for "' c.name '"']); c.tag = 'unknown'; end; if ~isfield(c,'filter') disp(c); warning(['No filter field for "' c.name '"']); c.filter = '*'; end; if ~isfield(c,'num') disp(c); warning(['No num field for "' c.name '"']); c.num = Inf; end; if length(c.num)~=1 && length(c.num)~=2 disp(c); warning(['Num field for "' c.name '" is wrong length']); c.num = Inf; end; if isfield(c,'val') && iscell(c.val) && numel(c.val)>=1, if ischar(c.val{1}) c.val{1} = cellstr(c.val{1}); end; end; if ~isfield(c,'help'), c.help = {'File selection'}; end; case {'branch'} if ~isfield(c,'tag') disp(c); warning(['No tag field for "' c.name '"']); c.tag = 'unknown'; end; if ~isfield(c,'val') disp(c); warning(['No val field for "' c.name '"']); c.val = {}; end; c.expanded = false; if ~isfield(c,'help'), c.help = {'Branch structure'}; end; case {'choice'} if ~isfield(c,'tag') disp(c); warning(['No tag field for "' c.name '"']); c.tag = 'unknown'; end; if ~isfield(c,'values') || ~iscell(c.values) disp(c); error(['Bad values for "' c.name '"']); end; for i=1:length(c.values) c.values{i} = tidy_struct(c.values{i}); end; if ~isfield(c,'val') || ~iscell(c.val) || length(c.val) ~= 1 c.val = {c.values{1}}; end; c.expanded = true; if ~isfield(c,'help'), c.help = {'Choice structure'}; end; case {'repeat'} if ~isfield(c,'values') || ~iscell(c.values) disp(c); error(['Bad values for "' c.name '"']); end; for i=1:length(c.values) c.values{i} = tidy_struct(c.values{i}); end; if length(c.values)>1 && ~isfield(c,'tag') disp(c); warning(['No tag field for "' c.name '"']); c.tag = 'unknown'; end; if length(c.values)==1 && isfield(c,'tag') % disp(c); warning(['"' c.name '" has unused tag']); c = rmfield(c,'tag'); end; c.expanded = true; if ~isfield(c,'help'), c.help = {'Repeated structure'}; end; if isfield(c,'num') && numel(c.num)==1, if isfinite(c.num), c.num = [c.num c.num]; else c.num = [0 c.num]; end; end; end; if ~isfield(c,'val'), c.val = {}; end; %switch c.type %case {'menu','entry','files'} % %if isempty(c.val) % if isfield(c,'def') % c.val = getdef(c.def); % if strcmp(c.type,'files') && ~isempty(c.val) % c.val = {cellstr(c.val{1})}; % end; % end; % %end; %end; if isfield(c,'val') for i=1:length(c.val) c.val{i} = tidy_struct(c.val{i}); end; end; if isfield(c,'values') && strcmp(c.type,'repeat') for i=1:length(c.values) c.values{i} = tidy_struct(c.values{i}); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [newjobs,newjobhelps] = fromfile(job) if ischar(job) filenames = cellstr(job); else filenames = job; end; newjobs = {}; newjobhelps = {}; for cf = 1:numel(filenames) jobhelps = {[]}; [p,nam,ext] = fileparts(filenames{cf}); switch ext case '.xml', spm('Pointer','Watch'); try loadxml(filenames{cf},'jobs'); catch questdlg('LoadXML failed',filenames{cf},'OK','OK'); return; end; try loadxml(filenames{cf},'jobhelps'); end; spm('Pointer'); case '.mat' try S=load(filenames{cf}); jobs = S.jobs; if isfield(S,'jobhelps') jobhelps=S.jobhelps; end; catch questdlg('Load failed',filenames{cf},'OK','OK'); end; case '.m' opwd = pwd; try if ~isempty(p) cd(p); end clear(nam); eval(nam); catch questdlg('Load failed',filenames{cf},'OK','OK'); end; cd(opwd); otherwise questdlg(['Job ' nam ': Unknown extension (' ext ')'],... 'This job not loaded','OK','OK'); end; if exist('jobs','var') newjobs = {newjobs{:} jobs{:}}; clear jobs; newjobhelps = {newjobhelps{:} jobhelps{:}}; clear jobhelps; else questdlg(['No jobs (' nam ext ')'],'No jobs','OK','OK'); end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = hide_null_jobs(c) c = hide_null_jobs1(c); c = hide_null_jobs2(c); return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,flg] = hide_null_jobs1(c) if ~isstruct(c) || ~isfield(c,'type'), flg = true; return; end; if ~include(c), flg = false; c.hidden = true; return; end; switch c.type, case {'repeat','branch','choice'}, msk1 = true; msk2 = true; if isfield(c,'val') && ~isempty(c.val), msk1 = true(1,numel(c.val)); for i=1:length(c.val) [c.val{i},msk1(i)] = hide_null_jobs1(c.val{i}); end; end; if isfield(c,'values') && ~isempty(c.values), msk2 = true(1,numel(c.values)); for i=1:length(c.values) [c.values{i},msk2(i)] = hide_null_jobs1(c.values{i}); end; end; flg = any(msk1) || any(msk2); if ~flg, c.hidden = true; end; otherwise flg = true; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function ok = include(c) % Check that the modality is OK ok = true; if isfield(c,'modality'), mod = getdef('modality'); if ~isempty(mod), mod = mod{1}; ok = false; for i=1:length(c.modality), if strcmpi(c.modality{i},mod), ok = true; return; end; end; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function [c,flg] = hide_null_jobs2(c) if ~isstruct(c) || ~isfield(c,'type') flg = 0; return; end; if isfield(c,'prog'), flg = 1; return; end; switch c.type, case {'repeat','branch','choice'}, flg = 0; msk1 = []; msk2 = []; if isfield(c,'val'), msk1 = ones(1,numel(c.val)); for i=1:length(c.val) [c.val{i},msk1(i)] = hide_null_jobs2(c.val{i}); end; end; if isfield(c,'values'), msk2 = ones(1,numel(c.values)); for i=1:length(c.values) [c.values{i},msk2(i)] = hide_null_jobs2(c.values{i}); end; end; if (sum(msk1) + sum(msk2))>0, flg = 1; end; if ~flg, c.hidden = 1; end; otherwise flg = 0; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c = job_to_struct(c,job,jobhelp,tag) % Modify a structure based on a batch job if isstruct(c) && isfield(c,'hidden'), return; end; switch c.type case {'const','menu','files','entry'} if ~strcmp(gettag(c),tag), return; end; if ischar(job) && strcmp(job,'<UNDEFINED>') c.val = {}; else c.val{1} = job; end; c.jobhelp = jobhelp; case {'branch'} if ~strcmp(gettag(c),tag), return; end; if ~isstruct(job), return; end; if ~isempty(jobhelp) && isstruct(jobhelp) && isfield(jobhelp, 'jobhelp') c.jobhelp = jobhelp.jobhelp; end; tag = fieldnames(job); for i=1:length(tag) for j=1:length(c.val) if strcmp(gettag(c.val{j}),tag{i}) try c.val{j} = job_to_struct(c.val{j},job.(tag{i}),jobhelp.(tag{i}), ... tag{i}); catch c.val{j} = job_to_struct(c.val{j},job.(tag{i}),[], ... tag{i}); end; break; end; end; end; case {'choice'} if ~strcmp(gettag(c),tag), return; end; if ~isstruct(job), return; end; tag = fieldnames(job); if length(tag)>1, return; end; tag = tag{1}; for j=1:length(c.values) if strcmp(gettag(c.values{j}),tag) try c.val = {job_to_struct(c.values{j},job.(tag),jobhelp.(tag),tag)}; catch c.val = {job_to_struct(c.values{j},job.(tag),[],tag)}; end; end; end; case {'repeat'} if ~strcmp(gettag(c),tag), return; end; if length(c.values)==1 && strcmp(c.values{1}.type,'branch') if ~isstruct(job), return; end; c.val = {}; for i=1:length(job) if strcmp(gettag(c.values{1}),tag) try c.val{i} = job_to_struct(c.values{1},job(i),jobhelp(i), tag); catch c.val{i} = job_to_struct(c.values{1},job(i),[],tag); end; c.val{i}.removable = true; end; end; elseif length(c.values)>1 if ~iscell(job), return; end; c.val = {}; for i=1:length(job) tag = fieldnames(job{i}); if length(tag)>1, return; end; tag = tag{1}; for j=1:length(c.values) if strcmp(gettag(c.values{j}),tag) try c.val{i} = job_to_struct(c.values{j},job{i}.(tag),jobhelp{i}.(tag),tag); catch c.val{i} = job_to_struct(c.values{j}, job{i}.(tag),[],tag); end; c.val{i}.removable = true; break; end; end; end; else if ~iscell(job), return; end; c.val = {}; for i=1:length(job) try c.val{i} = job_to_struct(c.values{1},job{i},jobhelp{i},tag); catch c.val{i} = job_to_struct(c.values{1},job{i},[],tag); end; c.val{i}.removable = true; end; end; end; return; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function doc = showdoc(str,wid) if nargin<1, str = ''; end; if nargin<2, wid = 60; end; tmp = [0 find([str '.']=='.')]; node = {}; for i=1:length(tmp)-1, tmp1 = str((tmp(i)+1):(tmp(i+1)-1)); if ~isempty(tmp1), node = {node{:},tmp1}; end; end; if numel(node)>1 && strcmp(node{1},'jobs'), node = node(2:end); end; c = initialise_struct; doc = showdoc1(node,c,wid); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function doc = showdoc1(node,c,wid) doc = {}; if isempty(node), doc = showdoc2(c,'',wid); return; end; if isfield(c,'values'), for i=1:numel(c.values), if isfield(c.values{i},'tag') && strcmp(node(1),c.values{i}.tag), doc = showdoc1(node(2:end),c.values{i},wid); return; end; end; end; if isfield(c,'val'), for i=1:numel(c.val), if isfield(c.val{i},'tag') && strcmp(node(1),c.val{i}.tag), doc = showdoc1(node(2:end),c.val{i},wid); return; end; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function doc = showdoc2(c,lev,wid) doc = {''}; if ~isempty(lev) && sum(lev=='.')==1, % doc = {doc{:},repmat('_',1,80),''}; end; if isfield(c,'name'), str = sprintf('%s %s', lev, c.name); %under = repmat('-',1,length(str)); doc = {doc{:},str}; % if isfield(c,'modality'), % txt = 'Only for '; % for i=1:numel(c.modality), % txt = [txt ' ' c.modality{i}]; % end; % doc = {doc{:},'',txt, ''}; %end; if isfield(c,'help'); hlp = spm_justify(wid,c.help); doc = {doc{:},hlp{:}}; end; switch (c.type), case {'repeat'}, if length(c.values)==1, doc = {doc{:}, '', sprintf('Repeat "%s", any number of times.',c.values{1}.name)}; else doc = {doc{:}, '', 'Any of the following options can be chosen, any number of times'}; i = 0; for ii=1:length(c.values), if isstruct(c.values{ii}) && isfield(c.values{ii},'name'), i = i+1; doc = {doc{:}, sprintf(' %2d) %s', i,c.values{ii}.name)}; end; end; end; doc = {doc{:},''}; case {'choice'}, doc = {doc{:}, '', 'Any one of these options can be selected:'}; i = 0; for ii=1:length(c.values), if isstruct(c.values{ii}) && isfield(c.values{ii},'name'), i = i+1; doc = {doc{:}, sprintf(' %2d) %s', i,c.values{ii}.name)}; end; end; doc = {doc{:},''}; case {'branch'}, doc = {doc{:}, '', sprintf('This item contains %d fields:', length(c.val))}; i = 0; for ii=1:length(c.val), if isstruct(c.val{ii}) && isfield(c.val{ii},'name'), i = i+1; doc = {doc{:}, sprintf(' %2d) %s', i,c.val{ii}.name)}; end; end; doc = {doc{:},''}; case {'menu'}, doc = {doc{:}, '', 'One of these values is chosen:'}; for k=1:length(c.labels), doc = {doc{:}, sprintf(' %2d) %s', k, c.labels{k})}; end; doc = {doc{:},''}; case {'files'}, if length(c.num)==1 && isfinite(c.num(1)) && c.num(1)>=0, tmp = spm_justify(wid,sprintf('A "%s" file is selected by the user.',c.filter)); else tmp = spm_justify(wid,sprintf('"%s" files are selected by the user.\n',c.filter)); end; doc = {doc{:}, '', tmp{:}, ''}; case {'entry'}, switch c.strtype, case {'e'}, d = 'Evaluated statements'; case {'n'}, d = 'Natural numbers'; case {'r'}, d = 'Real numbers'; case {'w'}, d = 'Whole numbers'; otherwise, d = 'Values'; end; tmp = spm_justify(wid,sprintf('%s are entered.',d)); doc = {doc{:}, '', tmp{:}, ''}; end; i = 0; doc = {doc{:},''}; if isfield(c,'values'), for ii=1:length(c.values), if isstruct(c.values{ii}) && isfield(c.values{ii},'name'), i = i+1; lev1 = sprintf('%s%d.', lev, i); doc1 = showdoc2(c.values{ii},lev1,wid); doc = {doc{:}, doc1{:}}; end; end; end; if isfield(c,'val'), for ii=1:length(c.val), if isstruct(c.val{ii}) && isfield(c.val{ii},'name'), i = i+1; lev1 = sprintf('%s%d.', lev, i); doc1 = showdoc2(c.val{ii},lev1,wid); doc = {doc{:}, doc1{:}}; end; end; end; doc = {doc{:}, ''}; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function jobhelp = showjobhelp(str,wid) if nargin<1, str = ''; end; if nargin<2, wid = 60; end; tmp = [0 find([str '.']=='.')]; node = {}; for i=1:length(tmp)-1, tmp1 = str((tmp(i)+1):(tmp(i+1)-1)); if ~isempty(tmp1), node = {node{:},tmp1}; end; end; if numel(node)>1 && strcmp(node{1},'jobs'), node = node(2:end); end; c = get(batch_box,'userdata'); jobhelp = showjobhelp1(node,c,wid); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function jobhelp = showjobhelp1(node,c,wid) jobhelp = {}; if isempty(node), jobhelp = showjobhelp2(c,'',wid); return; end; %if isfield(c,'values'), % for i=1:numel(c.values), % if isfield(c.values{i},'tag') && strcmp(node(1),c.values{i}.tag), % jobhelp = showjobhelp1(node(2:end),c.values{i},wid); % return; % end; % end; %end; if isfield(c,'val'), for i=1:numel(c.val), if isfield(c.val{i},'tag') && strcmp(node(1),c.val{i}.tag), jobhelp = showjobhelp1(node(2:end),c.val{i},wid); return; end; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function jobhelp = showjobhelp2(c,lev,wid) jobhelp = {''}; if ~isempty(lev) && sum(lev=='.')==1, % jobhelp = {jobhelp{:},repmat('_',1,80),''}; end; if isfield(c,'name') && isfield(c,'jobhelp'), str = sprintf('%s %s', lev, c.name); jobhelp = {jobhelp{:},str}; hlp = spm_justify(wid,c.jobhelp); jobhelp = {jobhelp{:},hlp{:}}; jobhelp = {jobhelp{:}, ''}; end; i = 0; if isfield(c,'val'), for ii=1:length(c.val), if isstruct(c.val{ii}) && isfield(c.val{ii},'name'), i = i+1; lev1 = sprintf('%s%d.', lev, i); jobhelp1 = showjobhelp2(c.val{ii},lev1,wid); jobhelp = {jobhelp{:}, jobhelp1{:}}; end; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function edit_jobhelp(varargin) h = findobj(0,'tag','help_box'); col1 = getdef('ui.colour1'); if numel(col1)~=1 || ~isnumeric(col1{1}) || numel(col1{1})~=3, col1 = [0.8 0.8 1]; else col1 = col1{1}; end; set(h,'Style','edit','HorizontalAlignment','left', 'Callback', ... @edit_jobhelp_accept, 'BackgroundColor',col1); run_in_current_node(@get_jobhelp,0,h); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c=get_jobhelp(c,h) % for editing, use unjustified version of help string if isfield(c,'jobhelp') set(h,'String',c.jobhelp); end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function edit_jobhelp_accept(varargin) h = findobj(0,'tag','help_box'); col2 = getdef('ui.colour2'); if numel(col2)~=1 || ~isnumeric(col2{1}) || numel(col2{1})~=3, col2 = [1 1 0.8]; else col2 = col2{1}; end; jobhelp = get(h,'string'); set(h,'Style','listbox', 'HorizontalAlignment', ... 'Center', 'Callback',[], 'BackgroundColor',col2, 'String', ... spm_justify(h,jobhelp)); run_in_current_node(@set_jobhelp,1,jobhelp); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function c=set_jobhelp(c,txt) c.jobhelp = txt;
github
spm/spm5-master
spm_bst_headmodeler.m
.m
spm5-master/spm_bst_headmodeler.m
82,570
utf_8
3a01e74cf6f9309c284033afc212220a
function [varargout] = spm_bst_headmodeler(varargin); % SPM_BST_HEADMODELER - Solution to the MEG/EEG forward problem % function [varargout] = bst_headmodeler(varargin); % Authorized syntax: % [OPTIONS] = spm_bst_headmodeler; % [G, Gxyz, OPTIONS] = spm_bst_headmodeler(OPTIONS); % % --------------------------------- INPUTS ------------------------------------- % INPUTS % % [OPTIONS] = spm_bst_headmodeler; Returns the default values for the OPTIONS % parameter structure % % StudyFile: the name of a BrainStorm study file. We suppose the % corresponding BrainStorm channel file is available in the same folder % with the conventional file name (e.g., for a study file calls % meg_brainstormstudy.mat, BST_HEADMODELER expects to find the % corresponding channel file under the name meg_channel.mat). If the % channel file were not sitting in the same folder as the study file, % OPTIONS.ChannelFile enforces computation of the forward model with the % channel information contained in OPTIONS.ChannelFile. % % If no further input arguments are specified, forward modeling is % completed with the default parameters specified below % % OPTIONS a structure where optional parameters may be specified using the % following fields Note: if no options are specified, BST_HEADMODELER will % proceed to the computation of the foward problem on a 3D grid of source % locations that cover the entire head volume See % OPTIONS.VolumeSourceGridSpacing for default settings % % Important notice: there is no need to define all the following fields % when using the OPTIONS argument. The undefined field(s) will be assigned % default values. % % * % * Fields Related to forward approach % * % % .Method: is either a character string or a cell array of two strings that % specifies the kind of approach to be applied to the compuation % of the foward model In case Method is a cell array, it should % contain 2 strings, one to specifiy the method to be used for MEG % and the other for . If only a single string is specified, the % foward computation will be completed on the set of corresponding % CHANndx only (i.e. MEG or MEG) Available forward modeling % methods and corresponding authorized strings for Method: % - MEG % 'meg_sphere' (DEFAULT) : Spherical head model designed % following the Sarvas analytical formulation (i.e. % considering the true orientation % of the magnetic field sensors) (see OPTIONS.HeadCenter) % 'meg_os' : MEG overlapping sphere forward model % 'meg_bem' : Apply BEM computation (see OPTIONS.BEM for details) % - % 'eeg_sphere' : Single-sphere forward modeling (see % OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity) % 'eeg_3sphere' : EEG forward modeling with a set of 3 % concentric spheres (Scalp, Skull, Brain/CSF) (see % OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity) % 'eeg_3sphereBerg' (DEFAULT) : Same as eeg_3sphere with % correction for possible dipoles outside the sphere % 'eeg_os' : EEG overlapping sphere head model (see % OPTIONS.HeadCenter, OPTIONS.Radii, OPTIONS.Conductivity) % 'eeg_bem' : Apply BEM computation (see OPIONS.BEM for details) % % Default is {'meg_sphere','eeg_3sphereBerg'}; % % .HeadModelName : a character string that specifies the name of the % headmodel represented by this file, e.g "Spherical", % "Overlapping Spheres", "Constant Collocation BEM", etc. % Default is "Default", meaning it will include the the % name(s) of the method(s) used in the MEG and/or EEG % forward models % % * % * Fields Related to function's I/O % * % % .HeadModelFile : Specifies the name of the head model file where to store % the forward model. If set to 'default', the default % nomenclature for BrainStorm's head model file name is % used and BST_HEADMODELER creates a file in StudyFile's % folder. % Default is empty. % .ImageGridFile : Specifies the name of the file where to store the full % cortical gain matrix file If set to 'default', the % default nomenclature for BrainStorm's head model file % name is used and BST_HEADMODELER creates a file in % StudyFile's folder. % Default is empty. % .ImageGridBlockSize : Number of sources for which to compute the forward % model at a time in a block computation routines % (saves memory space). This option is relevant only % when some forward modeling on cortical surface is % requested (i.e. when .Cortex is specified) % Default is 2000 % .FileNamePrefix : A string that specifies the prefix for all file names % (Channel, HeadModel, Gain Matrices) when .HeadModelFile % is set to 'default' and .ChannelFile is empty. % Default is 'bst_' % .Verbose : Toggles verbose mode on/off; % Default is 1 (on) % % * % * Fields Related to Head Geometry * % * % % .Scalp : A structure specifying the Scalp surface envelope to serve % for parameter adjustment of best-fitting sphere, with % following fields: % .FileName : A string specifying the name of the BrainStorm % tessellation file containing the Scalp % tessellation (default is 1); % .iGrid : An integer for the index of the Scalp surface in % the Faces, Vertices and Comments cell arrays in % the tessellation file % Default is empty (Best-fitting sphere is % computed from the sensor array). % .HeadCenter: a 3-element vector specifying the coordinates, in the % sensors coordinate system, of the center of the spheres that % might be used in the head model. % Default is estimated from the center of the best-fitting % sphere to the sensor locations % .Radii : a 3-element vector containing the radii of the single or 3 % concentric spheres, when needed; % Order must be the following : [Rcsf, Routerskull, Rscalp]; % Default is estimated from the best-fitting sphere to the % sensor locations and OPTIONS.Radii is set to: Rscalp [.88 % .93 1]. Rscalp is estimated from the radius of the % best-fitting sphere; % .Conductivity : a 3-element vector containing the values for the % conductivity of the tissues in the following order: % [Ccsf, Cskull, Cscalp]; % Default is set to [.33 .0042 .33]; % .EEGRef : the NAME (not index of the channel file) of the electrode % that acts as the reference channel for the EEG. If data is % referenced to instantaneous average (i.e. so called % average-reference recording) value is 'AVERAGE REF'; % IMPORTANT NOTICE: When user calls bst_headmodeler with the % .ChannelLoc option and .ChannelType = 'EEG'and wants the EEG % reference to be e.g. channel 26, then .EEGRef should be set % to 'EEG 26' % Default is 'AVERAGE REF'. % % .OS_ComputeParam : if 1, force computation of all sphere parameters when % choosing a method based on either the MEG or EEG % overlapping-sphere technique, if 0 and when % .HeadModelFile is specified, sphere parameters are % loaded from the pre-computed HeadModel file. % Default is 1. % % .BEM : Structure that specifies the necessary BEM parameters % .Interpolative : Flag indicating whether exact or % interpolative approach is used to compute % the forward solution using BEM. % if set to 1, exact computation is run on a % set of points distributed wihtin the inner % head volume and any subsequent request for % a forward gain vector (e.g. during a % volumic source scan using RAP-MUSIC) is % computed using an interpolation of the % forward gain vectors of the closest volumic % grid points. This allows faster computation % of the BEM solution during source search. % if set to 0, exact computation is required % at every source location. % We recommend to set it to 0 (default) when % sources have fixed location, e.g. % constrained on the cortical surface. % .EnvelopeNames : a cell array of strutures that specifies % the ORDERED tessellated surfaces to be % included in the BEM computation. % .EnvelopeNames{k}.TessFile : A string for % the name of the tessellation file % containing the kth surface % .EnvelopeNames{k}.TessName : A string for % the name of the surface within the % tessellation file This string should match % one of the Comment strings in the % tessellation file. The chosen surfaces must % be ordered starting by the the innermost % surface (e.g. brain or inner skull % surface) and finishing with the outermost % layer (e.g. the scalp) % .Basis : set to either 'constant' or 'linear' (default) % .Test : set to either 'Galerkin' or 'Collocation' (default) % .ISA : Isolated-skull approach set to 0 or 1 (default is 1) % .NVertMax : Maximum number of vertices per envelope, % therefore leading to decimation of orginal % surfaces if necessary % (default is 1000) % .ForceXferComputation: if set to 1, force recomputation of % existing transfer matrices in current % study folder (replace existing % files); % Default is 1 % % * % * Fields Related to Sensor Information * % * % % .ChannelFile : Specifies the name of the file containing the channel % information (needs to be a BrainStorm channel file). If % file does not exists and sensor information is provided in % .ChannelLoc, a BrainStorm Channl file with name % .ChannelFile is created % Default is left blank as this information is extracted % from the channel file associated to the chosen BrainStorm % studyfile. % .Channel : A full BrainStorm channel structure if no channel file is % specified; % Default is empty % .ChannelType : A string specifying the type of channel in ChannelLoc. Can % be either 'MEG' or 'EEG'. Note that the same channel type % is assumed for every channel. % Default is empty % .ChannelLoc : Specifies the location of the channels where to compute % the forward model Can be either a 3xNsens (for EEG or % MEG-magnetometer) or 6xNsens matrix (for the % MEG-gradiometer case). (for magnetometer or gradiometer % MEG - channel weights are set to -1 and 1 for each % magnetometer in the gradiometer respectively) Note that % in the MEG-gradiometer case, the 3 first (res. last) rows % of .ChannelLoc stand for each of the magnetometers of the % gradiometer set. In the case of a mixture of MEG magneto % and MEG gradio-meters, .ChannelLoc needs to be a 6xNsens % matrix where the last 3 rows are filled with NaN for % MEG-magnetometers. If ones wants to handle both EEG and MEG % sensors, please create a full ChannelFile and use the % .ChannelFile option. % Default is empty (Information extracted from the ChannelFile). % .ChannelOrient : Specifies the orientation of the channels where to % compute the EEG or MEG forward model Can be either a % 3xNsens (for EEG and magnetometer MEG) or 6xNsens (for % gradiometer MEG) matrix or a cell array of such matrices % (one cell per type of method selected) % Default is empty (Information extracted from the % ChannelFile or assume radial orientation when % .ChannelLoc is filled). % % * % * Fields Related to Source Models * % * % .SourceModel : A vector indicating the type of source models to be % computed; The following code is enfoced: % -1 : Compute the forward fields of Current Dipole sources % (available for all forward approaches) % 1 : 1st-order Current Multipole Sources % (available for sphere-based MEG approaches only) % User can set OPTIONS.SourceModel to e.g., [-1 1] to % compute forward models from both source models. % Default is -1 % % % * % * Fields Related to Source Localization * % * % .Cortex : A structure specifying the Cortex surface % envelope to serve as an image support with % following fields. % .FileName : A string specifying the name of % the BrainStorm tessellation file % containing the Cortex % tessellation; % .iGrid : An integer for the index of the % Cortex surface in the Faces, % Vertices and Comments cell arrays % in the tessellation file (default % is 1) % Default is empty. % .GridLoc : A 3xNsources matrix that contains the % locations of the sources at which the forward % model will be computed % Default is empty (Information taken from % OPTIONS.Cortex or OPTIONS.VolumeSourceGrid); % .GridOrient : a 3xNsources matrix that forces the source % orientation at every vertex of the .ImageGrid % cortical surface; % Defaults is empty; this information being % extracted from the corresponding tessellated % surface. % .ApplyGridOrient : if set to 1, force computation of the forward % fields by considering the local orientation of % the cortical surface; % If set to 0, a set of 3 orthogonal dipoles are % considered at each vertex location on the % tessellated surface. % Default is 1. % .VolumeSourceGrid : if set to 1, a 3D source grid is designed to % fit inside the head volume and will serve as a % source space for scannig techniques such as % RAP-MUSIC; % if set to 0, this grid will be computed at the % first call of e.g. RAP-MUSIC); % Default is 1 % .VolumeSourceGridSpacing : Spacing in centimeters between two consecutive % sources in the 3D source grid described above; % Default is 2 cm. % .VolumeSourceGridLoc : a 3xN matrix specifying the locations of the % grid points that will be used to design the % volumic search grid (see .VolumicSourceGrid) % Default is empty (locations are estimated % automatically to cover the estimated inner % head volume) % .SourceLoc : a 3xNsources matrix that contains the % locations of the sources at which the forward % model will be computed % Default is empty (Information taken from % OPTIONS.ImageGrid or % OPTIONS.VolumeSourceGrid); % .SourceOrient : a 3xNsources matrix that contains the % orientations of the sources at which the % forward model will be computed % Default is empty. % % % --------------------------------- OUTPUTS ------------------------------------ % OUTPUT % G if the number of sources (Nsources) if less than % .ImageGridBlockSize then G is a gain matrix of dimension % Nsensors x Nsources: Each column of G is the forward field % created by a dipolar source of unit amplitude. Otherwise, G is % the name of the binary file containing the gain matrix. This % file can be read using the READ_GAIN function. % % Gxyz As for G but for each dipole moment % % OPTIONS Returns the OPTIONS structure with updated fields following the % call to BST_HEADMODELER. Can be useful to obtain a full % BrainStorm Channel structure when only the .ChannelLoc and % possibly .ChannelOrient fields were provided. %<autobegin> ---------------------- 27-Jun-2005 10:43:31 ----------------------- % ------ Automatically Generated Comments Block Using AUTO_COMMENTS_PRE7 ------- % % CATEGORY: Forward Modeling % % Alphabetical list of external functions (non-Matlab): % toolbox\bem_gain.m % toolbox\bem_xfer.m % toolbox\berg.m % toolbox\bst_message_window.m % toolbox\colnorm.m % toolbox\get_channel.m % toolbox\get_user_directory.m % toolbox\good_channel.m % toolbox\gridmaker.m % toolbox\inorcol.m % toolbox\norlig.m % toolbox\overlapping_sphere.m % toolbox\rownorm.m % toolbox\save_fieldnames.m % toolbox\source_grids.m % toolbox\view_surface.m % % Subfunctions in this file, in order of occurrence in file: % BEMGaingridFname = bem_GainGrid(DataType,OPTIONS,BEMChanNdx) % g = gterm_constant(r,rq) % % At Check-in: $Author: Silvin $ $Revision: 68 $ $Date: 12/15/05 4:14a $ % % This software is part of BrainStorm Toolbox Version 27-June-2005 % % Principal Investigators and Developers: % ** Richard M. Leahy, PhD, Signal & Image Processing Institute, % University of Southern California, Los Angeles, CA % ** John C. Mosher, PhD, Biophysics Group, % Los Alamos National Laboratory, Los Alamos, NM % ** Sylvain Baillet, PhD, Cognitive Neuroscience & Brain Imaging Laboratory, % CNRS, Hopital de la Salpetriere, Paris, France % % See BrainStorm website at http://neuroimage.usc.edu for further information. % % Copyright (c) 2005 BrainStorm by the University of Southern California % This software distributed under the terms of the GNU General Public License % as published by the Free Software Foundation. Further details on the GPL % license can be found at http://www.gnu.org/copyleft/gpl.html . % % FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE % UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY % WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF % MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY % LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE. %<autoend> ------------------------ 27-Jun-2005 10:43:31 ----------------------- % /---Script Author--------------------------------------\ % | | % | *** Sylvain Baillet Ph.D. | % | Cognitive Neuroscience & Brain Imaging Laboratory | % | CNRS UPR640 - LENA | % | Hopital de la Salpetriere, Paris, France | % | [email protected] | % | | % \------------------------------------------------------/ % % Date of creation: March 2002 % Default options settings-------------------------------------------------------------------------------------------------- DefaultMethod = {'meg_sphere','eeg_3sphereBerg'}; ReducePatchScalpNVerts = 500; BEM_defaults = struct(... 'Basis','linear',... 'Test','galerkin',... 'Interpolative',0,... 'ISA',1,... 'NVertMax',1000,... 'ForceXferComputation', 1, ... 'checksurf',0); Def_OPTIONS = struct(... 'ApplyGridOrient',1,... 'BEM', BEM_defaults,... 'Channel', [],... 'ChannelFile', '',... 'ChannelLoc', '',... 'ChannelOrient', '',... 'ChannelType', '',... 'Conductivity', [.33 .0042 .33],... 'Cortex',[],... 'EEGRef','',... 'HeadCenter',[],... 'HeadModelFile', '',... 'HeadModelName','Default',... 'ImageGridBlockSize', 2000,... 'ImageGridFile', '',... 'GridOrient',[],... 'Method', {DefaultMethod},... 'OS_ComputeParam', 1,... 'PrefixFileName','bst_',... 'Radii', [],... 'Scalp',[],... 'SourceLoc',[],... 'SourceModel', [-1],... 'SourceOrient',[],... 'StudyFile','',... 'TessellationFile','',... 'VolumeSourceGrid',1,... 'VolumeSourceGridSpacing', 2,... 'VolumeSourceGridLoc', [],... 'Verbose', 1 ... ); if nargin == 0 varargout{1} = Def_OPTIONS; return else OPTIONS = varargin{1}; end % Check field names of passed OPTIONS and fill missing ones with default values DefFieldNames = fieldnames(Def_OPTIONS); for k = 1:length(DefFieldNames) if ~isfield(OPTIONS,DefFieldNames{k}) | strcmp(DefFieldNames{k},'BEM') if ~isfield(OPTIONS,DefFieldNames{k}) OPTIONS = setfield(OPTIONS,DefFieldNames{k},getfield(Def_OPTIONS,DefFieldNames{k})); elseif strcmp(DefFieldNames{k},'BEM') BEM_DefFieldNames = fieldnames(BEM_defaults); for kk = 1:length(BEM_DefFieldNames) if ~isfield(OPTIONS.BEM,BEM_DefFieldNames{kk}) OPTIONS.BEM = setfield(OPTIONS.BEM,BEM_DefFieldNames{kk},getfield(BEM_defaults,BEM_DefFieldNames{kk})); end end end end end if isempty(OPTIONS.Conductivity) OPTIONS.Conductivity = Def_OPTIONS.Conductivity; end clear Def_OPTIONS if isempty(OPTIONS.HeadModelFile) & ~isempty(OPTIONS.ImageGridFile) % Force creation of a headmodel file OPTIONS.HeadModelFile = 'default'; end OPTIONS.HeadModelFileOld = OPTIONS.HeadModelFile; % What type of forward model (MEG and/or EEG) ? DataType.MEG = strmatch('meg',OPTIONS.Method); % Rank of the respective forward method in cell array Method (ie could be Method = {'meg_bem','eeg_sphere'} or vice-versa) DataType.EEG = strmatch('eeg',OPTIONS.Method); if ~iscell(OPTIONS.Method) OPTIONS.Method = {OPTIONS.Method}; end MegMethod = []; if ~isempty(DataType.MEG) MegMethod = OPTIONS.Method{DataType.MEG}; % String indicating the forward method selected for MEG (res. EEG) end EegMethod = []; if ~isempty(DataType.EEG) EegMethod = OPTIONS.Method{DataType.EEG}; end % Check inputs integrity %Source models if ~isempty(find(OPTIONS.SourceModel == 0)) | ~isempty(find(abs(OPTIONS.SourceModel) > 1)) % unValid source models if ~isempty(DataType.MEG) errordlg('Valid source model orders for MEG are: -1 (Current Dipole) and 1 (fist-order Current Multipole Expansion)') end if ~isempty(DataType.EEG) errordlg('Valid source model order for EEG is: -1 (Current Dipole) ') end varargout = cell(nargout,1); return end % Source locations if isempty(OPTIONS.SourceLoc) & ~OPTIONS.VolumeSourceGrid & isempty(OPTIONS.Cortex) % No source locations were specified errordlg('No source locations are specified. Please fill either one of the following fields of OPTIONS: .SourceLoc / .VolumeSourceGrid / .Cortex') varargout = cell(nargout,1); return end %-------------------------------------------------------------------------------------------------------------------------------------------- % % HEAD MODELING BEGINS % %-------------------------------------------------------------------------------------------------------------------------------------------- % Get Channel Information ------------------------------------------------------------------------------------------------------------------ if ~isempty(OPTIONS.Channel) Channel = OPTIONS.Channel; else if isempty(OPTIONS.ChannelFile) & isempty(OPTIONS.ChannelLoc) % Load Channel file in current folder [Channel, ChannelFile] = get_channel(fullfile(User.STUDIES,OPTIONS.StudyFile)); OPTIONS.ChannelFile = fullfile(fileparts(fullfile(User.STUDIES,OPTIONS.StudyFile)),ChannelFile); if isempty(ChannelFile) errordlg(sprintf('Channel file %s is missing. Please have it available it the current study folder.',OPTIONS.ChannelFile), 'Missing Channel File') return end elseif isempty(OPTIONS.ChannelLoc) & exist(OPTIONS.ChannelFile,'file') % If no specific channel locations are given and channel file exists, load the proper channel file OPTIONS.rooot = strrep(lower(OPTIONS.ChannelFile),'channel.mat',''); try load(OPTIONS.ChannelFile) catch cd(User.STUDIES) load(OPTIONS.ChannelFile) end else % Create a dummy Channel structure with Channel Locations (res. Orientations) specified in OPTIONS.ChannelLoc (res .ChannelOrient) if OPTIONS.Verbose, bst_message_window('Creating the channel structure from information in the OPTIONS fields. . .'), end % Get Channel Locations nchan = size(OPTIONS.ChannelLoc,2); % Number of channels Channel = struct('Loc',[],'Orient',[],'Comment','','Weight',[],'Type','','Name',''); Channel(1:nchan) = deal(Channel); ChanType = upper(OPTIONS.ChannelType); if isempty(ChanType) errordlg('Please specify a channel type (i.e. MEG or EEG) in the ChannelType field of OPTIONS'), bst_message_window('Please specify a channel type (i.e. MEG or EEG) in the ChannelType field of OPTIONS'), varargout = cell(nargout,1); return end [Channel(:).Type] = deal(ChanType); if size(OPTIONS.ChannelLoc,1) == 6 % MEG Gradiometers or mixture gradio/magneto meters OPTIONS.ChannelLoc = reshape(OPTIONS.ChannelLoc,3,nchan*2); iGradFlag = 1; % Flag - gradiometer-type sensor set else iGradFlag = 0; % Flag - EEG or magnetometer-type sensor set end ichan = 1; for k = 1:nchan if iGradFlag Channel(k).Loc = OPTIONS.ChannelLoc(:,ichan:ichan+1); ichan = ichan+2; else if strcmp(ChanType,'MEG') Channel(k).Loc = OPTIONS.ChannelLoc(:,ichan); %elseif strcmp(ChanType,'EEG') % Artificially add a dummy column full of zeros to each Channel(k).Loc %Channel(k).Loc = [OPTIONS.ChannelLoc(:,ichan) [0 0 0]']; elseif strcmp(ChanType,'EEG') % Artificially add a dummy column full of zeros to each Channel(k).Loc Channel(k).Loc = [OPTIONS.ChannelLoc(:,ichan)]; end ichan = ichan+1; end Channel(k).Name = sprintf('%s %d',ChanType,k); Channel(k).Comment = int2str(k); end clear ichan k % Get Channel Orientations if isempty(OPTIONS.ChannelOrient) & strcmp(ChanType,'MEG') % No channel orientation were specified: use radial sensors if OPTIONS.Verbose, bst_message_window('Assign radial orientation to all Channels. . .'), end if isempty(OPTIONS.HeadCenter) if iGradFlag Vertices = OPTIONS.ChannelLoc(:,1:2:end)'; else Vertices = OPTIONS.ChannelLoc'; end nscalp = size(Vertices,1); if nscalp > 500 % 500 points is more than enough to compute scalp's best fitting sphere Vertices = Vertices(unique(round(linspace(1,nscalp,500))),:); nscalp = size(Vertices,1); end nmes = size(Vertices,1); % Run parameters fit -------------------------------------------------------------------------------------------------------------- mass = mean(Vertices); % center of mass of the scalp vertex locations R0 = mean(norlig(Vertices - ones(nscalp,1)*mass)); % Average distance between the center of mass and the scalp points vec0 = [mass,R0]; [minn,brp] = fminsearch('dist_sph',vec0,[],Vertices); OPTIONS.HeadCenter = minn(1:end-1); if isempty(OPTIONS.Radii) OPTIONS.Radii = minn(end); OPTIONS.Radii = minn(end)*[1/1.14 1/1.08 1]; end if OPTIONS.Verbose, bst_message_window({... sprintf('Center of the Sphere : %3.1f %3.1f %3.1f (cm)',100*OPTIONS.HeadCenter),... sprintf('Radius : %3.1f (cm)',100*OPTIONS.Radii(3)),... '-> DONE',' '}) end clear minn brp mass R0 Vertices vec0 end tmp = [Channel.Loc] - repmat(OPTIONS.HeadCenter',1,nchan*(1+(iGradFlag==1))); OPTIONS.ChannelOrient = tmp*inorcol(tmp); % Radial orientation for every channel clear tmp elseif ~isempty(OPTIONS.ChannelOrient) & strcmp(ChanType,'MEG') & iGradFlag OPTIONS.ChannelOrient = reshape(OPTIONS.ChannelOrient,3,nchan*2); end if strcmp(ChanType,'MEG') for k=1:nchan Channel(k).Orient = OPTIONS.ChannelOrient(:,((1+(iGradFlag==1))*k-1):(1+(iGradFlag==1))*k); end end clear k % Define Weights if iGradFlag [Channel(:).Weight] = deal([1 -1]); else [Channel(:).Weight] = deal([1]); end if strcmp(ChanType,'MEG') % Force no reference channels Channel(1).irefsens = []; end % New Channel stbemructure completed: save as a new channel file if ~isempty(OPTIONS.ChannelFile) %OPTIONS.ChannelFile = [OPTIONS.rooot,'channel.mat']; save(OPTIONS.ChannelFile,'Channel') if OPTIONS.Verbose, bst_message_window({... sprintf('Channel file created in : %s',OPTIONS.ChannelFile),... '-> DONE',' '}), end end end %load(OPTIONS.ChannelFile) OPTIONS.Channel = Channel; end % Find MEG and EEG channel indices MEGndx = good_channel(Channel,[],'MEG'); EEGndx = good_channel(Channel,[],'EEG'); EEGREFndx = good_channel(Channel,[],'EEG REF'); MEG = ~isempty(MEGndx) & ~isempty(DataType.MEG); % == 1 if MEG is requested and is available EEG = ~isempty(EEGndx) & ~isempty(DataType.EEG); if ~EEG & ~MEG errordlg('Please check that data (MEG or EEG) and channel types are compatible.') return end if EEG if isempty(OPTIONS.EEGRef) % EEG Reference Channel EEGREFndx = good_channel(Channel,[],'EEG REF'); if isempty(EEGREFndx) % Average EEG reference anyway [Channel(EEGndx).Comment] = deal('AVERAGE REF'); end else % EEG Reference is specified switch(OPTIONS.EEGRef) case 'AVERAGE REF' [Channel(:).Comment] = deal('AVERAGE REF'); otherwise EEGREFndx = strmatch(OPTIONS.EEGRef,char(Channel(:).Name)); if isempty(EEGREFndx) errordlg(sprintf(... 'No channel named ''%s'' was found amongst available EEG channels. Cannot use it as a reference for EEG.',OPTIONS.EEGRef... )) return end end end end if MEG & isempty(MEGndx) % User wants to compute MEG but no MEG data is available errordlg('Sorry - No MEG data is available'), return end if EEG & isempty(EEGndx) % User wants to compute EEG but no EEG data is available errordlg('Sorry - No EEG data is available'), return end % Computation of parameters of the best-fitting sphere -------------------------------------------------------------------------------------------------------------- if length(findstr('bem',[OPTIONS.Method{:}])) ~= length(OPTIONS.Method)% Only if sphere-based head model is requested in any modality (MEG or EEG) % Best-fitting sphere parameters -------------------------------------------------------------------------------------------------------------- if isempty(OPTIONS.HeadCenter) | isempty(OPTIONS.Radii) if OPTIONS.Verbose, bst_message_window('Estimating Center of the Head. . .'), end if isempty(OPTIONS.Scalp) % Best-fitting sphere is derived from the sensor array % ans = questdlg('No scalp surface was selected - Do you want to use a spherical approximation of the head derived from the sensor locations instead ?',... % '','Yes','No','Yes'); if EEG & length(EEGndx) > 9 % If EEG is available but a reasonable number of electrodes, use it to compute the sphere parameters ndx = [EEGndx]; % Compute Sphere parameters from EEG sensors only else ndx = [MEGndx]; end Vertices = zeros(length(ndx),3); for k=1:length(ndx) Vertices(k,:) = Channel(ndx(k)).Loc(:,1)'; end else % Best-fitting sphere is computed from the set of vertices of the scalp surface enveloppe try load(fullfile(User.SUBJECTS,OPTIONS.Scalp.FileName),'Vertices') catch load(OPTIONS.Scalp.FileName,'Vertices') end if ~isfield(OPTIONS.Scalp,'iGrid') % Apply Default OPTIONS.Scalp.iGrid = 1; end try Vertices = Vertices{OPTIONS.Scalp.iGrid}'; catch errordlg(sprintf(... 'Tessellation file %s does not contain %d enveloppes',... OPTIONS.Scalp.FileName,OPTIONS.Scalp.iGrid)) end end nscalp = size(Vertices,1); nmes = size(Vertices,1); % Run parameters fit -------------------------------------------------------------------------------------------------------------- mass = mean(Vertices); % center of mass of the scalp vertex locations R0 = mean(norlig(Vertices - ones(nscalp,1)*mass)); % Average distance between the center of mass and the scalp points vec0 = [mass,R0]; [SphereParams,brp] = fminsearch('dist_sph',vec0,[],Vertices); end % no head center and sphere radii were specified by user % Assign default values for sphere parameters % if none were specified before if isempty(OPTIONS.Radii) OPTIONS.Radii = SphereParams(end)*[1/1.14 1/1.08 1]; end if isempty(OPTIONS.HeadCenter) OPTIONS.HeadCenter = SphereParams(1:end-1)'; end if isempty(OPTIONS.Conductivity) OPTIONS.Conductivity = [.33 .0042 .33]; end end % Use BEM Approach, so proceed to the selection of the envelopes % --------------------------------------------------------------------------------------------------------- %Create HeadModel Param structure Param(1:length(Channel)) = deal(struct('Center',[],'Radii',[],'Conductivity',[],'Berg',[])); if ~isempty(findstr('os',[OPTIONS.Method{:}])) % Overlapping-Sphere EEG or MEG is requested: load the scalp's tessellation if isempty(OPTIONS.Scalp) errordlg('Please specify a subject tessellation file for Scalp enveloppe in OPTIONS.Scalp when using Overlapping-Sphere forward approach'); return end % load(fullfile(User.SUBJECTS,BrainStorm.SubjectTess),'Faces'); try load(fullfile(User.SUBJECTS,OPTIONS.Scalp.FileName),'Faces','Vertices'); catch load(OPTIONS.Scalp.FileName,'Faces','Vertices'); end Faces = Faces{OPTIONS.Scalp.iGrid}; Vertices = Vertices{OPTIONS.Scalp.iGrid}'; if size(Vertices,1) > ReducePatchScalpNVerts % Reducepatch the scalp tessellation for fastest OS computation nfv = reducepatch(Faces,Vertices,2*ReducePatchScalpNVerts); if OPTIONS.Verbose, bst_message_window({... sprintf('Decimated scalp tessellation from %d to %d vertices.',size(Vertices,1),size(nfv.vertices,1)),... ' '}); end clear Faces Vertices SubjectFV.vertices = nfv.vertices'; SubjectFV.faces = nfv.faces; clear nfv else SubjectFV.vertices = Vertices; % Available from the computation of the head center above clear Vertices SubjectFV.faces = Faces; clear Faces end if length(findstr('os',[OPTIONS.Method{:}])) == 2 % OS approach requested fro both MEG and EEG ndx = [MEGndx,EEGndx]; else if MEG if strcmpi('meg_os',OPTIONS.Method{DataType.MEG}) % OS for MEG only ndx = MEGndx; end end if EEG if strcmpi('eeg_os',OPTIONS.Method{DataType.EEG}) % OS for EEG only ndx = [EEGndx, EEGREFndx]; end end end if isempty(OPTIONS.HeadModelFile) | OPTIONS.OS_ComputeParam % Compute all spheres parameters %------------------------------------------------------------------ Sphere = overlapping_sphere(Channel(ndx),SubjectFV,OPTIONS.Verbose,OPTIONS.Verbose); if OPTIONS.Verbose bst_message_window({... 'Computing Overlapping-sphere model -> DONE',' '}) end [Param(ndx).Center] = deal(Sphere.Center); [Param(ndx).Radii] = deal(Sphere.Radius); [Param(ndx).Conductivity] = deal(OPTIONS.Conductivity); elseif exist(OPTIONS.HeadModelFile,'file') load(OPTIONS.HeadModelFile,'Param') % or use precomputed if OPTIONS.Verbose bst_message_window({... sprintf('Sphere parameters loaded from : %s -> DONE',OPTIONS.HeadModelFile),' '}) end else errordlg(sprintf('Headmodel file %s does not exist in Matlab''s search path',OPTIONS.HeadModelFile)) return end end if ~isempty(findstr('sphere',[OPTIONS.Method{:}])) % Single or nested-sphere approaches [Param([MEGndx, EEGndx, EEGREFndx]).Center] = deal(OPTIONS.HeadCenter); [Param([MEGndx, EEGndx, EEGREFndx]).Radii] = deal(OPTIONS.Radii); [Param([MEGndx, EEGndx, EEGREFndx]).Conductivity] = deal(OPTIONS.Conductivity); if EEG & strcmpi('eeg_3sphereberg',lower(OPTIONS.Method{DataType.EEG})) % BERG APPROACH if ~isempty(OPTIONS.HeadModelFile) & exist(OPTIONS.HeadModelFile,'file') if OPTIONS.Verbose, bst_message_window('Checking for previous EEG "BERG" parameters'), end ParamOld = load(OPTIONS.HeadModelFile,'Param'); iFlag = 0; % Flag if isfield(ParamOld.Param,'Berg') & ~isempty(ParamOld.Param(1).Radii) % Check if these older parameters were computed with the same as current radii and conductivity values if ParamOld.Param(1).Radii ~= Param(1).Radii; iFlag = 1; end if ParamOld.Param(1).Conductivity ~= Param(1).Conductivity; iFlag = 1; end else iFlag = 1; end else iFlag = 1; end if iFlag == 1 if OPTIONS.Verbose , bst_message_window('Computing EEG "BERG" Parameters. . .'), end [mu_berg_tmp,lam_berg_tmp] = berg(OPTIONS.Radii,OPTIONS.Conductivity); Param(EEGndx(1)).Berg.mu = mu_berg_tmp; clear mu_berg_tmp Param(EEGndx(1)).Berg.lam = lam_berg_tmp; clear lam_berg_tmp if OPTIONS.Verbose, bst_message_window({'Computing EEG "BERG" Parameters -> DONE',' '}), end else if OPTIONS.Verbose , bst_message_window('Using Previous EEG "BERG" Parameters'), end Param(EEGndx(1)).Berg.mu = ParamOld.Param(1).Berg.mu; Param(EEGndx(1)).Berg.lam = ParamOld.Param(1).Berg.lam; clear ParamOld end [Param.Berg]= deal(Param(EEGndx(1)).Berg); end end if ~isempty(findstr('bem',[OPTIONS.Method{:}])) % BEM approaches - Compute transfer matrices if OPTIONS.BEM.Interpolative==0 & OPTIONS.VolumeSourceGrid %& isempty(OPTIONS.Cortex) % User wants volumic grid : force Interpolative approach OPTIONS.BEM.Interpolative = 1; % CBB (SB, 07-May-2004)| Should work also for volumic grid hwarn = warndlg('Volumic Source Grid BEM is only available for interpolative BEM. BEM computation will be now forced to interpolative. If you want a non-interpolative BEM on a cortical image grid, first uncheck the Volumic Grid box from headmodeler gui.','Limitation from current BrainStorm version'); drawnow waitfor(hwarn) end if MEG if ~isempty(findstr('bem',OPTIONS.Method{DataType.MEG})) % BEM is requested for MEG BEMChanNdx{DataType.MEG} = MEGndx; end end if EEG if ~isempty(findstr('bem',OPTIONS.Method{DataType.EEG})) % BEM is requested for EEG BEMChanNdx{DataType.EEG} = sort([EEGndx,EEGREFndx]); % EEGREFndx = [] is average ref end end OPTIONS.Param = Param; if OPTIONS.BEM.Interpolative % Computation of gain matrix over 3D interpolative grid if OPTIONS.BEM.ForceXferComputation BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data else try BEMGaingridFileName = OPTIONS.BEM.GaingridFileName; catch cd(User.STUDIES) BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data end end if MEG & EEG [Param(MEGndx).bem_gaingrid_mfname] = deal(BEMGaingridFileName.MEG); [Param([EEGndx]).bem_gaingrid_mfname] = deal(BEMGaingridFileName.EEG); else [Param(:).bem_gaingrid_mfname] = deal(BEMGaingridFileName); end else % BEM gain matrix computation over cortical surface BEMGaingridFileName = bem_GainGrid(DataType, OPTIONS, BEMChanNdx); [Param(:).bem_gaingrid_mfname] = deal(''); end OPTIONS = rmfield(OPTIONS,'Param'); ndx = sort([BEMChanNdx{:}]); [Param(ndx).Center] = deal([]); test=0; % this test is nowhere defined ? if OPTIONS.VolumeSourceGrid % Now define the outer scalp envelope for the source volume gridding if requested if OPTIONS.BEM.ForceXferComputation | ~test global nfv SubjectFV.vertices = nfv(end).vertices'; SubjectFV.faces = nfv(end).faces; clear Faces else % Changed by Rik 4/10/07 to call from SPM without User files if exist('User') load(fullfile(User.SUBJECTS,fileparts(OPTIONS.Subject),OPTIONS.BEM.EnvelopeNames{end}.TessFile)) else load(OPTIONS.BEM.EnvelopeNames{end}.TessFile) end %%%%%% idScalp = find(strcmpi(OPTIONS.BEM.EnvelopeNames{end}.TessName,Comment)); clear Comment if isempty(idScalp) errodlg(sprintf(... 'Scalp tessellation %s was not found in %s.',OPTIONS.BEM.EnvelopeNames{end}.TessName, OPTIONS.BEM.EnvelopeNames{end}.TessFile),... 'Error during BEM computation') return end SubjectFV.vertices = Vertices{idScalp}'; clear Vertices SubjectFV.faces = Faces{idScalp}; clear Faces end end end % if BEM if EEG switch(lower(OPTIONS.Method{DataType.EEG})) case 'eeg_sphere' [Param(EEGndx).EEGType] = deal('EEG_SINGLE'); case 'eeg_3sphere' [Param(EEGndx).EEGType] = deal('EEG_3SHELL'); case 'eeg_3sphereberg' [Param(EEGndx).EEGType] = deal('EEG_BERG'); case 'eeg_os' [Param(EEGndx).EEGType] = deal('EEG_OS'); case 'eeg_bem' [Param(EEGndx).EEGType] = deal('BEM'); if EEG & ~MEG [Param(EEGndx).bem_gaingrid_mfname] = deal(BEMGaingridFileName); end end else tmp = []; [Param.Conductivity] = deal(tmp); [Param.Berg] = deal(tmp); [Param.EEGType] = deal(tmp); end %_________________________________________________________________________________________________________________________________________________________________________ % % The following part is an adaptation of the former HEADMODEL_MAKE script % % ________________________________________________________________________________________________________________________________________________________________________ % Allocate function names depending on the selected forward approaches specified in the Method argument Function = cell(1,length(Channel)); %allocate function names if MEG if ~isempty(findstr('bem',OPTIONS.Method{DataType.MEG})) % MEG BEM Function(MEGndx) = deal({'meg_bem'}); if isfield(Channel(MEGndx(1)),'irefsens') Function(Channel(MEGndx(1)).irefsens) = deal({'meg_bem'}); end else Function(MEGndx) = deal({'os_meg'}); if isfield(Channel(MEGndx(1)),'irefsens') Function(Channel(MEGndx(1)).irefsens) = deal({'os_meg'}); end if isfield(OPTIONS,'BEM') OPTIONS = rmfield(OPTIONS,'BEM'); end end end if EEG if ~isempty(findstr('bem',OPTIONS.Method{DataType.EEG})) % MEG BEM Function(EEGndx) = deal({'eeg_bem'}); else Function(EEGndx) = deal({'eeg_sph'}); if isfield(OPTIONS,'BEM') OPTIONS = rmfield(OPTIONS,'BEM'); end end end %-------------------------------------------------------------------------- DIMS = [3 12]; % number of columns for each parametric source model: Current Dipole / Current Multipole HeadModel.Param = Param; HeadModel.Function = Function; %% ------------------------------------------------------------------------- % % Now proceed to forward modeling of cortical grids or at some other specific source locations % %% ------------------------------------------------------------------------- if ~isempty(OPTIONS.Cortex), % subject has cortical vertices as source supports % First make room in memory HeadModel.SearchGain = []; clear SearchGridLoc SearchGain G if OPTIONS.Verbose, bst_message_window({... 'Computing Gain Matrix '}) end % Find the cortical grid where to compute the forward model in the tessellation file try ImageGrid = load(fullfile(User.SUBJECTS,OPTIONS.Cortex.FileName),'Comment','Vertices'); catch ImageGrid = OPTIONS.Cortex.ImageGrid; end if ~isfield(OPTIONS.Cortex,'iGrid') OPTIONS.Cortex.iGrid = 1; end if OPTIONS.Cortex.iGrid > length(ImageGrid.Comment) % Corresponding cortical surface not found errordlg(sprintf('Cortical Tessellation file "%s" does not contain %d surfaces',... OPTIONS.Cortex.FileName,OPTIONS.Cortex.iGrid)) return end GridLoc = ImageGrid.Vertices{OPTIONS.Cortex.iGrid}; % keep only the desired cell ImageGrid = rmfield(ImageGrid,'Vertices'); elseif ~isempty(OPTIONS.SourceLoc) % Specific source locations are provided if size(OPTIONS.SourceLoc,1) ~= 3 OPTIONS.SourceLoc = OPTIONS.SourceLoc'; end GridLoc = OPTIONS.SourceLoc; else rmfield(OPTIONS,'rooot'); if nargout == 1 varargout{1} = OPTIONS; else varargout{1} = HeadModel; varargout{2} = OPTIONS; end return % No ImageGrid requested end if ~isempty(OPTIONS.Cortex) GridName{OPTIONS.Cortex.iGrid} = ImageGrid.Comment{OPTIONS.Cortex.iGrid}; OPTIONS.Cortex.Name = ImageGrid.Comment{OPTIONS.Cortex.iGrid}; end for Order = OPTIONS.SourceModel % Compute gain matrices for each requested source models (-1 0 1) i = 1; % Index to cell in headmodel cell arrays (MMII convention) switch(Order) case -1 Dims = DIMS(1);% number of columns per source case 1 Dims = DIMS(2);% number of columns per source end if ~isempty(OPTIONS.Cortex) & OPTIONS.ApplyGridOrient % Use cortical grid try load(OPTIONS.Cortex.FileName,'Faces'); catch Faces = ImageGrid.Faces; end Faces = Faces{OPTIONS.Cortex.iGrid}; ptch = patch('Vertices',GridLoc','Faces',Faces,'Visible','off'); set(get(ptch,'Parent'),'Visible','off') GridOrient{i} = get(ptch,'VertexNormals')'; delete(ptch); end if isempty(OPTIONS.GridOrient) & isempty(OPTIONS.SourceOrient) % Consider the cortical patch's normals if isempty(OPTIONS.Cortex) % Specific source locations in .SourceLoc but nohing in. SourceOrient OPTIONS.ApplyGridOrient = 0; % No source orientation specified: Force computation of full gain matrix else [nrm,GridOrient{i}] = colnorm(GridOrient{i}); % Now because some orientations may be ill-set to [0 0 0] with the get(*,'VertexNormals' command) % set these orientation to arbitrary [1 1 1]: izero = find(nrm == 0);clear nrm if ~isempty(izero) GridOrient{i}(:,izero) = repmat([1 1 1]'/norm([1 1 1]),1,length(izero)); end clear izero end elseif ~isempty(OPTIONS.GridOrient) % Apply user-defined cortical source orientations if size(OPTIONS.GridOrient,2) == size(GridLoc,2) % Check size integrity GridOrient{i} = OPTIONS.GridOrient; [nrm,GridOrient{i}] = colnorm(GridOrient{i}); clear nrm else errordlg(sprintf('The source orientations you have provided are for %0.f sources. Considered cortical surface has %0.f sources. Computation aborted',... size(OPTIONS.GridOrient,2),size(GridOrient{i},2))); return end elseif ~isempty(OPTIONS.SourceOrient) % Apply user-defined specific source orientations if size(OPTIONS.SourceOrient,2) == size(GridLoc,2) % Check size integrity GridOrient{i} = OPTIONS.SourceOrient; [nrm,GridOrient{i}] = colnorm(GridOrient{i}); clear nrm else errordlg(sprintf('The source orientations you have provided are for %0.f sources. Computation aborted',... size(OPTIONS.SourceOrient,2))); return end end nv = size(GridLoc,2); % number of grid points jj = 0; % Number of OPTIONS.ImageGridBlockSize for j = 1:(OPTIONS.ImageGridBlockSize):nv, jj = jj+1; if 1%OPTIONS.ApplyGridOrient ndx = [0:OPTIONS.ImageGridBlockSize-1]+j; else ndx = [0:3*OPTIONS.ImageGridBlockSize-1]+j; end if 1%OPTIONS.ApplyGridOrient if(ndx(end) > nv), % last OPTIONS.ImageGridOPTIONS.ImageGridBlockSizeSize too long ndx = [ndx(1):nv]; end else if(ndx(end) > 3*nv), ndx = [ndx(1):3*nv]; end end % Compute MEG if MEG & ~isempty(MEGndx) Gmeg = NaN*zeros(length(MEGndx),Dims*length(ndx)); if ~isempty(Function{MEGndx(1)}) if MEG & EEG clear('gain_bem_interp2'); % Free persistent variables to avoid confusion end if isfield(OPTIONS,'BEM') % BEM computation if ~OPTIONS.BEM.Interpolative % ~interpolative : retrieve stored gain matrix global GBEM_grid tmpndx = [3*(ndx(1)-1)+1:min([3*nv,3*ndx(end)])];%[0:3*OPTIONS.ImageGridBlockSize-1]+j; Gmeg = GBEM_grid(MEGndx,tmpndx); end else Gmeg = feval(Function{MEGndx(1)},GridLoc(:,ndx),Channel,Param,Order,OPTIONS.Verbose); end end else Gmeg = []; end if EEG & ~isempty(EEGndx) & i==1 % % Order -1 only for now in EEG Geeg = NaN*zeros(length(EEGndx),Dims*length(ndx)); if ~isempty(Function{EEGndx(1)}) if MEG & EEG clear('gain_bem_interp2'); % Free persistent variables to avoid confusion end if isfield(OPTIONS,'BEM') % BEM computation if ~OPTIONS.BEM.Interpolative % ~interpolative : retrieve stored gain matrix global GBEM_grid %Geeg = GBEM_grid(EEGndx,[j:min([3*nv,j+3*OPTIONS.ImageGridBlockSize-1])]); tmpndx = [3*(ndx(1)-1)+1:min([3*nv,3*ndx(end)])];%[0:3*OPTIONS.ImageGridBlockSize-1]+j; %min(tmpndx ), max(tmpndx) Geeg = GBEM_grid(EEGndx,tmpndx); end else Geeg = feval(Function{EEGndx(1)},GridLoc(:,ndx),Channel,Param,Order,OPTIONS.Verbose); end end else Geeg = []; end G = NaN*zeros(length(OPTIONS.Channel),length(ndx)); Gxyz = NaN*zeros(length(OPTIONS.Channel),Dims*length(ndx)); if OPTIONS.ApplyGridOrient % Gain matrix with fixed orientation - G %------------------------------------------------------------------ src = 0; src_ind = 0; for k = 1:Dims:Dims*length(ndx)-2 src = src+1; src_ind = src_ind+1; if ~isempty(Gmeg) G(MEGndx,src) = Gmeg(:,k:k+2) * GridOrient{1}(:,src_ind); end if ~isempty(Geeg) & (i==1)% % Order -1 only G(EEGndx,src) = Geeg(:,k:k+2) * GridOrient{1}(:,src_ind); end end else if MEG Gxyz(MEGndx,:) = Gmeg; end if EEG Gxyz(EEGndx,:) = Geeg; end end % Gain matrix for moments - Gxyz %------------------------------------------------------------------ if MEG Gxyz(MEGndx,:) = Gmeg; end if EEG Gxyz(EEGndx,:) = Geeg; end end end % Cortical gain matrix for each source model if nargout == 1 varargout{1} = OPTIONS; end if nargout == 2 varargout{1} = G; varargout{2} = Gxyz; end if nargout == 3 varargout{1} = G; varargout{2} = Gxyz; varargout{3} = OPTIONS; end %------------------------------------------------------------------------------------------------------------------------------ % % SUB-FUNCTIONS % %------------------------------------------------------------------------------------------------------------------------------ function BEMGaingridFname = bem_GainGrid(DataType,OPTIONS,BEMChanNdx) % Computation of the BEM gain matrix on the 3D interpolative grid for MEG and/or EEG data % DataType : a structure with fields MEG and EEG. DataType.MEG (res. DataType.EEG) is set to 1 if MEG (res. EEG) data is available % OPTIONS : the OPTIONS structure, input argument from bst_headmodeler % BEMChanNdx : a cell array of channel indices such that : BEMChanNdx{DataType.EEG} = EEGndx (res. MEG). % % BEMGaingridFname: a structure with fields: % .EEG : string with the name of the file containing the gain matrix of the 3D BEM interpolative grid in EEG % .MEG : same as .EEG respectively to MEG BEM model. % Detect the requested BEM computations: MEG and/or EEG___________________________________ %User = get_user_directory; %if isempty(User) User.STUDIES = pwd; User.SUBJECTS = pwd; %end MEG = ~isempty(BEMChanNdx(DataType.MEG)); % == 1 if MEG is requested EEG = ~isempty(BEMChanNdx(DataType.EEG)); % == 1 if EEG is requested if MEG MEGndx = BEMChanNdx{DataType.MEG}; end if EEG %EEGndx = BEMChanNdx{DataType.EEG}; EEGndx = OPTIONS.EEGndx; % EEG sensors (not including EEG reference channel, if any) EEGREFndx = good_channel(OPTIONS.Channel,[],'EEG REF'); end if MEG & EEG [Param(:).mode] = deal(3); elseif ~MEG & EEG [Param(:).mode] = deal(1); elseif MEG & ~EEG [Param(:).mode] = deal(2); else errordlg('Please check that the method requested for forward modeling has an authorized name'); return end % BEM parameters ________________________________________________________________________ % Determine what basis functions to use constant = ~isempty(strmatch('constant',lower(OPTIONS.BEM.Basis))); if constant == 0 [Param(:).basis_opt] = deal(1); else [Param(:).basis_opt] = deal(0); end % Determine what Test to operate collocation = ~isempty(strmatch('collocation',lower(OPTIONS.BEM.Test))); if collocation == 0 [Param(:).test_opt] = deal(1); else [Param(:).test_opt] = deal(0); end % Insulated-skull approach isa = OPTIONS.BEM.ISA; if isa == 1 [Param(:).ISA] = deal(1); else [Param(:).ISA] = deal(0); end Param.Ntess_max = OPTIONS.BEM.NVertMax; Param.Conductivity = deal(OPTIONS.Conductivity); %_________________________________________________________________________________________ % Load surface envelopes information______________________________________________________ % Find the indices of the enveloppes selected for BEM computation if ~isfield(OPTIONS.BEM,'EnvelopeNames') errordlg('Please specify the ordered set of head-tissue envelopes by filling the OPTIONS.BEM.EnvelopeNames field') return end if isempty(OPTIONS.BEM.EnvelopeNames) errordlg('Please specify the ordered set of head-tissue envelopes by filling the OPTIONS.BEM.EnvelopeNames field') return end for k = 1:length(OPTIONS.BEM.EnvelopeNames) try % Changed by Rik 4/10/07 to call from SPM without User files load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Comment'); catch try load(OPTIONS.BEM.EnvelopeNames{end}.TessFile,'Comment'); %%%%%% catch % Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile try OPTIONS.BEM.EnvelopeNames{k}.TessFile = [OPTIONS.BEM.EnvelopeNames{k}.TessFile,'.mat']; load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Comment'); catch cd(User.SUBJECTS) load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Comment'); end end end Comment = strrep(Comment,' ',''); % find surface in current tessellation file OPTIONS.BEM.EnvelopeNames{k}.SurfId = find(strcmpi(OPTIONS.BEM.EnvelopeNames{k}.TessName,Comment)); IDs(k) = OPTIONS.BEM.EnvelopeNames{k}.SurfId; if isempty(OPTIONS.BEM.EnvelopeNames{k}.SurfId) errordlg(... sprintf('Surface %s was not found in file %s',... OPTIONS.BEM.EnvelopeNames{k}.TessName, OPTIONS.BEM.EnvelopeNames{k}.TessFile)) return end % Load vertex locations try tmp = load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Vertices'); catch % Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile tmp = load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Vertices'); end Vertices{k} = tmp.Vertices{OPTIONS.BEM.EnvelopeNames{k}.SurfId}'; % Load faces try tmp = load(fullfile(User.SUBJECTS,OPTIONS.subjectpath,OPTIONS.BEM.EnvelopeNames{k}.TessFile),'Faces'); catch% Maybe user is using command line call to function with absolute-referenced files OPTIONS.*.TessFile tmp = load(OPTIONS.BEM.EnvelopeNames{k}.TessFile,'Faces'); end Faces(k) = tmp.Faces(OPTIONS.BEM.EnvelopeNames{k}.SurfId); end clear Comment tmp cd(User.STUDIES) %_________________________________________________________________________________________ % Channel Parameters______________________________________________________________________ if MEG R_meg1 = zeros(length(MEGndx),3); O_meg1 = R_meg1; R_meg2 = R_meg1; O_meg2 = O_meg1; flaggrad = zeros(length(MEGndx),1);% if = 1 - Flag to indicate there are some gradiometers here i = 0; for k = MEGndx i = i+1; R_meg1(i,:) = OPTIONS.Channel(k).Loc(:,1)'; O_meg1(i,:) = OPTIONS.Channel(k).Orient(:,1)'; if size(OPTIONS.Channel(k).Loc,2) == 2 if sum(OPTIONS.Channel(k).Loc(:,1)-OPTIONS.Channel(k).Loc(:,2))~=0 % Gradiometer R_meg2(i,:) = OPTIONS.Channel(k).Loc(:,2)'; O_meg2(i,:) = OPTIONS.Channel(k).Orient(:,2)'; flaggrad(k-min(MEGndx)+1) = 1; end end end O_meg1 = (O_meg1' * inorcol(O_meg1'))'; if exist('O_meg2','var') O_meg2 = (O_meg2' * inorcol(O_meg2'))'; end % Handle MEG reference channels if necessary irefsens = good_channel(OPTIONS.Channel,[],'MEG REF'); if ~isempty(irefsens) flaggrad_REF = zeros(length(irefsens),1);% if = 1 - Flag to indicate there are some gradiometers here R_meg_REF = zeros(length(irefsens),3); O_meg_REF = R_meg_REF; R_meg_REF = R_meg_REF; O_meg_REF = R_meg_REF; if ~isempty(irefsens) & ~isempty(OPTIONS.Channel(MEGndx(1)).Comment) % Reference Channels are present if OPTIONS.Verbose, bst_message_window('Reference Channels have been detected.'), end end i = 0; for k = irefsens i = i+1; R_meg_REF(i,:) = OPTIONS.Channel(k).Loc(:,1)'; O_meg_REF(i,:) = OPTIONS.Channel(k).Orient(:,1)'; if size(OPTIONS.Channel(k).Loc,2) == 2 if sum(OPTIONS.Channel(k).Loc(:,1)-OPTIONS.Channel(k).Loc(:,2))~=0 % Reference Gradiometer R_meg_REF2(i,:) = OPTIONS.Channel(k).Loc(:,2)'; O_meg_REF2(i,:) = OPTIONS.Channel(k).Orient(:,2)'; flaggrad_REF(k-min(irefsens)+1) = 1; end end end else R_meg_REF = []; O_meg_REF = R_meg_REF; R_meg_REF = R_meg_REF; O_meg_REF = R_meg_REF; end MEGndx_orig = MEGndx; else R_meg1 = zeros(length(EEGndx),3); % Use dummy channel locations O_meg1 = R_meg1; R_meg2 = R_meg1; O_meg2 = O_meg1; end if EEG R_eeg = zeros(length([EEGREFndx,EEGndx]),3); i = 0; for k = [EEGREFndx,EEGndx] i = i+1; R_eeg(i,:) = OPTIONS.Channel(k).Loc(:,1)'; end if ~MEG flaggrad = []; irefsens = []; end else R_eeg = NaN * zeros(size(R_meg1)); % Dummy coordinates end %_________________________________________________________________________________________ %Compute Transfer Matrices__________________________________________________________________ BrainStorm.iscalp = IDs(end); % Index of the outermost surface (scalp, supposedly) eeg_answ = ''; meg_answ = ''; % Check whether some transfer-matrix files already exist for current study fn_eeg = sprintf('%s_eegxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); fn_meg = sprintf('%s_megxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); if MEG test = exist(fn_meg,'file'); elseif EEG test = exist(fn_eeg,'file'); else MEG& EEG test = exist(fn_eeg,'file') & exist(fn_meg,'file'); end if (OPTIONS.BEM.ForceXferComputation | ~test) | OPTIONS.BEM.Interpolative % Force (re)computation of transfer matrices, even if files exist in current study folder % if OPTIONS.Verbose, bst_message_window('Computing the BEM Transfer Matrix (this may take a while)....'), end global nfv nfv = bem_xfer(R_eeg,R_meg1,O_meg1,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ... Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg,Param.Ntess_max,OPTIONS.Verbose,OPTIONS.BEM.checksurf); if ~isempty(find(flaggrad)) if OPTIONS.Verbose, bst_message_window({'Gradiometers detected',... 'Computing corresponding Gain Matrix. . .'}), end %fn_meg_2 = fullfile(pwd,[OPTIONS.rooot,'_megxfer_2.mat']); fn_meg_2 = sprintf('%s_megxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); bem_xfer(R_eeg,R_meg2,O_meg2,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ... Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_2,Param.Ntess_max,0,OPTIONS.BEM.checksurf); % Verbose = 0 if OPTIONS.Verbose, bst_message_window('Gradiometer Channel Gain Matrix is Completed.'), end end if ~isempty(irefsens) % Do the same for reference channels %fn_meg_REF = fullfile(pwd,[OPTIONS.rooot,'_megxfer_REF.mat']); fn_meg_REF = sprintf('%s_megREFxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); bem_xfer(R_eeg,R_meg_REF,O_meg_REF,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ... Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_REF,Param.Ntess_max,0,OPTIONS.BEM.checksurf);% Verbose = 0 if ~isempty(find(flaggrad_REF)) if OPTIONS.Verbose, bst_message_window({'MEG Reference Channels detected',... 'Computing corresponding Gain Matrix. . .'}), end %fn_meg_REF2 = fullfile(pwd,[OPTIONS.rooot,'_megxfer_REF2.mat']); fn_meg_REF2 = sprintf('%s_megREFxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); bem_xfer(R_eeg,R_meg_REF2,O_meg_REF2,Vertices,Faces,Param(1).Conductivity,Param(1).mode, ... Param(1).basis_opt,Param(1).test_opt,Param(1).ISA,fn_eeg,fn_meg_REF2,Param.Ntess_max,0,OPTIONS.BEM.checksurf);% Verbose = 0 if OPTIONS.Verbose, bst_message_window('MEG Reference Channel Gain Matrix is Completed.'), end end end end % Computation of TRANSFER MATRIX Completed ___________________________________________________ %%%% THIS PART SPECIFIES PARAMETERS USED TO GENERATE THE 3-D GRID %%%%%%%%%% if OPTIONS.BEM.Interpolative%1%~exist(BEMGridFileName,'file') if OPTIONS.Verbose, bst_message_window('Computing BEM Interpolative Grid. . .'), end BEMGridFileName = [OPTIONS.rooot,'grid.mat']; % update tessellated envelope with surfaces possibly modified by % BEM_XFER (downsampling, alignment, embedding etc.) Vertices = {nfv(:).vertices}; Faces = {nfv(:).faces}; gridmaker(Vertices,Faces,BEMGridFileName,OPTIONS.Verbose); if OPTIONS.Verbose, bst_message_window('Computing BEM Interpolative Grid -> DONE'), % Visualization of surfaces + grid points for k = 1:length(Vertices) [hf,hs(k),hl] = view_surface('Head envelopes & a subset of BEM interpolative grid points',Faces{k},Vertices{k}); view(90,0) delete(hl) end camlight rotate3d on set(hs(1),'FaceAlpha',.3,'edgealpha',.3,'edgecolor','none','facecolor','r') set(hs(2),'FaceAlpha',.2,'edgealpha',.2,'edgecolor','none','facecolor','g') set(hs(3),'FaceAlpha',.1,'edgealpha',.1,'edgecolor','none','facecolor','b') hold on load(BEMGridFileName) hgrid = scatter3(Rq_bemgrid(1:10:end,1),Rq_bemgrid(1:10:end,2),Rq_bemgrid(1:10:end,3),'.','filled'); end else global GBEM_grid % Grid points are the locations of the distributed sources if isempty(OPTIONS.Cortex) % CBB (SB, 07-May-2004)| Should work also for volumic grid errordlg('Please select a cortical grid for computation of BEM vector fields') return end try load(OPTIONS.Cortex.FileName); % Load tessellation supporting the source locations and orientations catch Users = get_user_directory; load(fullfile(Users.SUBJECTS,OPTIONS.Cortex.FileName)); % Load tessellation supporting the source locations and orientations end BEMGridFileName.Loc = Vertices{OPTIONS.Cortex.iGrid}; clear Vertices if OPTIONS.ApplyGridOrient % Take cortex normals into account ptch = patch('Vertices',BEMGridFileName.Loc','Faces',Faces{OPTIONS.Cortex.iGrid},'Visible','off'); set(get(ptch,'Parent'),'Visible','off') clear Faces BEMGridFileName.Orient = get(ptch,'VertexNormals')'; delete(ptch); [nrm,BEMGridFileName.Orient] = colnorm(BEMGridFileName.Orient); % Now because some orientations may be ill-set to [0 0 0] with the get(*,'VertexNormals' command) % set these orientation to arbitrary [1 1 1]: izero = find(nrm == 0);clear nrm if ~isempty(izero) BEMGridFileName.Orient(:,izero) = repmat([1 1 1]'/norm([1 1 1]),1,length(izero)); end clear izero else BEMGridFileName.Orient = []; end %if OPTIONS.Verbose, bst_message_window(sprintf('Loading BEM interpolative grid points from %s', BEMGridFileName)), end end % This part computes the gain matrices defined on precomputed grid------------------------------------------------------------ % Assign file names where to store the gain matrices if MEG & ~EEG bem_xfer_mfname = {fn_meg}; %BEMGaingridFname = [OPTIONS.rooot,'_meggain_grid.mat']; BEMGaingridFname = sprintf('%s_MEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); test = exist(BEMGaingridFname,'file'); elseif EEG & ~ MEG bem_xfer_mfname = {fn_eeg}; %BEMGaingridFname = [OPTIONS.rooot,'_eeggain_grid.mat']; BEMGaingridFname = sprintf('%s_EEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); test = exist(BEMGaingridFname,'file'); elseif EEG & MEG bem_xfer_mfname = {fn_meg,fn_eeg}; % BEMGaingridFname.MEG = [OPTIONS.rooot,'_meggain_grid.mat']; % BEMGaingridFname.EEG = [OPTIONS.rooot,'_eeggain_grid.mat']; BEMGaingridFname.MEG = sprintf('%s_MEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); BEMGaingridFname.EEG = sprintf('%s_EEGGainGrid_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); test = exist(BEMGaingridFname.MEG,'file') & exist(BEMGaingridFname.EEG,'file'); end if 1%OPTIONS.BEM.ForceXferComputation | ~test% Recompute gain matrices when transfer matrices have been recomputed just before if OPTIONS.Verbose if OPTIONS.BEM.Interpolative bst_message_window('Computing the BEM gain matrix for interpolative grid. . .'), else bst_message_window('Computing the BEM gain matrix for source grid. . .'), end end t0 = clock; if OPTIONS.Verbose, if MEG & EEG bst_message_window('for MEG and EEG channels. . .') elseif EEG bst_message_window('for EEG channels. . .') elseif MEG bst_message_window('for MEG channels. . .') end end if length(bem_xfer_mfname) == 1 % xor(MEG,EEG) bem_gain(BEMGridFileName,bem_xfer_mfname{1},Param(1).ISA,BEMGaingridFname, OPTIONS.Verbose); else % MEG gaingrid matrix bem_gain(BEMGridFileName,bem_xfer_mfname{1},Param(1).ISA,BEMGaingridFname.MEG, OPTIONS.Verbose); % EEG gaingrid matrix bem_gain(BEMGridFileName,bem_xfer_mfname{2},Param(1).ISA,BEMGaingridFname.EEG, OPTIONS.Verbose); end if OPTIONS.Verbose, bst_message_window('-> DONE'), end if ~isempty(find(flaggrad)) % Compute forward model on the second set of magnetometers from the gradiometers array bem_xfer_mfname = sprintf('%s_megxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); bem_gaingrid_mfname_2 = sprintf('%s_MEGGainGrid2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); if OPTIONS.Verbose, bst_message_window('MEG - completing gradiometers. . .'), end bem_gain(BEMGridFileName,bem_xfer_mfname,Param(1).ISA,bem_gaingrid_mfname_2,OPTIONS.Verbose); if OPTIONS.Verbose, bst_message_window('-> DONE'), end if MEG & EEG G1 = load(BEMGaingridFname.MEG); else G1 = load(BEMGaingridFname); end G2 = load(bem_gaingrid_mfname_2); % Apply respective weights within the gradiodmeters meg_chans = [OPTIONS.Channel(MEGndx(find(flaggrad))).Weight]; w1 = meg_chans(1:2:end); w2 = meg_chans(2:2:end); G1.GBEM_grid(find(flaggrad),:) = w1'*ones(1,size(G1.GBEM_grid,2)).*G1.GBEM_grid(find(flaggrad),:)... + w2' * ones(1,size(G1.GBEM_grid,2)).*G2.GBEM_grid(find(flaggrad),:); clear G2 % is there special reference channel considerations? if ~isempty(irefsens) % Forward model on all reference sensors bem_xfer_mfname_REF = sprintf('%s_megREFxfer_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); bem_gaingrid_mfname_REF = sprintf('%s_MEGGainGrid_REF_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); if OPTIONS.Verbose, bst_message_window('MEG reference channels. . .'), end bem_gain(BEMGridFileName,bem_xfer_mfname_REF,Param(1).ISA,bem_gaingrid_mfname_REF,OPTIONS.Verbose); if OPTIONS.Verbose, bst_message_window('-> DONE'), end if ~isempty(find(flaggrad_REF)) % Gradiometers are present in reference channels bem_xfer_mfname_REF2 = sprintf('%s_megREFxfer2_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); bem_gaingrid_mfname_REF2 = sprintf('%s_MEGGainGrid2_REF_%s_%s.mat',OPTIONS.rooot, OPTIONS.BEM.Basis,OPTIONS.BEM.Test); if OPTIONS.Verbose, bst_message_window('MEG reference channels / completing gradiometers. . .'), end bem_gain(BEMGridFileName,bem_xfer_mfname_REF2,Param(1).ISA,bem_gaingrid_mfname_REF2,OPTIONS.Verbose); if OPTIONS.Verbose, bst_message_window('-> DONE'), end GR = load(bem_gaingrid_mfname_REF); GR2 = load(bem_gaingrid_mfname_REF2); meg_chans = [OPTIONS.Channel(irefsens(find(flaggrad_REF))).Weight]; w1 = meg_chans(1:2:end); w2 = meg_chans(2:2:end); GR.GBEM_grid(find(flaggrad_REF),:) = w1'*ones(1,size(GR.GBEM_grid,2)).*GR.GBEM_grid(find(flaggrad_REF),:)... + w2' * ones(1,size(GR.GBEM_grid,2)).*GR2.GBEM_grid(find(flaggrad_REF),:); %GR.GBEM_grid(find(flaggrad_REF),:) = GR.GBEM_grid(find(flaggrad_REF),:) - GR2.GBEM_grid(find(flaggrad_REF),:); clear GR2; end % Apply nth-order gradient correction on good channels only %Weight by the current nth-order correction coefficients %G1.GBEM_grid = G1.GBEM_grid - Channel(MEGndx(1)).Gcoef(find(ChannelFlag(irefsens)>0),:)*GR.GBEM_grid; G1.GBEM_grid = G1.GBEM_grid - OPTIONS.Channel(MEGndx(1)).Comment*GR.GBEM_grid; end GBEM_grid = 1e-7*G1.GBEM_grid; if MEG & EEG save(BEMGaingridFname.MEG,'GBEM_grid','-append'); else save(BEMGaingridFname,'GBEM_grid','-append'); end end % Detect EEG reference - if none is specified in the .Comment or Type fields, % and if none was passed through OPTIONS.EEGRef % -> Apply average-referencing of the potentials by default. if EEG % EEG Reference Channel EEGREFndx = good_channel(OPTIONS.Channel,[],'EEG REF'); if MEG & EEG load(BEMGaingridFname.EEG,'GBEM_grid') else load(BEMGaingridFname,'GBEM_grid') end if isempty(EEGREFndx)% AVERAGE REF GBEM_grid = GBEM_grid - repmat(mean(GBEM_grid),size(GBEM_grid,1),1); else % GBEM_grid = GBEM_grid(setdiff(EEGndx,EEGREFndx)-EEGndx(1)+1,:) - repmat(GBEM_grid(EEGREFndx-EEGndx(1)+1,:),size(GBEM_grid(setdiff(EEGndx,EEGREFndx)-EEGndx(1)+1,:),1),1); GBEM_grid = GBEM_grid(2:end,:) - repmat(GBEM_grid(1,:),length(EEGndx),1); % SB : EEG REF is stored as first sensor in GBEM_grid; see line 2226 end if MEG save(BEMGaingridFname.EEG,'GBEM_grid','-append') else save(BEMGaingridFname,'GBEM_grid','-append') end end if MEG & EEG meg = load(BEMGaingridFname.MEG,'GBEM_grid'); eeg = load(BEMGaingridFname.EEG,'GBEM_grid'); GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2)); GBEM_grid(MEGndx,:)= meg.GBEM_grid; clear meg GBEM_grid(EEGndx,:)= eeg.GBEM_grid; clear eeg elseif MEG meg = load(BEMGaingridFname,'GBEM_grid'); % Changed by Rik (to make it work!) % GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2)); GBEM_grid = zeros(length(OPTIONS.Channel),size(meg.GBEM_grid,2)); GBEM_grid(MEGndx,:)= meg.GBEM_grid; clear meg elseif EEG eeg = load(BEMGaingridFname,'GBEM_grid'); GBEM_grid = zeros(length(OPTIONS.Channel),size(GBEM_grid,2)); EEGndx = OPTIONS.EEGndx; GBEM_grid(EEGndx,:)= eeg.GBEM_grid; clear eeg %clear GBEM_grid % % Now save the combined MEG/EEG gaingrid matrix in a single file % MEGEEG_BEMGaingridFname = strrep(BEMGaingridFname.EEG,'eeg','meg_eeg'); % Gmeg = load(BEMGaingridFname.MEG,'GBEM_grid'); % GBEM_grid = NaN * zeros(length(OPTIONS.Channel),size(Gmeg.GBEM_grid,2)); % GBEM_grid(MEGndx,:) = Gmeg.GBEM_grid; clear Gmeg % eeg = load(BEMGaingridFname.EEG); % % save_fieldnames(eeg,MEGEEG_BEMGaingridFname); % % GBEM_grid(setdiff(EEGndx,EEGREFndx),:) = eeg.GBEM_grid; clear eeg % % save(MEGEEG_BEMGaingridFname,'GBEM_grid','-append') % % BEMGaingridFname = MEGEEG_BEMGaingridFname; else save(BEMGaingridFname,'GBEM_grid','-append') end telap_meg_interp = etime(clock,t0); end function g = gterm_constant(r,rq) %gterm_constant % function g = gterm_constant(r,rq) %<autobegin> -------- 20-Nov-2002 14:06:02 ------------------------------ % ---- Automatically Generated Comments Block using auto_comments ----------- % % Alphabetical list of external functions (non-Matlab): % toolbox\rownorm.m %<autoend> ---------- 20-Nov-2002 14:06:02 ------------------------------ if size(rq,1) == 1 % Just one dipole r_rq= [r(:,1)-rq(1),r(:,2)-rq(2),r(:,3)-rq(3)]; n = rownorm(r_rq).^3; g = r_rq./[n,n,n]; else g = zeros(size(r,1),3*size(rq,1)); isrc = 1; for k = 1:size(rq,1) r_rq= [r(:,1)-rq(k,1),r(:,2)-rq(k,2),r(:,3)-rq(k,3)]; n = rownorm(r_rq).^3; g(:,3*(isrc-1)+1: 3*isrc) = r_rq./[n,n,n]; isrc = isrc + 1; end end
github
spm/spm5-master
spm_config_slice_timing.m
.m
spm5-master/spm_config_slice_timing.m
7,569
utf_8
2c1d50399145c9dff01b929a2de64556
function opts = spm_config_slice_timing % configuration file for slice timing %____________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Darren Gitelman % $Id: spm_config_slice_timing.m 1032 2007-12-20 14:45:55Z john $ % --------------------------------------------------------------------- scans.type = 'files'; scans.name = 'Session'; scans.tag = 'scans'; scans.filter = 'image'; scans.num = [2 Inf]; scans.help = {'Select images to acquisition correct.'}; % --------------------------------------------------------------------- data.type = 'repeat'; data.name = 'Data'; data.values = {scans}; data.num = [1 Inf]; data.help = {[... 'Subjects or sessions. The same parameters specified below will ',... 'be applied to all sessions.']}; % --------------------------------------------------------------------- nslices.type = 'entry'; nslices.name = 'Number of Slices'; nslices.tag = 'nslices'; nslices.strtype = 'n'; nslices.num = [1 1]; nslices.help = {'Enter the number of slices'}; % --------------------------------------------------------------------- refslice.type = 'entry'; refslice.name = 'Reference Slice'; refslice.tag = 'refslice'; refslice.strtype = 'n'; refslice.num = [1 1]; refslice.help = {'Enter the reference slice'}; % --------------------------------------------------------------------- TR.type = 'entry'; TR.name = 'TR'; TR.tag = 'tr'; TR.strtype = 'r'; TR.num = [1 1]; TR.help = {'Enter the TR in seconds'}; % --------------------------------------------------------------------- TA.type = 'entry'; TA.name = 'TA'; TA.tag = 'ta'; TA.strtype = 'e'; TA.num = [1 1]; TA.help = {['The TA (in seconds) must be entered by the user. ',... 'It is usually calculated as TR-(TR/nslices). You can simply enter ',... 'this equation with the variables replaced by appropriate numbers.']}; % --------------------------------------------------------------------- sliceorder.type = 'entry'; sliceorder.name = 'Slice order'; sliceorder.tag = 'so'; sliceorder.strtype = 'e'; sliceorder.num = [1 Inf]; sliceorder.help = {... ['Enter the slice order. Bottom slice = 1. Sequence types ',... 'and examples of code to enter are given below.'],... '',... 'ascending (first slice=bottom): [1:1:nslices]',... '',... 'descending (first slice=top): [nslices:-1:1]',... '',... 'interleaved (middle-top):',... ' for k = 1:nslices,',... ' round((nslices-k)/2 + (rem((nslices-k),2) * (nslices - 1)/2)) + 1,',... ' end',... '',... 'interleaved (bottom -> up): [1:2:nslices 2:2:nslices]',... '',... 'interleaved (top -> down): [nslices:-2:1, nslices-1:-2:1]'}; % --------------------------------------------------------------------- opts.type = 'branch'; opts.name = 'Slice Timing'; opts.tag = 'st'; opts.val = {data,nslices,TR,TA,sliceorder,refslice}; opts.prog = @slicetiming; opts.vfiles = @vfiles; opts.modality = {'FMRI'}; opts.help = {... ['Correct differences in image acquisition time between slices. '... 'Slice-time corrected files are prepended with an ''a''.'],... '',... ['Note: The sliceorder arg that specifies slice acquisition order is '... 'a vector of N numbers, where N is the number of slices per volume. '... 'Each number refers to the position of a slice within the image file. '... 'The order of numbers within the vector is the temporal order in which '... 'those slices were acquired. '... 'To check the order of slices within an image file, use the SPM Display '... 'option and move the cross-hairs to a voxel co-ordinate of z=1. This '... 'corresponds to a point in the first slice of the volume.'],... '',... ['The function corrects differences in slice acquisition times. '... 'This routine is intended to correct for the staggered order of '... 'slice acquisition that is used during echo-planar scanning. The '... 'correction is necessary to make the data on each slice correspond '... 'to the same point in time. Without correction, the data on one '... 'slice will represent a point in time as far removed as 1/2 the TR '... 'from an adjacent slice (in the case of an interleaved sequence).'],... '',... ['This routine "shifts" a signal in time to provide an output '... 'vector that represents the same (continuous) signal sampled '... 'starting either later or earlier. This is accomplished by a simple '... 'shift of the phase of the sines that make up the signal. '... 'Recall that a Fourier transform allows for a representation of any '... 'signal as the linear combination of sinusoids of different '... 'frequencies and phases. Effectively, we will add a constant '... 'to the phase of every frequency, shifting the data in time.'],... '',... ['Shifter - This is the filter by which the signal will be convolved '... 'to introduce the phase shift. It is constructed explicitly in '... 'the Fourier domain. In the time domain, it may be described as '... 'an impulse (delta function) that has been shifted in time the '... 'amount described by TimeShift. '... 'The correction works by lagging (shifting forward) the time-series '... 'data on each slice using sinc-interpolation. This results in each '... 'time series having the values that would have been obtained had '... 'the slice been acquired at the same time as the reference slice. '... 'To make this clear, consider a neural event (and ensuing hemodynamic '... 'response) that occurs simultaneously on two adjacent slices. Values '... 'from slice "A" are acquired starting at time zero, simultaneous to '... 'the neural event, while values from slice "B" are acquired one '... 'second later. Without correction, the "B" values will describe a '... 'hemodynamic response that will appear to have began one second '... 'EARLIER on the "B" slice than on slice "A". To correct for this, '... 'the "B" values need to be shifted towards the Right, i.e., towards '... 'the last value.'],... '',... ['This correction assumes that the data are band-limited (i.e. there '... 'is no meaningful information present in the data at a frequency '... 'higher than that of the Nyquist). This assumption is support by '... 'the study of Josephs et al (1997, NeuroImage) that obtained '... 'event-related data at an effective TR of 166 msecs. No physio-'... 'logical signal change was present at frequencies higher than our '... 'typical Nyquist (0.25 HZ).'],... '',... ['Written by Darren Gitelman at Northwestern U., 1998. '... 'Based (in large part) on ACQCORRECT.PRO from Geoff Aguirre and '... 'Eric Zarahn at U. Penn.']}; % --------------------------------------------------------------------- function slicetiming(varargin) job = varargin{1}; Seq = job.so; TR = job.tr; TA = job.ta; nslices = job.nslices; refslice = job.refslice; timing(2) = TR - TA; timing(1) = TA / (nslices -1); for i = 1:length(job.scans) P = strvcat(job.scans{i}); spm_slice_timing(P,Seq,refslice,timing) end return; % --------------------------------------------------------------------- % --------------------------------------------------------------------- function vf = vfiles(varargin) job = varargin{1}; n = 0; for i=1:numel(job.scans), n = n + numel(job.scans{i}); end; vf = cell(n,1); n = 1; for i=1:numel(job.scans), for j = 1:numel(job.scans{i}) [pth,nam,ext,num] = spm_fileparts(job.scans{i}{j}); vf{n} = fullfile(pth,['a', nam, ext, num]); n = n+1; end end; return; % --------------------------------------------------------------------- % ---------------------------------------------------------------------
github
spm/spm5-master
ctf_read_meg4.m
.m
spm5-master/ctf_read_meg4.m
14,622
utf_8
999fb8dfe3a3dd39bcb904c6d62c1e79
function [ctf] = ctf_read_meg4(folder,ctf,CHAN,TIME,TRIALS,COEFS); % ctf_read_meg4 - read meg4 format data from a CTF .ds folder % % [ctf] = ctf_read_meg4([folder],[ctf],[CHAN],[TIME],[TRIALS]); % % This function reads all or select portions of the raw meg data matrix in % the .meg4 file within any .ds folder. It may call the ctf_read_res4 % function to identify the relevant parameters of the dataset. % % The .meg4 file contains the raw numbers sampled from the electronics. In % this function, these raw analog2digial numbers are multiplied by the % appropriate sensor gains, which are read from the .res4 file. However, % note that the data values returned can be very small (10^-12 Tesla), % which may be a problem for some computations. % % INPUTS % % If you do not wish to specify an input option, use [], but keep the order % of the input options as above. Only specify as many input options as % required. With no input options, the function will prompt for a folder, % call ctf_read_res4 and then read all of the data matrix. % % folder - the directory of the .ds data set to read. By % default, a gui prompts for the folder. % % ctf - a struct with setup, sensor and data fields. If the setup field is % missing or empty, this function calls ctf_read_res4. % % CHAN - a integer array of channel numbers to read. % eg, [30:35] reads channels 30 to 35. Also % If CHAN = 'eeg', read only eeg channels/sensorIndices % If CHAN = 'meg', read only meg channels/sensorIndices % If CHAN = 'ref', read only reference channels/sensorIndices % If CHAN = 'other', read only the other channels/sensorIndices % If CHAN = 'megeeg', read meg and eeg channels/sensorIndices % If CHAN = 'eegmeg', read eeg and meg channels/sensorIndices % % TIME - eg. [0 5] - the desired time interval to read, in sec. % If TIME = 'all', all data is read (the default) % % TRIALS - If TRIALS = n, the nth trial will be read. % If TRIALS = [3,5,8], reads trials 3,5, and 8 such that % ctf.data(:,:,1) = data for trial 3, % ctf.data(:,:,2) = data for trial 5, and % ctf.data(:,:,3) = data for trial 8. % If TRIALS = [3:7], reads trials 3 to 7 % If TRIALS = 'all', reads all data (the default) % % OUTPUTS % % ctf.data - matrix of all the data read, such that data(x,y,z) % contains sample point x, channel y and trial z. The % input options, CHAN, TIME, TRIALS can be used to % select subsections of the .meg4 data matrix % % ctf.sensor - has the following fields: % .names - cell array of sensor names % .location - array of sensor locations for plotting % .orientation - array of sensor orientations % % ctf.res4 - has the following fields % .file - the .res4 file path and file name % .header - the format of the .res4 file % % ctf.meg4 - has the following fields % .file - the .meg4 file path and file name % .header - the format of the .meg4 file % % % <>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> % % < > % % < DISCLAIMER: > % % < > % % < THIS PROGRAM IS INTENDED FOR RESEARCH PURPOSES ONLY. > % % < THIS PROGRAM IS IN NO WAY INTENDED FOR CLINICAL OR > % % < OFFICIAL USE. > % % < > % % <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<> % % % $Revision: 253 $ $Date: 2004/08/19 03:17:10 $ % Copyright (C) 2003 Darren L. Weber % % 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % Modified: 11/2003, Darren.Weber_at_radiology.ucsf.edu % - modified from NIH code simply to allocate data into % one large struct (ctf) % - modified channel selection section at the end so % that it doesn't try to get orientation information for % EEG channels % - changed ctf.data into a 3D matrix, rather than a % cell array of matrices % Modified: 07/2004, Arnaud Delorme, fixed reading time interval %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %----------------------------------------------- % ensure we have the data parameters if ~exist('COEFS','var'), COEFS = false; end if ~exist('folder','var'), if ~exist('ctf','var'), ctf = ctf_folder; else ctf = ctf_folder([],ctf); end else if ~exist('ctf','var'), ctf = ctf_folder(folder); else ctf = ctf_folder(folder,ctf); end end if ~isfield(ctf,'setup'), ctf = ctf_read_res4(ctf.folder,1,COEFS); end %-------------------------------------------------------------- ver = '$Revision: 253 $'; fprintf('\nCTF_READ_MEG4 [v %s]\n',ver(11:15)); tic; %---------------------------------------------------------------- % open the data file [folderPath,folderName,folderExt] = fileparts(ctf.folder); ctf.meg4.file = findmeg4file( ctf.folder ); [fid,message] = fopen(ctf.meg4.file,'rb','s'); if fid < 0, error('cannot open .meg4 file'); end %---------------------------------------------------------------- % Read the header % The data file consists of a header and the raw samples from the % electronics. The header is the 8-byte character sequence: MEG41CP+NULL. header_bytes = 8; ctf.meg4.header = char(fread(fid,[1,header_bytes],'char')); % check the format if strmatch('MEG41CP',ctf.meg4.header), % OK, we can handle this format else msg = sprintf('May not read "%s" format correctly',ctf.meg4.header); warning(msg); end %-------------------------------------------------------------- % check the function input parameters and assign any defaults if ~exist('CHAN','var'), CHAN = 'all'; end if ~exist('TIME','var'), TIME = 'all'; end if ~exist('TRIALS','var'), TRIALS = 'all'; end if isempty(CHAN), CHAN = 'all'; end if isempty(TIME), TIME = 'all'; end if isempty(TRIALS), TRIALS = 'all'; end CHAN = ctf_channel_select(ctf,CHAN); switch num2str(TIME), case 'all', TIME = ctf.setup.time_sec; TIME_index = 1:ctf.setup.number_samples; otherwise % assume the input is a range of times in sec % check the range if TIME(1) < ctf.setup.time_sec(1), fprintf('...setting TIME(1) = ctf.setup.time_sec(1)\n'); TIME(1) = ctf.setup.time_sec(1); end if TIME(end) > ctf.setup.time_sec(end), fprintf('...setting TIME(end) = ctf.setup.time_sec(end)\n'); TIME(end) = ctf.setup.time_sec(end); end % now find the nearest indices into the samples matrix TIME_index = intersect(find(ctf.setup.time_sec >= TIME(1)), find(ctf.setup.time_sec <= TIME(end))); % TIME_index = interp1(ctf.setup.time_sec,1:ctf.setup.number_samples,TIME,'nearest'); % now ensure that the TIME array is consistent with ctf.setup.time_sec TIME = ctf.setup.time_sec(TIME_index); end TIME = sort(TIME); % check the duration duration = TIME(end) - TIME(1); if duration > ctf.setup.duration_trial, fprintf('...TIME input too large for trial\n'); fprintf('...setting TIME = %g seconds (ctf.setup.duration_trial)',ctf.setup.duration_trial); duration = ctf.setup.duration_trial; end if duration <= 0, fprintf('...TIME(end) - TIME(1) is <= 0, quitting now!\n'); return end % calculate the number of samples selected number_samples = round((duration) * ctf.setup.sample_rate) + 1; switch num2str(TRIALS), case 'all', TRIALS = 1:ctf.setup.number_trials; otherwise % assume the input is an array of trials end TRIALS = unique(sort(TRIALS)); %---------------------------------------------------------------- % Calculate sensor gains megIndex = ctf.sensor.index.meg_sens; refIndex = ctf.sensor.index.meg_ref; eegIndex = ctf.sensor.index.eeg_sens; otherIndex = ctf.sensor.index.other; channel_gain = zeros(1,ctf.setup.number_channels); channel_gain(megIndex) = [ctf.sensor.info(megIndex).proper_gain] .* [ctf.sensor.info(megIndex).q_gain]; channel_gain(refIndex) = [ctf.sensor.info(refIndex).proper_gain] .* [ctf.sensor.info(refIndex).q_gain]; channel_gain(eegIndex) = [ctf.sensor.info(eegIndex).q_gain]; channel_gain(otherIndex) = [ctf.sensor.info(otherIndex).q_gain]; %------------------------------------------------------------------------- % Read trial data from .meg4 file % The data is stored as a sequence of (signed) 4-byte integers, starting % with the first trial and first channel, then the first trial and second % channel, etc. The number of channels per trial and the number of samples % in every trialchannel block are constant per dataset. The constants are % found in the general resources stored in the resource file, see 'The % Resource File Format'. The numbers stored in the data file are the raw % numbers collected from the electronics. For these numbers to be useful, % the various gains, stored in the sensor resources, must be applied. number_trials = length(TRIALS); number_channels = length(CHAN); ctf.data = zeros(number_samples, number_channels, number_trials); % Calculate trial byte size trial_bytes = 4 * ctf.setup.number_samples * ctf.setup.number_channels; trial_count = 0; for trial = 1:length(TRIALS), trial_number = TRIALS(trial); if trial > 1, fprintf('\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b'); end fprintf('...reading %4d of %4d trials\n', trial, ctf.setup.number_trials); % calculate the byte offset in the file for this trial trial_offset = header_bytes + ( trial_bytes * ( trial_number - 1 ) ); for channel = 1:length(CHAN), channel_number = CHAN(channel); % calculate the channel offset in the current trial channel_offset = 4 * ctf.setup.number_samples * ( channel_number - 1 ); % seek to the trial offset, relative to the beginning of the file fseek(fid,trial_offset,-1); % now seek to the channel offset, in the current trial fseek(fid,channel_offset,0); % read the entire set of samples for this channel channel_samples = fread(fid, [ctf.setup.number_samples,1], 'int32'); % extract just the selected time array channel_samples = channel_samples(TIME_index); if channel_gain(channel_number), channel_samples2tesla = channel_samples ./ channel_gain(channel_number); else channel_samples2tesla = channel_samples; end % assign the selected time samples into the ctf.data matrix ctf.data(:,channel,trial) = channel_samples2tesla; end end fclose(fid); %------------------------------------------------------------------------- % assign sensor locations and orientations for selected channels, this % section will simplify the data allocated by ctf_read_res4 fprintf('...sorting %d from %d sensors\n',number_channels, ctf.setup.number_channels); ctf.sensor.location = zeros(3,number_channels); ctf.sensor.orientation = zeros(3,number_channels); ctf.sensor.label = []; for c = 1:length(CHAN), channel = CHAN(c); % All channels have a label if length(ctf.sensor.info(channel).label) <= 5, ctf.sensor.label{1,c} = ctf.sensor.info(channel).label; else ctf.sensor.label{1,c} = ctf.sensor.info(channel).label(1:5); end % All channels have a location % EEG channels do not have any orientation switch ctf.sensor.info(channel).index, case {ctf.sensor.type.meg_sens, ctf.sensor.type.meg_ref}, %0=Reference Channels, %1=More Reference Channels, %5=MEG Channels % MEG channels are radial gradiometers, so they have an inner (1) and % an outer (2) location - it might be better to take the average of % their locations if ~isempty(ctf.sensor.info(channel).location), ctf.sensor.location(:,c) = ctf.sensor.info(channel).location(:,1); end if ~isempty(ctf.sensor.info(channel).orientation), ctf.sensor.orientation(:,c) = ctf.sensor.info(channel).orientation(:,1); end case ctf.sensor.type.eeg_sens, %9=EEG Channels if ~isempty(ctf.sensor.info(channel).location), ctf.sensor.location(:,c) = ctf.sensor.info(channel).location(:,1); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NEED TO CHECK ctf.setup parameters here, to adjust for any changes % required by the CHAN, TIME, TRIALS inputs % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % modify the setup parameters so they correspond with the data selected ctf.setup.number_samples = number_samples; ctf.setup.number_channels = number_channels; ctf.setup.number_trials = number_trials; if ctf.setup.number_samples ~= size(ctf.data,1), error('ctf.setup.number_samples ~= size(ctf.data,1)'); end if ctf.setup.number_channels ~= size(ctf.data,2), error('ctf.setup.number_channels ~= size(ctf.data,2)'); end if ctf.setup.number_trials ~= size(ctf.data,3), error('ctf.setup.number_trials ~= size(ctf.data,3)'); end t = toc; fprintf('...done (%6.2f sec)\n\n',t); return % find file name if truncated or with uppercase extension % added by Arnaud Delorme June 15, 2004 % ------------------------------------------------------- function meg4name = findmeg4file( folder ) meg4name = dir([ folder filesep '*.meg4' ]); if isempty(meg4name) meg4name = dir([ folder filesep '*.MEG4' ]); end; if isempty(meg4name) error('No file with extension .meg4 or .MEG4 in selected folder'); else meg4name = [ folder filesep meg4name.name ]; end; return
github
spm/spm5-master
spm_uw_apply.m
.m
spm5-master/spm_uw_apply.m
15,337
utf_8
9eac00bda2d4c00e4062104e135d045a
function varargout = spm_uw_apply(ds,flags) % Reslices images volume by volume % FORMAT spm_uw_apply(ds,[flags]) % or % FORMAT P = spm_uw_apply(ds,[flags]) % % % ds - a structure created by spm_uw_estimate.m containing the fields: % ds can also be an array of structures, each struct corresponding % to one sesssion (it hardly makes sense to try and pool fields across % sessions since there will have been a reshimming). In that case each % session is unwarped separately, unwarped into the distortion space of % the average (default) position of that series, and with the first % scan on the series defining the pahse encode direction. After that each % scan is transformed into the space of the first scan of the first series. % Naturally, there is still only one actual resampling (interpolation). % It will be assumed that the same unwarping parameters have been used % for all sessions (anything else would be truly daft). % % .P - Images used when estimating deformation field and/or % its derivative w.r.t. modelled factors. Note that this % struct-array may contain .mat fields that differ from % those you would observe with spm_vol(P(1).fname). This % is because spm_uw_estimate has an option to re-estimate % the movement parameters. The re-estimated parameters are % not written to disc (in the form of .mat files), but rather % stored in the P array in the ds struct. % % .order - Number of basis functions to use for each dimension. % If the third dimension is left out, the order for % that dimension is calculated to yield a roughly % equal spatial cut-off in all directions. % Default: [8 8 *] % .sfP - Static field supplied by the user. It should be a % filename or handle to a voxel-displacement map in % the same space as the first EPI image of the time- % series. If using the FieldMap toolbox, realignment % should (if necessary) have been performed as part of % the process of creating the VDM. Note also that the % VDM mut be in undistorted space, i.e. if it is % calculated from an EPI based field-map sequence % it should have been inverted before passing it to % spm_uw_estimate. Again, the FieldMap toolbox will % do this for you. % .regorder - Regularisation of derivative fields is based on the % regorder'th (spatial) derivative of the field. % Default: 1 % .lambda - Fudge factor used to decide relative weights of % data and regularisation. % Default: 1e5 % .jm - Jacobian Modulation. If set, intensity (Jacobian) % deformations are included in the model. If zero, % intensity deformations are not considered. % .fot - List of indexes for first order terms to model % derivatives for. Order of parameters as defined % by spm_imatrix. % Default: [4 5] % .sot - List of second order terms to model second % derivatives of. Should be an nx2 matrix where % e.g. [4 4; 4 5; 5 5] means that second partial % derivatives of rotation around x- and y-axis % should be modelled. % Default: [] % .fwhm - FWHM (mm) of smoothing filter applied to images prior % to estimation of deformation fields. % Default: 6 % .rem - Re-Estimation of Movement parameters. Set to unity means % that movement-parameters should be re-estimated at each % iteration. % Default: 0 % .noi - Maximum number of Iterations. % Default: 5 % .exp_round - Point in position space to do Taylor expansion around. % 'First', 'Last' or 'Average'. % .p0 - Average position vector (three translations in mm % and three rotations in degrees) of scans in P. % .q - Deviations from mean position vector of modelled % effects. Corresponds to deviations (and deviations % squared) of a Taylor expansion of deformation fields. % .beta - Coeffeicents of DCT basis functions for partial % derivatives of deformation fields w.r.t. modelled % effects. Scaled such that resulting deformation % fields have units mm^-1 or deg^-1 (and squares % thereof). % .SS - Sum of squared errors for each iteration. % % flags - a structure containing various options. The fields are: % % mask - mask output images (1 for yes, 0 for no) % To avoid artifactual movement-related variance the realigned % set of images can be internally masked, within the set (i.e. % if any image has a zero value at a voxel than all images have % zero values at that voxel). Zero values occur when regions % 'outside' the image are moved 'inside' the image during % realignment. % % mean - write mean image % The average of all the realigned scans is written to % mean*.img. % % interp - the interpolation method (see e.g. spm_bsplins.m). % % which - Values of 0 or 1 are allowed. % 0 - don't create any resliced images. % Useful if you only want a mean resliced image. % 1 - reslice all the images. % % udc - Values 1 or 2 are allowed % 1 - Do only unwarping (not correcting % for changing sampling density). % 2 - Do both unwarping and Jacobian correction. % % % The spatially realigned images are written to the orginal % subdirectory with the same filename but prefixed with an 'u'. % They are all aligned with the first. %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % Jesper Andersson % $Id: spm_uw_apply.m 1746 2008-05-28 17:43:42Z guillaume $ tiny = 5e-2; global defaults def_flags = struct('mask', 1,... 'mean', 1,... 'interp', 4,... 'wrap', [0 1 0],... 'which', 1,... 'udc', 1); defnames = fieldnames(def_flags); % % Replace hardcoded defaults with spm_defaults % when exist and defined. % if exist('defaults','var') && isfield(defaults,'realign') && isfield(defaults.realign,'write') wd = defaults.realign.write; if isfield(wd,'interp'), def_flags.interp = wd.interp; end if isfield(wd,'wrap'), def_flags.wrap = wd.wrap; end if isfield(wd,'mask'), def_flags.mask = wd.mask; end end if nargin < 1 || isempty(ds) ds = load(spm_select(1,'.*uw\.mat$','Select Unwarp result file'),'ds'); ds = ds.ds; end % % Default to using Jacobian modulation for the reslicing if it was % used during the estimation phase. % if ds(1).jm ~= 0 def_flags.udc = 2; end % % Replace defaults with user supplied values for all fields % defined by user. Also, warn user of any invalid fields, % probably reflecting misspellings. % if nargin < 2 || isempty(flags) flags = def_flags; end for i=1:length(defnames) if ~isfield(flags,defnames{i}) %flags = setfield(flags,defnames{i},getfield(def_flags,defnames{i})); flags.(defnames{i}) = def_flags.(defnames{i}); end end flagnames = fieldnames(flags); for i=1:length(flagnames) if ~isfield(def_flags,flagnames{i}) warning('Warning, unknown flag field %s',flagnames{i}); end end ntot = 0; for i=1:length(ds) ntot = ntot + length(ds(i).P); end hold = [repmat(flags.interp,1,3) flags.wrap]; linfun = inline('fprintf(''%-60s%s'', x,repmat(sprintf(''\b''),1,60))'); % % Create empty sfield for all structs. % [ds.sfield] = deal([]); % % Make space for output P-structs if required % if nargout > 0 oP = cell(length(ds),1); end % % First, create mask if so required. % if flags.mask || flags.mean, linfun('Computing mask..'); spm_progress_bar('Init',ntot,'Computing available voxels',... 'volumes completed'); [x,y,z] = ndgrid(1:ds(1).P(1).dim(1),1:ds(1).P(1).dim(2),1:ds(1).P(1).dim(3)); xyz = [x(:) y(:) z(:) ones(prod(ds(1).P(1).dim(1:3)),1)]; clear x y z; if flags.mean Count = zeros(prod(ds(1).P(1).dim(1:3)),1); Integral = zeros(prod(ds(1).P(1).dim(1:3)),1); end % if flags.mask msk = zeros(prod(ds(1).P(1).dim(1:3)),1); % end tv = 1; for s=1:length(ds) def_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2)); Bx = spm_dctmtx(ds(s).P(1).dim(1),ds(s).order(1)); By = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2)); Bz = spm_dctmtx(ds(s).P(1).dim(3),ds(s).order(3)); if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP) T = ds(s).sfP.mat\ds(1).P(1).mat; txyz = xyz * T'; c = spm_bsplinc(ds(s).sfP,ds(s).hold); ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold); ds(s).sfield = ds(s).sfield(:); clear c txyz; end for i=1:size(ds(s).beta,2) def_array(:,i) = spm_get_def(Bx,By,Bz,ds(s).beta(:,i)); end sess_msk = zeros(prod(ds(1).P(1).dim(1:3)),1); for i = 1:numel(ds(s).P) T = inv(ds(s).P(i).mat) * ds(1).P(1).mat; txyz = xyz * T'; txyz(:,2) = txyz(:,2) + spm_get_image_def(ds(s).P(i),ds(s),def_array); tmp = false(size(txyz,1),1); if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).P(i).dim(1)+tiny); end if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).P(i).dim(2)+tiny); end if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).P(i).dim(3)+tiny); end sess_msk = sess_msk + real(tmp); spm_progress_bar('Set',tv); tv = tv+1; end msk = msk + sess_msk; if flags.mean, Count = Count + repmat(length(ds(s).P),prod(ds(s).P(1).dim(1:3)),1) - sess_msk; end % Changed 23/3-05 % % Include static field in estmation of mask. % if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP) T = inv(ds(s).sfP.mat) * ds(1).P(1).mat; txyz = xyz * T'; tmp = false(size(txyz,1),1); if ~flags.wrap(1), tmp = tmp | txyz(:,1) < (1-tiny) | txyz(:,1) > (ds(s).sfP.dim(1)+tiny); end if ~flags.wrap(2), tmp = tmp | txyz(:,2) < (1-tiny) | txyz(:,2) > (ds(s).sfP.dim(2)+tiny); end if ~flags.wrap(3), tmp = tmp | txyz(:,3) < (1-tiny) | txyz(:,3) > (ds(s).sfP.dim(3)+tiny); end msk = msk + real(tmp); end if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield) ds(s).sfield = []; end end if flags.mask, msk = find(msk ~= 0); end end linfun('Reslicing images..'); spm_progress_bar('Init',ntot,'Reslicing','volumes completed'); jP = ds(1).P(1); jP = rmfield(jP,{'fname','descrip','n','private'}); jP.dim = jP.dim(1:3); jP.dt = [spm_type('float64'), spm_platform('bigend')]; jP.pinfo = [1 0]'; tv = 1; for s=1:length(ds) def_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2)); Bx = spm_dctmtx(ds(s).P(1).dim(1),ds(s).order(1)); By = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2)); Bz = spm_dctmtx(ds(s).P(1).dim(3),ds(s).order(3)); if isfield(ds(s),'sfP') && ~isempty(ds(s).sfP) T = ds(s).sfP.mat\ds(1).P(1).mat; txyz = xyz * T'; c = spm_bsplinc(ds(s).sfP,ds(s).hold); ds(s).sfield = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),ds(s).hold); ds(s).sfield = ds(s).sfield(:); clear c txyz; end for i=1:size(ds(s).beta,2) def_array(:,i) = spm_get_def(Bx,By,Bz,ds(s).beta(:,i)); end if flags.udc > 1 ddef_array = zeros(prod(ds(s).P(1).dim(1:3)),size(ds(s).beta,2)); dBy = spm_dctmtx(ds(s).P(1).dim(2),ds(s).order(2),'diff'); for i=1:size(ds(s).beta,2) ddef_array(:,i) = spm_get_def(Bx,dBy,Bz,ds(s).beta(:,i)); end end for i = 1:length(ds(s).P) linfun(['Reslicing volume ' num2str(tv) '..']); % % Read undeformed image. % T = inv(ds(s).P(i).mat) * ds(1).P(1).mat; txyz = xyz * T'; if flags.udc > 1 [def,jac] = spm_get_image_def(ds(s).P(i),ds(s),def_array,ddef_array); else def = spm_get_image_def(ds(s).P(i),ds(s),def_array); end txyz(:,2) = txyz(:,2) + def; if flags.udc > 1 jP.dat = reshape(jac,ds(s).P(i).dim(1:3)); jtxyz = xyz * T'; c = spm_bsplinc(jP.dat,hold); jac = spm_bsplins(c,jtxyz(:,1),jtxyz(:,2),jtxyz(:,3),hold); end c = spm_bsplinc(ds(s).P(i),hold); ima = spm_bsplins(c,txyz(:,1),txyz(:,2),txyz(:,3),hold); if flags.udc > 1 ima = ima .* jac; end % % Write it if so required. % if flags.which PO = ds(s).P(i); PO.fname = prepend(PO.fname,'u'); PO.mat = ds(1).P(1).mat; PO.descrip = 'spm - undeformed'; ivol = ima; if flags.mask ivol(msk) = NaN; end ivol = reshape(ivol,PO.dim(1:3)); PO = spm_create_vol(PO); for ii=1:PO.dim(3), PO = spm_write_plane(PO,ivol(:,:,ii),ii); end; if nargout > 0 oP{s}(i) = PO; end end % % Build up mean image if so required. % if flags.mean Integral = Integral + nan2zero(ima); end spm_progress_bar('Set',tv); tv = tv+1; end if isfield(ds(s),'sfield') && ~isempty(ds(s).sfield) ds(s).sfield = []; end end if flags.mean % Write integral image (16 bit signed) %----------------------------------------------------------- sw = warning('off','MATLAB:divideByZero'); Integral = Integral./Count; warning(sw); PO = ds(1).P(1); [pth,nm,xt,vr] = spm_fileparts(deblank(ds(1).P(1).fname)); PO.fname = fullfile(pth,['meanu' nm xt vr]); PO.pinfo = [max(max(max(Integral)))/32767 0 0]'; PO.descrip = 'spm - mean undeformed image'; PO.dt = [4 spm_platform('bigend')]; ivol = reshape(Integral,PO.dim); spm_write_vol(PO,ivol); end linfun(' '); spm_figure('Clear','Interactive'); if nargout > 0 varargout{1} = oP; end return; %_______________________________________________________________________ function PO = prepend(PI,pre) [pth,nm,xt,vr] = spm_fileparts(deblank(PI)); PO = fullfile(pth,[pre nm xt vr]); return; %_______________________________________________________________________ %_______________________________________________________________________ function vo = nan2zero(vi) vo = vi; vo(~isfinite(vo)) = 0; return; %_______________________________________________________________________
github
spm/spm5-master
spm_config_ecat.m
.m
spm5-master/spm_config_ecat.m
2,202
utf_8
0fa0f021012dd7020140f0082d29bff4
function opts = spm_config_ecat % Configuration file for ecat import jobs %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_config_ecat.m 512 2006-05-05 08:14:50Z volkmar $ %_______________________________________________________________________ data.type = 'files'; data.name = 'ECAT files'; data.tag = 'data'; data.ufilter = '.*v'; data.filter = 'any'; data.num = Inf; data.help = {'Select the ECAT files to convert.'}; dtype.type = 'menu'; dtype.name = 'Data Type'; dtype.tag = 'dtype'; dtype.labels = {'UINT8 - unsigned char','INT16 - signed short','INT32 - signed int','FLOAT - single prec. float','DOUBLE - double prec. float'}; dtype.values = {spm_type('uint8'),spm_type('int16'),spm_type('int32'),spm_type('float32'),spm_type('float64')}; dtype.val = {spm_type('int16')}; dtype.help = {[... 'Data-type of output images. '... 'Note that the number of bits used determines '... 'the accuracy, and the abount of disk space needed.']}; ext.type = 'menu'; ext.name = 'NIFTI Type'; ext.tag = 'ext'; ext.labels = {'.nii only','.img + .hdr'}; ext.values = {'.nii','.img'}; ext.val = {'.img'}; ext.help = {[... 'Output files can be written as .img + .hdr, ',... 'or the two can be combined into a .nii file.']}; op1.type = 'branch'; op1.name = 'Options'; op1.tag = 'opts'; op1.val = {ext}; op1.help = {'Conversion options'}; opts.type = 'branch'; opts.name = 'ECAT Import'; opts.tag = 'ecat'; opts.val = {data,op1}; opts.prog = @convert_ecat; opts.modality = {'PET'}; %opts.vfiles = @vfiles; opts.help = {[... 'ECAT 7 Conversion. ECAT 7 is the image data format used by the more recent CTI '... 'PET scanners.']}; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function convert_ecat(job) for i=1:length(job.data), spm_ecat2nifti(job.data{i},job.opts); end; return; %function vf = vfiles(job) %vf = cell(size(job.data)); %for i=1:numel(job.data), % [pth,nam,ext,versn] = fileparts(job.data{i}); % vf{i} = fullfile(pwd,[nam job.opts.ext versn]); %end;
github
spm/spm5-master
spm_read_netcdf.m
.m
spm5-master/spm_read_netcdf.m
3,729
utf_8
f97b5b0974ef8ceb2fe48cbf083b73e2
function cdf = spm_read_netcdf(fname) % Read the header information from a NetCDF file into a data structure. % FORMAT cdf = spm_read_netcdf(fname) % fname - name of NetCDF file % cdf - data structure % % See: http://www.unidata.ucar.edu/packages/netcdf/ % _______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: spm_read_netcdf.m 112 2005-05-04 18:20:52Z john $ dsiz = [1 1 2 4 4 8]; fp=fopen(fname,'r','ieee-be'); if fp==-1, cdf = []; return; end; % Return null if not a CDF file. %----------------------------------------------------------------------- mgc = fread(fp,4,'uchar')'; if ~all(['CDF' 1] == mgc), cdf = []; fclose(fp); return; end % I've no idea what this is for numrecs = fread(fp,1,'uint32'); cdf = struct('numrecs',numrecs,'dim_array',[], 'gatt_array',[], 'var_array', []); dt = fread(fp,1,'uint32'); if dt == 10, % Dimensions nelem = fread(fp,1,'uint32'); for j=1:nelem, str = readname(fp); dim_length = fread(fp,1,'uint32'); cdf.dim_array(j).name = str; cdf.dim_array(j).dim_length = dim_length; end; dt = fread(fp,1,'uint32'); end while ~dt, dt = fread(fp,1,'uint32'); end; if dt == 12, % Attributes nelem = fread(fp,1,'uint32'); for j=1:nelem, str = readname(fp); nc_type= fread(fp,1,'uint32'); nnelem = fread(fp,1,'uint32'); val = fread(fp,nnelem,dtypestr(nc_type)); if nc_type == 2, val = deblank([val' ' ']); end padding= fread(fp,ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar'); cdf.gatt_array(j).name = str; cdf.gatt_array(j).nc_type = nc_type; cdf.gatt_array(j).val = val; end; dt = fread(fp,1,'uint32'); end while ~dt, dt = fread(fp,1,'uint32'); end; if dt == 11, % Variables nelem = fread(fp,1,'uint32'); for j=1:nelem, str = readname(fp); nnelem = fread(fp,1,'uint32'); val = fread(fp,nnelem,'uint32'); cdf.var_array(j).name = str; cdf.var_array(j).dimid = val+1; cdf.var_array(j).nc_type = 0; cdf.var_array(j).vsize = 0; cdf.var_array(j).begin = 0; dt0 = fread(fp,1,'uint32'); if dt0 == 12, nelem0 = fread(fp,1,'uint32'); for jj=1:nelem0, str = readname(fp); nc_type= fread(fp,1,'uint32'); nnelem = fread(fp,1,'uint32'); val = fread(fp,nnelem,dtypestr(nc_type)); if nc_type == 2, val = deblank([val' ' ']); end padding= fread(fp,... ceil(nnelem*dsiz(nc_type)/4)*4-nnelem*dsiz(nc_type),'uchar'); cdf.var_array(j).vatt_array(jj).name = str; cdf.var_array(j).vatt_array(jj).nc_type = nc_type; cdf.var_array(j).vatt_array(jj).val = val; end; dt0 = fread(fp,1,'uint32'); end; cdf.var_array(j).nc_type = dt0; cdf.var_array(j).vsize = fread(fp,1,'uint32'); cdf.var_array(j).begin = fread(fp,1,'uint32'); end; dt = fread(fp,1,'uint32'); end; fclose(fp); return; %_______________________________________________________________________ %_______________________________________________________________________ function str = dtypestr(i) % Returns a string appropriate for reading or writing the CDF data-type. types = char('uint8','uint8','int16','int32','float32','float64'); str = deblank(types(i,:)); return; %_______________________________________________________________________ %_______________________________________________________________________ function name = readname(fp) % Extracts a name from a CDF file pointed to at the right location by % fp. stlen = fread(fp,1,'uint32'); name = deblank([fread(fp,stlen,'uchar')' ' ']); padding= fread(fp,ceil(stlen/4)*4-stlen,'uchar'); return; %_______________________________________________________________________