Skip to content

Python API Reference

This page documents the main Python modules in BERA Tools using mkdocstrings.

Tools API

Copyright (C) 2025 Applied Geospatial Research Group.

This script is licensed under the GNU General Public License v3.0. See https://gnu.org/licenses/gpl-3.0 for full license details.

Author: Richard Zeng

Description

This script is part of the BERA Tools. Webpage: https://github.com/BERATool/beratools

The purpose of this script is to provide main interface for line grouping tool.

Copyright (C) 2025 Applied Geospatial Research Group.

This script is licensed under the GNU General Public License v3.0. See https://gnu.org/licenses/gpl-3.0 for full license details.

Author: Richard Zeng

Description

This script is part of the BERA Tools. Webpage: https://github.com/BERATool/beratools

The purpose of this script is the public interface for vertex optimization.

Copyright (C) 2025 Applied Geospatial Research Group.

This script is licensed under the GNU General Public License v3.0. See https://gnu.org/licenses/gpl-3.0 for full license details.

Author: Richard Zeng

Description

This script is part of the BERA Tools. Webpage: https://github.com/BERATool/beratools

The purpose of this script is to provide main interface for centerline tool.

centerline

centerline(in_line, in_raster, line_radius, proc_segments, out_line, centerline_method=value, guided_strategy=value, simplify_centerline=False, simplify_diameter=10.0, lcp_simplify_enabled=False, lcp_simplify_diameter=10.0, lcp_smooth_enabled=False, lcp_smooth_iterations=1, chm_mode=value, chm_buffer_width=5.0, chm_buffer_multiplier=0.5, astar_corridor_line_bias_weight=0.1, astar_corridor_distance_penalty_weight=0.2, corridor_simplify_polygon=False, corridor_simplify_length=0.5, corridor_smooth_polygon=False, corridor_polygon_smooth_iterations=1, use_angle_grouping=True, processes=0, call_mode=CLI, log_level='INFO')

Run centerline extraction.

guided_strategy modes: - MAIN_ROUTE: unguided main-route extraction. - PAIRWISE: endpoint-guided search over endpoint node pairs. - VIRTUAL_NODES: endpoint-guided search using virtual source/destination graph nodes. - DIRECT_INSERT: endpoint-guided search by inserting endpoints directly into the Voronoi graph.

Copyright (C) 2025 Applied Geospatial Research Group.

This script is licensed under the GNU General Public License v3.0. See https://gnu.org/licenses/gpl-3.0 for full license details.

Author: Richard Zeng

Description

This script is part of the BERA Tools. Webpage: https://github.com/BERATool/beratools

The purpose of this script is to provide main interface for canopy footprint tool.

canopy_footprint_abs

canopy_footprint_abs(in_line, in_chm, corridor_thresh=3.0, max_ln_width=32.0, exp_shk_cell=0, out_footprint=None, footprint_mode='absolute', tree_radius=1.5, max_line_dist=1.5, canopy_avoidance=0.0, exponent=1.0, canopy_thresh_percentage=50, simplify_footprint_polygon=True, footprint_simplify_length=0.5, smooth_footprint_polygon=False, footprint_polygon_smooth_iterations=1, processes=0, call_mode=CLI, log_level='INFO')

Run canopy footprint in absolute or adaptive mode.

CenterlineParams

Bases: float, Enum

Parameters for centerline generation.

These parameters are used to control the behavior of centerline generation and should be adjusted based on the specific requirements of the application.

CenterlineStatus

Bases: IntEnum

Status of centerline generation.

This enum is used to indicate the status of centerline generation. It can be used to track the success or failure of the centerline generation process.

SeedLine

SeedLine(line_gdf, ras_file, proc_segments, line_radius, guided_strategy='main_route', centerline_method=value, lcp_simplify_enabled=False, lcp_simplify_diameter=10.0, lcp_smooth_enabled=False, lcp_smooth_iterations=1, chm_mode=value, chm_buffer_width=5.0, chm_buffer_multiplier=0.5, astar_corridor_line_bias_weight=0.1, astar_corridor_distance_penalty_weight=0.2, corridor_simplify_polygon=False, corridor_simplify_length=0.5, corridor_smooth_polygon=False, corridor_polygon_smooth_iterations=1)

Class to store seed line and least cost path.

Logger

Logger(logger_name, queue=None, file_level=DEFAULT_FILE_LEVEL, console_level=DEFAULT_CONSOLE_LEVEL)

Configure a named BERA Tools logger.

The logger uses two handlers:

  • File handler: Stores timestamped messages at file_level or higher.

  • Console handler: Displays concise messages at console_level or higher.

Each logger is configured only once. Creating another Logger instance with the same name reuses the existing handlers.

