Sunday, 18 May 2025

Moon Crater Pattern using Python

 


import matplotlib.pyplot as plt

import numpy as np

from scipy.ndimage import gaussian_filter


size=500

terrain=np.zeros((size,size))

def add_crater(map,x0,y0,radius,depth):

    x=np.arange(map.shape[0])

    y=np.arange(map.shape[1])

    X,Y=np.meshgrid(x,y,indexing='ij')

    crater = -depth * np.exp(-(((X - x0)**2 + (Y - y0)**2) / (2 * radius**2)))

    map+=crater

num_craters=100

np.random.seed(42)

for _ in range(num_craters):

    x=np.random.randint(0,size)

    y=np.random.randint(0,size)

    radius=np.random.randint(5,25)

    depth=np.random.uniform(0.1,0.6)

    add_crater(terrain,x,y,radius,depth)

terrain=gaussian_filter(terrain,sigma=1)

plt.figure(figsize=(6,6))

plt.imshow(terrain,cmap='gray',origin='lower')

plt.title('Moon Crater Pattern using Python')

plt.axis('off')

plt.colorbar(label='Depth')

plt.tight_layout()

plt.show()

#source code --> clcoding.com 

Code Explanation:

Step 1: Import Libraries

import numpy as np

import matplotlib.pyplot as plt

from scipy.ndimage import gaussian_filter

numpy (as np): Used for numerical operations, creating arrays, and random number generation.

 matplotlib.pyplot (as plt): Used for creating and displaying the plot.

 scipy.ndimage.gaussian_filter: Used to smooth the terrain to make the craters look more natural (optional).

 Step 2: Initialize Base Terrain (Flat Moon Surface)

size = 500

terrain = np.zeros((size, size))

size = 500: Defines the grid size of the terrain, creating a 500x500 map of the surface.

 terrain = np.zeros((size, size)): Initializes a flat terrain of zeros (0), where each point represents the surface height (0 means the flat surface).

 Step 3: Function to Add a Crater

def add_crater(map, x0, y0, radius, depth):

    x = np.arange(map.shape[0])

    y = np.arange(map.shape[1])

    X, Y = np.meshgrid(x, y, indexing='ij')

    crater = -depth * np.exp(-(((X - x0)**2 + (Y - y0)**2) / (2 * radius**2)))

    map += crater

add_crater() is a function that adds a Gaussian-shaped crater to the map.

 x0, y0: The center of the crater (location of the impact).

 radius: The size of the crater (affects how quickly the depth decreases away from the center).

 depth: The depth of the crater.

 Inside the function:

 x = np.arange(map.shape[0]): Creates an array of x-coordinates for the grid (from 0 to the map width).

 y = np.arange(map.shape[1]): Creates an array of y-coordinates for the grid (from 0 to the map height).

 X, Y = np.meshgrid(x, y, indexing='ij'): Creates a 2D grid of coordinates based on x and y. X holds the x-coordinates, and Y holds the y-coordinates.

 crater = -depth * np.exp(-(((X - x0)**2 + (Y - y0)**2) / (2 * radius**2))): This is the Gaussian function that creates a depression centered at (x0, y0) with the specified radius and depth. The formula creates a bell-shaped curve that decays as you move away from the center, simulating the impact of a crater.

 map += crater: Adds the crater depression to the terrain.

 Step 4: Generate Random Craters

num_craters = 100

np.random.seed(42)  # Reproducibility

 for _ in range(num_craters):

    x = np.random.randint(0, size)

    y = np.random.randint(0, size)

    radius = np.random.randint(5, 25)

    depth = np.random.uniform(0.1, 0.6)

    add_crater(terrain, x, y, radius, depth)

num_craters = 100: Sets the number of craters to be added to the map. In this case, 100 random craters will be placed.

 np.random.seed(42): Sets the random seed for reproducibility. This ensures that the random number generator produces the same sequence of random numbers every time you run the code.

 The loop generates random crater parameters (x, y, radius, and depth):

 x = np.random.randint(0, size): Randomly selects the x-coordinate of the crater (within the grid's size).

 y = np.random.randint(0, size): Randomly selects the y-coordinate of the crater.

 radius = np.random.randint(5, 25): Randomly chooses a radius for the crater, between 5 and 25 units.

 depth = np.random.uniform(0.1, 0.6): Randomly selects a depth for the crater, between 0.1 and 0.6.

 add_crater(terrain, x, y, radius, depth): Calls the add_crater() function to add each randomly generated crater to the terrain.

 Step 5: Smooth the Terrain (Optional)

terrain = gaussian_filter(terrain, sigma=1)

gaussian_filter(terrain, sigma=1): Smooths the terrain slightly using a Gaussian filter.

 sigma=1: Controls the amount of smoothing (higher values result in more smoothing).

 This step is optional but can make the craters appear more natural, as it reduces harsh edges and makes the craters blend more smoothly with the surrounding terrain.

 Step 6: Plot the Cratered Surface

plt.figure(figsize=(8, 8))

plt.imshow(terrain, cmap='gray', origin='lower')

plt.title("Moon Crater Pattern", fontsize=16)

plt.axis('off')

plt.colorbar(label="Depth")

plt.tight_layout()

plt.show()

plt.figure(figsize=(8, 8)): Creates a new figure for the plot with a size of 8x8 inches.

 

plt.imshow(terrain, cmap='gray', origin='lower'):

 

terrain: The data to be visualized (the cratered surface).

 

cmap='gray': Uses a grayscale color map to visualize the depths. Lighter shades represent higher elevations, while darker shades represent lower elevations (craters).

 

origin='lower': Ensures that the origin of the plot is at the bottom-left, as is standard for most geographic data.

 

plt.title("Moon Crater Pattern", fontsize=16): Adds a title to the plot.

 

plt.axis('off'): Hides the axis lines and labels for a cleaner visualization.

 

plt.colorbar(label="Depth"): Adds a color bar to the side of the plot to show the depth values, so you can interpret the grayscale values in terms of depth.

 

plt.tight_layout(): Adjusts the layout to ensure the plot fits well in the figure without any clipping.

 

plt.show(): Displays the plot.

 


0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (161) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (254) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (299) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (225) Data Strucures (14) Deep Learning (75) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (48) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (197) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (12) PHP (20) Projects (32) Python (1219) Python Coding Challenge (898) Python Quiz (348) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)