brails.types.asset_inventory module

This module defines classes associated with asset inventories.

AssetInventory()

A class representing a Asset Inventory.

Asset(asset_id, coordinates[, features])

A data structure for an asset that holds it coordinates and features.

class brails.types.asset_inventory.Asset(asset_id: str | int, coordinates: List[List[float]], features: Dict[str, Any] | None = None)

Bases: object

A data structure for an asset that holds it coordinates and features.

Attributes:

asset_id (str|int):: Unique identifier for the asset. coordinates (list[List[float]]): A list of coordinate pairs

[[lon1, lat1], [lon2, lat2], …, [lonN, latN]].

features (dict[str, any]): A dictionary of features (attributes) for

the asset.

Methods:
add_features(additional_features: dict[str, any],

overwrite: bool = True): Update the existing features in the asset.

print_info(): Print the coordinates and features of the asset.

add_features(additional_features: Dict[str, Any], overwrite: bool = True) Tuple[bool, int]

Update the existing features in the asset.

Args:
additional_features (dict[str, any]): New features to merge into

the asset’s features.

overwrite (bool, optional): Whether to overwrite existing features.

Defaults to True.

print_info() None

Print the coordinates and features of the asset.

remove_features(feature_list: List[str]) bool

Update the existing features in the asset.

Args:

feature_list (dict[str, any]): List of features to be removed

Return:

bool: True if features are removed

class brails.types.asset_inventory.AssetInventory

Bases: object

A class representing a Asset Inventory.

Attributes:

inventory (dict): The inventory stored in a dict accessed by asset_id

Methods:

add_asset(asset_id, Asset): Add an asset to the inventory. add_asset_coordinates(asset_id, coordinates): Add an asset to the

inventory with just a list of coordinates.

add_asset_features(asset_id, features, overwrite): Append new features

to the asset.

add_model_predictions(predictions, feature_key): Add model predictions

to assets under a specified feature key.

change_feature_names(feature_name_mapping): Rename feature names in an

AssetInventory using user-specified mapping.

convert_polygons_to_centroids(): Convert polygon geometries in the

inventory to their centroid points.

get_asset_coordinates(asset_id): Get coordinates of a particular

assset.

get_asset_features(asset_id): Get features of a particular assset. get_asset_ids(): Return the asset ids as a list. get_coordinates(): Return a list of footprints. get_extent(buffer): Calculate the geographical extent of the inventory. get_geojson(): Return inventory as a geojson dict.

get_random_sample(size, seed): Get subset of the inventory. write_to_geojson(): Write inventory to file in GeoJSON format. Also

return inventory as a geojson dict.

join(inventory_to_join, method=”get_points_in_polygons”): Perform a

spatial join with another AssetInventory using the specified method.

print_info(): Print the asset inventory. remove_asset(asset_id): Remove an asset to the inventory. remove_features(feature_list): Remove features from the inventory. read_from_csv(file_path, keep_existing, str_type, id_column): Read

inventory dataset from a csv table

add_asset_features_from_csv(file_path, id_column): Add asset features

from a csv file.

add_asset(asset_id: str | int, asset: Asset) bool

Add an Asset to the inventory.

Args:
asset_id (str | int):

The unique identifier for the asset.

asset (Asset):

The asset to be added.

Returns:
bool:

True if the asset was added successfully, False otherwise.

Raises:
TypeError:

If asset is not an instance of Asset.

add_asset_coordinates(asset_id: str | int, coordinates: List[List[float]]) bool

Add an Asset to the inventory by adding its coordinate information.

Args:
asset_id (str|int):

The unique identifier for the asset.

coordinates (list[list[float]]):

A two-dimensional list representing the geometry in [[lon1, lat1], [lon2, lat2], …, [lonN, latN]] format.

Returns:

bool: True if the asset was added successfully, False otherwise.

add_asset_features(asset_id: str | int, new_features: Dict[str, Any], overwrite: bool = True) bool

Add new asset features to the Asset with the specified ID.

Args:
asset_id (str|int):

The unique identifier for the asset.

new_features (dict):

A dictionary of features to add to the asset.

overwrite (bool):

Whether to overwrite existing features with the same keys. Defaults to True.

Returns:
bool: True if features were successfully added, False if the asset

does not exist or the operation fails.

add_asset_features_from_csv(file_path: str, id_column: str | None) bool

Read inventory data from a CSV file and add it to the inventory.

Args:
file_path (str):

The path to the CSV file

id_column (str):

The name of column that contains id values. If None, new indicies will be assigned

Returns:
bool:

True if assets were addded, False otherwise.

add_model_predictions(predictions: Dict[Any, Any], feature_key: str) None

Add model predictions to the inventory.

This method goes through the inventory and updates each item by adding the corresponding model prediction as a new feature under the specified key. Items without a matching prediction are left unchanged.

Args:
predictions (dict):

A dictionary where keys correspond to inventory items and values represent the predicted features to be added.

