Sunday, August 24, 2025

#6 Civil Applications using Python

 Let’s dive deeper into civil engineering applications with Python.

I’ll give you detailed, explained code for three real-world tasks:

  1. BMD (Bending Moment Diagram) & SFD plotting

  2. Rainfall data analysis (Hydrology)

  3. Survey data processing (Coordinate method for area)


📘 1. Shear Force & Bending Moment Diagram (SFD & BMD)

🎯 Theory

  • A beam under loads has Shear Force (V) and Bending Moment (M) at every section.

  • Equilibrium conditions are used to compute reactions at supports.

  • For a simply supported beam with span L and a point load P at midspan:

    • Reactions: RA=RB=P/2R_A = R_B = P/2

    • Shear force is +RA+R_A till midspan, then RB-R_B.

    • Bending moment: linear, max at midspan: Mmax=PL4M_{max} = \frac{PL}{4}.

🐍 Python Code

import numpy as np
import matplotlib.pyplot as plt

# Beam parameters
L = 6   # length of beam in meters
P = 20  # point load in kN at midspan
a = L/2 # location of load

# Reactions
RA = RB = P/2

# Discretize beam
x = np.linspace(0, L, 100)

# Shear force (piecewise function)
V = np.piecewise(x, [x <= a, x > a], [RA, -RB])

# Bending moment (linear on each side)
M = np.piecewise(x, [x <= a, x > a],
                 [lambda x: RA*x,
                  lambda x: RB*(L-x)])

# Plotting
plt.figure(figsize=(8,6))

plt.subplot(2,1,1)
plt.plot(x, V, color="blue")
plt.axhline(0, color="black", linewidth=0.7)
plt.title("Shear Force Diagram (SFD)")
plt.ylabel("Shear Force (kN)")
plt.grid(True)

plt.subplot(2,1,2)
plt.plot(x, M, color="red")
plt.axhline(0, color="black", linewidth=0.7)
plt.title("Bending Moment Diagram (BMD)")
plt.xlabel("Beam Length (m)")
plt.ylabel("Moment (kNm)")
plt.grid(True)

plt.tight_layout()
plt.show()

✅ This shows the jump in shear at load point and the triangular bending moment distribution.


📘 2. Rainfall Data Analysis (Hydrology)

🎯 Theory

  • Rainfall data is collected from multiple stations.

  • Arithmetic mean method or Thiessen polygon method is used for average rainfall.

  • Here we’ll use pandas to process rainfall data and matplotlib to plot annual trends.

🐍 Python Code

import pandas as pd
import matplotlib.pyplot as plt

# Example rainfall data (mm) for 5 years
data = {
    "Year": [2018, 2019, 2020, 2021, 2022],
    "Station_A": [850, 920, 870, 910, 890],
    "Station_B": [800, 880, 860, 930, 910],
    "Station_C": [780, 850, 810, 870, 860]
}

df = pd.DataFrame(data)

# Compute average rainfall (Arithmetic Mean)
df["Avg_Rainfall"] = df[["Station_A","Station_B","Station_C"]].mean(axis=1)

print("Rainfall Data:\n", df)

# Plot rainfall trend
plt.figure(figsize=(7,4))
plt.plot(df["Year"], df["Station_A"], marker="o", label="Station A")
plt.plot(df["Year"], df["Station_B"], marker="o", label="Station B")
plt.plot(df["Year"], df["Station_C"], marker="o", label="Station C")
plt.plot(df["Year"], df["Avg_Rainfall"], marker="s", linestyle="--", color="black", label="Average")

plt.title("Annual Rainfall Analysis")
plt.xlabel("Year")
plt.ylabel("Rainfall (mm)")
plt.legend()
plt.grid(True)
plt.show()

✅ This produces a line chart showing rainfall variation across stations and the average.
Civil engineers use such analysis for hydrological design (dams, canals, urban drainage).


📘 3. Survey Data Processing (Coordinate Method for Area)

🎯 Theory

  • For a closed traverse, area can be computed using the Shoelace Formula:

A=12(xiyi+1xi+1yi)A = \frac{1}{2} \left| \sum (x_i y_{i+1} - x_{i+1} y_i) \right|
  • Commonly used in surveying and GIS.

🐍 Python Code

# Coordinates of a land parcel (survey data)
coords = [(0,0), (60,0), (80,40), (40,60), (0,40)]

# Apply Shoelace formula
area = 0
n = len(coords)
for i in range(n):
    x1, y1 = coords[i]
    x2, y2 = coords[(i+1) % n]  # next point (cyclic)
    area += (x1*y2 - x2*y1)

area = abs(area)/2
print("Surveyed Land Area =", area, "sq.m")

