Solving the Heat Equation with Dirichlet Boundary Conditions

This code solve the heat equation
u_t=u_(xx)
u(0,t)=u(L,t)=0
u(x,0)=f(x).

Constants

L=π;

Construction of Initial Data

f[x_]:=Piecewise[{{x,0<x<π/2},{π-x,x>π/2}}]
Plot[f[x],{x,0,L},AxesLabel->{"x", "f(x)"}, LabelStyle-> Directive[Bold, Black, Medium], PlotStyle-> Thickness[0.0075]]

Calculation of Fourier Coefficients

For this problem we know that the solutions are of the form
u(x,t)=\Sum_{i=1}^{\infty} b_n e^{-n^2t}\sin(nx).
We can use orthogonality to find the coefficients b_n.

Simplify[Integrate[Sin[n*x]^2,{x,0,π},Assumptions->n∈Integers],Assumptions->n∈Integers]

Simplify[Simplify[Integrate[f[x]*Sin[n*x],{x,0,π}],Assumptions->n∈Integers],Assumptions->n∈Integers]

b[n_]:=2/π*((8 Cos[((n π)/4)] ((Sin[((n π)/4)])^3))/(n^2));

Construction of Solution

u[x_,t_,N_]:=Sum[b[n]*Exp[-n^2*t]*Sin[n*x],{n,1,N}]

Plot of Solution at Different Times as Compared with Dominant Mode

M=50;
plot1=Plot[{u[x,0,M],u[x,1,M],u[x,2,M]},{x,0,L},AxesLabel->{"x", "f(x)"}, LabelStyle-> Directive[Bold, Black, Medium], PlotStyle-> Thickness[0.0075]]

M=1;
plot2=Plot[{u[x,0,M],u[x,1,M],u[x,2,M]},{x,0,L},AxesLabel->{"x", "f(x)"}, LabelStyle-> Directive[Bold, Black, Medium], PlotStyle-> {{Black,Thickness[0.0075],Dashed}}]

Show[plot1,plot2]

Density Plot of Solution

Density/Contour Plot

M=10;
T=3;
DensityPlot[u[x,t,M], {x, 0, L}, {t, 0, T}, PlotRange->{0,π/2}, PlotLegends->Automatic, PlotPoints-> 10, FrameLabel->{"x","t"}, LabelStyle->Directive[Bold, Black, Medium]]

ContourPlot[u[x,t,M], {x, 0, L}, {t, 0, T}, PlotRange->{0,π/2}, PlotLegends->Automatic, PlotPoints-> 10, FrameLabel->{"x","t"}, LabelStyle->Directive[Bold, Black, Medium]]

T=2;
Animate[Plot[{u[x, t,M],u[x, t,1]},{x, 0, L}, PlotRange->{{0,L}, {0,π/2}}, AxesLabel->{"x", "u(x,t)"}, LabelStyle-> Directive[Bold, Black, Medium], PlotStyle-> {Thickness[0.01],{Thickness[.01],Black,Dashed}}],{t, 0, T}]