Close Menu
    Trending
    • Gemini introducerar funktionen schemalagda åtgärder i Gemini-appen
    • AIFF 2025 Runway’s tredje årliga AI Film Festival
    • AI-agenter kan nu hjälpa läkare fatta bättre beslut inom cancervård
    • Not Everything Needs Automation: 5 Practical AI Agents That Deliver Enterprise Value
    • Prescriptive Modeling Unpacked: A Complete Guide to Intervention With Bayesian Modeling.
    • 5 Crucial Tweaks That Will Make Your Charts Accessible to People with Visual Impairments
    • Why AI Projects Fail | Towards Data Science
    • The Role of Luck in Sports: Can We Measure It?
    ProfitlyAI
    • Home
    • Latest News
    • AI Technology
    • Latest AI Innovations
    • AI Tools & Technologies
    • Artificial Intelligence
    ProfitlyAI
    Home » 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

    ProfitlyAIBy ProfitlyAIMay 30, 2025No Comments7 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    have change into extra frequent and devastating throughout the globe, with the consequences of local weather change in latest a long time. 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 tutorial research.

    On this article, we’ll construct a primary 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 approach to discover geospatial information and flood dangers, even and not using a background in hydraulic modeling.

    What you’ll Study

    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 an everyday grid (referred to as raster information) comprises an elevation worth. Not like digital photographs that retailer colour data, DEMs retailer top information, sometimes excluding floor options like vegetation, buildings, and different man-made constructions.

    DEMs are generally utilized in fields resembling 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 information, together with the USGS Nationwide Map, NASA Earthdata, and the Shuttle Radar Topography Mission (SRTM).

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

    Be aware: The info offered 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 beneath.

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

    2. Tips on how to load and visualize elevation information with Python

    Now we’ll use Python to set a viable setting to visualise and analyze some preliminary details about DEM information. First, let’s import the mandatory 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 information like DEMs.
    • matplotlib.pyplot: Creates static and interactive visualizations.
    • numpy: Handles numerical operations and array-based information.
    • 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 perform to load DEM Information
    def load_dem(path):
        with rasterio.open(path) as src:
            dem = src.learn(1)
            remodel = src.remodel
            nodata = src.nodata
    
            if nodata isn't None:
                # Masks no-data values
                dem = np.ma.masked_equal(dem, nodata)
    
            return dem, remodel

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

    Visualizing DEM information

    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 features). To raised perceive flood inundation, it’s 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 information of the DEM file. As mentioned earlier, the DEM we’re utilizing makes use of the WGS84 coordinate system (EPSG: 4326).

    We will adapt the helper perform to load DEM recordsdata as follows:

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

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

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

    dem, remodel = load_dem("s06_w039_1arc_v3.tif")
    
    # Compute extent from remodel
    extent = [
        transform[2],                          # xmin (longitude)
        remodel[2] + remodel[0] * dem.form[1],  # xmax
        remodel[5] + remodel[4] * dem.form[0],  # ymin (latitude)
        remodel[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 remodel affine object. It units the minimal and most longitude (xmin, xmax) and latitude (ymin, ymax) in order that the plot exhibits coordinates on the axes as a substitute of pixel indices.

    Lastly, now we have the next outcomes:

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

    3. Tips on how to simulate flood eventualities with elevation thresholds

    Now, we’ll exhibit a easy but helpful technique for visualizing flood eventualities and simulating inundation. It consists of defining a top threshold and producing a binary masks that identifies all areas with elevation beneath this degree.

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

    flood_threshold = 40  # meters
    flood_mask = (dem <= flood_threshold).astype(int)
    
    plt.imshow(flood_mask, extent=extent, cmap='Blues')
    plt.title(f"Flooded Space (Threshold: {flood_threshold}m)")
    plt.xlabel("Longitude")
    plt.ylabel("Latitude")
    plt.present()
    Flooded space simulation (picture by the writer).

    With only a few strains of code, we are able to visualize the influence of various flood eventualities on the realm of curiosity (AOI). Nevertheless, as a result of this visualization is static, it doesn’t present how the flood progresses over time. To cope with that, we’ll use matplotlib’s FuncAnimation to create a dynamic visualization.

    4. Tips on how to animate flood development with Python

    We’ll now simulate a progressive flood state of affairs by rising the water degree 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 perform
    def replace(body):
        degree = flood_levels[frame]
        masks = np.the place(dem <= degree, 1, np.nan)
        flood_overlay.set_data(masks)
        title.set_text(f"Flood Degree: {degree} m")
        return flood_overlay, title
    
    # Create animation
    ani = FuncAnimation(fig, replace, frames=len(flood_levels), interval=300, blit=True)
    plt.tight_layout()
    plt.present()
    
    # save the output as a gif
    ani.save("flood_simulation.gif", author='pillow', fps=5)
    Flood development (Credit score: U.S. Geological Survey)

    For those who’re desirous about creating animations with Python, this step-by-step tutorial is a good place to begin.

    Conclusion and subsequent steps

    On this article, we created a primary workflow to carry out a flood simulation in Python utilizing elevation information from a DEM file. After all, this mannequin doesn’t implement essentially the most superior strategies on the topic, nonetheless for visualization and communication, this elevation threshold technique gives a robust and accessible entry level.

    Extra superior simulation strategies embody:

    • Connectivity-based flood propagation
    • Move course and accumulation
    • Time-based movement modeling

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

    The entire code is accessible here.

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

    References

    [1] U.S. Geological Survey. Nationwide Map. U.S. Division of the Inside. Retrieved Might 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 Might 17, 2025, from https://www.usgs.gov/faqs/what-a-digital-elevation-model-dem

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

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

    Information Supply: DEM information used on this mission is offered 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 ArticleFueling seamless AI at scale
    Next Article LLM Optimization: LoRA and QLoRA | Towards Data Science
    ProfitlyAI
    • Website

    Related Posts

    Artificial Intelligence

    Not Everything Needs Automation: 5 Practical AI Agents That Deliver Enterprise Value

    June 6, 2025
    Artificial Intelligence

    Prescriptive Modeling Unpacked: A Complete Guide to Intervention With Bayesian Modeling.

    June 6, 2025
    Artificial Intelligence

    5 Crucial Tweaks That Will Make Your Charts Accessible to People with Visual Impairments

    June 6, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Top Posts

    Anthropic introducerar Integrations som ansluter användares appar och verktyg direkt till Claude

    May 3, 2025

    Get Started with Rust: Installation and Your First CLI Tool – A Beginner’s Guide

    May 13, 2025

    Kernel Case Study: Flash Attention

    April 3, 2025

    A Google Gemini model now has a “dial” to adjust how much it reasons

    April 17, 2025

    How to build a better AI benchmark

    May 8, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    Most Popular

    Prototyping Gradient Descent in Machine Learning

    May 24, 2025

    Google AMIE verktyg för medicinsk diagnostik uppgraderas med visuell tolkning

    May 4, 2025

    A small US city experiments with AI to find out what residents want

    April 15, 2025
    Our Picks

    Gemini introducerar funktionen schemalagda åtgärder i Gemini-appen

    June 7, 2025

    AIFF 2025 Runway’s tredje årliga AI Film Festival

    June 7, 2025

    AI-agenter kan nu hjälpa läkare fatta bättre beslut inom cancervård

    June 7, 2025
    Categories
    • AI Technology
    • AI Tools & Technologies
    • Artificial Intelligence
    • Latest AI Innovations
    • Latest News
    • Privacy Policy
    • Disclaimer
    • Terms and Conditions
    • About us
    • Contact us
    Copyright © 2025 ProfitlyAI All Rights Reserved.

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