# Plotting the boundary
xs, ys = zip(*coords)
plt.figure(figsize=(6,6))
plt.fill(xs + (xs[0],), ys + (ys[0],), color="lightblue", alpha=0.6, edgecolor="black")
plt.scatter(xs, ys, color="red")
for i, (x,y) in enumerate(coords):
    plt.text(x+1, y+1, f"P{i+1}")
plt.title("Survey Plot (Coordinate Method)")
plt.xlabel("X (m)")
plt.ylabel("Y (m)")
plt.axis("equal")
plt.grid(True)
plt.show()

✅ This computes land area from survey coordinates and plots the site boundary.


🔑 Summary

  • BMD/SFD → Structural engineering visualization.

  • Rainfall analysis → Hydrology applications.

  • Survey data processing → Surveying/GIS applications.

#5 Visualization & Project Work

 👍 — here’s a more detailed Module 6: Visualization & Project Work code set for your mini course.

This module focuses on Matplotlib, Seaborn, and optional GeoPandas for civil engineering visualization.


🔹 1. Stress–Strain Curve (Lab Data Visualization)

import matplotlib.pyplot as plt # Sample lab data stress = [0, 50, 100, 150, 200, 250, 280] strain = [0, 0.001, 0.002, 0.0032, 0.0042, 0.005, 0.006] plt.figure(figsize=(6,4)) plt.plot(strain, stress, marker='o', color='b', label="Stress-Strain") plt.xlabel("Strain") plt.ylabel("Stress (N/mm²)") plt.title("Stress-Strain Curve") plt.grid(True) plt.legend() plt.show()

🔹 2. Rainfall vs. Runoff Relationship

import numpy as np rainfall = [20, 40, 60, 80, 100, 120] # mm runoff = [5, 15, 28, 40, 60, 85] # mm plt.figure(figsize=(6,4)) plt.scatter(rainfall, runoff, color='green', label="Observed Data") plt.plot(rainfall, runoff, linestyle="--", color="black") plt.xlabel("Rainfall (mm)") plt.ylabel("Runoff (mm)") plt.title("Rainfall vs Runoff") plt.legend() plt.grid(True) plt.show()

🔹 3. Bar Bending Schedule (BBS) Automation

import pandas as pd # Example BBS data (Beam reinforcement) data = { "Bar Mark": ["B1", "B2", "B3"], "Diameter (mm)": [12, 16, 20], "Length (m)": [6, 8, 12], "No. of Bars": [10, 8, 6] } bbs = pd.DataFrame(data) bbs["Total Length (m)"] = bbs["Length (m)"] * bbs["No. of Bars"] bbs["Weight (kg)"] = bbs["Total Length (m)"] * bbs["Diameter (mm)"] * 0.006165 # IS formula print("Bar Bending Schedule:\n") print(bbs)

🔹 4. Traffic Flow Line Graph

time = np.arange(0, 11) # minutes vehicles = [50, 55, 60, 70, 85, 90, 95, 92, 88, 85, 80] plt.figure(figsize=(6,4)) plt.plot(time, vehicles, marker="o", color="red") plt.xlabel("Time (minutes)") plt.ylabel("Number of Vehicles") plt.title("Traffic Flow Simulation") plt.grid(True) plt.show()

🔹 5. Optional: Plotting Survey/GIS Data (GeoPandas)

# Uncomment if geopandas is installed # import geopandas as gpd # world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) # world[world.name == "India"].plot() # plt.title("India Map - Example for Civil GIS Work") # plt.show()

✅ With these codes, students can visualize structural, hydrological, and transportation data.

#4 Google Co Lab Notebook for all Modules

complete Colab notebook that covers all 6 modules from the mini course:

  • Module 1 – Python Basics for Engineers

  • Module 2 – Numerical Computation & Engineering Math

  • Module 3 – Structural Engineering Applications

  • Module 4 – Surveying & Geotechnical Applications

  • Module 5 – Hydrology & Transportation

  • Module 6 – Visualization & Project Work



#3 Module 1 Colab

Ready-to-use Colab notebook content (you can copy-paste into a .ipynb or open directly in Colab):


📘 Python for Civil Engineering – Module 1: Basics

# Module 1: Python Foundations for Engineers This notebook covers: 1. Factor of Safety (FoS) 2. BMI Calculator 3. Simple Interest 4. Material Quantity Estimation (Loop Example)

🔹 1. Factor of Safety

# Factor of Safety Calculation def factor_of_safety(strength, stress): if stress == 0: return "Stress cannot be zero!" return strength / stress # Example usage strength = float(input("Enter material strength (N/mm²): ")) stress = float(input("Enter applied stress (N/mm²): ")) fos = factor_of_safety(strength, stress) print(f"Factor of Safety = {fos:.2f}") if isinstance(fos, float): if fos >= 1.5: print("✅ Safe design") else: print("⚠️ Not safe, redesign required")