Parameters

logger_name : str Name of the logger.

int, default logging.INFO

Minimum logging level written to the log file.

int, default logging.INFO

Minimum logging level written to the console.

get_logger

get_logger() -> Logger

Return the configured logger.

Two convenience methods are attached to the logger:

logger.file_only(message, *args, level=logging.INFO) Write only to file handlers.

logger.debug_file_only(message, *args) Write a DEBUG message only to file handlers.

Returns

logging.Logger Configured logger instance.

print

print(message, flush: bool = True) -> None

Log a message at INFO level.

This method provides compatibility with code that previously used print() for progress or status messages.

Parameters

message : object Message or object to log.

bool, default True

Flush all configured handlers after logging.

flush

flush() -> None

Flush all handlers associated with this logger.

Flushing should normally be used only for important progress messages, shutdown handling, or debugging. Flushing every log record can significantly reduce performance.

debug_file_only staticmethod

debug_file_only(message, *args, logger_name: Optional[str] = None) -> None

Write a DEBUG message only to file handlers.

The message is not sent to console handlers.

Parameters

message : object Log message or formatting template.

*args Values used with standard logging percent formatting.

str

Name of an existing configured logger.

file_only staticmethod

file_only(message, *args, level: int = INFO, logger_name: Optional[str] = None) -> None

Write a message directly to the logger's file handlers.

Console handlers are intentionally bypassed.

Unlike a regular logger call, this method sends the record directly to each file handler. This allows a DEBUG file-only record to be written even when the logger's effective level is INFO or WARNING, provided the file handler accepts that level.

Parameters

message : object Log message or formatting template.

*args Values used with standard logging percent formatting.

int, default logging.INFO

Logging level associated with the record.

str

Name of an existing configured logger.

Notes

This method does not flush the file handler after every message. Operating-system and Python buffering improve performance during large multiprocessing jobs. Use Logger.flush() when an immediate flush is required.

ToolBase

ToolBase()

Bases: object

Base class for tools.

CenterlineStrategy

Bases: Enum

Guided strategy for centerline extraction.

CenterlineMethod

Bases: Enum

Least-cost path and corridor raster method for centerline extraction.

CenterlineChmMode

Bases: Enum

CHM preprocessing mode for centerline extraction.

CenterlineFlags

Bases: Flag

Flags for the centerline algorithm.

ParallelMode

Bases: IntEnum

Defines the parallel mode for the algorithms.

find_corridor_threshold

find_corridor_threshold(raster)

Find the optimal corridor threshold by raster histogram Parameters


raster : corridor raster

Returns

corridor_threshold : float

main_line_footprint_relative

main_line_footprint_relative(in_line: str, in_chm: str, max_ln_width: float, out_footprint: str, out_centerline: str, exp_shk_cell: int, tree_radius: float, max_line_dist: float, canopy_avoidance: float, exponent: float, full_step: bool, canopy_thresh_percentage: int, processes: int, debug_mode: bool = BT_DEBUGGING) -> None

This function take the centerlines with forest canopy height and distance to edge to generate dynamic footprint from input CHM. An option smooth centerlines will be generated. Args: in_line: Path like string for input centerlines in_chm: Path like string input CHM max_ln_width: Maximum processing width for input lines out_footprint: Path like string output footprint out_centerline: (Option) Path like string output centerline exp_shk_cell: Range as integer used for cell erosion tree_radius: Radius of trees influence in the cost raster max_line_dist: Maximum Euclidean distance from canopy canopy_avoidance: 0 < Ratio < 1 of importance between canopy search radius and Euclidean distance exponent: Affects the cost of vegetated areas in an exponential fashion canopy_thresh_percentage: Percentage as integer range 1-100

Returns:

Type Description
None

New saved footprints and/or with smoothed centerlines dataset(s).

centerline_is_valid

centerline_is_valid(centerline, input_line, cid=None)

Check if centerline is valid.

Parameters:

Name Type Description Default
centerline _type_

description

required
input_line LineString

Seed line or least cost path.

required

Returns:

Name Type Description
bool

True if line is valid

snap_end_to_end

snap_end_to_end(in_line, line_reference, max_snap_dist=None, cid=None)

Snap centerline ends to opposite seedline endpoints.

Prevents

start -> seed_start end -> seed_start

which creates a ring.

find_centerline

find_centerline(poly, input_line, guided_strategy='main_route', endpoint_mode=None, endpoint_candidate_k=8, allow_regeneration=True, cell_size=1.0, corridor_id='UNKNOWN')

Find centerline from polygon and input line.

Parameters:

Name Type Description Default
poly

sh_geom.Polygon

required
input_line LineString

Least cost path or seed line

required

