### Basic Regularization Example Source: https://github.com/dpird-dma/building-regulariser/blob/main/README.md A simple example demonstrating the basic usage of the `regularize_geodataframe` function with default parameters. ```python from buildingregulariser import regularize_geodataframe import geopandas as gpd buildings = gpd.read_file("buildings.gpkg") regularized = regularize_geodataframe(buildings) ``` -------------------------------- ### Install Building Regulariser Source: https://github.com/dpird-dma/building-regulariser/blob/main/README.md Install the library using pip, conda, or uv. Ensure you have Python 3.9+. ```bash pip install buildingregulariser ``` ```bash conda install conda-forge::buildingregulariser ``` ```bash uv add buildingregulariser ``` -------------------------------- ### Quick Start: Load and Regularize Buildings Source: https://github.com/dpird-dma/building-regulariser/blob/main/README.md Load building footprints using GeoPandas and then regularize them using the `regularize_geodataframe` function. Save the results to a new file. ```python import geopandas as gpd from buildingregulariser import regularize_geodataframe # Load your building footprints buildings = gpd.read_file("buildings.gpkg") # Regularize the building footprints regularized_buildings = regularize_geodataframe( buildings, ) # Save the results regularized_buildings.to_file("regularized_buildings.gpkg") ``` -------------------------------- ### Perform Geometric Calculations with Geometry Utilities Source: https://context7.com/dpird-dma/building-regulariser/llms.txt Demonstrates usage of low-level geometry functions including distance, azimuth, line equations, intersections, projections, and rotations. ```python import numpy as np from buildingregulariser.geometry_utils import ( calculate_distance, calculate_azimuth_angle, create_line_equation, calculate_line_intersection, calculate_parallel_line_distance, project_point_to_line, rotate_point, rotate_edge, ) # Calculate Euclidean distance between two points p1 = np.array([0, 0]) p2 = np.array([3, 4]) distance = calculate_distance(p1, p2) print(f"Distance: {distance}") # Output: 5.0 # Calculate azimuth angle of a line segment (degrees, 0-360) start = np.array([0, 0]) end = np.array([1, 1]) azimuth = calculate_azimuth_angle(start, end) print(f"Azimuth: {azimuth}°") # Output: 45.0° # Create line equation Ax + By + C = 0 p1 = np.array([0, 0]) p2 = np.array([1, 1]) A, B, C = create_line_equation(p1, p2) print(f"Line equation: {A}x + {B}y + {C} = 0") # Calculate intersection of two lines line1 = create_line_equation(np.array([0, 0]), np.array([1, 0])) # Horizontal line2 = create_line_equation(np.array([0.5, -1]), np.array([0.5, 1])) # Vertical intersection = calculate_line_intersection(line1, line2) print(f"Intersection: {intersection}") # Output: (0.5, 0.0) # Calculate distance between parallel lines line1 = create_line_equation(np.array([0, 0]), np.array([1, 0])) # y = 0 line2 = create_line_equation(np.array([0, 5]), np.array([1, 5])) # y = 5 dist = calculate_parallel_line_distance(line1, line2) print(f"Parallel line distance: {dist}") # Project a point onto a line projected = project_point_to_line( point_x=2, point_y=3, line_x1=0, line_y1=0, line_x2=10, line_y2=0 ) print(f"Projected point: {projected}") # Output: (2.0, 0.0) # Rotate a point clockwise around a center point = np.array([1, 0]) center = np.array([0, 0]) rotated = rotate_point(point, center, angle_degrees=90) print(f"Rotated point: {rotated}") # Output: (0.0, -1.0) approximately # Rotate an edge around its midpoint start = np.array([0, 0]) end = np.array([2, 0]) rotated_edge = rotate_edge(start, end, rotation_angle=45) print(f"Rotated edge: {rotated_edge}") ``` -------------------------------- ### Loading Input Data Source: https://github.com/dpird-dma/building-regulariser/blob/main/Example use.ipynb Load building geometries from a GeoPackage file. ```python test_data_dir = Path("test data/input") original_buildings = gpd.read_file(test_data_dir / "test_data.gpkg") ``` -------------------------------- ### Importing Dependencies Source: https://github.com/dpird-dma/building-regulariser/blob/main/Example use.ipynb Required imports for processing geodata and measuring execution time. ```python import geopandas as gpd from buildingregulariser import regularize_geodataframe from pathlib import Path import time ``` -------------------------------- ### Visualizing Results with Folium Source: https://github.com/dpird-dma/building-regulariser/blob/main/Example use.ipynb Create an interactive map to compare original and regularized building footprints. ```python import folium # Create a Folium map with desired zoom settings and satellite tiles m = folium.Map( location=[-31.882, 115.929], zoom_start=20, max_zoom=20, tiles="https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}", attr="Google", ) # Add the buildings layer with a different color original_buildings.to_crs(epsg=4326).explore( m=m, name="Original Buildings", style_kwds={ "color": "white", "weight": 3, "fillOpacity": 0.0, }, ) # Add the regularized_gdf layer with a distinct color regularized_buildings.to_crs(epsg=4326).explore( m=m, name="Regularized Buildings", style_kwds={"fillColor": "red", "color": "blue", "weight": 3, "fillOpacity": 0.4}, ) folium.LayerControl().add_to(m) m ``` -------------------------------- ### Fine-tuning Regularization Parameters Source: https://github.com/dpird-dma/building-regulariser/blob/main/README.md Customize the regularization process by adjusting parameters such as alignment thresholds, simplification tolerance, and enabling features like 45-degree angle support, circle detection, and neighbor alignment. ```python regularized = regularize_geodataframe( buildings, parallel_threshold=2.0, # Higher values allow less edge alignment simplify_tolerance=0.5, # Controls simplification level, should be 2-3 x the raster pixel size allow_45_degree=True, # Enable 45-degree angles allow_circles=True, # Enable circle detection circle_threshold=0.9 # IOU threshold for circle detection neighbor_alignment=True, # After regularization try to align each building with neighboring buildings neighbor_search_distance: float = 100.0, # The search distance around each building to find neighbors neighbor_max_rotation: float = 10, # The maximum rotation allowed to align with neighbors ) ``` -------------------------------- ### Building Regulariser Function Source: https://github.com/dpird-dma/building-regulariser/blob/main/README.md This snippet details the parameters and return value of the main building regularization function. ```APIDOC ## Building Regulariser ### Description Regularizes polygon geometries by analyzing edges, aligning them to principal directions, and optionally enforcing specific angles or detecting circular shapes. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **geodataframe** (GeoDataFrame) - Required - Input GeoDataFrame with polygon geometries. - **parallel_threshold** (float) - Optional - Distance threshold for handling parallel lines (default: 1.0). - **simplify** (bool) - Optional - If True, applies simplification to the geometry (default: True). - **simplify_tolerance** (float) - Optional - Tolerance for simplification (default: 0.5). - **allow_45_degree** (bool) - Optional - If True, allows edges to be oriented at 45-degree angles (default: True). - **diagonal_threshold_reduction** (float) - Optional - Used to reduce the chance of diagonal edges being generated, can be from 0 to 22.5 (default: 15.0). - **allow_circles** (bool) - Optional - If True, detects and converts near-circular shapes to perfect circles (default: True). - **circle_threshold** (float) - Optional - Intersection over Union (IoU) threshold for circle detection (default: 0.9). - **num_cores** (int) - Optional - Number of CPU cores to use for parallel processing (default: 1). - **include_metadata** (bool) - Optional - Include the main direction, IOU, perimeter and aligned_direction (if used) in output gdf. - **neighbor_alignment** (bool) - Optional - If True, try to align each building with neighboring buildings (default: False). - **neighbor_search_distance** (float) - Optional - The distance to find neighboring buildings (default: 350.0). - **neighbor_max_rotation** (int) - Optional - The maximum allowable rotation to align with neighbors (default: 10). ### Request Example ```json { "geodataframe": "", "parallel_threshold": 1.0, "simplify": true, "simplify_tolerance": 0.5, "allow_45_degree": true, "diagonal_threshold_reduction": 15.0, "allow_circles": true, "circle_threshold": 0.9, "num_cores": 4, "include_metadata": false, "neighbor_alignment": false, "neighbor_search_distance": 350.0, "neighbor_max_rotation": 10 } ``` ### Response #### Success Response (200) - **regularized_geodataframe** (GeoDataFrame) - A new GeoDataFrame with regularized polygon geometries. #### Response Example ```json { "regularized_geodataframe": "" } ``` ``` -------------------------------- ### Regularize GeoDataFrame building footprints Source: https://context7.com/dpird-dma/building-regulariser/llms.txt Processes a GeoDataFrame of building footprints to align edges and simplify geometries. Requires a GeoDataFrame as input and supports parallel processing for large datasets. ```python import geopandas as gpd from buildingregulariser import regularize_geodataframe # Load building footprints from a GeoPackage file buildings = gpd.read_file("buildings.gpkg") # Basic regularization with default parameters regularized = regularize_geodataframe(buildings) # Advanced regularization with fine-tuned parameters regularized = regularize_geodataframe( geodataframe=buildings, parallel_threshold=2.0, # Distance threshold for merging parallel edges (units match CRS) target_crs="EPSG:32650", # Reproject to UTM zone 50N before processing simplify=True, # Apply initial simplification simplify_tolerance=0.5, # Simplification tolerance (2-3x raster pixel size) allow_45_degree=True, # Enable 45-degree angle alignment diagonal_threshold_reduction=15, # Reduce likelihood of diagonal edges (0-22.5 degrees) allow_circles=True, # Detect and convert near-circular shapes circle_threshold=0.9, # IoU threshold for circle detection (0-1) num_cores=4, # Use 4 CPU cores for parallel processing (0 = all cores) include_metadata=True, # Include main_direction, iou, perimeter in output neighbor_alignment=True, # Align buildings with neighboring structures neighbor_search_distance=100.0, # Search radius for finding neighbors neighbor_max_rotation=10, # Maximum rotation angle for neighbor alignment (degrees) ) # Save regularized buildings regularized.to_file("regularized_buildings.gpkg") # Check included metadata columns when include_metadata=True print(regularized.columns) # ['geometry', 'main_direction', 'iou', 'perimeter', 'aligned_direction', ...] ``` -------------------------------- ### Regularizing Geometries Source: https://github.com/dpird-dma/building-regulariser/blob/main/Example use.ipynb Apply regularization to a GeoDataFrame and calculate processing speed. ```python start = time.time() regularized_buildings = regularize_geodataframe( original_buildings, simplify_tolerance=2.0, ) print(f"{len(original_buildings) / (time.time() - start):.0f} polygons/sec") ``` -------------------------------- ### Align Polygons with Neighbor Directions Source: https://context7.com/dpird-dma/building-regulariser/llms.txt Aligns polygon orientation with dominant neighbor directions. Requires a GeoDataFrame with a 'main_direction' column. Adjust buffer_size and max_rotation as needed. ```python import geopandas as gpd from buildingregulariser.neighbor_alignment import align_with_neighbor_polygons # Assume we have a GeoDataFrame with regularized polygons # that includes 'main_direction' column from prior regularization gdf = gpd.read_file("regularized_buildings.gpkg") # Add required 'main_direction' column if not present # (normally added by regularize_geodataframe with include_metadata=True) if 'main_direction' not in gdf.columns: gdf['main_direction'] = 0 # Default direction # Align buildings with their neighbors aligned_gdf = align_with_neighbor_polygons( gdf=gdf, num_cores=4, # Number of CPU cores for parallel processing buffer_size=100.0, # Search radius for finding neighbors (CRS units) max_rotation=10, # Maximum rotation angle allowed (degrees) include_metadata=True, # Keep 'aligned_direction' and 'perimeter' columns ) # The aligned GeoDataFrame contains: # - Rotated geometries aligned with neighboring buildings # - 'aligned_direction': The direction used for alignment # - 'perimeter': Polygon perimeter (used as weight) print(aligned_gdf[['main_direction', 'aligned_direction']].head()) # Save results aligned_gdf.to_file("aligned_buildings.gpkg") ``` -------------------------------- ### Regularize GeoDataFrame Source: https://context7.com/dpird-dma/building-regulariser/llms.txt The main entry point for regularizing building footprints in a GeoDataFrame. This function processes polygon geometries by aligning their edges to principal directions, detecting and converting near-circular shapes, simplifying complex polygons, and optionally aligning buildings with neighboring structures. ```APIDOC ## POST /api/regularize_geodataframe ### Description Regularizes building footprints within a GeoDataFrame. ### Method POST ### Endpoint /api/regularize_geodataframe ### Parameters #### Request Body - **geodataframe** (GeoDataFrame) - Required - The input GeoDataFrame containing building footprints. - **parallel_threshold** (float) - Optional - Distance threshold for merging parallel edges (units match CRS). - **target_crs** (string) - Optional - Target CRS to reproject to before processing (e.g., "EPSG:32650"). - **simplify** (boolean) - Optional - Whether to apply initial simplification. - **simplify_tolerance** (float) - Optional - Simplification tolerance (e.g., 0.5). - **allow_45_degree** (boolean) - Optional - Whether to enable 45-degree angle alignment. - **diagonal_threshold_reduction** (float) - Optional - Reduces likelihood of diagonal edges (0-22.5 degrees). - **allow_circles** (boolean) - Optional - Whether to detect and convert near-circular shapes. - **circle_threshold** (float) - Optional - IoU threshold for circle detection (0-1). - **num_cores** (integer) - Optional - Number of CPU cores to use for parallel processing (0 = all cores). - **include_metadata** (boolean) - Optional - Whether to include metadata columns (main_direction, iou, perimeter). - **neighbor_alignment** (boolean) - Optional - Whether to align buildings with neighboring structures. - **neighbor_search_distance** (float) - Optional - Search radius for finding neighbors. - **neighbor_max_rotation** (float) - Optional - Maximum rotation angle for neighbor alignment (degrees). ### Request Example ```json { "geodataframe": "...", "parallel_threshold": 2.0, "target_crs": "EPSG:32650", "simplify": true, "simplify_tolerance": 0.5, "allow_45_degree": true, "diagonal_threshold_reduction": 15, "allow_circles": true, "circle_threshold": 0.9, "num_cores": 4, "include_metadata": true, "neighbor_alignment": true, "neighbor_search_distance": 100.0, "neighbor_max_rotation": 10 } ``` ### Response #### Success Response (200) - **regularized_geodataframe** (GeoDataFrame) - The GeoDataFrame with regularized building footprints. - **metadata** (object) - Included if `include_metadata` is true, containing columns like `main_direction`, `iou`, `perimeter`. #### Response Example ```json { "regularized_geodataframe": "...", "metadata": { "main_direction": [10.5, 25.1, ...], "iou": [0.85, 0.92, ...], "perimeter": [40.2, 35.5, ...] } } ``` ``` -------------------------------- ### Analyze Polygon Edges for Main Direction Source: https://context7.com/dpird-dma/building-regulariser/llms.txt Determines the dominant structural direction of a polygon by analyzing its edge azimuth angles. Uses histogram analysis with adjustable bin sizes for coarse and fine refinement. ```python import numpy as np from buildingregulariser.regularization import analyze_edges # Define polygon coordinates (NOT closed - no repeated first point) coordinates = np.array([ [0, 0], [10, 0.5], [10.2, 8], [0.3, 7.8] ]) # Analyze edges to find main direction edge_data = analyze_edges( coordinates=coordinates, coarse_bin_size=5, # Size of coarse histogram bins (degrees) fine_bin_size=1, # Size of fine histogram bins (degrees) ) # edge_data contains: # - 'azimuth_angles': Array of edge angles (0-360 degrees) # - 'edge_indices': Array of [start_idx, end_idx] pairs # - 'main_direction': Dominant structural direction (0-90 degrees) print(f"Edge azimuths: {edge_data['azimuth_angles']}") print(f"Main direction: {edge_data['main_direction']}°") print(f"Number of edges: {len(edge_data['edge_indices'])}") ``` -------------------------------- ### Regularize a single Shapely Polygon Source: https://context7.com/dpird-dma/building-regulariser/llms.txt Processes an individual Shapely Polygon to align edges and detect circular shapes. This function returns a dictionary containing the regularized geometry and quality metrics. ```python from shapely.geometry import Polygon from buildingregulariser.regularization import regularize_single_polygon # Create a sample irregular polygon coords = [ (0, 0), (10.2, 0.3), (10.5, 8.1), (5.2, 8.3), (5.1, 4.9), (0.2, 5.1), (0, 0) ] irregular_polygon = Polygon(coords) # Regularize the polygon result = regularize_single_polygon( polygon=irregular_polygon, parallel_threshold=1.0, # Distance threshold for parallel edge handling allow_45_degree=True, # Allow 45-degree orientations diagonal_threshold_reduction=15, # Make diagonal edges less likely allow_circles=True, # Enable circle detection circle_threshold=0.9, # IoU threshold for circle conversion simplify=True, # Apply initial simplification simplify_tolerance=0.5, # Simplification tolerance ) # Result is a dictionary containing: # - 'geometry': The regularized Shapely Polygon # - 'iou': Intersection over Union with original (quality metric) # - 'main_direction': Detected main direction angle (degrees) regularized_polygon = result['geometry'] quality_score = result['iou'] main_angle = result['main_direction'] print(f"IoU with original: {quality_score:.3f}") print(f"Main direction: {main_angle}°") print(f"Vertex count: {len(regularized_polygon.exterior.coords)}") ``` -------------------------------- ### Regularize Polygon Coordinate Array Source: https://context7.com/dpird-dma/building-regulariser/llms.txt Aligns polygon edges to principal directions (parallel, perpendicular, or 45 degrees to main direction). Enforces precise angles and returns regularized coordinates. Requires closed coordinate arrays. ```python import numpy as np from buildingregulariser.regularization import regularize_coordinate_array # Define closed polygon coordinates (first point == last point) coordinates = np.array([ [0, 0], [10.2, 0.3], [10.5, 8.1], [0.3, 7.8], [0, 0] ]) # Regularize the coordinates regularized_coords, main_direction = regularize_coordinate_array( coordinates=coordinates, parallel_threshold=1.0, # Distance threshold for parallel lines allow_45_degree=True, # Allow 45-degree orientations diagonal_threshold_reduction=15, # Make diagonals less likely (0-22.5) angle_enforcement_tolerance=0.1, # Max deviation from target angle (degrees) ) # Result is a closed numpy array of regularized coordinates print(f"Main direction: {main_direction}°") print(f"Original vertices: {len(coordinates)}") print(f"Regularized vertices: {len(regularized_coords)}") print(f"Regularized coordinates:\n{regularized_coords}") ``` -------------------------------- ### Clean Polygon Geometries Source: https://context7.com/dpird-dma/building-regulariser/llms.txt Removes empty geometries, slivers, and redundant vertices from a GeoDataFrame. Can be used for post-processing. Adjust simplify_tolerance for desired level of detail. ```python import geopandas as gpd from buildingregulariser.coordinator import cleanup_geometry # Load a GeoDataFrame with potentially problematic geometries gdf = gpd.read_file("buildings_with_artifacts.gpkg") # Clean up geometries cleaned_gdf = cleanup_geometry( result_geodataframe=gdf, simplify_tolerance=0.5, # Controls buffer size and simplification ) # The cleaning process: # 1. Removes empty and null geometries # 2. Applies positive-negative-positive buffer sequence to remove slivers # 3. Simplifies to remove collinear vertices # 4. Removes any geometries that became empty after processing print(f"Original count: {len(gdf)}") print(f"Cleaned count: {len(cleaned_gdf)}") ``` -------------------------------- ### Regularize Single Polygon Source: https://context7.com/dpird-dma/building-regulariser/llms.txt Regularizes a single Shapely Polygon by analyzing its edges, aligning them to principal directions, and optionally converting circular shapes. This is the core function used internally by `regularize_geodataframe`. ```APIDOC ## POST /api/regularize_single_polygon ### Description Regularizes a single Shapely Polygon. ### Method POST ### Endpoint /api/regularize_single_polygon ### Parameters #### Request Body - **polygon** (Polygon) - Required - The input Shapely Polygon. - **parallel_threshold** (float) - Optional - Distance threshold for parallel edge handling. - **allow_45_degree** (boolean) - Optional - Whether to allow 45-degree orientations. - **diagonal_threshold_reduction** (float) - Optional - Makes diagonal edges less likely. - **allow_circles** (boolean) - Optional - Whether to enable circle detection. - **circle_threshold** (float) - Optional - IoU threshold for circle conversion (0-1). - **simplify** (boolean) - Optional - Whether to apply initial simplification. - **simplify_tolerance** (float) - Optional - Simplification tolerance. ### Request Example ```json { "polygon": {"type": "Polygon", "coordinates": [[(0, 0), (10.2, 0.3), (10.5, 8.1), (5.2, 8.3), (5.1, 4.9), (0.2, 5.1), (0, 0)]]}, "parallel_threshold": 1.0, "allow_45_degree": true, "diagonal_threshold_reduction": 15, "allow_circles": true, "circle_threshold": 0.9, "simplify": true, "simplify_tolerance": 0.5 } ``` ### Response #### Success Response (200) - **geometry** (Polygon) - The regularized Shapely Polygon. - **iou** (float) - Intersection over Union with the original polygon (quality metric). - **main_direction** (float) - Detected main direction angle in degrees. #### Response Example ```json { "geometry": {"type": "Polygon", "coordinates": [...]}, "iou": 0.88, "main_direction": 15.5 } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.