ACCESS THE COMPLETE LIBRARY OF COURSES & TUTORIALS ➡️
31. Refactor - Tidying up with functions
Direct Stiffness Method in Python
📂 Please log in or enroll to access resources

Summary

In this lecture, we'll cover:

  • Refactoring our existing structural analysis code to improve efficiency and readability
  • Creating a function to calculate the global element stiffness matrix
  • Automating the extraction of the structure stiffness matrix using restrained degrees of freedom
  • Using list comprehensions and NumPy’s delete function to reduce the primary stiffness matrix
  • Writing a reusable function to calculate member axial forces from nodal displacements

In this lecture, we focus on refactoring the code we developed previously so that it becomes cleaner, more efficient and easier to reuse. We begin by defining key problem parameters at the outset, such as the total number of degrees of freedom and the restrained degrees of freedom. We then encapsulate the repeated calculation of the global element stiffness matrix into a dedicated function. By passing in properties such as Young’s modulus, cross-sectional area, member length and orientation, we ensure that we can compute stiffness matrices for any member simply by calling the function rather than rewriting the same code multiple times.

We then improve the way we extract the structure stiffness matrix from the primary stiffness matrix. Instead of manually removing rows and columns, we use a list comprehension to determine the restrained indices and NumPy’s delete function to systematically remove the appropriate rows and columns. This makes the reduction process automatic and directly driven by the restrained degrees of freedom defined at the start of the script. Finally, we refactor the calculation of member axial forces into a separate function that takes nodal displacements and member properties as inputs. This allows us to compute forces for multiple members in a consistent and compact way, reinforcing the benefits of modular, well-structured code.

Next up:

In the next lecture, we begin Section 6, where we apply the direct stiffness method to a larger 8-bar truss, reinforcing the same procedure at a bigger scale.

Tags

stiffness matrix assemblyPython refactoringNumPy matrix operations

Please log in or enroll to continue

If you've already enrolled, please log in to continue.

The Direct Stiffness Method for Truss Analysis with Python

Build your own finite element truss analysis software using Python and tackle large scale structures.

After completing this course...

  • You’ll understand how to use the Direct Stiffness Method to build complete structural models that can be solved using Python.
  • You’ll have your own analysis programme to identify displacements, reactions and internal member forces for any truss.
  • You’ll understand how common models of elastic behaviour such as plane stress and plane strain apply to real-world structures.
Next Lesson
32. Section 6 overview