• Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
Wednesday, February 25, 2026
newsaiworld
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
Morning News
No Result
View All Result
Home Artificial Intelligence

Simulating Flood Inundation with Python and Elevation Information: A Newbie’s Information

Admin by Admin
June 1, 2025
in Artificial Intelligence
0
Kelly sikkema whs7fpfkwq unsplash scaled 1.jpg
0
SHARES
3
VIEWS
Share on FacebookShare on Twitter

READ ALSO

Optimizing Token Era in PyTorch Decoder Fashions

Is the AI and Knowledge Job Market Lifeless?


have change into extra frequent and devastating throughout the globe, with the results of local weather change in current a long time. On this context, flood modeling has an vital function in threat 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 technique to discover geospatial information and flood dangers, even with out 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 a daily grid (referred to as raster information) accommodates an elevation worth. Not like digital photographs that retailer colour info, DEMs retailer peak information, usually excluding floor options like vegetation, buildings, and different man-made constructions.

DEMs are generally utilized in fields comparable to mapping, hydrology, environmental monitoring, and earth sciences. They function a foundational dataset for any software 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 Nationwide Geospatial Program, which is freely accessible and launched into the general public area.

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

The realm of curiosity (AOI) on this research is positioned 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. How you can 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 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 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 operate 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 just isn't None:
            # Masks no-data values
            dem = np.ma.masked_equal(dem, nodata)

        return dem, remodel

The operate above reads the elevation information and checks whether or not the file contains “no-data values”. No-data values are used to symbolize areas with out legitimate elevation information (e.g., outdoors 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 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 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 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 operate to load DEM information as follows:

def load_dem(path):
    with rasterio.open(path) as src:
        dem = src.learn(1)
        remodel = src.remodel
        nodata = src.nodata

        if nodata just isn't None:
            # Masks nodata values
            dem = np.ma.masked_equal(dem, nodata)

        return dem, remodel

The operate 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() operate.

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 can 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, we have now the next outcomes:

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

3. How you can simulate flood situations with elevation thresholds

Now, we’ll show a easy but helpful methodology for visualizing flood situations 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 <= 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 creator).

With only a few traces of code, we are able to visualize the affect of various flood situations 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 take care of that, we’ll use matplotlib’s FuncAnimation to create a dynamic visualization.

4. How you can animate flood development with Python

We’ll now simulate a progressive flood situation by growing 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 <= stage, 1, np.nan)
    flood_overlay.set_data(masks)
    title.set_text(f"Flood Degree: {stage} 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)

If you happen to’re keen on creating animations with Python, this step-by-step tutorial is a superb place to start out.

Conclusion and subsequent steps

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

Extra superior simulation strategies embrace:

  • Connectivity-based flood propagation
  • Stream route and accumulation
  • Time-based circulation modeling

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

The entire code is offered right 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 reinforce or develop the strategy.

References

[1] U.S. Geological Survey. Nationwide Map. U.S. Division of the Inside. Retrieved Could 17, 2025, from https://www.usgs.gov/packages/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/secure/subjects/georeferencing.html

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

Information Supply: DEM information used on this venture is offered by the U.S. Geological Survey (USGS) via the Nationwide Map and is within the public area.

Tags: beginnersDataElevationfloodGuideInundationPythonSimulating

Related Posts

1 1 1.jpeg
Artificial Intelligence

Optimizing Token Era in PyTorch Decoder Fashions

February 25, 2026
Comp 23 0 00 09 03.jpg
Artificial Intelligence

Is the AI and Knowledge Job Market Lifeless?

February 24, 2026
Image 143.jpg
Artificial Intelligence

Construct Efficient Inner Tooling with Claude Code

February 23, 2026
Lucid origin modern flat vector illustration of ai coding while security shields around an ap 0.jpg
Artificial Intelligence

The Actuality of Vibe Coding: AI Brokers and the Safety Debt Disaster

February 23, 2026
Chatgpt image feb 18 2026 at 08 49 33 pm.jpg
Artificial Intelligence

AI in A number of GPUs: How GPUs Talk

February 22, 2026
Igor omilaev eggfz5x2lna unsplash scaled 1.jpg
Artificial Intelligence

Architecting GPUaaS for Enterprise AI On-Prem

February 21, 2026
Next Post
019429b9 3c76 7189 a3a4 b63f126379ec.jpeg

Czech Justice Minister Resigns Over $45M Bitcoin Donation Scandal

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

POPULAR NEWS

Chainlink Link And Cardano Ada Dominate The Crypto Coin Development Chart.jpg

Chainlink’s Run to $20 Beneficial properties Steam Amid LINK Taking the Helm because the High Creating DeFi Challenge ⋆ ZyCrypto

May 17, 2025
Gemini 2.0 Fash Vs Gpt 4o.webp.webp

Gemini 2.0 Flash vs GPT 4o: Which is Higher?

January 19, 2025
Image 100 1024x683.png

Easy methods to Use LLMs for Highly effective Computerized Evaluations

August 13, 2025
Blog.png

XMN is accessible for buying and selling!

October 10, 2025
0 3.png

College endowments be a part of crypto rush, boosting meme cash like Meme Index

February 10, 2025

EDITOR'S PICK

Over 48000 bitcoin pulled from exchanges in a week as price nears 100000.jpg

Japan’s Metaplanet Doubles Down On Bitcoin As Value Dives Below $115,000, Buys 775 Extra BTC ⋆ ZyCrypto

August 18, 2025
1200x720 2 1761808216lgqod3acnl.jpg

Cryptobanco to Showcase Its Platform at SiGMA Central Rome 2025

October 30, 2025
0 7eueoj Fk3igarxn.webp.webp

The Case for Centralized AI Mannequin Inference Serving

April 2, 2025
Rosidi 10 free online courses to master python 2.png

10 Free On-line Programs to Grasp Python in 2025

July 27, 2025

About Us

Welcome to News AI World, your go-to source for the latest in artificial intelligence news and developments. Our mission is to deliver comprehensive and insightful coverage of the rapidly evolving AI landscape, keeping you informed about breakthroughs, trends, and the transformative impact of AI technologies across industries.

Categories

  • Artificial Intelligence
  • ChatGPT
  • Crypto Coins
  • Data Science
  • Machine Learning

Recent Posts

  • Why Buyers Are Not Shopping for Bitcoin And Ethereum Regardless of ‘Low’ Costs
  • LLM Embeddings vs TF-IDF vs Bag-of-Phrases: Which Works Higher in Scikit-learn?
  • AMD and Meta Broaden Partnership with 6 GW of AMD GPUs for AI Infrastructure
  • Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy

© 2024 Newsaiworld.com. All rights reserved.

No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us

© 2024 Newsaiworld.com. All rights reserved.

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?