pyorps.core

Core types and base classes for geospatial data processing.

class pyorps.core.CostAssumptions(source=None)[source]

Bases: object

A class for handling cost assumptions for rasterization.

This class handles: - Loading cost assumptions from files (CSV, Excel, JSON) or generating of cost assumptions from a dictionary or a GeoDataFrame. - Mapping costs to features in a GeoDataFrame - Managing hierarchical cost structures

Initialize the CostAssumptions object.

Parameters:

source (str | dict | None) –

  1. Path to a cost assumptions file

  2. A dictionary of cost values

__init__(source=None)[source]

Initialize the CostAssumptions object.

Parameters:

source (str | dict | None) –

  1. Path to a cost assumptions file

  2. A dictionary of cost values

apply_to_geodataframe(gdf, main_feature=None, side_features=None)[source]

Apply cost assumptions to a GeoDataFrame.

Parameters:
  • gdf (GeoDataFrame) – GeoDataFrame to apply costs to

  • main_feature (str | None) – Main feature column name

  • side_features (list[str] | None) – list of side feature column names or single side feature name

Returns:

GeoDataFrame with ‘cost’ column added

convert_df_to_cost_dict(df)[source]

Convert a DataFrame to a nested dictionary for cost assumptions.

Parameters:

df (DataFrame) – DataFrame containing cost assumptions with hierarchical structure

Returns:

dictionary of cost assumptions with nested structure based on DataFrame columns

Return type:

dict

Uses one numeric column for costs, and all other columns as a hierarchical index: - The first column is the ‘main_feature’ - All additional columns are ‘side_features’

cost_dict_to_df(cost_dict)[source]

Convert cost assumptions dictionary to DataFrame.

Parameters:

cost_dict (dict) – Dictionary of cost assumptions

Returns:

DataFrame representation of cost assumptions

Return type:

DataFrame

load(source)[source]

Load cost assumptions from a file or dictionary.

Parameters:

source (str | dict) – Path to a file or a dictionary containing cost assumptions

Returns:

dictionary of cost assumptions

Return type:

dict

to_csv(filepath, separator=';', decimal='.', encoding='ISO-8859-1')[source]

Save the cost assumptions to a CSV file.

Parameters:
  • filepath (str) – Path where to save the CSV file

  • separator (str) – Column separator character (default is ‘;’)

  • decimal (str) – Decimal separator character (default is ‘.’)

  • encoding (str) – The encoding of the file (default is ‘ISO-8859-1’)

Return type:

None

to_excel(filepath, sheet_name='CostAssumptions', index=False)[source]

Save the cost assumptions to an Excel file.

Parameters:
  • filepath (str) – Path where to save the Excel file

  • sheet_name (str) – Name of the worksheet (default is ‘CostAssumptions’)

  • index (bool) – Whether to write row indices (default is False)

Return type:

None

to_json(filepath, indent=2, encoding='ISO-8859-1')[source]

Save the cost assumptions to a JSON file.

Parameters:
  • filepath (str) – Path where to save the JSON file

  • indent (int) – Number of spaces for indentation (default is 2)

  • encoding (str) – The encoding of the file (default is ‘ISO-8859-1’)

Return type:

None

pyorps.core.get_zero_cost_assumptions(gdf, main_feature, side_features)[source]

Generate cost assumptions with zero values for all feature combinations.

Creates structures matching format for CostAssumptions: - Without side features: {main_feature: {val1: 0, val2: 0, …}} - With side features: {(main_feature, side_feature1, …): {(val1, val2, …): 0, …}}

Parameters:
  • gdf (GeoDataFrame) – GeoDataFrame with feature columns

  • main_feature (str) – Primary feature column name

  • side_features (list[str]) – List of secondary feature column names

Returns:

Instacne of zero-cost assumptions

Return type:

CostAssumptions

pyorps.core.detect_feature_columns(gdf, max_features_per_column=50)[source]

Analyze columns in a geodataframe to identify the best candidates for main_feature and side_features based on statistical metrics.

