import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d
# Generate the central point
center = np.array([[0, 0]])
# Function to generate random points within a circle
def generate_points_in_circle(radius, num_points):
theta = np.random.uniform(0, 2 * np.pi, num_points)
r = radius * np.sqrt(np.random.uniform(0, 1, num_points))
x = r * np.cos(theta)
y = r * np.sin(theta)
return np.vstack((x, y)).T
# Generate 21 other points around the central point
radius = 1
num_points = 21
other_points = generate_points_in_circle(radius, num_points)
# Combine central point and other points
points = np.vstack((center, other_points))
# Compute the Voronoi diagram
vor = Voronoi(points)
# Find points adjacent to the central point
adjacent_indices = set()
for ridge_point in vor.ridge_points:
if 0 in ridge_point:
# Identify the index of the adjacent point
idx = ridge_point[0] if ridge_point[1] == 0 else ridge_point[1]
adjacent_indices.add(idx)
# Convert set to a sorted list
adjacent_indices = sorted(adjacent_indices)
# Create Adj_P containing points adjacent to the central point
Adj_P = points[adjacent_indices]
# Indices of non-adjacent points
non_adjacent_indices = [i for i in range(1, len(points)) if i not in adjacent_indices]
# Plotting
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111)
# Plot Voronoi diagram
voronoi_plot_2d(vor, ax=ax, show_vertices=False, line_colors='orange',
line_width=2, line_alpha=0.6, point_size=2)
# Plot points with different colors
ax.plot(points[0, 0], points[0, 1], 'ro', markersize=8, label='Central Point')
ax.plot(points[adjacent_indices, 0], points[adjacent_indices, 1], 'go', markersize=6, label='Adjacent Points')
ax.plot(points[non_adjacent_indices, 0], points[non_adjacent_indices, 1], 'bo', markersize=6, label='Non-Adjacent Points')
# Customize plot
ax.legend()
ax.set_title('Voronoi Diagram with Adjacent Regions Highlighted')
plt.axis('equal')
plt.show()
# Output Adj_P
print("Adj_P (Points adjacent to the central point):")
print(Adj_P)
This code performs the following tasks:
-
Generates 22 points where the first point is at the center (0, 0) and the other 21 points are randomly distributed around it within a circle of radius 1.
-
Computes the Voronoi diagram using these points.
-
Identifies which of the 21 points have Voronoi regions adjacent to that of the central point by examining the ridge_points attribute of the Voronoi diagram.
-
Creates a set Adj_P containing only the points adjacent to the central point.
-
Plots the Voronoi diagram and distinctly colors:
- The central point in red.
- The adjacent points in green.
- The non-adjacent points in blue.
-
Displays the plot and prints the coordinates of the adjacent points.