Generating a Vinokur-type stretching algorithm for 2D mesh generation typically involves applying a non-linear transformation in each dimension independently. The core idea is to map uniformly spaced points in a computational domain (e.g., [0,1]) to a physical domain, clustering points towards boundaries or other regions of interest.
The "Vinokur stretching" often refers to a class of functions, prominently using hyperbolic tangents or sines, to achieve this clustering. A common form aims to control the distribution of points to resolve boundary layers or other flow features.
Here, we'll implement a flexible 1D stretching function and then use it to generate a 2D structured mesh.
Key Concepts:
- 1D Stretching Function: A function that takes uniform points in
[0,1] and transforms them into a non-uniform distribution, clustering points towards one or both ends. We'll implement a few common hyperbolic tangent (tanh) variants.
- 2D Structured Mesh: Generated by taking the Cartesian product of stretched 1D point distributions in X and Y directions using
numpy.meshgrid.
- Stretching Parameter (
beta): Controls the intensity of the clustering. Higher beta values result in stronger clustering.
Let's define different stretching types:
tanh_left_end: Clusters points towards the start (e.g., x=0).
tanh_right_end: Clusters points towards the end (e.g., x=L).
tanh_both_ends: Clusters points symmetrically towards both ends.
tanh_middle: Clusters points towards the center of the domain.
uniform: No stretching, points are evenly distributed.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def vinokur_stretch_1d(n_points, length, beta, stretch_type='tanh_both_ends'):
"""
Generates 1D stretched coordinates using Vinokur-type transformations.
Parameters:
-----------
n_points : int
Number of points to generate (including start and end).
length : float
The total length of the 1D domain (e.g., x_max - x_min).
beta : float
Stretching parameter. Higher positive values mean stronger clustering.
- For 'tanh_left_end', 'tanh_right_end', 'tanh_middle': beta > 0 for clustering.
- For 'tanh_both_ends': beta > 0 for clustering at ends.
stretch_type : str
Type of stretching to apply. Options:
'uniform': Evenly spaced points.
'tanh_left_end': Clusters points towards the start (0).
'tanh_right_end': Clusters points towards the end (length).
'tanh_both_ends': Clusters points towards both start and end symmetrically.
'tanh_middle': Clusters points towards the middle of the domain.
Returns:
--------
numpy.ndarray
An array of 1D coordinates.
"""
if n_points < 2:
return np.array([0.0]) if n_points == 1 else np.array([])
# Create uniformly spaced points in [0, 1] computational space
s_uniform = np.linspace(0, 1, n_points)
if stretch_type == 'uniform' or beta == 0:
x_stretched = s_uniform
elif stretch_type == 'tanh_left_end':
# Clusters points towards s=0
if np.tanh(beta) == 0: # Avoid division by zero if beta is extremely small
x_stretched = s_uniform
else:
x_stretched = (np.tanh(beta * s_uniform)) / np.tanh(beta)
elif stretch_type == 'tanh_right_end':
# Clusters points towards s=1
if np.tanh(beta) == 0:
x_stretched = s_uniform
else:
x_stretched = 1 - (np.tanh(beta * (1 - s_uniform))) / np.tanh(beta)
elif stretch_type == 'tanh_both_ends':
# Clusters points towards both s=0 and s=1 (symmetric)
# For positive beta, this variant of tanh mapping clusters points towards ends.
# It uses a transformation of the form x = 0.5 * (1 + tanh(A*(2s-1))/tanh(A))
# where A is negative for clustering at ends.
if np.tanh(-beta * 0.5) == 0: # Avoid division by zero
x_stretched = s_uniform
else:
x_stretched = 0.5 * (1 + np.tanh(-beta * (s_uniform - 0.5)) / np.tanh(-beta * 0.5))
elif stretch_type == 'tanh_middle':
# Clusters points towards the middle (s=0.5)
# For positive beta, this variant of tanh mapping clusters points towards middle.
if np.tanh(beta * 0.5) == 0: # Avoid division by zero
x_stretched = s_uniform
else:
x_stretched = 0.5 * (1 + np.tanh(beta * (s_uniform - 0.5)) / np.tanh(beta * 0.5))
else:
raise ValueError(f"Unknown stretch_type: {stretch_type}. "
"Choose from 'uniform', 'tanh_left_end', 'tanh_right_end', "
"'tanh_both_ends', 'tanh_middle'.")
# Scale to the desired physical length
return x_stretched * length
def generate_vinokaur_mesh_2d(
nx, ny,
x_range=(0.0, 1.0), y_range=(0.0, 1.0),
beta_x=3.0, beta_y=3.0,
stretch_type_x='tanh_both_ends', stretch_type_y='tanh_both_ends'
):
"""
Generates a 2D structured mesh using Vinokur-type stretching functions.
Parameters:
-----------
nx : int
Number of points in the X-direction.
ny : int
Number of points in the Y-direction.
x_range : tuple (float, float)
(x_min, x_max) for the X-dimension.
y_range : tuple (float, float)
(y_min, y_max) for the Y-dimension.
beta_x : float
Stretching parameter for the X-dimension.
beta_y : float
Stretching parameter for the Y-dimension.
stretch_type_x : str
Type of stretching for X-dimension (see vinokur_stretch_1d).
stretch_type_y : str
Type of stretching for Y-dimension (see vinokur_stretch_1d).
Returns:
--------
tuple (numpy.ndarray, numpy.ndarray)
X : 2D array of X-coordinates for each mesh point.
Y : 2D array of Y-coordinates for each mesh point.
"""
x_min, x_max = x_range
y_min, y_max = y_range
# Generate 1D stretched coordinates
x_coords_1d = vinokur_stretch_1d(nx, (x_max - x_min), beta_x, stretch_type_x) + x_min
y_coords_1d = vinokur_stretch_1d(ny, (y_max - y_min), beta_y, stretch_type_y) + y_min
# Create the 2D mesh using meshgrid
X, Y = np.meshgrid(x_coords_1d, y_coords_1d)
return X, Y
def plot_mesh(X, Y, title="2D Vinokur Stretched Mesh", ax=None):
"""
Plots the generated 2D mesh.
Parameters:
-----------
X : numpy.ndarray
2D array of X-coordinates.
Y : numpy.ndarray
2D array of Y-coordinates.
title : str
Title for the plot.
ax : matplotlib.axes.Axes, optional
Axes to plot on. If None, a new figure and axes are created.
"""
if ax is None:
fig, ax = plt.subplots(figsize=(8, 8))
# Plot mesh lines
ax.plot(X, Y, 'k-', lw=0.5) # Horizontal lines
ax.plot(X.T, Y.T, 'k-', lw=0.5) # Vertical lines
# Plot mesh points (optional, useful for dense meshes to see distribution)
# ax.plot(X.flatten(), Y.flatten(), 'o', markersize=2, color='blue', alpha=0.5)
ax.set_xlabel("X-coordinate")
ax.set_ylabel("Y-coordinate")
ax.set_title(title)
ax.set_aspect('equal', adjustable='box')
ax.grid(True, linestyle=':', alpha=0.6)
# Set limits to match the mesh extent
ax.set_xlim(X.min(), X.max())
ax.set_ylim(Y.min(), Y.max())
if ax is None:
plt.show() # Only show if we created the figure internally
# --- Examples ---
if __name__ == "__main__":
# Example 1: Uniform Mesh
print("Generating Uniform Mesh...")
X_uniform, Y_uniform = generate_vinokaur_mesh_2d(
nx=21, ny=21,
x_range=(0, 1), y_range=(0, 1),
beta_x=0, beta_y=0, # beta=0 results in uniform
stretch_type_x='uniform', stretch_type_y='uniform'
)
# Example 2: Stretching at both ends in X and Y
print("Generating Mesh with Both Ends Stretching...")
X_both_ends, Y_both_ends = generate_vinokaur_mesh_2d(
nx=31, ny=31,
x_range=(0, 1), y_range=(0, 1),
beta_x=5.0, beta_y=5.0, # Stronger clustering
stretch_type_x='tanh_both_ends', stretch_type_y='tanh_both_ends'
)
# Example 3: Stretching at left end in X, right end in Y
print("Generating Mesh with Mixed Stretching (X-left, Y-right)...")
X_mixed, Y_mixed = generate_vinokaur_mesh_2d(
nx=31, ny=31,
x_range=(-0.5, 0.5), y_range=(0.0, 1.5),
beta_x=4.0, beta_y=4.0,
stretch_type_x='tanh_left_end', stretch_type_y='tanh_right_end'
)
# Example 4: Stretching towards the middle in X, uniform in Y
print("Generating Mesh with Middle Stretching in X...")
X_middle, Y_middle = generate_vinokaur_mesh_2d(
nx=41, ny=21,
x_range=(0, 2), y_range=(0, 1),
beta_x=6.0, beta_y=0.0,
stretch_type_x='tanh_middle', stretch_type_y='uniform'
)
# Example 5: High Beta for stronger clustering
print("Generating Mesh with High Beta Stretching...")
X_high_beta, Y_high_beta = generate_vinokaur_mesh_2d(
nx=51, ny=51,
x_range=(0, 1), y_range=(0, 1),
beta_x=10.0, beta_y=10.0, # Very strong clustering
stretch_type_x='tanh_both_ends', stretch_type_y='tanh_both_ends'
)
# --- Plotting all examples ---
fig, axes = plt.subplots(3, 2, figsize=(14, 18))
axes = axes.flatten()
plot_mesh(X_uniform, Y_uniform, title="1. Uniform Mesh (beta=0)", ax=axes[0])
plot_mesh(X_both_ends, Y_both_ends, title="2. Tanh Both Ends (beta=5)", ax=axes[1])
plot_mesh(X_mixed, Y_mixed, title="3. X-Left, Y-Right (beta=4)", ax=axes[2])
plot_mesh(X_middle, Y_middle, title="4. X-Middle, Y-Uniform (beta=6)", ax=axes[3])
plot_mesh(X_high_beta, Y_high_beta, title="5. Tanh Both Ends (beta=10)", ax=axes[4])
# Add an empty subplot or specific notes
axes[5].set_visible(False) # Hide the last subplot if not used
plt.tight_layout()
plt.show()
Explanation:
-
vinokur_stretch_1d(n_points, length, beta, stretch_type) function:
- It takes the number of points (
n_points), the length of the 1D domain, a beta parameter for stretching intensity, and stretch_type string.
- It first creates
s_uniform, which are n_points evenly spaced values from 0 to 1. This represents the computational domain.
- Based on
stretch_type:
uniform: Simply returns the uniformly spaced points.
tanh_left_end: Uses tanh(beta * s_uniform) / tanh(beta). For beta > 0, this compresses points towards s=0.
tanh_right_end: Uses 1 - (tanh(beta * (1 - s_uniform)) / tanh(beta)). This is a flipped version of tanh_left_end, compressing points towards s=1.
tanh_both_ends: This commonly used form 0.5 * (1 + np.tanh(-beta * (s_uniform - 0.5)) / np.tanh(-beta * 0.5)) ensures that for positive beta, points cluster at both s=0 and s=1. The negative sign in front of beta in the tanh arguments makes a positive beta correspond to clustering at the ends.
tanh_middle: This form 0.5 * (1 + np.tanh(beta * (s_uniform - 0.5)) / np.tanh(beta * 0.5)) clusters points towards s=0.5 for positive beta.
- Finally, the stretched coordinates (which are in
[0,1]) are scaled by the length of the physical domain.
- Error handling is included for
beta=0 (which would cause division by zero in tanh(beta)) by defaulting to uniform spacing, and for invalid stretch_type.
-
generate_vinokaur_mesh_2d(...) function:
- Takes
nx, ny (number of points in each direction) and domain x_range, y_range.
- It calls
vinokur_stretch_1d separately for the X and Y dimensions, applying their respective beta and parameters.
The examples demonstrate various combinations of stretching types and beta values, showcasing the flexibility of the approach. You can easily modify the nx, ny, x_range, y_range, beta values, and stretch_type to generate different mesh distributions for your specific needs.