Parameters:
  • gdf (GeoDataFrame) – GeoDataFrame to analyze

  • max_features_per_column (int) – Maximum number of unique values allowed in a

  • column (categorical)

Returns:

tuple of (main_feature, side_features)

Raises:

NoSuitableColumnsError – When no suitable columns are found for feature selection

Return type:

tuple[str, list[str]]

pyorps.core.save_empty_cost_assumptions(geo_dataset, save_path, main_feature=None, side_features=None, file_type='csv', **kwargs)[source]

Generate and save empty cost assumptions with zero values for a geo dataset.

This function analyzes the given dataset to detect appropriate feature columns, creates a CostAssumptions object with zero costs for all feature combinations, and saves it to the specified path in the requested format.

Parameters:
  • geo_dataset (Any) – GeoDataset object with a ‘data’ attribute containing a GeoDataFrame

  • save_path (str | Path) – File path where the cost assumptions should be saved

  • main_feature (str | None) – Column name for the primary feature

  • side_features (list[str] | None) – List containing a single column name for the secondary feature

  • file_type (str) – Output file format - one of ‘json’, ‘csv’, or ‘excel’ (default is ‘json’)

Raises:
Returns:

This function saves to a file and doesn’t return a value

Return type:

None

class pyorps.core.Path(source, target, algorithm, graph_api, path_indices, path_coords, path_geometry, euclidean_distance, runtimes, path_id, search_space_buffer_m, neighborhood, total_length=None, total_cost=None, length_by_category=None, length_by_category_percent=None)[source]

Bases: object

Dataclass representing a path in a raster graph. Used as container for all path metrics and information.

Parameters:
__eq__(other)[source]

Check for equality between two paths.

Parameters:

other (Any)

Return type:

bool

__init__(source, target, algorithm, graph_api, path_indices, path_coords, path_geometry, euclidean_distance, runtimes, path_id, search_space_buffer_m, neighborhood, total_length=None, total_cost=None, length_by_category=None, length_by_category_percent=None)
Parameters:
Return type:

None

__repr__()[source]

Return a detailed string representation of the path.

Return type:

str

__str__()[source]

Return a string representation of the path including the path_id, source and target, as well as the path’s total length and total cost.

Returns:

A string representation of the path.

Return type:

str

length_by_category: dict[float, float] | None = None
length_by_category_percent: dict[float, float] | None = None
to_geodataframe_dict()[source]

Convert Path object to a dictionary suitable for GeoDataFrame creation.

Returns:

dictionary with path data formatted for GeoDataFrame

Return type:

dict

total_cost: float | None = None
total_length: float | None = None
source: tuple[float, float] | list[float]
target: tuple[float, float] | list[float]
algorithm: str
graph_api: str
path_indices: list[int | int32 | int64 | uint32 | uint64] | ndarray[int]
path_coords: list[tuple[float, float] | list[float]]
path_geometry: LineString
euclidean_distance: float
runtimes: dict[str, float]
path_id: int
search_space_buffer_m: float
neighborhood: str
class pyorps.core.PathCollection[source]

Bases: object

Container for Path objects with O(1) retrieval by path ID and O(n) lookup for source and target information. Paths can be added with new id by replacing a Path object with the same ID already existing in th PathCollection.

Create an empty PathCollection for collecting Paths with their IDs in a dictionary.

__eq__(other)[source]

Check if PathCollections are equal. They do not have to be in the same order to be equal!

Return type:

bool

__getitem__(path_id)[source]

Get path by path_id of the Path object from the PathCollection.

__init__()[source]

Create an empty PathCollection for collecting Paths with their IDs in a dictionary.

__iter__()[source]

Iterate through all paths in the PathCollection.

__len__()[source]

Return the number of paths in the PathCollection.

__repr__()[source]

Return a detailed string representation of the path collection.

Return type:

str

__str__()[source]

Return a string representation of the path collection.

Return type:

str

add(path, replace=False)[source]

