#002 - SciPy in Structural and Civil Engineering, Part 1/3: Numerical Integration
The first in a 3 part series on the practical applications of SciPy, a Python package, in the field of structural and civil engineering.
Precision and efficiency are paramount in the world of structural and civil engineering. SciPy, a Python package, excels (no pun intended) in both aspects. This post delves into its practical applications, focusing on how it aids professional engineers. Weβll wade into the weeds a little bit but itβs not too bad so come and join me and see how it compares to the ultimate juggernaut, MS Excel.
Other posts in this series:
SciPy in Structural and Civil Engineering, Part 2/3: Optimization and Interpolation
SciPy in Structural and Civil Engineering, Part 3/3: Structural Dynamics
At a high level, SciPy is a Python library used extensively in scientific and engineering disciplines. It builds upon the fundamental capabilities of NumPy and offers a wide range of specialized tools and functions for mathematical tasks such as numerical integration, optimization, linear algebra, signal processing, statistics, and more. SciPy empowers engineers to solve complex mathematical and technical problems efficiently and accurately.
Numerical Integration
The first aspect of SciPy we will investigate is itβs suitability for numerical integration.
The pre-built methods and functions in SciPy make complicated computations much, much easier. If you are curious, I highly recommend taking a look at the official documentation.
Numerical integration, at its core, involves approximating the definite integral of a function. In hydropower engineering (my neck of the woods), this often translates to evaluating integrals related to fluid dynamics, such as flow rate calculations.
SciPy's quad
function is a cornerstone of numerical integration. It utilizes adaptive quadrature techniques, such as the Gauss-Kronrod method, to compute integrals accurately.
Adaptive quadrature is a numerical technique that dynamically adjusts the number of subintervals used for integration to ensure accurate results, making it suitable for a wide range of mathematical functions and integral calculations.
Below, is the function flow_rate()
takes as input the actual mathematical function to be integrated and the integration bounds, returning both the integral's result and an estimate of the absolute error.
import scipy.integrate as spi
def flow_rate():
result, _ = spi.quad(lambda x: flow_function(x), 0, 10)
return result
I wish these Substack code blocks had syntax highlighting!
The lambda function in the example represents the function to be integrated, and the integration bounds are specified as [0, 10]
. The result is the integral's value, which in hydropower engineering can represent critical parameters like flow rates.
let's provide a mathematical equivalent to the code and explain it step by step.
Mathematical Equivalent: The formula below is the same as the code we just wrote with a = 0, b = 10.
In our hydropower engineering context, this could be a function describing the behaviour of fluid flow at different points along a channel or pipe.
Scipy's quad
function is used to compute this integral numerically. It approximates the area under the curve of the function by dividing it into smaller segments and summing their areas.
Here's a step-by-step explanation of the code:
import scipy.integrate as spi
This line imports SciPy's integration module, making its functions available for use.
def flow_rate():
Defines a Python function called
flow_rate
for calculating the flow rate.result, _ = spi.quad(lambda x: flow_function(x), 0, 10)
This line uses the
spi.quad
function, where:lambda x: flow_function(x)
is an anonymous (lambda) function representing f(x). It takes an input x and returns f(x) for that value.0
and10
are the lower and upper bounds of integration, denoted as a and b.
return result
: Theresult
variable holds the numerical approximation of the integral, which, in our context, represents the flow rate.
In essence, SciPy's quad
function takes the mathematical integral, divides it into manageable segments, and calculates the sum of their areas, providing a numerical approximation of the integral's value. This is especially useful when we cannot find a closed-form (analytical) solution for the integral or when dealing with complex functions.
The result obtained through this process represents the desired quantity, such as a flow rate, with precision and efficiency.
The power of SciPy's quad
function lies in its ability to handle a wide range of integrals, including those with complex, variable, or even discontinuous functions. Its adaptive nature ensures that the desired level of accuracy is achieved efficiently.
By employing adaptive quadrature techniques, SciPy ensures that integral approximations meet the stringent accuracy requirements of engineering projects. This makes SciPy an indispensable tool in the quest for precision and efficiency in hydropower and water resource design and development where issues like cavitation or turbulence are critical for equipment design and performance.
But doesnβt Excel do this?
Yes, BUT Excel's integration techniques are simpler and more suitable for basic numerical integration tasks often encountered in general data analysis and simple mathematical modelling. Here are key limitations and reasons for the simplicity of Excel's integration capabilities:
Limited Integration Methods: Excel primarily uses basic numerical integration techniques, such as the trapezoidal rule or Simpson's rule, to approximate integrals. These methods work well for relatively simple functions but may not provide highly accurate results for complex or oscillatory functions.
Single Variable Integration: Excel's built-in functions are typically designed for single-variable integration. While you can use Excel for basic double or triple integrals, it becomes cumbersome for multidimensional integration compared to specialized mathematical software.
Limited Function Support: Excel's integration functions may not handle all mathematical functions, especially those involving special functions or complex mathematical expressions. In contrast, specialized mathematical software libraries like SciPy have extensive support for various mathematical functions.
Limited Customization: Excel's integration capabilities offer limited customization options. Users have less control over the integration process, including specifying convergence criteria or handling singularities.
Scalability: For complex engineering or scientific simulations that require extensive numerical integration, Excel's performance may become a limiting factor. Dedicated numerical computation tools like SciPy are optimized for such tasks.
Non-Interactive Environment: Excel is primarily used for spreadsheet-based calculations and is not designed as an interactive numerical computation environment. This makes it less suitable for iterative or complex numerical analysis tasks.
Lack of Advanced Features: Excel lacks advanced features commonly found in specialized numerical software, such as adaptive integration, parallel processing, and support for large datasets.
So Why is This Important?
Structural engineering encompasses a wide range of areas where numerical integration and advanced numerical techniques can be leveraged for analysis and design. Here are key areas within structural engineering that benefit from numerical integration:
Dynamics Analysis: Numerical integration is crucial for dynamic analysis in structural engineering. This includes analyzing the response of structures to dynamic loads such as earthquakes, wind, or machinery vibrations. Techniques like the finite element method (FEM) combined with numerical integration play a significant role in dynamic analysis.
3D Finite Element (FE) Models: 3D FE models of structures are commonly used for detailed stress analysis, deformation, and stability assessments. Numerical integration within the context of FEM helps solve complex structural problems, including static and dynamic analyses.
Fatigue Analyses: Fatigue analyses involve the assessment of how structures respond to cyclic loading over time. Numerical integration is used to evaluate stress and strain histories, which are then compared to fatigue life models to predict the durability of structures.
Thermal Analyses: Thermal analysis in structural engineering assesses the impact of temperature variations on structures. Numerical techniques, including numerical integration, are used to calculate temperature distributions and their effects on material properties and structural behaviour.
Buckling Analysis: Buckling analysis is crucial for assessing the stability of structures under different loads. Numerical integration helps solve eigenvalue problems and assess critical buckling loads.
Nonlinear Analysis: Many structural problems involve nonlinear behaviour, such as material nonlinearity (e.g., plasticity) or geometric nonlinearity (e.g., large deformations). Numerical integration techniques, like Newton-Raphson iterations, are employed to solve these complex nonlinear equations.
Seismic Analysis: Numerical integration is essential in seismic analysis to determine the response of structures during earthquakes. It helps assess structural performance, including deformation and stress distribution.
Optimization: Structural optimization involves finding the best design parameters to meet specific performance criteria, such as minimizing weight while ensuring structural integrity. Numerical integration plays a role in gradient-based optimization algorithms.
Structural Health Monitoring: Numerical integration is used in real-time structural health monitoring to assess the condition of existing structures based on sensor data, enabling early detection of potential issues.
In all these areas, numerical integration is a fundamental tool for solving complex mathematical equations that describe structural behaviour. It allows engineers to precisely analyze and design structures, assess safety, and optimize designs for various performance criteria. Specialized software and libraries, such as finite element analysis (FEA) software and numerical computation tools like SciPy and MATLAB, are commonly employed for these tasks, providing the necessary numerical integration capabilities.
Beyond SciPy and Related Python Libraries
While SciPy itself is a comprehensive library that includes numerical integration capabilities, specialized Python libraries build upon SciPy and offer additional features and tools for specific areas of structural engineering.
PyNite: My favourite structural library, Pynite, is a specialized civil and structural engineering library. It supports 3D static and P-Ξ analysis, various load types, load classifications, and load combinations. It generates shear, moment, and deflection results and diagrams, handles internal nodes, and includes tension/compression elements, plate elements, and meshing algorithms. The library reports support reactions, offers rendering, and generates PDF reports for structural models and results.
FEniCS: FEniCS is a robust finite element framework for solving partial differential equations (PDEs). It provides a high-level Python interface for defining and solving complex problems in structural mechanics, fluid dynamics, and other engineering fields. FEniCS leverages SciPy and other numerical libraries for its operations.
OpenSeesPy: OpenSees is a popular software framework for simulating the behaviour of structural and geotechnical systems. OpenSeesPy is a Python library that provides a Pythonic interface to OpenSees. It integrates seamlessly with SciPy when used for structural analysis and simulations.
Sfepy: SfePy (Simple Finite Elements in Python) is a framework for solving systems of coupled partial differential equations by finite element methods. It is tailored for problems in solid mechanics, fluid dynamics, and electromagnetics. SfePy utilizes SciPy for its numerical computations.
Tclabz: Tclabz is a library for solving thermal analysis problems, including transient heat conduction and heat transfer simulations. It builds on SciPy and is specifically designed for thermal analysis in structural engineering and other related fields.
PyDy: PyDy (Python Dynamics) is a library for modelling and simulating the dynamics of mechanical systems. It is particularly useful for multibody dynamics simulations and can be combined with SciPy for the numerical integration of dynamic equations.
While these libraries leverage SciPy and other numerical libraries under the hood, they provide higher-level abstractions and tools tailored to the needs of structural engineers, making it easier to set up and solve complex engineering problems. Depending on your specific requirements, one or more of these libraries may be suitable for your structural engineering projects. Each project has its own learning curve and documentation to help you solve your problems in new and novel ways.
Feedback
Do you use SciPy? Or any of the libraries mentioned above?
Do you find posts like this to be a bit heavy, or would you like to see more?
What topics are you interested in?
Let me know in the comments, and Iβll see you next time for more Flocode insights!
All the best in your coding journey.
See you in the next post!
James π
It's a good intro ! I'm excited..
Very interested in seeing examples on optimization for design!