Returns: centerline (sh_geom.LineString): Centerline status (CenterlineStatus): Status of centerline generation

process_single_centerline

process_single_centerline(row_and_path)

Find centerline.

Args: row_and_path (list of row (gdf and lc_path)): and least cost path first is GeoPandas row, second is input line, (least cost path)

Returns: row: GeoPandas row with centerline

regenerate_centerline

regenerate_centerline(poly, input_line, corridor_id='UNKNOWN', cell_size=1.0, guided_strategy='pairwise', endpoint_mode='strict', endpoint_candidate_k=8)

Regenerates centerline when initial poly is not valid. Split the corridor polygon, extract each half independently, and merge the two centerlines.

Parameters:

Name Type Description Default
input_line LineString

Seed line or least cost path.

required

Returns:

Type Description

sh_geom.MultiLineString

configure_worker_logging

configure_worker_logging(queue)

Configure worker process logger.

cut_line_by_length

cut_line_by_length(line, length, merge_threshold=0.5)

Split line into segments of equal length.

Merge the last segment with the second-to-last if its length is smaller than the given threshold.

Parameters:

Name Type Description Default
line

LineString Line to be split by distance along the line.

required
length

float Length of each segment to cut.

required
merge_threshold

float, optional Threshold below which the last segment is merged with the previous one. Default is 0.5.

required

Returns:

Type Description

List of LineString objects A list containing the resulting line segments.

Example

">>> from shapely.geometry import LineString ">>> line = LineString([(0, 0), (10, 0)]) ">>> segments = cut_line_by_length(line, 3, merge_threshold=1) ">>> for segment in segments: ">>> print(f"Segment: {segment}, Length: {segment.length}")

Output: Segment: LINESTRING (0 0, 3 0), Length: 3.0 Segment: LINESTRING (3 0, 6 0), Length: 3.0 Segment: LINESTRING (6 0, 9 0), Length: 3.0 Segment: LINESTRING (9 0, 10 0), Length: 1.0

After merging the last segment with the second-to-last segment:

Output: Segment: LINESTRING (0 0, 3 0), Length: 3.0 Segment: LINESTRING (3 0, 6 0), Length: 3.0 Segment: LINESTRING (6 0, 10 0), Length: 4.0

chk_df_multipart

chk_df_multipart(df: GeoDataFrame, chk_shp_in_string: str) -> tuple[GeoDataFrame, bool]

This function is check the input geopandas.GeoDataFrame object contains multipart geometry. If multipart geometry is found, function will try to explode and return single geometry and a boolean of multipart is found or not. Args: df: Any geopandas.GeoDataFrame like chk_shp_in_string: String that the input GeoDataFrame geometry type, i.e. 'Point', 'Polygon', 'LineString'

Returns:

main_canopy_threshold_relative

main_canopy_threshold_relative(in_line: str, in_chm: str, canopy_percentile: int, canopy_thresh_percentage: int, full_step: bool, processes: int, out_dyn_centerline: str = None) -> str | None

This is a function finding approximate surrounding forest canopy height and surrounding forest edge distance from input CHM Args: in_line: Path like string in_chm: Path like string canopy_percentile: Percentile as integer range 1-100 canopy_thresh_percentage: Percentage as integer range 1-100

Returns:

Type Description
str | None

Path like string of the saved centerlines with extra attributes

Copyright (C) 2025 Applied Geospatial Research Group.

This script is licensed under the GNU General Public License v3.0. See https://gnu.org/licenses/gpl-3.0 for full license details.

Author: Richard Zeng, Maverick Fong

Description

This script is part of the BERA Tools. Webpage: https://github.com/BERATool/beratools

This file hosts the ground_footprint tool.

prepare_line_args

prepare_line_args(line_gdf, poly_gdf, n_samples, offset, width_percentile)

Generate arguments for each line in the GeoDataFrame.

Returns:

Name Type Description
line_args

list row : inter_poly : n_samples : offset : width_percentile :

generate_sample_points

generate_sample_points(line, n_samples=10)

Generate evenly spaced points along a line.

Parameters:

Name Type Description Default
line LineString

The line along which to generate points.

required
n_samples int

The number of points to generate (default is 10).

10

Returns:

Name Type Description
list

List of shapely Point objects.

generate_fixed_width_footprint

generate_fixed_width_footprint(line_gdf, max_width=False)

Create a buffer around each line.

In the GeoDataFrame using its 'max_width' attribute and saves the resulting polygons in a new shapefile.

Args: line_gdf: GeoDataFrame containing LineString with 'max_width' attribute. max_width: Use max width or not to produce buffer.

calculate_average_width

calculate_average_width(line, in_poly, offset, n_samples)

Calculate the average width of a polygon perpendicular to the given line.