🔹 2. BMI Calculator (Worker Health Check)

# BMI Calculation def bmi(weight, height): return weight / (height ** 2) weight = float(input("Enter weight (kg): ")) height = float(input("Enter height (m): ")) bmi_value = bmi(weight, height) print(f"BMI = {bmi_value:.2f}") if bmi_value < 18.5: print("Underweight ❗") elif 18.5 <= bmi_value < 24.9: print("Normal ✅") elif 25 <= bmi_value < 29.9: print("Overweight ⚠️") else: print("Obese 🚨")

🔹 3. Simple Interest (Finance in Construction Projects)

# Simple Interest Calculator def simple_interest(principal, rate, time): return (principal * rate * time) / 100 p = float(input("Enter Principal Amount (₹): ")) r = float(input("Enter Rate of Interest (%): ")) t = float(input("Enter Time (years): ")) si = simple_interest(p, r, t) print(f"Simple Interest = ₹{si:.2f}") print(f"Total Amount Payable = ₹{p + si:.2f}")

🔹 4. Material Quantity Estimation (Loop Example)

# Calculate volume of multiple beams (loop example) n = int(input("Enter number of beams: ")) total_volume = 0 for i in range(n): print(f"\nBeam {i+1}") length = float(input(" Enter length (m): ")) breadth = float(input(" Enter breadth (m): ")) depth = float(input(" Enter depth (m): ")) volume = length * breadth * depth total_volume += volume print(f" Volume = {volume:.2f} m³") print(f"\nTotal Concrete Volume for {n} beams = {total_volume:.2f} m³")

✅ Now you can upload this as a Colab notebook.

#1 Intro to Mini Course on Python 4 Civil Engineers

 A mini course on "Python for Civil Engineering" will help civil engineers and students apply programming to solve real-world engineering problems like structural analysis, surveying, hydrology, and construction management.

Here’s a structured 6-module mini course with outcomes, topics, and practice exercises.


📘 Mini Course: Python for Civil Engineering

🎯 Course Outcomes

By the end of this course, learners will be able to:

  1. Apply Python basics to solve engineering calculations.

  2. Use scientific libraries (NumPy, Pandas, Matplotlib) for data analysis and visualization.

  3. Automate structural and geotechnical calculations.

  4. Perform hydrology and transportation simulations.

  5. Work with real-world data (CSV, Excel, GIS).


🏗️ Module 1: Python Foundations for Engineers

  • Python installation (Anaconda / VS Code / Jupyter).

  • Basics: variables, data types, input/output.

  • Control structures: if-else, loops.

  • Functions for engineering calculations.

Exercise:

  • Write a program to calculate the factor of safety (FoS = Strength / Stress).

  • Create a function to compute BMI (basic health check for construction workers).


📊 Module 2: Numerical Computation & Engineering Math

  • Using NumPy for arrays and matrices.

  • Solving linear equations (structural equilibrium problems).

  • Numerical methods: roots, interpolation, integration.

Exercise:

  • Solve a 2D truss equilibrium system using linear algebra.

  • Compute the area under a stress-strain curve using numerical integration.


🏢 Module 3: Structural Engineering Applications

  • Beam deflection & bending moment using Python.

  • Load distribution analysis.

  • Automating IS Code formulas.

Exercise:

  • Plot Shear Force Diagram (SFD) and Bending Moment Diagram (BMD) for a simply supported beam with point loads.


🌍 Module 4: Surveying & Geotechnical Applications

  • Handling Excel/CSV data (field survey data).

  • Coordinate geometry & leveling calculations.

  • Soil mechanics: bearing capacity, settlement calculation.

Exercise:

  • Import total station survey data (CSV) and compute area using coordinate method.

  • Write a program to calculate Terzaghi’s Bearing Capacity.


💧 Module 5: Hydrology & Transportation

  • Rainfall analysis using Pandas.

  • Peak discharge estimation (Rational Method).

  • Traffic flow simulation using Python loops.

Exercise:

  • Read rainfall data from Excel and compute average rainfall using Thiessen polygon method.

  • Simulate traffic density with varying inflow/outflow.


📈 Module 6: Visualization & Project Work

  • Data visualization using Matplotlib & Seaborn.

  • GIS basics with geopandas (optional).

  • Mini project.

Mini Project Ideas:

  • Analyze cement concrete strength test data and plot stress-strain curve.

  • Create a rainfall vs. runoff visualization for a watershed.

  • Automate bar bending schedule (BBS) generation from beam data.


⏳ Duration

  • 6 Modules → 2 hours each → 12 hours mini course

  • Ideal for 2-week (6 sessions) or 6-week (weekend) program.



#6 Civil Applications using Python

 Let’s dive deeper into civil engineering applications with Python . I’ll give you detailed, explained code for three real-world tasks: ...