%% Solve PDE and Compute Partial Derivatives
% This example shows how to solve a transistor partial differential equation (PDE) and use the results to obtain partial derivatives that are part of solving a larger problem.
% Consider the PDE
% \frac{\partial u}{\partial t}=D\frac{\partial^2 u}{\partial x^2 }-\frac{D\eta }{L}\frac{\partial u}{\partial x}\ldotp
% This equation arises in transistor theory [1], and u\left(x,t\right) is a function describing the concentration of excess charge carriers (or holes) in the base of a PNP transistor. D and \eta are physical constants. The equation holds on the interval 0\le x\le L for times t\ge 0.
% The initial condition includes a constant K and is given by
% u\left(x,0\right)=\frac{K\;L}{D}\left(\frac{1-e^{-\eta \left(1-x/L\right)} }{\eta }\right)\ldotp
% The problem has boundary conditions given by
% u\left(0,t\right)=u\left(L,t\right)=0\ldotp
% For fixed x, the solution to the equation u\left(x,t\right) describes the collapse of excess charge as t\to \infty. This collapse produces a current, called the emitter discharge current, which has another constant I_p:
% I\left(t\right)={\left\lbrack \frac{I_p D}{K}\frac{\partial }{\partial x}u\left(x,t\right)\right\rbrack }_{x=0} \ldotp
% The equation is valid for t>0 due to the inconsistency in the boundary values at x=0 for t=0 and t>0. Since the PDE has a closed-form series solution for u\left(x,t\right), you can calculate the emitter discharge current analytically as well as numerically, and compare the results.
% To solve this problem in MATLAB, you need to code the PDE equation, initial conditions, and boundary conditions, then select a suitable solution mesh before calling the solver pdepe. You either can include the required functions as local functions at the end of a file (as done here), or save them as separate, named files in a directory on the MATLAB path.
%
%% Define Physical Constants
% To keep track of the physical constants, create a structure array with fields for each one. When you later define functions for the equations, the initial condition, and the boundary conditions, you can pass in this structure as an extra argument so that the functions have access to the constants.

C.L = 1;
C.D = 0.1;
C.eta = 10;
C.K = 1;
C.Ip = 1;