Constants

Copyright (C) 2025 Applied Geospatial Research Group.

This script is licensed under the GNU General Public License v3.0. See https://gnu.org/licenses/gpl-3.0 for full license details.

Author: Richard Zeng

Description

This script is part of the BERA Tools. Webpage: https://github.com/BERATool/beratools

The purpose of this script is to provide common constants.

CenterlineStrategy

Bases: Enum

Guided strategy for centerline extraction.

CenterlineMethod

Bases: Enum

Least-cost path and corridor raster method for centerline extraction.

CenterlineChmMode

Bases: Enum

CHM preprocessing mode for centerline extraction.

CenterlineFlags

Bases: Flag

Flags for the centerline algorithm.

ParallelMode

Bases: IntEnum

Defines the parallel mode for the algorithms.

Logger

Copyright (C) 2025 Applied Geospatial Research Group.

This script is licensed under the GNU General Public License v3.0. See https://gnu.org/licenses/gpl-3.0 for full license details.

Author: Richard Zeng

Description

This script is part of the BERA Tools. Webpage: https://github.com/BERATool/beratools

This module provides logger configuration and convenience functions for BERA Tools.

Each named logger can write to:

  1. A log file using a detailed timestamped format.
  2. The console using a concise message-only format.

The module also adds two convenience methods to each configured logger:

logger.file_only(...)
logger.debug_file_only(...)

These methods bypass console handlers and write directly to the logger's file handler.

NoParsingFilter

Bases: Filter

Exclude messages beginning with the word parsing.

This reduces console and file noise from repetitive parsing messages. The comparison is case-sensitive to retain the behavior of the original implementation.

filter

filter(record: LogRecord) -> bool

Return False for messages beginning with parsing.

Parameters

record : logging.LogRecord Logging record being evaluated.

Returns

bool True when the record should be logged. False when the record should be discarded.

Logger

Logger(logger_name, queue=None, file_level=DEFAULT_FILE_LEVEL, console_level=DEFAULT_CONSOLE_LEVEL)

Configure a named BERA Tools logger.

The logger uses two handlers:

  • File handler: Stores timestamped messages at file_level or higher.

  • Console handler: Displays concise messages at console_level or higher.

Each logger is configured only once. Creating another Logger instance with the same name reuses the existing handlers.

Parameters

logger_name : str Name of the logger.

int, default logging.INFO

Minimum logging level written to the log file.

int, default logging.INFO

Minimum logging level written to the console.

get_logger

get_logger() -> Logger

Return the configured logger.

Two convenience methods are attached to the logger:

logger.file_only(message, *args, level=logging.INFO) Write only to file handlers.

logger.debug_file_only(message, *args) Write a DEBUG message only to file handlers.

Returns

logging.Logger Configured logger instance.

print

print(message, flush: bool = True) -> None

Log a message at INFO level.

This method provides compatibility with code that previously used print() for progress or status messages.

Parameters

message : object Message or object to log.

bool, default True

Flush all configured handlers after logging.

flush

flush() -> None

Flush all handlers associated with this logger.

Flushing should normally be used only for important progress messages, shutdown handling, or debugging. Flushing every log record can significantly reduce performance.

debug_file_only staticmethod

debug_file_only(message, *args, logger_name: Optional[str] = None) -> None

Write a DEBUG message only to file handlers.

The message is not sent to console handlers.

Parameters

message : object Log message or formatting template.

*args Values used with standard logging percent formatting.

str

Name of an existing configured logger.

file_only staticmethod

file_only(message, *args, level: int = INFO, logger_name: Optional[str] = None) -> None

Write a message directly to the logger's file handlers.

Console handlers are intentionally bypassed.

Unlike a regular logger call, this method sends the record directly to each file handler. This allows a DEBUG file-only record to be written even when the logger's effective level is INFO or WARNING, provided the file handler accepts that level.

Parameters

message : object Log message or formatting template.

*args Values used with standard logging percent formatting.

int, default logging.INFO

Logging level associated with the record.

str

Name of an existing configured logger.

Notes

This method does not flush the file handler after every message. Operating-system and Python buffering improve performance during large multiprocessing jobs. Use Logger.flush() when an immediate flush is required.

Tool Base

Copyright (C) 2025 Applied Geospatial Research Group.

This script is licensed under the GNU General Public License v3.0. See https://gnu.org/licenses/gpl-3.0 for full license details.

Author: Richard Zeng

Description

This script is part of the BERA Tools. Webpage: https://github.com/BERATool/beratools

The purpose of this script is to provide fundamental utilities for tools.

ToolBase

ToolBase()

Bases: object

Base class for tools.

configure_worker_logging

configure_worker_logging(queue)

Configure worker process logger.