by Xiaofeng Liu, Ph.D., P.E. Associate Professor
Department of Civil and Environmental Engineering
Institute of Computational and Data Sciences
Penn State University
223B Sackett Building, University Park, PA 16802
Web: http://water.engr.psu.edu/liu/
#Do not change this cell and the next one. They are for setting things up.
#make plots inline (instead of as a pop up window)
%matplotlib inline
#import the preamble in the parent directory
import sys
sys.path.append("../../")
from preamble import *
from IPython.display import display, HTML
Start to load preamble. Finished loading preamble.
The following is for the setup of writing equations with Latex.
%%javascript
MathJax.Hub.Config({
TeX: { equationNumbers: { autoNumber: "AMS" } }
});
This chapter will cover the basics of programming and Python, in preparation for the rest of the book. This chapter will cover the following topics:
This notebook will cover the first part, which is why computing is important for civil and environmental engineers.
Civil and environmental engineering is a very old engineering field, which probably has existed since the beginning of human civilization (note the "civil" part of this word). In public eyes, a civil or environmental engineer might not have too much to do with high technological advancement in fields such as mordern computing. This is indeed an unfortunate misconception of not only the public but also many people in this very field. As you will see in this book and many other places, computing is everywhere in civil and environmental engineering. Computing has weaved itself in almost all aspects of not only CEE but also the whole society. As a result, we often take computing for granted, a.k.a, without recognizing its existance, letting along its importance. In the 21th century, CEE practioners should master computing skill as other essentials such as surveying and drafting.
Before we go further, a proper definition of "computing methods" is in order. Any computing method in this book is defined as the use of computer to solve a mathematical problem or perform a calculation task. A more traditional (and narrower) name for "computing methods" is "numerical methods". However, the defintion of computing has evolved and the name "computing methods" suggest a much broader definition. Any task which can be automated with a computer can be call "computing". There are many examples in the profession of CEE, which will be introduced later on. One simple example is the work flow of retrieving some data (either download from a website such as USGS or read the result file from a computer software), processing the data (e.g., cleaning, grouping, and computation), and making a plot to visualize the results. A computing work flow like this can be automated with some a customized code, which greatly increases productivity and efficiency, and reduce the chance of human errors when done manually.
The topic of this book is computing methods. Importance of computing has been emphsized. However, the intent is definitely not to discount the critical role of manual calculation. Across the U.S. and around the globe, most of the CEE program curriculums probably emphasize more on hand calculations. In-class exercises, examples, homework, and projects are mostly done with a piece of paper and a pen. Hand calculation is an essential step in CEE education because it is probably the most effective way to learn a new concept, tool, or method. To some degree, most CEE curriculums also contain some courses and trainings on computing methods. However, based on the author's observation and experience, what is missing is the link among theories, methods, hand calculation, and computing techniques. Many CEE students are required to take some computing methods and programming classes, mostly very early during college years. At that time, students are not much exposed to technical courses in CEE and thus can not make the link between computing and CEE subjects. On the other hand, in the delivery of technical courses, instructors are usually constrained by time and the need to cover a broad spectrum of topics. They usually focus much more on theory and hand calculation, without too much devotion to the use of computers and computing. It is also disappointing to note that CEE professional license exams have almost no coverage on computing methods or technique, despite the fact that civil and environmental engineers use computer to perform computing tasks almost everyday. Based on the status quo of current CEE education, a book such as this and corresonding computing methods course offering are needed.
Computational tools are widely used in all engineering professions, including CEE. The following is a list of non-exclusive examples:
So no matter you realize or not, computing is everywhere in our life. Before you begin the reading and learning journey along with this book, it will be benefitial for you to think about the following two questions.
Your answer to these questions hopefully makes you more motivated to dive deep into the fascinating world of computing. The mastering of computing techniques can make an engineer more efficient and competitive in this ever faster changing world. In your career, you will likely spend hours with a computer everyday.
The implementation of computing methods will result in computational software or code. Some examples in CEE have been mentioned previously. Like anything else, there are some pros and cons associated with computational tools. These need to be always kept in mind when using computer codes.
The pros include:
The cons include:
In this book, the more concrete definition of computing methods is a numerical analysis which uses computer to solve mathematical models in the form of equations. These mathematical model equations, either algebraic or differential, are used to describe biological, geological, chemical, and many other physical processes encounted in CEE. The computed results, if they are computed correctly, are always only an approximation to the true solutions. In contrast to computing methods, analytical methods seek to solve the equations analytically (exactly). Unfortunately, analytical solutions are very rare and only exist when the situation is greatly simplified and many assumptions have to be made. For most real world problems, there is no analytical solution because of complexity. In addition to computing methods and analytical methods, we can also use experimental methods to solve problems, for example to use experimetns to test a design or study an engineering process.
In comparison with other two methods, computing methods and computational modeling can be used in the following scenarios:
Here, $C$ is contaminant concentration, $U$ is flow velocity, $D$ is a dispersion coefficient, $k$ is a reaction constant, $t$ is time, and $x$ is the coordiante along the river. Due to the nonlinear term $k C^2$, there is no analytical solution. However, with computing methods, it is relatively easy to get an approximate solution if boundary and initial conditions are set properly.
There are many other practical engineering issues which limit either analytical approach or experiments:
As a preview of a typical computing method, this part shows a simple example. This example shows a simplified version of a spherical particle settling in quiescent fluid. Particle settling is important for water treatment and river water quality. The motion of the particle is governed by the Newton's second law, which is a mathematical model: \begin{equation} m \frac{dU_z}{dt} = F_z \end{equation} where $m=\rho_p V$ is the particle mass, $\rho_p$ is particle density, $V$ is particle volume, $U_z$ is the particle velocity in $z$ (vertical) direction, $F_z$ is the total force on the particle in $z$, and $t$ is time. For simplicity, we assume the particle only settles in the vertical direction and there is not motion in other directions. We also define the downward direction is positive.
The total vertical force is made of three parts:
where $C_D$ is a constant.
Thus, the governing equation becomes \begin{equation} \rho_p V \frac{dU_z}{dt} = \rho_p V g - \rho_w V g - C_D U_z^2 \end{equation}
Divide both sides by the particle mass $\rho_p V$, we get Thus, the governing equation becomes \begin{equation} \frac{dU_z}{dt} = \frac{\rho_p-\rho_w}{\rho_p} g - \frac{C_D}{\rho_p V} U_z^2 \end{equation} which is a first-order, nonlinear ordinary differential equation for $U_z(t)$. In order to get an solution for this problem, we need an initial condition, i.e., what is the particle velocity at the beging. For example, if initially the particle is not moving, then the initial condition is \begin{equation} U_z(t=0) = 0 \end{equation}
To solve this equation with computer, one can use different methods. The simplest one is probably the finite difference method, which we will cover in later chapters. In essence, the continous the differential equation is "discretized" or "approximated" at discrete time, let's say time $t_{i}$ and $t_{i+1}$. We can also approximate the right hand side of the equation with values at time $t_i$. The discrete form the time derivative is then \begin{equation} \frac{dU_z}{dt} \approx \frac{U_z(t_{i+1})-U_z(t_{i})}{t_{i+1}-t_i} = \frac{\rho_p-\rho_w}{\rho_p} g - \frac{C_D}{\rho_p V} U_z(t_i)^2 \end{equation}
Starting with $i$ = 0, i.e., $t_0$ = 0, we can marching forward using the above approximation because the only unknown is $U_z(t_{i+1})$ and everything eles is either constant or already known at previous time step $t_i$. The method described here is only one of many which we will cover in the ODE chapter.
In the following, to show the result with less distraction to the numerical details, we will demonstrate the numerical solution of the problem by calling functions in a Python library. You do not need to pay attention to all the details of how the functions are called and the plot is made.
In the Python code below, the "odeint" function within the "scipy" library is called to the integrate the ODE from $t$ = 0 s to 0.5 s. Parameter values are specified in the code. Then, a plot is made to show the time history of the particle velocity. You can observe that the particle start from zero velocity and then increases its velocity (due to gravity) until it asymptotically approaches its terminal velocity at about 0.52 m/s.
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
plt.rc('text', usetex=True) #allow the use of Latex for math expressions and equations
plt.rc('font', family='serif') #specify the default font family to be "serif"
#dU_z/dt = (rhop-rhow)/rhop*g - C_D/rhop/V*U_z*U_z
def dUz_dt(U_z, t, rhop, rhow, g, C_D, V):
return (rhop-rhow)/rhop*g - C_D/rhop/V*U_z*U_z
#define parameters
rhop = 2650.0 #density of particle
rhow = 1000.0 #densit of water
g = 9.8 #gravity
C_D = 0.002 #constant for drag force
V = 4.0/3.0*3.14159*0.002**3 #volume of the particle
t = np.linspace(0, 0.5, 100) # time
Uz0 = 0.0 # initials condition
Uz, infodict = integrate.odeint(dUz_dt, Uz0, t, args=(rhop, rhow, g, C_D, V), full_output=True)
#print(Uz)
plt.plot(t, Uz, 'r-',label="Particle")
#set the limit for the x and y axes
plt.xlim([0,0.5])
plt.ylim([0,0.6])
#set x and y axes label and font size
plt.xlabel('Time (s)',fontsize=16)
plt.ylabel('Settling velocity (m/s)',fontsize=16)
#show the ticks on both axes and set the font size
plt.tick_params(axis='both', which='major', labelsize=12)
#show title and set font size
plt.title('Particle settling in quiescent water',fontsize=16)
plt.grid()
#show legend, set its location, font size, and turn off the frame
plt.legend(loc='lower right',fontsize=14,frameon=False)
#plt.savefig("particle_settling.png",dpi=300, bbox_inches='tight', pad_inches=0)
plt.show()
The above part of the chapter may give the reader the impression that it mostly praises computing methods and computational tools for their importance and usefulness. In fact, it is only part of the message. To make it clear that computing methods are only tools and they should be used properly, the following is a list of famous quotes in computational science which probably have been used in all computing-related courses and should be memorized by all who uses computer to solve engineering problems.