%
%% Code Equation
% Before you can code the equation, you need to make sure that it is in the form that the pdepe solver expects:
% c\left(x,t,u,\frac{\partial u}{\partial x}\right)\frac{\partial u}{\partial t}=x^{-m} \frac{\partial }{\partial x}\left(x^m f\left(x,t,u,\frac{\partial u}{\partial x}\right)\right)+s\left(x,t,u,\frac{\partial u}{\partial x}\right)\ldotp
% In this form, the PDE is
% \frac{\partial u}{\partial t}=x^0 \;\frac{\partial }{\partial x}\left(x^0 \;D\frac{\partial u}{\partial x}\right)-\frac{D\eta }{L}\frac{\partial u}{\partial x}\ldotp
% So the values of the coefficients in the equation are
% m=0 (Cartesian coordinates with no angular symmetry)
% c\left(x,t,u,\frac{\partial u}{\partial x}\right)=1
% f\left(x,t,u,\frac{\partial u}{\partial x}\right)=D\frac{\partial u}{\partial x}
% s\left(x,t,u,\frac{\partial u}{\partial x}\right)=-\frac{D\eta }{L}\frac{\partial u}{\partial x}
% Now you can create a function to code the equation. The function should have the signature [c,f,s] = transistorPDE(x,t,u,dudx,C):
% x is the independent spatial variable.
% t is the independent time variable.
% u is the dependent variable being differentiated with respect to x and t.
% dudx is the partial spatial derivative \partial u/\partial x.
% C is an extra input containing the physical constants.
% The outputs c, f, and s correspond to coefficients in the standard PDE equation form expected by pdepe.
% As a result, the equation in this example can be represented by the function:
% function [c,f,s] = transistorPDE(x,t,u,dudx,C)
% D = C.D;
% eta = C.eta;
% L = C.L;
%
% c = 1;
% f = D*dudx;
% s = -(D*eta/L)*dudx;
% end
% (Note: All functions are included as local functions at the end of the example.)
%
%% Code Initial Condition
% Next, write a function that returns the initial condition. The initial condition is applied at the first time value, and provides the value of u\left(x,t_0 \right) for any value of x. Use the function signature u0 = transistorIC(x,C) to write the function.
% The initial condition is
% u\left(x,0\right)=\frac{K\;L}{D}\left(\frac{1-e^{-\eta \left(1-x/L\right)} }{\eta }\right)\ldotp
% The corresponding function is
% function u0 = transistorIC(x,C)
% K = C.K;
% L = C.L;
% D = C.D;
% eta = C.eta;
%
% u0 = (K*L/D)*(1 - exp(-eta*(1 - x/L)))/eta;
% end
%
%% Code Boundary Conditions
% Now, write a function that evaluates the boundary conditions u\left(0,t\right)=u\left(1,t\right)=0. For problems posed on the interval a\le x\le b, the boundary conditions apply for all t and either x=a or x=b. The standard form for the boundary conditions expected by the solver is
% p\left(x,t,u\right)+q\left(x,t\right)f\left(x,t,u,\frac{\partial u}{\partial x}\right)=0\ldotp
% Written in this form, the boundary conditions for this problem are
% - For x=0, the equation is  u+0\cdot d\frac{\partial u}{\partial x}=0\ldotp The coefficients are:
% p_L \left(x,t,u\right)=u,
% q_L \left(x,t\right)=0\ldotp
% - Likewise for x=1, the equation is u+0\cdot d\frac{\partial u}{\partial x}=0\ldotp The coefficients are:
% p_R \left(x,t,u\right)=u,
% q_R \left(x,t\right)=0\ldotp
% The boundary function should use the function signature [pl,ql,pr,qr] = transistorBC(xl,ul,xr,ur,t):
% The inputs xl and ul correspond to x and u for the left boundary.
% The inputs xr and ur correspond to x and u for the right boundary.
% t is the independent time variable.
% The outputs pl and ql correspond to p_L \left(x,t,u\right) and q_L \left(x,t\right) for the left boundary (x=0 for this problem).
% The outputs pr and qr correspond to p_R \left(x,t,u\right) and q_R \left(x,t\right) for the right boundary (x=1 for this problem).
% The boundary conditions in this example are represented by the function:
% function [pl,ql,pr,qr] = transistorBC(xl,ul,xr,ur,t)
% pl = ul;
% ql = 0;
% pr = ur;
% qr = 0;
% end
%
%% Select Solution Mesh
% The solution mesh defines the values of x and t where the solution is evaluated by the solver. Since the solution to this problem changes rapidly, use a relatively fine mesh of 50 spatial points in the interval 0\le x\le L and 50 time points in the interval 0\le t\le 1.

x = linspace(0,C.L,50);
t = linspace(0,1,50);

%
%% Solve Equation
% Finally, solve the equation using the symmetry m, the PDE equation, the initial condition, the boundary conditions, and the meshes for x and t. Since pdepe expects the PDE function to use four inputs and the initial condition function to use one input, create function handles that pass in the structure of physical constants as an extra input.

m = 0;
eqn = @(x,t,u,dudx) transistorPDE(x,t,u,dudx,C);
ic = @(x) transistorIC(x,C);
sol = pdepe(m,eqn,ic,@transistorBC,x,t);

% pdepe returns the solution in a 3-D array sol, where sol(i,j,k) approximates the kth component of the solution u_kevaluated at t(i) and x(j). For this problem u has only one component, but in general you can extract the kth solution component with the command u = sol(:,:,k).

u = sol(:,:,1);

%
%% Plot Solution
% Create a surface plot of the solution u plotted at the selected mesh points for x and t.

surf(x,t,u)
title('Numerical Solution (50 mesh points)')
xlabel('Distance x')
ylabel('Time t')
zlabel('Solution u(x,t)')

% Now, plot just x and u to get a side view of the contours in the surface plot.

