polygen.polygen2d package
Submodules
polygen.polygen2d.IO module
- class IO[source]
Bases:
objectA comprehensive class for handling input/output operations for geometric data.
This class provides methods for: 1. Loading mesh files into Shapely polygons 2. Saving Voronoi cells to various formats 3. Exporting structured data for further analysis 4. Handling boundary and internal edge data
- DEFAULT_PRECISION = 8
Default precision for coordinate values in output files. :no-index:
- VORONOI_OUTPUT_DIR = 'meshFiles'
Default directory for Voronoi mesh outputs. :no-index:
- DATA_OUTPUT_DIR = 'voronoiDataFiles'
Default directory for data file outputs. :no-index:
polygen.polygen2d.constrainedPointGen module
- class ConstrainedPointGenerator(polygon, N, seed=None, k=30, margin=0.01, tolerance=0.01, max_iterations=50, workers=None, optimization=None)[source]
Bases:
objectA class to generate constrained point distributions inside a polygonal region using various methods, including Poisson Disc Sampling and quasi-random sequences (Sobol and Halton).
- Parameters:
polygon (Polygon or MultiPolygon) – A Shapely polygon or multipolygon that defines the region within which the points are generated.
N (int) – The target number of points to generate.
seed (int or None, optional) – Seed for the random number generator. Default is None.
k (int, optional) – Number of attempts to place a new point during Poisson Disc Sampling. Default is 30.
margin (float, optional) – A small margin to shrink the polygon before generating points. This helps to avoid boundary points. Default is 0.01.
tolerance (float, optional) – Tolerance for the number of generated points. Default is 0.01.
max_iterations (int, optional) – Maximum number of iterations for radius adjustment during Poisson Disc Sampling. Default is 50.
workers (int or None, optional) – Number of workers to use for parallel processing. If None, the number of workers is set based on the number of points (1 for N < 1000, or the number of CPU cores for N >= 1000). Default is None.
optimization (str or None, optional) – Optimization scheme for quasi-random sequences (Sobol or Halton). Default is None.
- polygon
The polygonal region within which points are generated.
- Type:
- max_iterations
The maximum number of iterations for adjusting the radius during Poisson Disc Sampling.
- Type:
- generate_poisson_points()[source]
Generate N points using Poisson Disc Sampling inside the polygon.
- generate_sequence_points(use_sobol=False)[source]
Generate N points using a quasi-random sequence (Sobol or Halton) inside the polygon.
- _generate_points(radius, shrunk_polygon)[source]
Generate points using Poisson Disc Sampling for a given radius within a shrunk polygon.
- _get_nearby_points(occupied_cells, grid, points, row, col, radius, cell_size)[source]
Helper method to return nearby points within a given grid for Poisson Disc Sampling.
Notes
Poisson Disc Sampling generates points such that no two points are closer than a specified radius, making it useful for applications like blue-noise sampling or spatial point distributions with minimum separation.
Quasi-random sequences (Sobol and Halton) generate points that cover the space more uniformly than pure random sampling, making them suitable for integration and optimization problems.
Examples
Poisson Disc Sampling:
>>> from shapely.geometry import Polygon >>> import numpy as np >>> polygon = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) >>> N = 100 >>> generator = ConstrainedPointGenerator(polygon, N) >>> points = generator.generate_poisson_points() >>> print(points.shape) (100, 2)
Generating points using Halton sequence:
>>> points_halton = generator.generate_sequence_points(use_sobol=False) >>> print(points_halton.shape) (100, 2)
Generating points using Sobol sequence:
>>> points_sobol = generator.generate_sequence_points(use_sobol=True) >>> print(points_sobol.shape) (128, 2) # Sobol generates points in powers of two
Performance Tips
For large numbers of points (N >= 1000), use multiple workers for parallel processing. By default, the number of workers is automatically set based on your CPU cores when N >= 1000.
The Sobol sequence is optimized for uniform space filling but can be slower when generating small numbers of points compared to Halton.
polygen.polygen2d.errorBasedLloyd module
- class PointHistoryBuffer(max_size, point_shape, dtype=<class 'numpy.float64'>)[source]
Bases:
objectMemory-efficient circular buffer for storing point configurations during Lloyd’s algorithm.
This class implements a circular buffer to store the history of point configurations and track the optimal configuration based on gradient norm values. It uses a deque data structure to maintain memory efficiency when storing multiple configurations.
- Parameters:
- optimal_config
Point configuration with the lowest gradient norm
- Type:
ndarray
Notes
The buffer automatically removes oldest configurations when max_size is reached.
- get_config(index)[source]
Retrieve a specific point configuration from the buffer.
- Parameters:
index (int) – Index of the configuration to retrieve
- Returns:
Point configuration at the specified index, or None if index is invalid
- Return type:
ndarray or None
- compute_weighted_centroid(X, Y, density_vals, mask, dx, dy)[source]
Compute the density-weighted centroid of a region using numerical integration.
This function calculates the centroid of a region weighted by a density function using discrete numerical integration over a grid.
- Parameters:
X (ndarray) – Meshgrid arrays of x and y coordinates
Y (ndarray) – Meshgrid arrays of x and y coordinates
density_vals (ndarray) – Array of density values at each grid point
mask (ndarray) – Boolean mask indicating points inside the region
dx (float) – Grid spacing in x and y directions
dy (float) – Grid spacing in x and y directions
- Returns:
(x_centroid, y_centroid) coordinates of the weighted centroid
- Return type:
- create_density_grid(bounds, samples, density_fn)[source]
Create a discretized grid and compute density values for numerical integration.
- Parameters:
- Returns:
X (ndarray) – 2D array of x-coordinates
Y (ndarray) – 2D array of y-coordinates
density_vals (ndarray) – 2D array of density values at grid points
dx (float) – Grid spacing in x-direction
dy (float) – Grid spacing in y-direction
- compute_adaptive_samples(polygon_region, reference_area, min_samples=20, max_samples=100)[source]
Determine appropriate grid resolution based on region size.
Adaptively computes the number of grid samples needed for accurate numerical integration based on the relative size of the region.
- Parameters:
polygon_region (shapely.geometry.Polygon) – Region to compute samples for
reference_area (float) – Area used to determine relative size for sampling For individual cells, this should be the expected cell area
min_samples (int) – Bounds for number of samples
max_samples (int) – Bounds for number of samples
- Returns:
Number of samples to use for the grid
- Return type:
Notes
The number of samples scales linearly with the relative area of the region.
- calculate_density_weighted_centroid(polygon_region, density_fn, is_uniform_density, total_area)[source]
Calculate the density-weighted centroid of a polygon region.
This function computes the centroid of a polygon region weighted by a density function using adaptive numerical integration.
- Parameters:
polygon_region (shapely.geometry.Polygon) – Region to calculate centroid for
density_fn (callable) – Function that takes (x, y) arrays and returns density values
is_uniform_density (bool) – If True, uses geometric centroid instead of weighted centroid
total_area (float) – Total area of the boundary polygon
- Returns:
(x, y) coordinates of the weighted centroid
- Return type:
Notes
For uniform density, returns the geometric centroid. Uses adaptive grid resolution based on region size for numerical integration.
- calculate_energy(points, voronoi, polygon, density_fn, is_uniform_density)[source]
Calculate Lloyd’s energy for the current point configuration.
Computes the total energy of the configuration defined as the sum of second moments of each Voronoi cell, weighted by the density function.
- Parameters:
points (ndarray) – Array of generator points, shape (n_points, 2)
voronoi (Voronoi) – Voronoi diagram for current points
polygon (shapely.geometry.Polygon) – Boundary polygon
density_fn (callable) – Function that takes (x, y) arrays and returns density values
is_uniform_density (bool) – If True, uses uniform density weighting
- Returns:
Total energy of the configuration
- Return type:
- compute_error_measure(polygon, points, centroids, cell_masses, density_fn, is_uniform_density)[source]
Compute the non-dimensionalized error measure with a simple cached density integral.
This function uses a single cached value for the density integral, which is computed only once for a given domain and density function combination. The cached value is stored as a function attribute using Python’s ability to attach attributes to functions.
- lloyd_with_density(polygon, seed_points, density_function=None, max_iterations=10000000, tol=1e-05, use_decay=True, decay_start=2.0, decay_mechanism='exponential', grad_increase_tol=1.2, history_buffer_size=10)[source]
This function provides a structured interface to run Lloyd’s algorithm (centroidal Voronoi tessellation) on a given polygon domain, using either uniform or non-uniform density functions for weighting.
- Parameters:
polygon (shapely.geometry.Polygon) – The domain in which to compute the centroidal Voronoi tessellation.
seed_points (array_like) – Initial seed points (n_points x 2) inside the polygon.
density_function (callable, optional) –
A function f(x, y) -> float that defines pointwise density. If None, a uniform density of 1 is assumed. Example density function:
def hexagonDensity(x, y): return np.exp(-20 * (x**2 + y**2)) + 0.05 * np.sin(np.pi * x)**2 * np.sin(np.pi * y)**2
max_iterations (int, optional) – Maximum number of Lloyd iterations (default=1e7).
tol (float, optional) – Convergence tolerance for the error measure (default=1e-5).
use_decay (bool, optional) – Whether to apply a decay factor to point movements (default=True).
decay_start (float, optional) – Starting value for decay (default=2.0). Decay moves from decay_start -> 1.
decay_mechanism ({'exponential', 'linear'}, optional) – Decay mode for point adjustments (default=’exponential’).
grad_increase_tol (float, optional) – Factor of tolerance for detecting error growth (default=1.2).
history_buffer_size (int, optional) – Maximum size of the point configuration buffer (default=10).
- Returns:
A tuple (points, metrics) where:
points: The final point configuration as a numpy array
metrics: A dictionary containing convergence information and error history
- Return type:
Notes
The algorithm uses a numerical integration approach if a non-uniform density is provided. This can be slower but gives more accurate centroid locations.
The algorithm stops if: - The error measure is below tol. - The error measure grows substantially beyond its minimum observed value. - The maximum iteration limit is reached.
polygen.polygen2d.extractVoronoiEdges module
- class VoronoiEdgeExtractor(use_kdtree=True)[source]
Bases:
objectA class for extracting and classifying edges from Voronoi tessellations.
This class provides functionality to identify boundary and internal edges from Voronoi cells, with support for both modified (with gaps) and original cell configurations.
- Parameters:
use_kdtree (bool, optional) – Whether to use KD-tree for edge mapping optimization, default=True
- _edge_cache
Cache of classified edges for each cell set
- Type:
Dict
Notes
Edge classification can be performed in two modes: 1. Using only modified cells (basic classification) 2. Using both modified and original cells (advanced classification)
The KD-tree optimization significantly improves performance for large tessellations by reducing edge mapping complexity from O(n²) to O(n log n).
- extract_edges(modified_cells, original_cells=None)[source]
Extract and classify edges from Voronoi cells.
- Parameters:
modified_cells (List[Union[Polygon, MultiPolygon]]) – Modified Voronoi cells (with gaps)
original_cells (Optional[List[Union[Polygon, MultiPolygon]]], optional) – Original Voronoi cells without gaps
- Returns:
Lists of boundary and internal edges
- Return type:
Tuple[List[LineString], List[LineString]]
Examples
>>> extractor = VoronoiEdgeExtractor() >>> boundary_edges, internal_edges = extractor.extract_edges( ... modified_cells, original_cells ... )
polygen.polygen2d.finiteThicknessCohesiveZone module
- class CohesiveZoneAdjuster(tolerance=0.005, max_iterations=10, verbose=False)[source]
Bases:
objectAn improved class for adjusting Voronoi cells to introduce finite-thickness cohesive zones.
This implementation addresses two key issues: 1. Preserves the original boundary of the domain 2. Creates uniform thickness gaps between adjacent cells
- Parameters:
- adjust_fixed_thickness(cells, thickness, preserve_boundary=True)[source]
Adjust cells using a fixed thickness value.
polygen.polygen2d.geometry module
- class Geometry[source]
Bases:
objectA class for generating various geometric shapes as Shapely polygons.
- circle(center, radius=None, point=None, name='Circle')[source]
Create a circular region given the center and either a radius or a point on the circle.
- annular_region(center_outer, radius_outer=None, point_outer=None, center_inner=None, radius_inner=None, point_inner=None, name='AnnularRegion')[source]
Create an annular region (a ring-shaped region) with specified outer and inner circles.
- annular_region_arc_WithStraightEnds(...)[source]
Create an annular region arc with straight ends using circular arcs.
- annular_region_arc_WithRoundedEnds(...)[source]
Create an annular region arc with smoothly closed ends using circular arcs.
- ellipse(center, semi_major_axis, semi_minor_axis, rotation=0, name='Ellipse')[source]
Create an elliptical region.
- rectangle(width, height, name='Rectangle')[source]
Create a rectangular region using width and height.
- rectangle_corners(point1, point2, name='RectangleCorners')[source]
Create a rectangular region using two opposite corners.
- square(center, side_length, name='Square')[source]
Create a square region given the center and side length.
- regular_polygon(center, radius, num_sides, name='RegularPolygon')[source]
Create a regular polygon with a given number of sides.
- triangle(point1, point2, point3, name='Triangle')[source]
Create a triangular region using three vertices.
- star(center, outer_radius, inner_radius, num_points, name='Star')[source]
Create a star-shaped polygon.
- trapezoid(base1, base2, height, name='Trapezoid')[source]
Create a trapezoidal region given the lengths of the bases and height.
- parallelogram(base, side_length, height, name='Parallelogram')[source]
Create a parallelogram given the base, side length, and height.
Examples
>>> from voronoi_meshing.geometry import Geometry >>> >>> # Create a circle >>> circle1 = Geometry.circle((0, 0), radius=5, name='CircleByRadius') >>> circle2 = Geometry.circle((0, 0), point=(3, 4), name='CircleByPoint') >>> >>> # Create an annular region >>> annular1 = Geometry.annular_region((0, 0), radius_outer=10, center_inner=(0, 0), ... radius_inner=5, name='AnnularByRadius') >>> annular2 = Geometry.annular_region((0, 0), point_outer=(7, 7), center_inner=(0, -1), ... point_inner=(3, 4), name='AnnularByPoint') >>> >>> # Create an elliptical region >>> ellipse = Geometry.ellipse(center=(0, 0), semi_major_axis=7, ... semi_minor_axis=4, rotation=30, name='Ellipse') >>> >>> # Create a rectangular region >>> rectangle = Geometry.rectangle(width=10, height=5, name='Rectangle') >>> >>> # Create a star-shaped region >>> star = Geometry.star(center=(0, 0), outer_radius=7, ... inner_radius=3, num_points=5, name='Star')
- Returns:
‘polygon’: The Shapely polygon object
’name’: The name of the geometry
- Return type:
Each method returns a dictionary containing
polygen.polygen2d.optimize module
- class MeshOptimizer(min_edge_length=None, verbose=False)[source]
Bases:
objectA class for optimizing mesh geometries by collapsing short edges in Voronoi cells and polygon boundaries.
This class provides functionality to analyze and optimize geometric meshes by identifying and collapsing short edges while preserving the overall structure of the mesh.
- Parameters:
- analyze_voronoi_edges(voronoi_cells, n=None, threshold=None)[source]
Analyze and print information about short edges in Voronoi cells.
- Parameters:
voronoi_cells (List[Union[Polygon, MultiPolygon]]) – List of Voronoi cells to analyze
n (int, optional) – Number of shortest edges to analyze, by default None
threshold (float, optional) – Length threshold for edge analysis, by default None
- Raises:
ValueError – If neither or both n and threshold are specified
- Return type:
- optimize_voronoi_cells(voronoi_cells, n=None, threshold=None)[source]
Optimize Voronoi cells by collapsing short edges.
- Parameters:
voronoi_cells (List[Union[Polygon, MultiPolygon]]) – List of Voronoi cells to optimize
n (int, optional) – Number of shortest edges to collapse, by default None
threshold (float, optional) – Length threshold for edge collapse, by default None
- Returns:
Optimized Voronoi cells
- Return type:
List[Union[Polygon, MultiPolygon]]
- Raises:
ValueError – If neither or both n and threshold are specified
- analyze_boundary_edges(polygon, n=None, threshold=None)[source]
Analyze and print information about short edges in polygon boundaries.
- Parameters:
polygon (Union[Polygon, MultiPolygon]) – Polygon to analyze
n (int, optional) – Number of shortest edges to analyze, by default None
threshold (float, optional) – Length threshold for edge analysis, by default None
- Raises:
ValueError – If neither or both n and threshold are specified
- Return type:
- optimize_boundary(polygon, n=None, threshold=None)[source]
Optimize polygon boundaries by collapsing short edges.
- Parameters:
polygon (Union[Polygon, MultiPolygon]) – Polygon to optimize
n (int, optional) – Number of shortest edges to collapse, by default None
threshold (float, optional) – Length threshold for edge collapse, by default None
- Returns:
Optimized polygon
- Return type:
Union[Polygon, MultiPolygon]
- Raises:
ValueError – If neither or both n and threshold are specified
polygen.polygen2d.plotting module
- get_figure_size(layout='single', journal_type='large')[source]
Calculate figure size in inches based on journal specifications.
- set_publication_style()[source]
Configure matplotlib for publication-quality figures following journal guidelines.
Key requirements implemented: - Vector graphics (saved as EPS) - Helvetica/Arial font - Consistent font sizing (8-12pt) - Minimum line width 0.3pt - No titles within figures - Proper figure dimensions
- plot_boundary_with_points(polygon, figure_name, points=None, show_figure=True, exterior_color='#1B365D', exterior_style='-', interior_color='r', interior_style='-', line_width=0.5, point_color='blue', point_size=0.5, point_alpha=1.0, point_marker='o', margins=0.01, dpi=1200, show_axes=False, output_dir='Plots')[source]
Plot polygon boundaries with optional seed points.
- Parameters:
polygon (shapely.geometry.Polygon or shapely.geometry.MultiPolygon) – The polygon(s) to be plotted. Can be either a single polygon or multiple polygons.
figure_name (str) – Name of the output figure. If no extension is provided, ‘.png’ is used.
points (ndarray, optional) – Array of points with shape (n, 2) containing x, y coordinates.
show_figure (bool, optional) – Whether to display the figure, by default True.
exterior_color (str, optional) – Color for exterior boundaries. Can use shorthand or full name. Common shorthands: ‘k’ (black), ‘r’ (red), ‘b’ (blue), ‘g’ (green), ‘y’ (yellow), ‘m’ (magenta), ‘c’ (cyan), ‘w’ (white). Default is ‘k’.
exterior_style (str, optional) – Line style for exterior boundaries. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘-’ (solid).
interior_color (str, optional) – Color for interior boundaries. Same color options as exterior_color. Default is ‘r’.
interior_style (str, optional) – Line style for interior boundaries. Same options as exterior_style. Default is ‘-’ (solid).
line_width (float, optional) – Width of all boundary lines, by default 0.5.
point_color (str, optional) – Color for points. Same color options as exterior_color. Default is ‘blue’.
point_size (float, optional) – Size of points, by default 0.5.
point_alpha (float, optional) – Transparency of points (0 to 1), by default 1.0.
point_marker (str, optional) – Marker style for points. Common options: ‘o’ (circle), ‘s’ (square), ‘^’ (triangle up), ‘v’ (triangle down), ‘*’ (star). Default is ‘o’.
margins (float or tuple, optional) – Margins around the plot. Can be: - Single float for same margins in x and y - Tuple (x_margin, y_margin) for different margins Default is 0.01 (1% margin in both x and y).
dpi (int, optional) – Resolution of saved figure in dots per inch, by default 1200.
show_axes (bool, optional) – Whether to show axes and ticks, by default False.
output_dir (str, optional) – Directory to save the figure, by default ‘Plots’.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style().
Color specifications can use either shorthand (e.g., ‘k’, ‘r’, ‘b’) or full names (e.g., ‘black’, ‘red’, ‘blue’). Additional valid color names include standard colors like ‘navy’, ‘forestgreen’, ‘darkred’, etc.
Examples
>>> from shapely.geometry import Polygon >>> import numpy as np >>> # Create a simple triangle >>> polygon = Polygon([(0, 0), (1, 0), (0.5, 1)]) >>> # Create some random points >>> points = np.random.rand(10, 2) >>> # Plot with custom styling >>> plot_boundary_with_points( ... polygon, ... 'triangle_plot', ... points=points, ... exterior_color='b', # or 'blue' ... interior_color='darkred', ... exterior_style='--', ... point_color='forestgreen', ... point_size=1.0 ... )
- plot_voronoi_cells(voronoi_cells, figure_name, points=None, show_figure=True, cell_color='#1B365D', cell_style='-', line_width=0.5, point_color='blue', point_size=0.5, point_alpha=1.0, point_marker='o', margins=0.01, dpi=1200, show_axes=False, output_dir='Plots')[source]
Plot Voronoi cells with optional seed points.
- Parameters:
voronoi_cells (list) – List of shapely.geometry.Polygon or shapely.geometry.MultiPolygon objects representing the Voronoi cells.
figure_name (str) – Name of the output figure. If no extension is provided, ‘.png’ is used.
points (ndarray, optional) – Array of points with shape (n, 2) containing x, y coordinates.
show_figure (bool, optional) – Whether to display the figure, by default True.
cell_color (str, optional) – Color for Voronoi cell boundaries. Can use shorthand or full name. Common shorthands: ‘k’ (black), ‘r’ (red), ‘b’ (blue), ‘g’ (green), ‘y’ (yellow), ‘m’ (magenta), ‘c’ (cyan), ‘w’ (white). Default is ‘k’.
cell_style (str, optional) – Line style for cell boundaries. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘-’ (solid).
line_width (float, optional) – Width of cell boundary lines, by default 0.5.
point_color (str, optional) – Color for points. Same color options as cell_color. Default is ‘blue’.
point_size (float, optional) – Size of points, by default 0.5.
point_alpha (float, optional) – Transparency of points (0 to 1), by default 1.0.
point_marker (str, optional) – Marker style for points. Common options: ‘o’ (circle), ‘s’ (square), ‘^’ (triangle up), ‘v’ (triangle down), ‘*’ (star). Default is ‘o’.
margins (float or tuple, optional) – Margins around the plot. Can be: - Single float for same margins in x and y - Tuple (x_margin, y_margin) for different margins Default is 0 (1% margin in both x and y).
dpi (int, optional) – Resolution of saved figure in dots per inch, by default 1200.
show_axes (bool, optional) – Whether to show axes and ticks, by default False.
output_dir (str, optional) – Directory to save the figure, by default ‘Plots’.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style().
Color specifications can use either shorthand (e.g., ‘k’, ‘r’, ‘b’) or full names (e.g., ‘black’, ‘red’, ‘blue’). Additional valid color names include standard colors like ‘navy’, ‘forestgreen’, ‘darkred’, etc.
Examples
>>> # Create some Voronoi cells and points >>> cells = [Polygon(...), Polygon(...)] # List of Voronoi cell polygons >>> points = np.array([[0, 0], [1, 1]]) # Seed points >>> # Plot with custom styling >>> plot_voronoi_cells( ... cells, ... 'voronoi_plot', ... points=points, ... cell_color='navy', ... cell_style='--', ... point_color='r', ... point_size=1.0 ... )
- plot_voronoi_edges(voronoi_cells, base_figure, original_cells=None, show_figure=True, boundary_color='r', boundary_style='-', internal_color='b', internal_style='-', line_width=0.5, margins=0.01, dpi=1200, show_axes=False, output_dir='Plots')[source]
Plot and save figures showing the whole Voronoi region, boundary edges, and internal edges.
- Parameters:
voronoi_cells (list) – List of shapely.geometry.Polygon objects representing clipped Voronoi cells.
base_figure (str) – Base name for the output figures. If no extension provided, ‘.png’ is used. Three files will be created with suffixes: ‘_whole’, ‘_boundary’, ‘_internal’.
original_cells (list, optional) – List of shapely.geometry.Polygon objects representing original Voronoi cells. If None, edge extraction will be performed only on voronoi_cells.
show_figure (bool, optional) – Whether to display the figures, by default True.
boundary_color (str, optional) – Color for boundary edges. Can use shorthand or full name. Common shorthands: ‘k’ (black), ‘r’ (red), ‘b’ (blue), ‘g’ (green). Default is ‘r’.
boundary_style (str, optional) – Line style for boundary edges. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘-’ (solid).
internal_color (str, optional) – Color for internal edges. Same color options as boundary_color. Default is ‘b’.
internal_style (str, optional) – Line style for internal edges. Same options as boundary_style. Default is ‘-’ (solid).
line_width (float, optional) – Width of all edge lines, by default 0.5.
margins (float or tuple, optional) – Margins around the plot. Can be: - Single float for same margins in x and y - Tuple (x_margin, y_margin) for different margins Default is 0.01 (1% margin in both x and y).
dpi (int, optional) – Resolution of saved figures in dots per inch, by default 1200.
show_axes (bool, optional) – Whether to show axes and ticks, by default False.
output_dir (str, optional) – Directory to save the figures, by default ‘Plots’.
Notes
The function creates three separate figures: 1. [basename]_whole: Complete Voronoi diagram 2. [basename]_boundary: Only boundary edges 3. [basename]_internal: Only internal edges
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style().
Color specifications can use either shorthand (e.g., ‘k’, ‘r’, ‘b’) or full names (e.g., ‘black’, ‘red’, ‘blue’).
Examples
>>> # Create Voronoi cells >>> voronoi_cells = [Polygon(...), Polygon(...)] >>> # Plot with default edge extraction >>> plot_voronoi_edges( ... voronoi_cells, ... 'voronoi_diagram', ... boundary_color='darkred', ... internal_color='navy' ... ) >>> >>> # Plot with original cells for edge comparison >>> original_cells = [Polygon(...), Polygon(...)] >>> plot_voronoi_edges( ... voronoi_cells, ... 'voronoi_diagram', ... original_cells=original_cells, ... boundary_color='darkred', ... internal_color='navy' ... )
- plot_voronoi_cells_with_short_edges(voronoi_cells, figure_name, N=None, threshold=None, points=None, show_figure=True, cell_color='#1B365D', cell_style='-', cell_width=0.5, short_edge_color='r', short_edge_style='-', short_edge_width=0.6, point_color='r', point_size=0.5, point_alpha=1.0, point_marker='o', margins=0.01, dpi=1200, show_axes=False, output_dir='Plots')[source]
Plot Voronoi cells with highlighted short edges based on either N shortest edges or a threshold length.
- Parameters:
voronoi_cells (list) – List of shapely.geometry.Polygon or shapely.geometry.MultiPolygon objects representing the Voronoi cells.
figure_name (str) – Name of the output figure. If no extension provided, ‘.png’ is used.
N (int, optional) – Number of shortest edges to highlight. Must specify either N or threshold, but not both.
threshold (float, optional) – Length threshold below which edges are highlighted. Must specify either N or threshold, but not both.
points (ndarray, optional) – Array of points with shape (n, 2) containing x, y coordinates.
show_figure (bool, optional) – Whether to display the figure, by default True.
cell_color (str, optional) – Color for Voronoi cell boundaries. Can use shorthand or full name. Common shorthands: ‘k’ (black), ‘r’ (red), ‘b’ (blue), ‘g’ (green). Default is ‘k’.
cell_style (str, optional) – Line style for cell boundaries. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘-’ (solid).
cell_width (float, optional) – Width of cell boundary lines, by default 0.5.
short_edge_color (str, optional) – Color for highlighted short edges. Same color options as cell_color. Default is ‘r’.
short_edge_style (str, optional) – Line style for short edges. Same options as cell_style. Default is ‘-’ (solid).
short_edge_width (float, optional) – Width of short edge lines, by default 2.0.
point_color (str, optional) – Color for points. Same color options as cell_color. Default is ‘r’.
point_size (float, optional) – Size of points, by default 0.5.
point_alpha (float, optional) – Transparency of points (0 to 1), by default 1.0.
point_marker (str, optional) – Marker style for points. Common options: ‘o’ (circle), ‘s’ (square), ‘^’ (triangle up), ‘v’ (triangle down), ‘*’ (star). Default is ‘o’.
margins (float or tuple, optional) – Margins around the plot. Can be: - Single float for same margins in x and y - Tuple (x_margin, y_margin) for different margins Default is 0.01 (1% margin in both x and y).
dpi (int, optional) – Resolution of saved figure in dots per inch, by default 1200.
show_axes (bool, optional) – Whether to show axes and ticks, by default False.
output_dir (str, optional) – Directory to save the figure, by default ‘Plots’.
- Raises:
ValueError – If neither or both N and threshold are specified. If N is negative. If threshold is negative. If points array has incorrect shape.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style().
Color specifications can use either shorthand (e.g., ‘k’, ‘r’, ‘b’) or full names (e.g., ‘black’, ‘red’, ‘blue’).
Examples
>>> # Highlight 5 shortest edges >>> plot_voronoi_cells_with_short_edges( ... voronoi_cells, ... 'short_edges', ... N=5, ... short_edge_color='red', ... short_edge_width=3.0 ... ) >>> >>> # Highlight edges shorter than 0.1 units >>> plot_voronoi_cells_with_short_edges( ... voronoi_cells, ... 'short_edges', ... threshold=0.1, ... cell_color='navy', ... short_edge_color='darkred' ... )
- plot_triangulated_geometry(geometry, triangulation, figure_name, highlight_short_edges=False, N=None, threshold=None, show_figure=True, cell_color='#1B365D', cell_style='-', cell_width=0.4, triangle_color='k', triangle_style='-', triangle_width=0.2, short_edge_color='r', short_edge_style='-', short_edge_width=0.4, margins=0.01, dpi=1200, show_axes=False, output_dir='Plots')[source]
Plot triangulated geometry - handles both single polygon and multiple Voronoi cells.
- Parameters:
geometry (Union[Polygon, List[Polygon]]) – Either a single shapely.geometry.Polygon or a list of Polygons (Voronoi cells)
triangulation (Union[List[Polygon], Dict[int, List[Polygon]]]) – Either a list of triangles (for single polygon) or a dictionary mapping cell indices to lists of triangles (for Voronoi cells)
original) (... (rest of parameters same as)
figure_name (str)
highlight_short_edges (bool)
N (int)
threshold (float)
show_figure (bool)
cell_color (str)
cell_style (str)
cell_width (float)
triangle_color (str)
triangle_style (str)
triangle_width (float)
short_edge_color (str)
short_edge_style (str)
short_edge_width (float)
dpi (int)
show_axes (bool)
output_dir (str)
Notes
The function now handles two cases: 1. Single polygon with holes and its triangulation 2. Multiple Voronoi cells and their triangulations (original functionality)
- plot_error_comparison(metrics1, metrics2, figure_name, show_figure=True, line1_color='k', line1_style='-', line1_width=1.0, line2_color='r', line2_style='--', line2_width=1.0, marker_size=4, grid_alpha=0.2, ref_line_color='gray', ref_line_style=':', ref_line_alpha=0.5, label1='Without Decay', label2='With Decay', dpi=1200, output_dir='Plots')[source]
Plot error comparison between two optimization methods.
- Parameters:
metrics1 (dict) – Dictionary containing error metrics for first method with keys: - ‘error_values’: list of error values per iteration - ‘min_error’: minimum error achieved
metrics2 (dict) – Dictionary containing error metrics for second method with same structure as metrics1.
figure_name (str) – Name of the output figure. If no extension provided, ‘.png’ is used.
show_figure (bool, optional) – Whether to display the figure, by default True.
line1_color (str, optional) – Color for first method’s line. Can use shorthand or full name. Common shorthands: ‘k’ (black), ‘r’ (red), ‘b’ (blue), ‘g’ (green). Default is ‘k’.
line1_style (str, optional) – Line style for first method. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘-’ (solid).
line1_width (float, optional) – Width of first method’s line, by default 1.0.
line2_color (str, optional) – Color for second method’s line. Same options as line1_color. Default is ‘r’.
line2_style (str, optional) – Line style for second method. Same options as line1_style. Default is ‘–’ (dashed).
line2_width (float, optional) – Width of second method’s line, by default 1.0.
marker_size (float, optional) – Size of markers at target error points, by default 4.
grid_alpha (float, optional) – Transparency of grid lines (0 to 1), by default 0.2.
ref_line_color (str, optional) – Color for reference line at target error. Same options as line1_color. Default is ‘gray’.
ref_line_style (str, optional) – Line style for reference line. Same options as line1_style. Default is ‘:’ (dotted).
ref_line_alpha (float, optional) – Transparency of reference line (0 to 1), by default 0.5.
label1 (str, optional) – Label for first method in legend, by default ‘Without Decay’.
label2 (str, optional) – Label for second method in legend, by default ‘With Decay’.
dpi (int, optional) – Resolution of saved figure in dots per inch, by default 1200.
output_dir (str, optional) – Directory to save the figure, by default ‘Plots’.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style(). Plot shows error on logarithmic scale vs. iteration number. Markers indicate where each method reaches the target error.
Examples
>>> metrics_no_decay = { ... 'error_values': [1.0, 0.5, 0.1, 0.01], ... 'min_error': 0.01 ... } >>> metrics_with_decay = { ... 'error_values': [1.0, 0.3, 0.05, 0.005], ... 'min_error': 0.005 ... } >>> plot_error_comparison( ... metrics_no_decay, ... metrics_with_decay, ... 'error_comparison', ... line1_color='navy', ... line2_color='darkred' ... )
- plot_boundary_with_short_edges(polygon, figure_name, N=None, threshold=None, show_figure=True, boundary_color='#1B365D', boundary_style='-', boundary_width=0.5, interior_color='r', interior_style='-', interior_width=0.5, short_edge_color='orange', short_edge_style='-', short_edge_width=2.0, short_edge_alpha=0.8, margins=0.01, dpi=1200, show_axes=False, output_dir='Plots')[source]
Plot polygon boundaries with highlighted short edges based on either N shortest edges or a threshold length.
- Parameters:
polygon (shapely.geometry.Polygon or shapely.geometry.MultiPolygon) – The polygon(s) whose boundary is to be plotted.
figure_name (str) – Name of the output figure. If no extension provided, ‘.png’ is used.
N (int, optional) – Number of shortest edges to highlight. Must specify either N or threshold, but not both.
threshold (float, optional) – Length threshold below which edges are highlighted. Must specify either N or threshold, but not both.
show_figure (bool, optional) – Whether to display the figure, by default True.
boundary_color (str, optional) – Color for exterior boundaries. Can use shorthand or full name. Common shorthands: ‘k’ (black), ‘r’ (red), ‘b’ (blue), ‘g’ (green). Default is ‘k’.
boundary_style (str, optional) – Line style for exterior boundaries. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘-’ (solid).
boundary_width (float, optional) – Width of exterior boundary lines, by default 0.5.
interior_color (str, optional) – Color for interior boundaries. Same color options as boundary_color. Default is ‘r’.
interior_style (str, optional) – Line style for interior boundaries. Same options as boundary_style. Default is ‘-’ (solid).
interior_width (float, optional) – Width of interior boundary lines, by default 0.5.
short_edge_color (str, optional) – Color for highlighted short edges. Same color options as boundary_color. Default is ‘orange’.
short_edge_style (str, optional) – Line style for short edges. Same options as boundary_style. Default is ‘-’ (solid).
short_edge_width (float, optional) – Width of short edge lines, by default 2.0.
short_edge_alpha (float, optional) – Transparency of short edges (0 to 1), by default 0.8.
margins (float or tuple, optional) – Margins around the plot. Can be: - Single float for same margins in x and y - Tuple (x_margin, y_margin) for different margins Default is 0.01 (1% margin in both x and y).
dpi (int, optional) – Resolution of saved figure in dots per inch, by default 1200.
show_axes (bool, optional) – Whether to show axes and ticks, by default False.
output_dir (str, optional) – Directory to save the figure, by default ‘Plots’.
- Raises:
ValueError – If neither or both N and threshold are specified. If N is negative. If threshold is negative.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style().
Examples
>>> # Highlight 5 shortest edges >>> plot_boundary_with_short_edges( ... polygon, ... 'boundary_short', ... N=5, ... short_edge_color='red', ... short_edge_width=3.0 ... ) >>> >>> # Highlight edges shorter than 0.1 units >>> plot_boundary_with_short_edges( ... polygon, ... 'boundary_short', ... threshold=0.1, ... boundary_color='navy', ... short_edge_color='orange' ... )
- plot_density_plate_with_hole(rect_point1, rect_point2, circle_center, circle_radius, figure_name, max_density=1.0, min_density=0.1, decay_rate=0.5, resolution=200, show_figure=True, colormap='viridis', rect_color='k', rect_style='-', rect_width=0.5, circle_color='r', circle_style='--', circle_width=0.5, view_elevation=30, view_azimuth=45, margins=0.01, dpi=1200, show_axes=True, output_dir='Plots')[source]
Create 2D heatmap and 3D surface plot of density function for a plate with hole.
- Parameters:
rect_point1 (tuple) – Lower-left corner coordinates (x, y) of the rectangular plate.
rect_point2 (tuple) – Upper-right corner coordinates (x, y) of the rectangular plate.
circle_center (tuple) – Center coordinates (x, y) of the circular hole.
circle_radius (float) – Radius of the circular hole.
figure_name (str) – Base name for the output figures. If no extension provided, ‘.png’ is used. Two files will be created with suffixes: ‘_2DHeatmap’ and ‘_3DSurface’.
max_density (float, optional) – Maximum density value at circle boundary, by default 1.0.
min_density (float, optional) – Minimum density value far from circle, by default 0.1.
decay_rate (float, optional) – Rate of density decay with distance from circle, by default 0.5.
resolution (int, optional) – Grid resolution for visualization, by default 200.
show_figure (bool, optional) – Whether to display the figures, by default True.
colormap (str, optional) – Matplotlib colormap name, by default ‘viridis’.
rect_color (str, optional) – Color for rectangle boundary. Can use shorthand or full name. Default is ‘k’.
rect_style (str, optional) – Line style for rectangle. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘-’ (solid).
rect_width (float, optional) – Width of rectangle boundary line, by default 0.5.
circle_color (str, optional) – Color for circle boundary. Same options as rect_color. Default is ‘r’.
circle_style (str, optional) – Line style for circle. Same options as rect_style. Default is ‘–’ (dashed).
circle_width (float, optional) – Width of circle boundary line, by default 0.5.
view_elevation (float, optional) – Elevation angle for 3D view, by default 30.
view_azimuth (float, optional) – Azimuth angle for 3D view, by default 45.
margins (float or tuple, optional) – Margins around the plot. Can be: - Single float for same margins in x and y - Tuple (x_margin, y_margin) for different margins Default is 0.01 (1% margin).
dpi (int, optional) – Resolution of saved figures in dots per inch, by default 1200.
show_axes (bool, optional) – Whether to show axes and ticks, by default True.
output_dir (str, optional) – Directory to save the figures, by default ‘Plots’.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style().
The density function uses an exponential decay from the circle boundary: density = max_density * exp(-decay_rate * distance) + min_density
Examples
>>> # Create density plots for a square plate with centered hole >>> plot_density_plate_with_hole( ... rect_point1=(-1, -1), ... rect_point2=(1, 1), ... circle_center=(0, 0), ... circle_radius=0.3, ... figure_name='density_plot', ... decay_rate=1.0 ... )
- plot_density_hexagon(hexagon_geometry, density_function, figure_name, resolution=200, show_figure=True, margins=0.01, colormap='viridis', hex_color='r', hex_style='--', hex_width=0.5, view_elevation=30, view_azimuth=45, dpi=1200, show_axes=True, output_dir='Plots')[source]
Create 2D heatmap and 3D surface plot of density function over a hexagonal region.
- Parameters:
hexagon_geometry (dict) – Dictionary containing the hexagonal geometry with key: - ‘polygon’: shapely.geometry.Polygon object representing the hexagon
density_function (callable) – Function that takes (x, y) arrays and returns density values. Must be vectorized to handle numpy arrays.
figure_name (str) – Base name for the output figures. If no extension provided, ‘.png’ is used. Two files will be created with suffixes: ‘_2DHeatmap’ and ‘_3DSurface’.
resolution (int, optional) – Grid resolution for visualization, by default 200.
show_figure (bool, optional) – Whether to display the figures, by default True.
margins (float or tuple, optional) – Margins around the plot. Can be: - Single float for same margins in x and y - Tuple (x_margin, y_margin) for different margins Default is 0.01 (1% margin).
colormap (str, optional) – Matplotlib colormap name, by default ‘viridis’.
hex_color (str, optional) – Color for hexagon boundary. Can use shorthand or full name. Common shorthands: ‘k’ (black), ‘r’ (red), ‘b’ (blue), ‘g’ (green). Default is ‘r’.
hex_style (str, optional) – Line style for hexagon. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘–’ (dashed).
hex_width (float, optional) – Width of hexagon boundary line, by default 0.5.
view_elevation (float, optional) – Elevation angle for 3D view, by default 30.
view_azimuth (float, optional) – Azimuth angle for 3D view, by default 45.
dpi (int, optional) – Resolution of saved figures in dots per inch, by default 1200.
show_axes (bool, optional) – Whether to show axes and ticks, by default True.
output_dir (str, optional) – Directory to save the figures, by default ‘Plots’.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style(). Points outside the hexagon are masked with NaN values.
Examples
>>> # Create hexagon with constant density >>> hex_geom = {'polygon': create_hexagon(center=(0, 0), radius=1)} >>> constant_density = lambda x, y: np.ones_like(x) >>> plot_density_hexagon( ... hex_geom, ... constant_density, ... 'hex_density', ... hex_color='blue', ... colormap='plasma' ... )
- plot_voronoi_cells_with_gaps(original_cells, adjusted_cells, figure_name, show_figure=True, cell_color='#1B365D', cell_style='-', cell_width=0.5, gap_color='r', gap_alpha=1.0, margins=0.01, dpi=1200, show_axes=False, output_dir='Plots')[source]
Plot Voronoi cells with highlighted gaps between adjacent cells.
- Parameters:
original_cells (list) – List of shapely.geometry.Polygon objects representing original Voronoi cells before adjustment.
adjusted_cells (list) – List of shapely.geometry.Polygon objects representing adjusted Voronoi cells with gaps.
figure_name (str) – Name of the output figure. If no extension provided, ‘.png’ is used.
show_figure (bool, optional) – Whether to display the figure, by default True.
cell_color (str, optional) – Color for cell boundaries. Can use shorthand or full name. Common shorthands: ‘k’ (black), ‘r’ (red), ‘b’ (blue), ‘g’ (green). Default is ‘k’.
cell_style (str, optional) – Line style for cell boundaries. Options: [‘-’, ‘–’, ‘-.’, ‘:’]. Default is ‘-’ (solid).
cell_width (float, optional) – Width of cell boundary lines, by default 0.5.
gap_color (str, optional) – Color to fill the gaps between cells, by default ‘lightgray’.
gap_alpha (float, optional) – Transparency of gap filling (0 to 1), by default 0.5.
margins (float or tuple, optional) – Margins around the plot. Can be: - Single float for same margins in x and y - Tuple (x_margin, y_margin) for different margins Default is 0.01 (1% margin in both x and y).
dpi (int, optional) – Resolution of saved figure in dots per inch, by default 1200.
show_axes (bool, optional) – Whether to show axes and ticks, by default False.
output_dir (str, optional) – Directory to save the figure, by default ‘Plots’.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style(). Gaps are visualized by plotting the difference between original and adjusted cells.
Examples
>>> # Plot cells with default gap styling >>> plot_voronoi_cells_with_gaps( ... original_cells, ... adjusted_cells, ... 'cells_with_gaps' ... ) >>> >>> # Custom styling for cells and gaps >>> plot_voronoi_cells_with_gaps( ... original_cells, ... adjusted_cells, ... 'cells_with_gaps', ... cell_color='navy', ... gap_color='lightblue', ... gap_alpha=0.3 ... )
- create_figure_grid(figure_paths, output_name, layout='1x2', figsize=None, show_figure=True, label_fontsize=10, label_distance=0.05, dpi=1200, output_dir='Plots')[source]
Create a publication-quality subplot grid from saved figures.
- Parameters:
figure_paths (list) – List of paths to individual figure images to be included in the grid.
output_name (str) – Name of the output file. If no extension provided, ‘.png’ is used.
layout (str, optional) – Layout of the grid. Must be one of: - ‘1x2’: 1 row, 2 columns - ‘1x3’: 1 row, 3 columns - ‘2x2’: 2 rows, 2 columns - ‘2x3’: 2 rows, 3 columns - ‘3x3’: 3 rows, 3 columns Default is ‘1x2’.
figsize (tuple, optional) – Custom figure size as (width, height) in inches. If None, uses preset sizes based on layout.
show_figure (bool, optional) – Whether to display the figure, by default True.
label_fontsize (float, optional) – Font size for subplot labels, by default 10.
label_distance (float, optional) – Distance of labels below subplots (in axis units), by default 0.05.
dpi (int, optional) – Resolution of saved figure in dots per inch, by default 1200.
output_dir (str, optional) – Directory to save the figure, by default ‘Plots’.
- Raises:
ValueError – If layout is not one of the supported options. If figsize is provided but not a tuple of length 2. If number of figure_paths exceeds subplot count for layout.
Notes
The function automatically creates the output directory if it doesn’t exist. Uses the publication style settings from set_publication_style(). Subplots are labeled alphabetically ((a), (b), etc.) below each figure. Empty subplots are removed if fewer figures than grid spaces.
Examples
>>> # Create a 1x2 grid from two figures >>> figure_paths = ['figure1.png', 'figure2.png'] >>> create_figure_grid( ... figure_paths, ... 'combined_figure', ... layout='1x2', ... label_fontsize=12 ... ) >>> >>> # Create a 2x2 grid with custom size >>> figure_paths = ['fig1.png', 'fig2.png', 'fig3.png', 'fig4.png'] >>> create_figure_grid( ... figure_paths, ... 'quad_figure', ... layout='2x2', ... figsize=(10, 10) ... )
polygen.polygen2d.triangularMeshing module
- class TriangularMesher(min_edge_length, min_angle=30.0, max_iterations=10)[source]
Bases:
objectA class to handle triangular meshing of polygonal geometries.
This class provides functionality to create high-quality triangular meshes from either single polygons (possibly with holes) or multiple polygons (e.g., Voronoi cells). It uses the Triangle library for mesh generation and ensures quality constraints are met.
- create_mesh(geometry)[source]
Create quality triangular mesh for polygon(s).
This method creates a high-quality triangular mesh for either a single polygon (possibly with holes) or multiple polygons (e.g., Voronoi cells). The mesh satisfies constraints on minimum edge length and minimum angle.
- Parameters:
geometry (Union[Polygon, List[Polygon]]) – Either a single polygon (possibly with holes) or a list of polygons to triangulate. Polygons can have interior holes.
- Returns:
- If input is a single polygon:
List of triangular polygons forming the mesh
- If input is a list of polygons:
Dictionary mapping polygon index to list of triangular polygons
- Return type:
Notes
Uses Triangle library for mesh generation
Applies iterative refinement to meet quality constraints
Handles both simple polygons and polygons with holes
For multiple polygons, indices in output dictionary match input list indices
Examples
>>> mesher = TriangularMesher(min_edge_length=0.1) >>> # Single polygon >>> triangles = mesher.triangulate(polygon) >>> # Multiple polygons >>> cell_triangulations = mesher.triangulate([poly1, poly2, poly3])
- save_mesh(geometry, triangulation, filename, output_dir=None, file_format=None)[source]
Save triangulated geometry to any meshio-supported format.
- Parameters:
geometry (Union[Polygon, List[Polygon]]) – Input geometry to triangulate and save
triangulation (Union[List[Polygon], Dict[int, List[Polygon]]]) – Triangulation result from create_mesh method
filename (str) – Output filename with appropriate extension
output_dir (str, optional) – Directory to save the file. If None, uses ‘meshFiles’
file_format (str, optional) – Output format (e.g., ‘vtk’, ‘abaqus’). If None, inferred from filename
- Returns:
Full path to the saved file
- Return type:
Examples
>>> mesher = TriangularMesher(min_edge_length=0.1) >>> # Save single polygon mesh >>> mesher.save_mesh(polygon, "mesh.vtk") >>> # Save multiple polygons with explicit format >>> mesher.save_mesh(cells, "mesh.inp", output_dir="results", ... file_format="abaqus")
- static triangulateCells_simple(voronoi_cells)[source]
Triangulate each Voronoi cell separately, including the centroid point in the triangulation, and maintaining cell boundaries.
Parameters:
- voronoi_cellslist of shapely.geometry.Polygon
The clipped Voronoi cells from generate_voronoi_cells
Returns:
: dict : Dictionary mapping cell index to list of triangles for that cell
- triangulate_geometry(geometry, min_edge_length, min_angle=30.0, max_iterations=10, save_mesh=False, filename=None, output_dir=None, file_format=None)[source]
Create a high-quality triangular mesh for polygon(s).
This function provides a simple interface to create triangular meshes for either a single polygon or multiple polygons. It handles polygons with or without interior holes and ensures the resulting mesh meets quality constraints for minimum edge length and minimum angles.
- Parameters:
geometry (Union[Polygon, List[Polygon]]) – Input geometry to triangulate. Can be either: * A single shapely.geometry.Polygon (possibly with holes) * A list of shapely.geometry.Polygon (e.g., Voronoi cells)
min_edge_length (float) – Minimum desired edge length for triangles in the mesh. Controls the mesh density.
min_angle (float, optional) – Minimum allowed angle in degrees for triangles, by default 30.0. Higher values (up to 34) create better-quality triangles but may require more iterations.
max_iterations (int, optional) – Maximum number of refinement iterations, by default 10. Increase if mesh quality constraints are not being met.
save_mesh (bool, optional) – Whether to save the mesh to a file, by default False. If True, either filename must be provided or a default will be used.
filename (str, optional) – Output filename with appropriate extension for mesh saving. Required if save_mesh is True and must include a valid extension. Common extensions: .vtk, .msh, .inp (Abaqus), .ans (ANSYS)
output_dir (str, optional) – Directory to save the mesh file. If None, uses ‘meshFiles’. Directory will be created if it doesn’t exist.
file_format (str, optional) – Output format override (e.g., ‘vtk’, ‘abaqus’, ‘ansys’). If None, format is inferred from filename extension.
- Returns:
- If input is a single polygon:
List of triangular polygons forming the mesh
- If input is a list of polygons:
Dictionary mapping polygon index to list of triangular polygons
- Return type:
- Raises:
ValueError – If save_mesh is True but no valid filename is provided. If the specified file format is not supported.
RuntimeError – If there are issues during mesh saving.
Notes
Uses the Triangle library (J.R. Shewchuk) for mesh generation
Applies iterative refinement to meet quality constraints
Automatically handles both simple polygons and polygons with holes
For multiple polygons, indices in output dictionary match input list indices
Invalid or empty polygons are skipped with a warning message
Failed triangulations return an empty list for that polygon
Examples
>>> # Basic triangulation without saving >>> domain = Polygon([(0,0), (1,0), (1,1), (0,1)], ... holes=[[(0.2,0.2), (0.4,0.2), (0.4,0.4), (0.2,0.4)]]) >>> triangles = triangulate_geometry(domain, min_edge_length=0.1)
>>> # Triangulate and save mesh >>> cells = [poly1, poly2, poly3] # list of shapely Polygons >>> cell_triangulations = triangulate_geometry( ... cells, ... min_edge_length=0.1, ... min_angle=32, ... save_mesh=True, ... filename="mesh.vtk", ... output_dir="results" ... )
See also
TriangularMesherThe class that implements the triangulation functionality
polygen.polygen2d.utils module
- generate_variable_names(input_obj)[source]
Generate variable names dynamically based on the given geometry object or .obj file.
Parameters: - input_obj: Path to the .obj file or a predefined geometric object from the Geometry class.
Returns: - A dictionary with dynamically generated variable names based on the input object’s name or file name.
- computeVoronoi2d(boundary, N_points, points_seed=42, margin=0.01, N_iter=100000, use_decay=True, edgeLength_threshold=None, cohesiveThickness=None, triangularMesh_minLength=None, visualize=False, saveData=True)[source]
Compute and visualize Voronoi diagrams within an arbitrarily shaped 2D region.
This function integrates various stages of Voronoi diagram generation and provides visualization and data-saving capabilities.
- Parameters:
boundary (2. Generate initial Poisson disk sampling points within the) – The path to the OBJ file defining the boundary or predefined geometry object
N_points (int) – Number of initial seed points for the Voronoi diagram
points_seed (int, optional) – Random seed for generating initial Poisson disk sampling points (default: 42)
margin (float, optional) – Margin to add around the boundary for generating seed points (default: 0.01)
N_iter (int, optional) – Number of iterations for Lloyd’s algorithm to relax the points (default: 100000)
use_decay (bool, optional) – Whether to use decay in Lloyd’s algorithm (default: True)
edgeLength_threshold (float, optional) – Length threshold for collapsing short edges in the Voronoi diagram (default: None)
cohesiveThickness (float, optional) – Thickness of the cohesive zone for adjusting the Voronoi cells (default: None)
triangularMesh_minLength (float, optional) – Minimum edge length for triangular meshing (default: None)
visualize (bool, optional) – Whether to show visualization plots (default: False)
saveData (bool, optional) – Whether to save the resulting data structures to files (default: True)
Cases (Use)
---------
Generation (1. Basic Voronoi Diagram) – Generate and visualize a Voronoi diagram within a given boundary. Example: computeVoroni(‘boundary.obj’, 100, visualize=True)
Collapsing (2. Optimized Voronoi Diagram with Edge) – Generate a Voronoi diagram and collapse edges shorter than a threshold. Example: computeVoroni(‘boundary.obj’, 100, edgeLength_threshold=0.1)
Saving (3. Data) – Save the resulting Voronoi cell and boundary data to files. Example: computeVoroni(‘boundary.obj’, 100, saveData=True)
Workflow
--------
file (1. Load the polygonal boundary from the specified OBJ)
boundary
algorithm (3. Relax the points using Lloyd's)
points (4. Generate Voronoi cells based on the relaxed)
mesh (5. Optionally collapse short edges and optimize the)
requested (7. Save data to files if)
requested
Example
>>> computeVoroni( ... boundary='boundary.obj', ... N_points=100, ... points_seed=42, ... margin=0.01, ... N_iter=100000, ... use_decay=True, ... edgeLength_threshold=0.1, ... cohesiveThickness=0.1, ... triangularMesh_minLength=0.02, ... visualize=True, ... saveData=True ... )
- computeVoronoi2d_fromInputFile(input_file_path)[source]
Compute the 2D Voronoi mesh from parameters specified in an input file.
This function reads the parameters from an input file and then calls the computeVoronoi2d function to generate the Voronoi diagram based on those parameters.
Parameters: - input_file_path (str): The path to the input file containing the parameters.
The input file should have the following format:
` boundary = /path/to/boundary.obj N_points = 100 points_seed = 42 margin = 0.01 N_iter = 100000 use_decay = True edgeLength_threshold = 0.1 cohesiveThickness = 0.1 triangularMesh_minLength = 0.02 visualize = False saveData = True `Example usage:
` # Assuming the input file is located at './examples/input.in' computeVoronoi2d_fromInputFile('./examples/input.in') `The function extracts the following parameters from the input file: - boundary: The path to the OBJ file defining the boundary. - N_points: Number of initial seed points for the Voronoi diagram. - points_seed: Random seed for generating initial Poisson disk sampling points. - margin: Margin to add around the boundary for generating seed points. - N_iter: Number of iterations for Lloyd’s algorithm to relax the points. - use_decay: Boolean indicating whether to use decay in Lloyd’s algorithm. - edgeLength_threshold: Length threshold for collapsing short edges in the Voronoi diagram. - cohesiveThickness: Thickness of the cohesive zone for adjusting the Voronoi cells. - triangularMesh_minLength: Minimum edge length for triangular meshing. - saveData: Boolean indicating whether to save the resulting data structures to .py files.
- print_docstring(obj)[source]
Print the docstring of a given object with enhanced formatting.
Parameters: - obj: The object whose docstring is to be printed.
- analyze_voronoi_cells(voronoi_cells)[source]
Analyze the Voronoi cells to calculate useful statistics such as average grain size, percentage of different grain sizes, and the lengths of the shortest edges.
Parameters: - voronoi_cells: List of Shapely Polygon or MultiPolygon objects representing the Voronoi cells.
Returns: - A dictionary containing various statistics about the Voronoi cells.
- get_voronoi_stats(voronoi_cells, N=None, threshold=None, file_name='Report_OriginalVoronoi.txt')[source]
Print useful statistics about the Voronoi cells, including the lengths of the shortest edges. Save the print statements in the Report.txt file inside the ‘Report’ directory.
Parameters: - voronoi_cells: List of Shapely Polygon or MultiPolygon objects representing the Voronoi cells. - N: Optional, the number of shortest edges to print. If None, print all edges. - threshold: Optional, the length threshold to print edges shorter than this value. If None, print edges based on N.
Prints the lengths of the edges in the format: Index: <index>, Length: <length>
- Example usage:
print_voronoi_statistics(voronoi_cells, N=10)
print_voronoi_statistics(voronoi_cells, threshold=0.1)
polygen.polygen2d.voroGen module
- class VoronoiGenerator(buffer_factor=1.0)[source]
Bases:
objectA class for generating constrained Voronoi tessellations within bounded regions.
This class handles the generation of Voronoi cells within a specified boundary, including proper handling of infinite regions and geometric validity checks.
- Parameters:
buffer_factor (float, optional) – Factor to extend bounding box beyond domain bounds, default=1.0
Notes
The Voronoi diagram V(P) for a set of points P = {p₁, …, pₙ} partitions the plane into n cells, where each cell V(pᵢ) consists of all points closer to pᵢ than to any other point in P:
\[V(pᵢ) = {x | ||x - pᵢ|| ≤ ||x - pⱼ|| for all j ≠ i}\]This implementation handles: - Infinite Voronoi regions using a bounding box - Invalid geometries through filtering - Proper cell clipping against the domain boundary
- generate_cells(domain, points)[source]
Generate constrained Voronoi cells within the given domain.
- Parameters:
domain (Union[Polygon, MultiPolygon]) – The boundary within which to generate Voronoi cells
points (np.ndarray) – Array of shape (N, 2) containing generator points
- Returns:
List of Voronoi cells clipped to the domain
- Return type:
List[Polygon]
Examples
>>> from shapely.geometry import Polygon >>> import numpy as np >>> domain = Polygon([(0,0), (1,0), (1,1), (0,1)]) >>> points = np.random.rand(10, 2) >>> generator = VoronoiGenerator() >>> cells = generator.generate_cells(domain, points)
Notes
The process involves: 1. Computing the Voronoi tessellation 2. Handling infinite regions with a bounding box 3. Clipping cells to the domain boundary 4. Filtering invalid geometries
For numerical stability, points should be reasonably distributed within the domain bounds.