Top 4 Python Modules For Engineering & Research | Towards Data Science

Python is perfect for a beginner as the syntax is easy to grasp and simple to understand. With this perk, it is already a leading programming language in the engineering and research fields. As engineers, we are tasked to “apply the principles of science and mathematics to develop economical solutions to technical problems”.
Python is one of the many tools that can help us achieve this task. I use Python at work to extract information from technical specification sheets, process experimental and testing results, and solve numerical calculations. Here are some of my favorite Python modules every engineer and researcher can utilize to increase their day-to-day output.
The math module is part of the Python standard library and contains mathematical tools and constants commonly used in engineering calculations. Need to know the arcsine of an angle? A single line of code will do the job.
math.asin(x)
Can't remember Euler's number, or the 4th decimal of pi? No problem, the math module got us covered.
math.e # returns 2.718281828459045
Of course, being named the math module, it also enables functions, like the trigonometry and logarithmic functions to be computed. Another favorite operator of mine is the “_” operator, where Python returns the value of the last operation.
23.74*0.56 # returns 13.2944_+0.582 # returns 13.8764_/math.e # returns 5.104842277471403
This is exceptionally handy when we need to come up with quick calculations. Let’s look at an example of using the methods from the math module to calculate RMS data from some vibration sensor readings (the magnitude of the readings).
Using an example of 10 sensor energy readings, we can find the RMS value by the following:
import mathN = 6with open("data.txt") as file:for i in range(6): line = next(file).strip()print(line)
list = [0.09539392, 1.722933545, 3.220776304, 0.291376046, 1.741062894]n = len(list)squares = 0for i in range(0,n):  squares += (list[i]**2)mean = (squares / (n))RMS = math.sqrt(mean)print(RMS)# returns 1.8147837337772996
Numpy (Numeric Python) is a Python module designed for scientific computation. It has many useful features and its core datatype is arrays. Numpy arrays are n-dimensional array objects used to represent vectors and matrixes.
Here are some examples of using Numpy based on a temperature sensor dataset from Kaggle.
We can check the contents of the dataset— i.e. the columns present, the number of readings, and the first/last 10 readings.
import numpy as npfrom numpy import genfromtxtdata = genfromtxt(data.csv", delimiter=',', names = True)print("Columns in dataset: " , data.dtype.names)Temp = data[:, 0] print(Temp[1: 10]) # returns first 10 elementsprint(Temp[-10:]) # returns last 10 elementsprint(Temp.size)# returns number of elements
Depending on our application, we can also also quickly filter out values in the Temperature column with readings greater than 30 degrees using the where() method.
index = np.where(Temp >= 30)print(Temp[index])
Simple data analysis like the percentile values, mean, median, standard deviation as well as the most frequent occurrence in a dataset can be computed using a few lines of code.
Here we explore the WaterTemperature column:
WaterTemp = data[:, 2]tenth, ninetieth = np.nanpercentile(WaterTemp[1:], q =[10, 90])mean, median, std = np.nanmean(WaterTemp), np.nanmedian(WaterTemp), np.nanstd(WaterTemp)values, counts = np.unique(WaterTemp, return_counts=True)print(tenth, ninetieth)print(mean, median, std)print(values[np.argmax(counts)])
To generate publication-quality figures and graphs with fewer lines of code, the Matplotlib module can be used, and within consists of the Pyplot module. Pyplot is especially useful for 2D plots, for example plotting histograms, dataset graphs, or visually examining simulation results.
An example of a simple 2D plot: (it looks better than Excel graphs huh?)
Fundamentally, we have the freedom to customize our plots ie: setting axes labels, adjusting lines and marker thickness, and even saving the plotted graphs into high-resolution images or PDFs.
Pyplot is one of my favorite tool, especially the subplot method where I can create multiple plots and save them into a PDF or JPEG document.
As engineers, we are often asked to make data-driven decisions, for example, identifying the number of rejected manufacturing parts based on CpK values, and Matplotlib is a useful library for us to easily visualize data trends for decision making.
The SciPy (SCIentific PYthon) module provides a vast arsenal of numerical and scientific processing algorithms useful to an engineer to perform calculations and solving equations. Let’s take a look at SciPy in action from another signal processing example below.
A 10 Hz sine wave signal is superpositioned with a 30Hz sine wave signal. We apply Fourier Transform on the signal and the coefficients are plotted against frequency.
import scipy as sp...df = 1/signal_lengtht = sp.arange(0, signal_length, dt)n_t = len(t)y = sp.sin (2*pi*10*t)+ sp.sin (2*pi*30*t) #Note that the arange and sin functions are available in numpy toof = sp.fft (y)frequencies = df * sp.arange(0 ,(n_t -1)/2)n_freq = len (frequencies)plt.subplot (2 ,1 ,1)plt.plot (t ,y)...plt.subplot (2 ,1 ,2)plt.plot(freqs, abs(f[0: n_freq]))...plt.show()
With a few lines of code, the Fourier Transform of a signal can be obtained and visualized. All functionality from NumPy is available in SciPy as well, and the latter extends the functionality of the former with a full-blown collection of algorithms such as integration, minimization, Fourier transformation, regression, morphology, and other applied mathematical techniques.
If you are interested to know more about signal processing, I’ve written another post about the topic here:
towardsdatascience.com
You may be asking why should one use Python when there are tools like MATLAB, Microsoft Excel and other engineering software? Well, most of them are closed-sourced software, and that can be expensive to use — especially when extra customized toolboxes and licenses are required.
Python, however, is free, open-sourced, and contains many modules and libraries that are as good as, or even better than paid software.
What we have seen in the above post is just the tip of an iceberg, but I hope it is sufficient to convince any engineers and scientists starting out with Python, of its powerful capabilities in handling, processing, and visualizing data sets. The 21st-century is changing rapidly and knowing Python will someday be necessary for traditional engineering disciplines.
Below is a list of additional resources for to learn more about the above modules:
Everything you need to know about the math moduleNumPy ReferenceMatplotlib & SciPy Reference
Everything you need to know about the math module
NumPy Reference
Matplotlib & SciPy Reference
No rights reserved
 by the author.