feature_key (str):

The key under which the predictions will be stored as a new feature in each inventory item.

Raises:
TypeError:

If predictions is not a dictionary or feature_key is not a string.

ValueError:

If none of the keys in predictions exist in self.inventory.

Example:
self.add_model_predictions(predictions={1:’gable’,

3:’flat’, 12:’hip’},

feature_key=’roof_type’)

change_feature_names(feature_name_mapping: Dict[str, str]) None

Rename feature names in an AssetInventory using user-specified mapping.

Args:
feature_name_mapping (dict):

A dictionary where keys are the original feature names and values are the new feature names.

Raises:
TypeError:

If the mapping is not a dictionary or contains invalid key-value pairs.

convert_polygons_to_centroids() None

Convert polygon geometries in the inventory to their centroid points.

Iterates through the asset inventory and replaces the coordinates of each polygon or linestring geometry with the coordinates of its centroid. Point geometries are left unchanged.

This function is useful for spatial operations that require point representations of larger geometries (e.g., matching, distance

calculations).

Notes:
  • Polygon coordinates are wrapped in a list to ensure proper GeoJSON structure.

  • Linestrings are treated as such unless the geometry is invalid or ambiguous.

Modifies:
self.inventory (dict):

Updates the coordinates field of each asset in-place by replacing polygons and linestrings with their centroid.

get_asset_coordinates(asset_id: str | int) Tuple[bool, List]

Get the coordinates of a particular asset.

Args:
asset_id (str | int):

The unique identifier for the asset.

Returns:
tuple[bool, list]]:

A tuple where the first element is a boolean indicating whether the asset was found, and the second element is a list of coordinate pairs in the format [[lon1, lat1], [lon2, lat2], …, [lonN, latN]] if the asset is present. Returns an empty list if the asset is not found.

get_asset_features(asset_id: str | int) Tuple[bool, Dict[str, Any]]

Get features of a particular asset.

Args:
asset_id (str|int):

The unique identifier for the asset.

Returns:
tuple[bool, Dict]:

A tuple where the first element is a boolean indicating whether the asset was found, and the second element is a dictionary containing the asset’s features if the asset is present. Returns an empty dictionary if the asset is not found.

get_asset_ids() List[str | int]

Retrieve the IDs of all assets in the inventory.

Returns:
list[str | int]:

A list of asset IDs, which may be strings or integers.

get_coordinates() Tuple[List[List[List[float]]], List[str | int]]

Get geometry (coordinates) and keys of all assets in the inventory.

Returns:
tuple[list[list[list[float, float]]], list[str | int]]: A tuple

containing: - A list of coordinates for each asset, where each coordinate

is represented as a list of [longitude, latitude] pairs.

  • A list of asset keys corresponding to each Asset.

get_dataframe() Tuple[DataFrame, DataFrame, int]

Convert the asset inventory into two structured DataFrames and count.

This method processes the internal asset inventory and returns: - A DataFrame containing the features of each asset, with support for

multiple possible worlds (realizations).

  • A DataFrame containing centroid coordinates (latitude and longitude) for spatial operations.

  • The total number of assets in the inventory.

The method flattens feature lists into separate columns if multiple possible worlds exist. It also derives centroid coordinates from the GeoJSON geometry for each asset.

Returns:
Tuple[pd.DataFrame, pd.DataFrame, int]:
  • Asset feature DataFrame (indexed by asset ID).

  • Asset geometry DataFrame with ‘Lat’ and ‘Lon’ columns.

  • Total number of assets (int).

Raises:
ValueError:

If a feature list’s length does not match the expected number of possible worlds.

get_extent(buffer: str | List[float] = 'default') box

Calculate the geographical extent of the inventory.

Args:
buffer (str or list[float]):

A string or a list of 4 floats. - ‘default’ applies preset buffer values. - ‘none’ applies zero buffer values. - A list of 4 floats defines custom buffer values for each

edge of the bounding box in the order: [minlon buffer, minlat buffer, maxlon buffer, maxlat buffer].

Returns:
shapely.geometry.box:

A Shapely polygon representing the extent of the inventory, with buffer applied.

Raises:

ValueError: If the buffer input is invalid.

get_geojson() Dict[str, Any]

Generate a GeoJSON representation of the assets in the inventory.

The function constructs a valid GeoJSON FeatureCollection, where each asset is represented as a Feature. Each feature contains: - A geometry field (Point, LineString, or Polygon) based on the

asset’s coordinates.

  • A properties field containing asset-specific metadata.

Additionally, the GeoJSON output includes: - A timestamp (generated) indicating when the data was created. - The BRAILS package version (if available). - A Coordinate Reference System (crs) definition set to “CRS84”.

Returns:
dict:

A dictionary formatted as a GeoJSON FeatureCollection containing all assets in the inventory.

Note:

Assets without geometry are excluded from the generated GeoJSON representation.