plot(x,u)
xlabel('Distance x')
ylabel('Solution u(x,t)')
title('Solution profiles at several times')

%
%% Compute Emitter Discharge Current
% Using a series solution for u\left(x,t\right), the emitter discharge current can be expressed as the infinite series [1]:
% I\left(t\right)=2\pi^2 I_p \left(\frac{1-e^{-\eta } }{\eta }\right)\sum_{n=1}^{\infty } \frac{n^2 }{n^2 \pi^2 +\eta^2 /4}e^{-\frac{\textrm{dt}}{L^2 }\left(n^2 \pi^2 +\eta^2 /4\right)} \ldotp
% Write a function to calculate the analytic solution for I\left(t\right) using 40 terms in the series. The only variable is time, but specify a second input to the function for the structure of constants.
% function It = serex3(t,C) % Approximate I(t) by series expansion.
% Ip = C.Ip;
% eta = C.eta;
% D = C.D;
% L = C.L;
%
% It = 0;
% for n = 1:40 % Use 40 terms
%   m = (n*pi)^2 + 0.25*eta^2;
%   It = It + ((n*pi)^2 / m)* exp(-(D/L^2)*m*t);
% end
% It = 2*Ip*((1 - exp(-eta))/eta)*It;
% end
% Using the numeric solution for u\left(x,t\right) as computed by pdepe, you can also calculate the numeric approximation for I\left(t\right) at x=0 with
% I\left(t\right)={\left\lbrack \frac{I_p D}{K}\frac{\partial }{\partial x}u\left(x,t\right)\right\rbrack }_{x=0} \ldotp
% Calculate the analytic and numeric solutions for I\left(t\right) and plot the results. Use pdeval to compute the value of \partial u/\partial x at x=0.

nt = length(t);
I = zeros(1,nt);
seriesI = zeros(1,nt);
iok = 2:nt;
for j = iok
   % At time t(j), compute du/dx at x = 0.
   [~,I(j)] = pdeval(m,x,u(j,:),0);
   seriesI(j) = serex3(t(j),C);
end
% Numeric solution has form I(t) = (I_p*D/K)*du(0,t)/dx
I = (C.Ip*C.D/C.K)*I;

plot(t(iok),I(iok),'o',t(iok),seriesI(iok))
legend('From PDEPE + PDEVAL','From series')
title('Emitter discharge current I(t)')
xlabel('Time t')

% The results match reasonably well. You can further improve the numeric result from pdepe by using a finer solution mesh.
%
%% Local Functions
% Listed here are the local helper functions that the PDE solver pdepe calls to calculate the solution. Alternatively, you can save these functions as their own files in a directory on the MATLAB path.

function [c,f,s] = transistorPDE(x,t,u,dudx,C) % Equation to solve
D = C.D;
eta = C.eta;
L = C.L;

c = 1;
f = D*dudx;
s = -(D*eta/L)*dudx;
end
% ----------------------------------------------------
function u0 = transistorIC(x,C) % Initial condition
K = C.K;
L = C.L;
D = C.D;
eta = C.eta;

u0 = (K*L/D)*(1 - exp(-eta*(1 - x/L)))/eta;
end
% ----------------------------------------------------
function [pl,ql,pr,qr] = transistorBC(xl,ul,xr,ur,t) % Boundary conditions
pl = ul;
ql = 0;
pr = ur;
qr = 0;
end
% ----------------------------------------------------
function It = serex3(t,C) % Approximate I(t) by series expansion.
Ip = C.Ip;
eta = C.eta;
D = C.D;
L = C.L;

It = 0;
for n = 1:40 % Use 40 terms
  m = (n*pi)^2 + 0.25*eta^2;
  It = It + ((n*pi)^2 / m)* exp(-(D/L^2)*m*t);
end
It = 2*Ip*((1 - exp(-eta))/eta)*It;
end
% ----------------------------------------------------

%% References
% [1] Zachmanoglou, E.C. and D.L. Thoe. Introduction to Partial Differential Equations with Applications. Dover, New York, 1986.
% Copyright 2019 The MathWorks, Inc.