Add a path to the PathCollection. If the Path’s path_id is None or if replace is False, the path_id of the Path object will set to self._next_id and self._next_id will be incremented. If the Path’s path_id is not None and replace is True, a Path with the same path_id (if present) will be replaced with the new Path object.

Parameters:
  • path (Path) – A Path object which should be added to the PathCollection.

  • replace (bool) – Whether to replace an existing Path object with the same path_id (if present) or not.

Return type:

None

property all

Return all Path objects from the values of the PathCollection’s _paths dictionary as a list.

Returns:

A list of all Path objects in the PathCollection.

get(path_id=None, source=None, target=None)[source]

Retrieve a stored path by ID, or by source AND target.

Parameters:
  • path_id (int) – The ID of the Path object to retrieve (must be None if path should be found by source and target)

  • source (Any) – The source Path object to retrieve (only used if path_id is None and target os set too; neglected otherwise)

  • target (Any) – The target Path object to retrieve (only used if path_id is None and target os set too; neglected otherwise)

Returns:

The Path object with the specified ID or source/target pair. None if no such path exists.

Return type:

Path | None

to_geodataframe_records()[source]

Convert all paths to a list of dictionaries suitable for a GeoDataFrame.

Returns:

List of dictionaries with path data formatted for a GeoDataFrame

Return type:

list

exception pyorps.core.CostAssumptionsError[source]

Bases: Exception

Base exception for CostAssumptions class.

exception pyorps.core.FileLoadError[source]

Bases: CostAssumptionsError

Exception raised when loading files fails.

exception pyorps.core.InvalidSourceError[source]

Bases: CostAssumptionsError

Exception raised when the provided source is invalid.

exception pyorps.core.FormatError[source]

Bases: CostAssumptionsError

Exception raised when data format is invalid.

exception pyorps.core.FeatureColumnError[source]

Bases: Exception

Base exception for feature column detection errors

exception pyorps.core.NoSuitableColumnsError[source]

Bases: FeatureColumnError

Exception raised when no suitable columns are found

exception pyorps.core.ColumnAnalysisError[source]

Bases: FeatureColumnError

Exception raised when column analysis fails

exception pyorps.core.WFSError[source]

Bases: Exception

Base exception for WFS-related errors.

exception pyorps.core.WFSConnectionError[source]

Bases: WFSError

Exception raised for connection issues with WFS services.

exception pyorps.core.WFSResponseParsingError[source]

Bases: WFSError

Exception raised when parsing WFS responses fails.

exception pyorps.core.WFSLayerNotFoundError[source]

Bases: WFSError

Exception raised when a requested layer cannot be found.

exception pyorps.core.RasterShapeError(raster_shape)[source]

Bases: Exception

Custom exception if the raster shape is not supported

Parameters:

raster_shape (tuple[int, ...])

Return type:

None

__init__(raster_shape)[source]
Parameters:

raster_shape (tuple[int, ...])

Return type:

None

exception pyorps.core.NoPathFoundError(source, target, add_message='')[source]

Bases: Exception

Custom exception if no path can be found in the graph for source and target

Parameters:
  • source (int)

  • target (int)

  • add_message (str)

Return type:

None

__init__(source, target, add_message='')[source]
Parameters:
  • source (int)

  • target (int)

  • add_message (str)

Return type:

None

exception pyorps.core.AlgorithmNotImplementedError(algorithm, graph_library)[source]

Bases: Exception

Custom exception if a specific algorithm is not implemented in the API or the graph library

Parameters:
  • algorithm (str)

  • graph_library (str)

Return type:

None

__init__(algorithm, graph_library)[source]
Parameters:
  • algorithm (str)

  • graph_library (str)

Return type:

None

Modules

cost_assumptions

PYORPS: An Open-Source Tool for Automated Power Line Routing

exceptions

PYORPS: An Open-Source Tool for Automated Power Line Routing

path

PYORPS: An Open-Source Tool for Automated Power Line Routing

types

PYORPS: An Open-Source Tool for Automated Power Line Routing