Explicit Finite Difference Method implementation in Python ( For 1D heat transfer)

There has been less work on the implementation of numerical method via python. In this blog, an example of solving a 1D  transient heat transfer problem via python will be discussed. Firstly, a simple heat 1D heat transfer problem will be stated. Then a python class will be built to solve this problem via an explicit finite difference method.

 Problem statement:

Use the explicit method to solve for the temperature distribution of a long, thin rod with a length of 10 cm and the following values: k= 0.49 cal/(s · cm · C), x = 2 cm, and t = 0.1 s. At t = 0, the temperature of the rod is zero and the boundary conditions are fixed for all times at T(0) = 100C and T(10) = 50C. Note that the rod is aluminum with C = 0.2174 cal/(g·C) and ρ = 2.7 g/cm3. Therefore, k = 0.49/(2.7 · 0.2174) =0.835 cm^2/s and λ = 0.835(0.1)/(2)2 = 0.020875. [Numerical Method for Engineers- Chapra]

Formula recap:

We know that, for 1D heat transfer, temperature T at any timestep l+1 for a nodal point i is,

Til+1=Tli+λ( Tli+1 -2Tli+Tli-1)
where, λ=kΔt∕(Δx2)
and k=K/ρC
Python Implementation:

At first, some necessary libraries are imported:
After that, a class named oneD_FDM_heat conduction is constructed. It takes following values as inputs:
conduction_coeff= conductivity
density,specific_heat delta_x,delta_t, and initial_value.
Note that initial_value is a list, which also takes two boundary values. For simplicity boundary conditions are considered constant temperature in this code.

Inside the class, three functions are used:

1. lambdavalue():
This function returns the value of lambda of the given input into the class. It doesn't require any input, rather input is associated with the input into the class.

2. temperature_profile():
This function returns the final temperature profile of the given input. The output of this function is a numpy array, where the first row is the initial nodal condition, and the subsequent rows are subsequent nodal temperature values. temperature_profile() function takes the number of total time steps as input and generates a numpy array having rows equals to the total time step value given as input.

3. plot_profile():
This function provides a plot of the nodal temperature values. It takes two inputs, one is time interval(at what interval values will be shown) and total time step ( how many plots will be shown).

The code of the class is:



Now, an object of class oneD_FDM_heat_transfer() is created:
So, the lambda value generation code:
Now, let we want to know the temperature profile for 6-time steps. The code is:

Finally, let,we want to plot the temperature graph for every 30 time-steps and up to 6-time steps. As the time step is 0.1, we will get plot at every 3s interval via the plot_profile function:

The full code can be found here.





Comments