Certainly! Below is the improved Python code implementing your instructions. The code generates two plots:
-
First Plot: Same as the original, showing the Voronoi diagram with the central point (red), adjacent points (blue), and non-adjacent points (black).
-
Second Plot: Uses the same central point and adjacent points but regenerates the non-adjacent points (black) so that they lie outside the convex hull of the central point and adjacent points. It also ensures that the new black points are within the same plot limits and maintains a minimum distance threshold from the adjacent blue points.
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, ConvexHull
from matplotlib.path import Path
# Function to plot the Voronoi diagram
def plot_voronoi(points, central_point_idx, adj_indices, title):
vor = Voronoi(points)
fig, ax = plt.subplots(figsize=(8, 8))
# Plot all points as black dots
ax.plot(points[:, 0], points[:, 1], 'ko', markersize=4, label='Other Points')
# Highlight the central point in red
ax.plot(points[central_point_idx, 0], points[central_point_idx, 1], 'ro', markersize=8, label='Central Point')
# Highlight adjacent points in blue
ax.plot(points[adj_indices, 0], points[adj_indices, 1], 'bo', markersize=6, label='Adjacent Points')
# Plot finite ridges (edges)
for simplex in vor.ridge_vertices:
simplex = np.asarray(simplex)
if np.all(simplex >= 0): # Finite ridge (no vertex at infinity)
ax.plot(vor.vertices[simplex, 0], vor.vertices[simplex, 1], 'k-', lw=0.8)
# Plot infinite ridges (edges) as solid lines
ptp_bound = points.ptp(axis=0) # Peak-to-peak (max - min) along each axis
max_bound = ptp_bound.max()
for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices):
simplex = np.asarray(simplex)
if np.any(simplex < 0): # Infinite ridge
# Indices of the two points defining the ridge
p1_idx, p2_idx = pointidx
p1 = vor.points[p1_idx]
p2 = vor.points[p2_idx]
# Compute the direction vector of the edge (perpendicular to the line between p1 and p2)
t = p2 - p1
t = t / np.linalg.norm(t)
n = np.array([-t[1], t[0]]) # Normal vector
# Finite Voronoi vertex
finite_vertex_idx = simplex[simplex >= 0][0]
finite_vertex = vor.vertices[finite_vertex_idx]
# Determine the direction to extend the infinite edge
midpoint = (p1 + p2) / 2
direction = np.sign(np.dot(midpoint - points.mean(axis=0), n)) * n
# Extend the edge far beyond the plot boundaries
far_point = finite_vertex + direction * max_bound * 10
# Plot the infinite edge as a solid line between the finite vertex and far point
ax.plot([finite_vertex[0], far_point[0]], [finite_vertex[1], far_point[1]], 'k-', lw=0.8)
# Set equal aspect ratio
ax.set_aspect('equal')
# Set plot limits to include all points with a margin
all_x = points[:, 0]
all_y = points[:, 1]
margin = R * 0.1 # 10% of R as margin
x_min = all_x.min() - margin
x_max = all_x.max() + margin
y_min = all_y.min() - margin
y_max = all_y.max() + margin
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
# Add labels and title
ax.set_xlabel('X-coordinate')
ax.set_ylabel('Y-coordinate')
ax.set_title(title)
# Display the legend
ax.legend()
plt.show()
# Generate the points
num_points = 21 # Number of points around the central point
R = 10 # Maximum radius for generating points around the center
# Generate random angles and radii
np.random.seed(0) # For reproducibility
theta = np.random.uniform(0, 2 * np.pi, num_points)
r = R * np.sqrt(np.random.uniform(0, 1, num_points)) # Uniform distribution within circle
# Convert polar coordinates to Cartesian coordinates
x = r * np.cos(theta)
y = r * np.sin(theta)
other_points = np.column_stack((x, y))
# Define the central point at (0, 0)
central_point = np.array([[0, 0]])
# Combine central point with other points
points = np.vstack((central_point, other_points))
# Create the Voronoi diagram
vor = Voronoi(points)
# Find indices of points whose regions are adjacent to the central point
ridge_points = vor.ridge_points # Indices of points between which each Voronoi ridge lies
# Initialize a list to store indices of adjacent points
Adj_indices = []
for pair in ridge_points:
if 0 in pair: # If the central point (index 0) is part of the ridge
neighbor = pair[0] if pair[1] == 0 else pair[1]
Adj_indices.append(neighbor)
# Remove duplicates and the central point itself if included
Adj_indices = np.unique(Adj_indices)
Adj_indices = Adj_indices[Adj_indices != 0] # Exclude central point
# Create the set Adj_P containing only points adjacent to the central point
Adj_P = points[Adj_indices.astype(int)]
# Compute the convex hull of the central point and adjacent points
hull_points = np.vstack((central_point, Adj_P))
hull = ConvexHull(hull_points)
hull_path = Path(hull_points[hull.vertices]) # Convex hull as a matplotlib path
# Find indices of non-adjacent points (P_no_adj)
all_indices = np.arange(len(points))
Non_Adj_indices = np.setdiff1d(all_indices, np.concatenate(([0], Adj_indices)))
P_no_adj = points[Non_Adj_indices.astype(int)]
num_black = len(Non_Adj_indices)
# Get plot limits
all_x = points[:, 0]
all_y = points[:, 1]
margin = R * 0.1 # 10% of R as margin
x_min = all_x.min() - margin
x_max = all_x.max() + margin
y_min = all_y.min() - margin
y_max = all_y.max() + margin
# Plot the first Voronoi diagram
plot_voronoi(points, 0, Adj_indices.astype(int), 'First Plot: Original Voronoi Diagram')
##############################
# Generate new black points for the second plot
min_distance_threshold = 0.5 # Minimum distance threshold from blue points
new_black_points = []
# Generate points until we have enough
while len(new_black_points) < num_black:
# Generate a random point within the plot limits
x_candidate = np.random.uniform(x_min, x_max)
y_candidate = np.random.uniform(y_min, y_max)
candidate_point = np.array([x_candidate, y_candidate])
# Check if the point lies outside the convex hull
if not hull_path.contains_point(candidate_point):
# Check the minimum distance to adjacent points (blue points)
distances = np.linalg.norm(Adj_P - candidate_point, axis=1)
if np.min(distances) >= min_distance_threshold:
new_black_points.append(candidate_point)
# Convert to numpy array
new_black_points = np.array(new_black_points)
# Combine points for the second plot
points2 = np.vstack((central_point, Adj_P, new_black_points))
# Indices for plotting
central_pt_idx = 0
adj_pt_indices = np.arange(1, len(Adj_P) + 1)
black_pt_indices = np.arange(len(Adj_P) + 1, len(points2))
# Plot the second Voronoi diagram
def plot_voronoi_second(points, central_pt_idx, adj_pt_indices, black_pt_indices, title):
vor = Voronoi(points)
fig, ax = plt.subplots(figsize=(8, 8))
# Plot all black points
ax.plot(points[black_pt_indices, 0], points[black_pt_indices, 1], 'ko', markersize=4, label='Other Points')
# Highlight the central point in red
ax.plot(points[central_pt_idx, 0], points[central_pt_idx, 1], 'ro', markersize=8, label='Central Point')
# Highlight adjacent points in blue
ax.plot(points[adj_pt_indices, 0], points[adj_pt_indices, 1], 'bo', markersize=6, label='Adjacent Points')
# Plot finite ridges (edges)
for simplex in vor.ridge_vertices:
simplex = np.asarray(simplex)
if np.all(simplex >= 0): # Finite ridge (no vertex at infinity)
ax.plot(vor.vertices[simplex, 0], vor.vertices[simplex, 1], 'k-', lw=0.8)
# Plot infinite ridges (edges) as solid lines
ptp_bound = points.ptp(axis=0) # Peak-to-peak (max - min) along each axis
max_bound = ptp_bound.max()
for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices):
simplex = np.asarray(simplex)
if np.any(simplex < 0): # Infinite ridge
# Indices of the two points defining the ridge
p1_idx, p2_idx = pointidx
p1 = vor.points[p1_idx]
p2 = vor.points[p2_idx]
# Compute the direction vector of the edge (perpendicular to the line between p1 and p2)
t = p2 - p1
t = t / np.linalg.norm(t)
n = np.array([-t[1], t[0]]) # Normal vector
# Finite Voronoi vertex
finite_vertex_idx = simplex[simplex >= 0][0]
finite_vertex = vor.vertices[finite_vertex_idx]
# Determine the direction to extend the infinite edge
midpoint = (p1 + p2) / 2
direction = np.sign(np.dot(midpoint - points.mean(axis=0), n)) * n
# Extend the edge far beyond the plot boundaries
far_point = finite_vertex + direction * max_bound * 10
# Plot the infinite edge as a solid line between the finite vertex and far point
ax.plot([finite_vertex[0], far_point[0]], [finite_vertex[1], far_point[1]], 'k-', lw=0.8)
# Set equal aspect ratio
ax.set_aspect('equal')
# Set plot limits to include all points with a margin
all_x = points[:, 0]
all_y = points[:, 1]
margin = R * 0.1 # 10% of R as margin
x_min = all_x.min() - margin
x_max = all_x.max() + margin
y_min = all_y.min() - margin
y_max = all_y.max() + margin
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
# Add labels and title
ax.set_xlabel('X-coordinate')
ax.set_ylabel('Y-coordinate')
ax.set_title(title)
# Display the legend
ax.legend()
plt.show()
# Plot the second Voronoi diagram
plot_voronoi_second(points2, central_pt_idx, adj_pt_indices, black_pt_indices, 'Second Plot: Voronoi Diagram with New Non-Adjacent Points')
Explanation of the Improvements:
-
Convex Hull Calculation: After identifying the adjacent points (Adj_P), we calculate the convex hull of the central point and adjacent points using ConvexHull. This convex envelope is used to ensure new black points lie outside it.
-
Generating New Non-Adjacent Points:
- We use rejection sampling to generate new black points that lie outside the convex hull and within the plot limits.
- We ensure that the new black points maintain a minimum distance (
min_distance_threshold) from the blue adjacent points (Adj_P) to avoid them being extremely close.
- The number of new black points generated (
num_black) matches the number of non-adjacent points in the first plot.
-
Plot Adjustments:
- Two separate plotting functions (
plot_voronoi and plot_voronoi_second) are used for clarity, handling the indices correctly for each plot.
- The central point (red), adjacent points (blue), and non-adjacent points (black) are consistently colored in both plots.
- The Voronoi diagrams are recreated for each plot to reflect the updated sets of points.
-
Same Plot Limits: The new black points are generated within the same plot limits as the original points to ensure consistency between the plots.
Note: The code includes comments at each step for clarity and understanding. Running this code in Google Colab will produce the desired plots as per your instructions.