Close Menu
    Trending
    • Your Team Will Love This Easy-to-Use PDF Editor
    • Patterns at Your Fingertips: A Practitioner’s Journey into Fingerprint Classification | by Everton Gomede, PhD | Jun, 2025
    • Get Microsoft 365 for Six People a Year for Just $100
    • The Age of Thinking Machines: Are We Ready for AI with a Mind of Its Own? | by Mirzagalib | Jun, 2025
    • Housing Market Hits a Record, More Sellers Than Buyers
    • Gaussian-Weighted Word Embeddings for Sentiment Analysis | by Sgsahoo | Jun, 2025
    • How a Firefighter’s ‘Hidden’ Side Hustle Led to $22M in Revenue
    • Hands-On CUDA ML Setup with PyTorch & TensorFlow on WSL2
    Finance StarGate
    • Home
    • Artificial Intelligence
    • AI Technology
    • Data Science
    • Machine Learning
    • Finance
    • Passive Income
    Finance StarGate
    Home»Artificial Intelligence»Simulating Flood Inundation with Python and Elevation Data: A Beginner’s Guide
    Artificial Intelligence

    Simulating Flood Inundation with Python and Elevation Data: A Beginner’s Guide

    FinanceStarGateBy FinanceStarGateMay 31, 2025No Comments7 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    have turn out to be extra frequent and devastating throughout the globe, with the results of local weather change in latest many years. On this context, flood modeling has an necessary function in danger evaluation and disaster-response operations, whereas additionally remaining a key focus of superior analysis and educational research.

    On this article, we’ll construct a fundamental flood inundation mannequin utilizing Python and a Digital Elevation Mannequin (DEM). We’ll use a flood fill method to incrementally simulate how rising water ranges have an effect on a panorama and animate the inundation course of. It’s a visible and hands-on strategy to discover geospatial knowledge and flood dangers, even with no background in hydraulic modeling.

    What you’ll Be taught

    1. What’s a Digital Elevation Mannequin (DEM)

    A Digital Elevation Mannequin (DEM) is a numerical illustration of the Earth’s floor, the place every cell (or pixel) in a daily grid (often called raster knowledge) incorporates an elevation worth. Not like digital photographs that retailer coloration info, DEMs retailer peak knowledge, sometimes excluding floor options like vegetation, buildings, and different man-made buildings.

    DEMs are generally utilized in fields equivalent to mapping, hydrology, environmental monitoring, and earth sciences. They function a foundational dataset for any utility that requires an in depth understanding of terrain and elevation.

    Many sources provide free and dependable DEM knowledge, together with the USGS Nationwide Map, NASA Earthdata, and the Shuttle Radar Topography Mission (SRTM).

    On this article, we’ll be utilizing a DEM supplied by the USGS National Geospatial Program, which is freely out there and launched into the general public area.

    Be aware: The info supplied by USGS has a spatial decision of 1 arc second (roughly 30 meters on the equator).

    The realm of curiosity (AOI) on this examine is situated within the Northeast area of Brazil. The DEM file covers a 1° × 1° tile, extending from 6°S, 39°W to five°S, 38°W, and makes use of the WGS84 coordinate system (EPSG: 4326), as illustrated under.

    Space of Curiosity (picture by the creator utilizing Google Maps and QGIS).

    2. Learn how to load and visualize elevation knowledge with Python

    Now we’ll use Python to set a viable surroundings to visualise and analyze some preliminary details about DEM knowledge. First, let’s import the required libraries.

    # import libraries
    import rasterio
    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.animation import FuncAnimation
    • rasterio: Reads and writes geospatial raster knowledge like DEMs.
    • matplotlib.pyplot: Creates static and interactive visualizations.
    • numpy: Handles numerical operations and array-based knowledge.
    • FuncAnimation: Generates animations by updating plots body by body.

    Subsequent, let’s use the rasterio library to open and visualize a DEM file of the AOI.

    # Helper operate to load DEM Information
    def load_dem(path):
        with rasterio.open(path) as src:
            dem = src.learn(1)
            rework = src.rework
            nodata = src.nodata
    
            if nodata just isn't None:
                # Masks no-data values
                dem = np.ma.masked_equal(dem, nodata)
    
            return dem, rework

    The operate above reads the elevation knowledge and checks whether or not the file consists of “no-data values”. No-data values are used to signify areas with out legitimate elevation knowledge (e.g., exterior protection or corrupted pixels). If a no-data worth is current, the operate replaces these pixels with np.nan, making it simpler to deal with or ignore them in later evaluation and visualizations.

    Visualizing DEM knowledge

    dem = load_dem("s06_w039_1arc_v3.tif")
    
    plt.imshow(dem, cmap='terrain')
    plt.title("Digital Elevation Mannequin")
    plt.colorbar(label="Elevation (m)")
    plt.present()
    DEM of the AOI (Credit score: U.S. Geological Survey)
    • Utilizing geographic coordinates within the visualization

    As we are able to see, the axes are in pixel coordinates (columns and contours). To raised perceive flood inundation, it’s very important to know the geographic coordinates (latitude and longitude) related to every pixel of the picture.

    To realize that, we’ll use the coordinate reference system knowledge of the DEM file. As mentioned earlier, the DEM we’re utilizing makes use of the WGS84 coordinate system (EPSG: 4326).

    We are able to adapt the helper operate to load DEM information as follows:

    def load_dem(path):
        with rasterio.open(path) as src:
            dem = src.learn(1)
            rework = src.rework
            nodata = src.nodata
    
            if nodata just isn't None:
                # Masks nodata values
                dem = np.ma.masked_equal(dem, nodata)
    
            return dem, rework

    The operate retrieves the rework knowledge from the DEM, which is an affine object that maps pixel positions (row, column) to geographic coordinates (latitude and longitude).

    To signify the geographic coordinates on the axes of the plot, it’ll be essential to discover the extent parameter from the imshow() operate.

    dem, rework = load_dem("s06_w039_1arc_v3.tif")
    
    # Compute extent from rework
    extent = [
        transform[2],                          # xmin (longitude)
        rework[2] + rework[0] * dem.form[1],  # xmax
        rework[5] + rework[4] * dem.form[0],  # ymin (latitude)
        rework[5]                          # ymax
    ]
    
    # Plot with utilizing geographic coordinates
    fig, ax = plt.subplots()
    img = ax.imshow(dem, cmap='terrain', extent=extent, origin='higher')
    ax.set_xlabel('Longitude')
    ax.set_ylabel('Latitude')
    plt.colorbar(img, label='Elevation (m)')
    plt.title('DEM Visualization')
    plt.present()

    The extent parameter will likely be used to outline the spatial bounds of the DEM plot utilizing values derived from the raster’s rework affine object. It units the minimal and most longitude (xmin, xmax) and latitude (ymin, ymax) in order that the plot reveals coordinates on the axes as a substitute of pixel indices.

    Lastly, we now have the next outcomes:

    DEM visualization with geographic coordinates (Credit score: U.S. Geological Survey).

    3. Learn how to simulate flood eventualities with elevation thresholds

    Now, we’ll show a easy but helpful methodology for visualizing flood eventualities and simulating inundation. It consists of defining a peak threshold and producing a binary masks that identifies all areas with elevation under this stage.

    On this instance, we simulate Flooding throughout all areas with elevations under 40 meters.

    flood_threshold = 40  # meters
    flood_mask = (dem 
    Flooded space simulation (picture by the creator).

    With just some traces of code, we are able to visualize the impression of various flood eventualities on the realm of curiosity (AOI). Nonetheless, as a result of this visualization is static, it doesn’t present how the flood progresses over time. To take care of that, we’ll use matplotlib’s FuncAnimation to create a dynamic visualization.

    4. Learn how to animate flood development with Python

    We’ll now simulate a progressive flood state of affairs by rising the water stage incrementally and producing a brand new masks at every step. We’ll overlay this masks on the terrain picture and animate it.

    # flood_levels defines how excessive the flood rises per body
    flood_levels = np.arange(15, 100, 5)
    
    # Arrange determine and axes
    fig, ax = plt.subplots()
    img = ax.imshow(dem, cmap='terrain', extent=extent, origin='higher')
    flood_overlay = ax.imshow(np.zeros_like(dem), cmap='Blues', alpha=0.4, extent=extent, origin='higher')
    title = ax.set_title("")
    ax.set_xlabel("Longitude")
    ax.set_ylabel("Latitude")
    
    # Animation operate
    def replace(body):
        stage = flood_levels[frame]
        masks = np.the place(dem 
    Flood development (Credit score: U.S. Geological Survey)

    In case you’re occupied with creating animations with Python, this step-by-step tutorial is a superb place to begin.

    Conclusion and subsequent steps

    On this article, we created a fundamental workflow to carry out a flood simulation in Python utilizing elevation knowledge from a DEM file. In fact, this mannequin doesn’t implement probably the most superior methods on the topic, nonetheless for visualization and communication, this elevation threshold methodology affords a strong and accessible entry level.

    Extra superior simulation methods embrace:

    • Connectivity-based flood propagation
    • Stream course and accumulation
    • Time-based circulate modeling

    Nonetheless, this hands-on method may be of nice profit for educators, college students, and analysts exploring Geospatial Data in catastrophe response research and environmental modeling.

    The whole code is on the market here.

    I strongly encourage readers to experiment with the code utilizing their very own elevation knowledge, adapt it to their particular context, and discover methods to reinforce or develop the method.

    References

    [1] U.S. Geological Survey. Nationwide Map. U.S. Division of the Inside. Retrieved Could 17, 2025, from https://www.usgs.gov/programs/national-geospatial-program/national-map

    [2] U.S. Geological Survey. What’s a digital elevation mannequin (DEM)? U.S. Division of the Inside. Retrieved Could 17, 2025, from https://www.usgs.gov/faqs/what-a-digital-elevation-model-dem

    [3] Gillies, S. Georeferencing — Rasterio documentation (secure). Rasterio. Retrieved Could 27, 2025, from https://rasterio.readthedocs.io/en/stable/topics/georeferencing.html

    [4] Gillies, Sean. Affine Transforms — Rasterio Documentation (Newest). Accessed Could 27, 2025. https://rasterio.readthedocs.io/en/latest/topics/transforms.html.

    Knowledge Supply: DEM knowledge used on this mission is supplied by the U.S. Geological Survey (USGS) by means of the Nationwide Map and is within the public area.



    Source link

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleFrom Text-to-Video to Hyper-Personalization: What’s Hot in AI Right Now | by Rana Mohsin | May, 2025
    Next Article Pillar To Post Home Inspectors is a Trusted Franchise in the Growing Home Inspection Industry
    FinanceStarGate

    Related Posts

    Artificial Intelligence

    How to Build an MCQ App

    May 31, 2025
    Artificial Intelligence

    LLM Optimization: LoRA and QLoRA | Towards Data Science

    May 31, 2025
    Artificial Intelligence

    The Secret Power of Data Science in Customer Support

    May 31, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Machine Learning Meets SEO: Smarter Keyword Research with AI | by Marketingdigitalzaa | Apr, 2025

    April 7, 2025

    Sales of Small Businesses Surged in Q1, Per New Report

    April 25, 2025

    Nvidia Rival FuriosaAI Rejected Meta’s $800 Million Offer

    March 27, 2025

    6 key lessons in building and enjoying your wealth

    March 27, 2025

    Starbucks Introduces a Strict New Dress Code for Baristas

    April 16, 2025
    Categories
    • AI Technology
    • Artificial Intelligence
    • Data Science
    • Finance
    • Machine Learning
    • Passive Income
    Most Popular

    Evolving Product Operating Models in the Age of AI

    March 22, 2025

    How I Make Money in Data Science (Beyond My 9–5) | by Tushar Mahuri | LearnAIforproft.com | May, 2025

    May 30, 2025

    Entrepreneur+ Subscribers-Only Event | March 26: This Stealth Mode Strategy Can Turn Your Side Hustle into a Six-Figure Success

    March 8, 2025
    Our Picks

    Trade Wars Could Be What The Housing Market Needs To Heat Up

    February 3, 2025

    Non-Parametric Density Estimation: Theory and Applications

    May 14, 2025

    I’m Extremely Competitive — Here’s How I Keep It from Becoming a Problem

    February 4, 2025
    Categories
    • AI Technology
    • Artificial Intelligence
    • Data Science
    • Finance
    • Machine Learning
    • Passive Income
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 Financestargate.com All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.