get_multi_keys() Tuple[List[str], List[str]]

Identify features that contain multiple realizations across assets.

Iterates through all assets and returns two lists: - Keys associated with multi-valued features (i.e., lists). - All unique feature keys present in the inventory.

Returns:
Tuple[List[str], List[str]]:
  • A list of keys corresponding to multi-realization features.

  • A complete list of all unique feature keys in the inventory.

get_n_pw() int

Get the number of possible worlds (realizations) in the inventory.

Returns:
int:

The number of possible worlds stored in the inventory.

get_random_sample(nsamples: int, seed: int | float | str | bytes | bytearray | None = None) AssetInventory

Generate a smaller AssetInventory with a random selection of assets.

This method randomly selects nsamples assets from the existing inventory and returns a new AssetInventory instance containing only these sampled assets. The randomness can be controlled using an optional seed for reproducibility.

Args:
nsamples (int):

The number of assets to randomly sample from the inventory. Must be a positive integer not exceeding the total number of assets.

seed (int | float | str | bytes | bytearray | None, optional):

A seed value for the random generator to ensure reproducibility. If None, the system default (current system time) is used.

Returns:
AssetInventory:

A new AssetInventory instance containing the randomly selected subset of assets.

Raises:
ValueError:

If nsamples is not a positive integer or exceeds the number of assets in the inventory.

get_world_realization(id: int = 0) AssetInventory

Extract a single realization (possible world) from an inventory.

This method generates a new AssetInventory instance where all features containing multiple possible worlds are reduced to a single realization specified by id. Features that are not lists are copied as-is.

Args:
id (int, default=0):

The index of the realization to extract. Must be within the range of available possible worlds (0-based indexing).

Returns:
AssetInventory:

A new inventory object representing the selected realization.

Raises:
Exception:
  • If id > 0 but the inventory only contains a single realization.

  • If any feature has fewer realizations than the specified id.

join(inventory_to_join: AssetInventory, method: str = 'get_points_in_polygons') None

Merge with another AssetInventory using specified spatial join method.

Args:
inventory_to_join (AssetInventory):

The inventory to be joined with the current one.

method (str):

The spatial join method to use. Defaults to ‘get_points_in_ polygons’. The method defines how the join operation is executed between inventories.

Raises:
TypeError:
  • If inventory_to_join is not an instance of AssetInventory.

  • If method is not a string.

Returns:

None: This method modifies the AssetInventory instance in place.

print_info() None

Print summary information about the AssetInventory.

This method outputs the name of the class, the type of data structure used to store the inventory, and basic information about each asset in the inventory, including its key and features.

Returns:

None

read_from_csv(file_path: str, keep_existing: bool, str_type: str = 'building', id_column: str | None = None) bool

Read inventory data from a CSV file and add it to the inventory.

Args:
file_path (str):

The path to the CSV file

keep_existing (bool):

If False, the inventory will be initialized

str_type (str):

“building” or “bridge”

id_column (str):

The name of column that contains id values. If None, new indices will be assigned

Returns:
bool:

True if assets were addded, False otherwise.

remove_asset(asset_id: str | int) bool

Remove an Asset from the inventory.

Args:
asset_id (str|int):

The unique identifier for the asset.

Returns:
bool:

True if asset was removed, False otherwise.

remove_features(feature_list: List[str]) bool

Remove specified features from all assets in the inventory.

Args:
feature_list (list[str]):

The unique identifier for the asset.

Returns:
bool:

True if features were removed, False otherwise.

update_world_realization(id: int, world_realization: AssetInventory) None

Update the current AssetInventory with a specific world realization.

This method integrates feature values from a single-world world_realization inventory into the current multi-world inventory by updating the realization at the specified index id.

Args:
id (int):

The index of the world (realization) to update. Must be less than self.n_pw.

world_realization (AssetInventory):

An AssetInventory instance representing a single realization of the world. All features in this inventory must be scalar (i.e., not lists).

Raises:
Exception:
  • If the specified id is not within the valid range of realizations.

  • If world_realization contains features with multiple realizations.

write_to_geojson(output_file: str = '') Dict

Write inventory to a GeoJSON file and return the GeoJSON dictionary.

This method generates a GeoJSON representation of the asset inventory, writes it to the specified file path (if provided), and returns the GeoJSON object.

Args:
output_file (str, optional):

Path to the output GeoJSON file. If empty, no file is written.

Returns:
Dict:

A dictionary containing the GeoJSON FeatureCollection.

brails.types.asset_inventory.clean_floats(obj: Any) Any

Recursively convert float values that are mathematically integers to int.

This function traverses a nested structure (e.g., dict, list, JSON-like object) and converts any float that is numerically equivalent to an integer into an int, improving the readability and cleanliness of the output, especially for serialization.

Args:
obj (Any):

A JSON-like object (dict, list, or primitive value) to process.

Returns:
Any:

The input object with eligible floats converted to integers.