voxcity.utils¶
Submodules¶
Attributes¶
Classes¶
Typed view of the dict returned by compute_grid_geometry(). |
|
Projects between lon_lat (WGS84) and uv_m (local grid metres). |
Functions¶
|
Get land cover classification mapping for a specific data source. |
|
Get a formatted string describing land cover classes for a specific source. |
|
Optimized version using direct numpy array indexing instead of np.vectorize. |
|
Convert an array of land cover class names to integer indices. |
|
Get priority rankings for land cover classes to resolve conflicts during classification. |
|
Create polygon geometries and spatial index from land cover GeoJSON data. |
|
Find the nearest land cover class for a given pixel color using RGB distance. |
|
Determine the dominant land cover class in a cell based on pixel majority. |
|
Safely rename a file, handling existing files by adding a number suffix. |
|
Safely extract a file from zip, handling existing files. |
|
Process an EPW file into a pandas DataFrame and header metadata. |
|
Read EPW file specifically for solar simulation purposes. |
Download and process EPW weather file from Climate.OneBuilding.Org based on coordinates. |
|
Returns a dictionary mapping material names to their corresponding ID values. |
|
|
Determines the appropriate modulo numbers for x, y, z based on window_ratio. |
|
Marks cells in voxelcity_grid based on building IDs and window ratio. |
|
Sets building materials based on a GeoDataFrame containing building information. |
|
Print voxel semantic codes to console. |
|
Print standard land cover class definitions to console. |
|
Print both voxel codes and land cover class definitions. |
|
Get the land cover class name for a given index. |
|
Get the semantic name for a voxel code. |
|
Summarize the contents of a voxel grid. |
|
Summarize the contents of a land cover grid. |
Package Contents¶
- voxcity.utils.get_land_cover_classes(source)[source]¶
Get land cover classification mapping for a specific data source.
Each data source has its own color-to-class mapping system. This function returns the appropriate RGB color to land cover class dictionary based on the specified source.
- Parameters:
source (str) – Name of the land cover data source. Supported sources: “Urbanwatch”, “OpenEarthMapJapan”, “ESRI 10m Annual Land Cover”, “ESA WorldCover”, “Dynamic World V1”, “Standard”, “OpenStreetMap”
- Returns:
Dictionary mapping RGB tuples to land cover class names
- Return type:
dict
Example
>>> classes = get_land_cover_classes("Urbanwatch") >>> print(classes[(255, 0, 0)]) # Returns 'Building'
- voxcity.utils.get_source_class_descriptions(source)[source]¶
Get a formatted string describing land cover classes for a specific source.
- Parameters:
source (str) – Name of the land cover data source.
- Returns:
Formatted string describing the source’s land cover classes.
- Return type:
str
- voxcity.utils.convert_land_cover(input_array, land_cover_source='Urbanwatch')[source]¶
Optimized version using direct numpy array indexing instead of np.vectorize. This is 10-100x faster than the original.
Returns 1-based class indices (1-14) for consistency with voxel representations.
- voxcity.utils.convert_land_cover_array(input_array, land_cover_classes)[source]¶
Convert an array of land cover class names to integer indices.
This function maps string-based land cover class names to integer indices for numerical processing and storage efficiency.
- Parameters:
input_array (numpy.ndarray) – Array containing land cover class names as strings
land_cover_classes (dict) – Dictionary mapping RGB tuples to class names
- Returns:
Array with 0-based integer indices corresponding to land cover classes
- Return type:
numpy.ndarray
Note
Classes not found in the mapping are assigned index -1 Indices are 0-based as source-specific indices. Use convert_land_cover() to remap to standard 1-based indices for voxel representation.
- voxcity.utils.get_class_priority(source)[source]¶
Get priority rankings for land cover classes to resolve conflicts during classification.
When multiple land cover classes are present in the same area, this priority system determines which class should take precedence. Higher priority values indicate classes that should override lower priority classes.
- Parameters:
source (str) – Name of the land cover data source
- Returns:
Dictionary mapping class names to priority values (higher = more priority)
- Return type:
dict
- Priority Logic for OpenStreetMap:
Built Environment: Highest priority (most definitive structures)
Water Bodies: High priority (clearly defined features)
Vegetation: Medium priority (managed vs natural)
Natural Non-Vegetation: Lower priority (often default classifications)
Uncertain/No Data: Lowest priority
- voxcity.utils.create_land_cover_polygons(land_cover_geojson)[source]¶
Create polygon geometries and spatial index from land cover GeoJSON data.
This function processes GeoJSON land cover data to create Shapely polygon geometries and builds an R-tree spatial index for efficient spatial queries.
- Parameters:
land_cover_geojson (list) – List of GeoJSON feature dictionaries containing land cover polygons with geometry and properties
- Returns:
- A tuple containing:
land_cover_polygons (list): List of tuples (polygon, class_name)
idx (rtree.index.Index): Spatial index for efficient polygon lookup
- Return type:
tuple
Note
Each GeoJSON feature should have: - geometry.coordinates[0]: List of coordinate pairs defining the polygon - properties.class: String indicating the land cover class
- voxcity.utils.get_nearest_class(pixel, land_cover_classes)[source]¶
Find the nearest land cover class for a given pixel color using RGB distance.
This function determines the most appropriate land cover class for a pixel by finding the class with the minimum RGB color distance to the pixel’s color.
- Parameters:
pixel (tuple) – RGB color values as (R, G, B) tuple
land_cover_classes (dict) – Dictionary mapping RGB tuples to class names
- Returns:
Name of the nearest land cover class
- Return type:
str
Example
>>> classes = {(255, 0, 0): 'Building', (0, 255, 0): 'Tree'} >>> nearest = get_nearest_class((250, 5, 5), classes) >>> print(nearest) # Returns 'Building'
- voxcity.utils.get_dominant_class(cell_data, land_cover_classes)[source]¶
Determine the dominant land cover class in a cell based on pixel majority.
This function analyzes all pixels within a cell, classifies each pixel to its nearest land cover class, and returns the most frequently occurring class.
- Parameters:
cell_data (numpy.ndarray) – 3D array of RGB pixel data for the cell
land_cover_classes (dict) – Dictionary mapping RGB tuples to class names
- Returns:
Name of the dominant land cover class in the cell
- Return type:
str
Note
If the cell contains no data, returns ‘No Data’
- voxcity.utils.safe_rename(src: pathlib.Path, dst: pathlib.Path) pathlib.Path[source]¶
Safely rename a file, handling existing files by adding a number suffix.
- voxcity.utils.safe_extract(zip_ref: zipfile.ZipFile, filename: str, extract_dir: pathlib.Path) pathlib.Path[source]¶
Safely extract a file from zip, handling existing files.
- voxcity.utils.process_epw(epw_path: str | pathlib.Path) Tuple[pandas.DataFrame, dict][source]¶
Process an EPW file into a pandas DataFrame and header metadata.
- voxcity.utils.read_epw_for_solar_simulation(epw_file_path)[source]¶
Read EPW file specifically for solar simulation purposes. Returns (df[DNI,DHI], lon, lat, tz, elevation_m).
- voxcity.utils.get_nearest_epw_from_climate_onebuilding(longitude: float, latitude: float, output_dir: str = './', max_distance: float | None = None, extract_zip: bool = True, load_data: bool = True, region: str | List[str] | None = None, allow_insecure_ssl: bool = False, allow_http_fallback: bool = False, ssl_verify: bool | str = True) Tuple[str | None, pandas.DataFrame | None, Dict | None][source]¶
Download and process EPW weather file from Climate.OneBuilding.Org based on coordinates.
- voxcity.utils.get_material_dict()[source]¶
Returns a dictionary mapping material names to their corresponding ID values.
The material IDs use negative values to distinguish them from other voxel types. Each material has a unique negative ID that can be used for material-based rendering and analysis.
- Returns:
- Dictionary with material names as keys and negative integer IDs as values.
Available materials: unknown, brick, wood, concrete, metal, stone, glass, plaster
- Return type:
dict
- voxcity.utils.get_modulo_numbers(window_ratio)[source]¶
Determines the appropriate modulo numbers for x, y, z based on window_ratio.
This function creates different window patterns by returning modulo values that control the spacing of windows in the x, y, and z dimensions. Lower window_ratio values result in sparser window patterns (higher modulo values), while higher ratios create denser patterns.
The function uses hash-based selection for certain ratios to introduce variety in window patterns for buildings with similar window ratios.
- Parameters:
window_ratio (float) – Value between 0 and 1.0 representing window density
- Returns:
- (x_mod, y_mod, z_mod) - modulo numbers for each dimension
Higher values = sparser windows, lower values = denser windows
- Return type:
tuple
- voxcity.utils.set_building_material_by_id(voxelcity_grid, building_id_grid_ori, ids, mark, window_ratio=0.125, glass_id=-16)[source]¶
Marks cells in voxelcity_grid based on building IDs and window ratio. Never sets glass_id to cells with maximum z index.
This function processes buildings by: 1. Finding all positions matching the specified building IDs 2. Setting the base material for all building voxels 3. Creating window patterns based on window_ratio and modulo calculations 4. Ensuring the top floor (maximum z) never gets windows (glass_id)
The window pattern is determined by the modulo values returned from get_modulo_numbers(), which creates different densities and arrangements of windows based on the window_ratio.
- Parameters:
voxelcity_grid (numpy.ndarray) – 3D numpy array representing the voxel grid
building_id_grid_ori (numpy.ndarray) – 2D numpy array containing building IDs
ids (list/array) – Building IDs to process
mark (int) – Material ID value to set for building cells
window_ratio (float) – Value between 0 and 1.0 determining window density: ~0.125: sparse windows (2,2,2) ~0.25: medium-sparse windows (2,2,1), (2,1,2), or (1,2,2) ~0.5: medium windows (2,1,1), (1,2,1), or (1,1,2) ~0.75: dense windows (2,1,1), (1,2,1), or (1,1,2) >0.875: maximum density (1,1,1)
glass_id (int) – Material ID for glass/window cells (default: -16)
- Returns:
Modified voxelcity_grid with building materials and windows applied
- Return type:
numpy.ndarray
- voxcity.utils.set_building_material_by_gdf(voxelcity_grid_ori, building_id_grid, gdf_buildings, material_id_dict=None)[source]¶
Sets building materials based on a GeoDataFrame containing building information.
This function iterates through a GeoDataFrame of building data and applies materials and window patterns to the corresponding buildings in the voxel grid. It handles missing material information by defaulting to ‘unknown’ material.
- Parameters:
voxelcity_grid_ori (numpy.ndarray) – 3D numpy array of the original voxel grid
building_id_grid (numpy.ndarray) – 2D numpy array containing building IDs
gdf_buildings (GeoDataFrame) – Building information with required columns: ‘building_id’: Unique identifier for each building ‘surface_material’: Material type (brick, wood, concrete, etc.) ‘window_ratio’: Float between 0-1 for window density
material_id_dict (dict, optional) – Dictionary mapping material names to IDs. If None, uses default from get_material_dict()
- Returns:
Modified voxelcity_grid with all building materials and windows applied
- Return type:
numpy.ndarray
- voxcity.utils.VOXEL_CODES¶
- voxcity.utils.LAND_COVER_CLASSES¶
- voxcity.utils.print_land_cover_classes() None[source]¶
Print standard land cover class definitions to console.
- voxcity.utils.print_class_definitions() None[source]¶
Print both voxel codes and land cover class definitions.
- voxcity.utils.get_land_cover_name(index: int) str[source]¶
Get the land cover class name for a given index.
- Parameters:
index – Land cover class index (1-14)
- Returns:
Class name string, or “Unknown” if index is invalid
- voxcity.utils.get_voxel_code_name(code: int) str[source]¶
Get the semantic name for a voxel code.
- Parameters:
code – Voxel code (negative for structures, positive for land cover)
- Returns:
Semantic name string
- voxcity.utils.summarize_voxel_grid(voxel_grid: numpy.ndarray, print_output: bool = True) Dict[int, int][source]¶
Summarize the contents of a voxel grid.
- Parameters:
voxel_grid – 3D numpy array of voxel codes
print_output – Whether to print the summary
- Returns:
Dictionary mapping voxel codes to counts
- voxcity.utils.summarize_land_cover_grid(land_cover_grid: numpy.ndarray, print_output: bool = True) Dict[int, int][source]¶
Summarize the contents of a land cover grid.
- Parameters:
land_cover_grid – 2D numpy array of land cover class indices
print_output – Whether to print the summary
- Returns:
Dictionary mapping class indices to counts