voxcity.utils ============= .. py:module:: voxcity.utils Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/voxcity/utils/classes/index /autoapi/voxcity/utils/lc/index /autoapi/voxcity/utils/logging/index /autoapi/voxcity/utils/material/index /autoapi/voxcity/utils/orientation/index /autoapi/voxcity/utils/projector/index /autoapi/voxcity/utils/shape/index /autoapi/voxcity/utils/weather/index /autoapi/voxcity/utils/zoning/index Attributes ---------- .. autoapisummary:: voxcity.utils.VOXEL_CODES voxcity.utils.LAND_COVER_CLASSES Classes ------- .. toctree:: :hidden: /autoapi/voxcity/utils/GridGeom /autoapi/voxcity/utils/GridProjector .. autoapisummary:: voxcity.utils.GridGeom voxcity.utils.GridProjector Functions --------- .. autoapisummary:: voxcity.utils.get_land_cover_classes voxcity.utils.get_source_class_descriptions voxcity.utils.convert_land_cover voxcity.utils.convert_land_cover_array voxcity.utils.get_class_priority voxcity.utils.create_land_cover_polygons voxcity.utils.get_nearest_class voxcity.utils.get_dominant_class voxcity.utils.safe_rename voxcity.utils.safe_extract voxcity.utils.process_epw voxcity.utils.read_epw_for_solar_simulation voxcity.utils.get_nearest_epw_from_climate_onebuilding voxcity.utils.get_material_dict voxcity.utils.get_modulo_numbers voxcity.utils.set_building_material_by_id voxcity.utils.set_building_material_by_gdf voxcity.utils.print_voxel_codes voxcity.utils.print_land_cover_classes voxcity.utils.print_class_definitions voxcity.utils.get_land_cover_name voxcity.utils.get_voxel_code_name voxcity.utils.summarize_voxel_grid voxcity.utils.summarize_land_cover_grid Package Contents ---------------- .. py:function:: get_land_cover_classes(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. :param source: Name of the land cover data source. Supported sources: "Urbanwatch", "OpenEarthMapJapan", "ESRI 10m Annual Land Cover", "ESA WorldCover", "Dynamic World V1", "Standard", "OpenStreetMap" :type source: str :returns: Dictionary mapping RGB tuples to land cover class names :rtype: dict .. rubric:: Example >>> classes = get_land_cover_classes("Urbanwatch") >>> print(classes[(255, 0, 0)]) # Returns 'Building' .. py:function:: get_source_class_descriptions(source) Get a formatted string describing land cover classes for a specific source. :param source: Name of the land cover data source. :type source: str :returns: Formatted string describing the source's land cover classes. :rtype: str .. py:function:: convert_land_cover(input_array, land_cover_source='Urbanwatch') 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. .. py:function:: convert_land_cover_array(input_array, land_cover_classes) 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. :param input_array: Array containing land cover class names as strings :type input_array: numpy.ndarray :param land_cover_classes: Dictionary mapping RGB tuples to class names :type land_cover_classes: dict :returns: Array with 0-based integer indices corresponding to land cover classes :rtype: 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. .. py:function:: get_class_priority(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. :param source: Name of the land cover data source :type source: str :returns: Dictionary mapping class names to priority values (higher = more priority) :rtype: 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 .. py:function:: create_land_cover_polygons(land_cover_geojson) 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. :param land_cover_geojson: List of GeoJSON feature dictionaries containing land cover polygons with geometry and properties :type land_cover_geojson: list :returns: A tuple containing: - land_cover_polygons (list): List of tuples (polygon, class_name) - idx (rtree.index.Index): Spatial index for efficient polygon lookup :rtype: 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 .. py:function:: get_nearest_class(pixel, land_cover_classes) 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. :param pixel: RGB color values as (R, G, B) tuple :type pixel: tuple :param land_cover_classes: Dictionary mapping RGB tuples to class names :type land_cover_classes: dict :returns: Name of the nearest land cover class :rtype: str .. rubric:: Example >>> classes = {(255, 0, 0): 'Building', (0, 255, 0): 'Tree'} >>> nearest = get_nearest_class((250, 5, 5), classes) >>> print(nearest) # Returns 'Building' .. py:function:: get_dominant_class(cell_data, land_cover_classes) 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. :param cell_data: 3D array of RGB pixel data for the cell :type cell_data: numpy.ndarray :param land_cover_classes: Dictionary mapping RGB tuples to class names :type land_cover_classes: dict :returns: Name of the dominant land cover class in the cell :rtype: str .. note:: If the cell contains no data, returns 'No Data' .. py:function:: safe_rename(src: pathlib.Path, dst: pathlib.Path) -> pathlib.Path Safely rename a file, handling existing files by adding a number suffix. .. py:function:: safe_extract(zip_ref: zipfile.ZipFile, filename: str, extract_dir: pathlib.Path) -> pathlib.Path Safely extract a file from zip, handling existing files. .. py:function:: process_epw(epw_path: Union[str, pathlib.Path]) -> Tuple[pandas.DataFrame, dict] Process an EPW file into a pandas DataFrame and header metadata. .. py:function:: read_epw_for_solar_simulation(epw_file_path) Read EPW file specifically for solar simulation purposes. Returns (df[DNI,DHI], lon, lat, tz, elevation_m). .. py:function:: get_nearest_epw_from_climate_onebuilding(longitude: float, latitude: float, output_dir: str = './', max_distance: Optional[float] = None, extract_zip: bool = True, load_data: bool = True, region: Optional[Union[str, List[str]]] = None, allow_insecure_ssl: bool = False, allow_http_fallback: bool = False, ssl_verify: Union[bool, str] = True) -> Tuple[Optional[str], Optional[pandas.DataFrame], Optional[Dict]] Download and process EPW weather file from Climate.OneBuilding.Org based on coordinates. .. py:function:: get_material_dict() 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 :rtype: dict .. py:function:: get_modulo_numbers(window_ratio) 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. :param window_ratio: Value between 0 and 1.0 representing window density :type window_ratio: float :returns: (x_mod, y_mod, z_mod) - modulo numbers for each dimension Higher values = sparser windows, lower values = denser windows :rtype: tuple .. py:function:: set_building_material_by_id(voxelcity_grid, building_id_grid_ori, ids, mark, window_ratio=0.125, glass_id=-16) 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. :param voxelcity_grid: 3D numpy array representing the voxel grid :type voxelcity_grid: numpy.ndarray :param building_id_grid_ori: 2D numpy array containing building IDs :type building_id_grid_ori: numpy.ndarray :param ids: Building IDs to process :type ids: list/array :param mark: Material ID value to set for building cells :type mark: int :param window_ratio: 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) :type window_ratio: float :param glass_id: Material ID for glass/window cells (default: -16) :type glass_id: int :returns: Modified voxelcity_grid with building materials and windows applied :rtype: numpy.ndarray .. py:function:: set_building_material_by_gdf(voxelcity_grid_ori, building_id_grid, gdf_buildings, material_id_dict=None) 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. :param voxelcity_grid_ori: 3D numpy array of the original voxel grid :type voxelcity_grid_ori: numpy.ndarray :param building_id_grid: 2D numpy array containing building IDs :type building_id_grid: numpy.ndarray :param gdf_buildings: 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 :type gdf_buildings: GeoDataFrame :param material_id_dict: Dictionary mapping material names to IDs. If None, uses default from get_material_dict() :type material_id_dict: dict, optional :returns: Modified voxelcity_grid with all building materials and windows applied :rtype: numpy.ndarray .. py:data:: VOXEL_CODES .. py:data:: LAND_COVER_CLASSES .. py:function:: print_voxel_codes() -> None Print voxel semantic codes to console. .. py:function:: print_land_cover_classes() -> None Print standard land cover class definitions to console. .. py:function:: print_class_definitions() -> None Print both voxel codes and land cover class definitions. .. py:function:: get_land_cover_name(index: int) -> str Get the land cover class name for a given index. :param index: Land cover class index (1-14) :returns: Class name string, or "Unknown" if index is invalid .. py:function:: get_voxel_code_name(code: int) -> str Get the semantic name for a voxel code. :param code: Voxel code (negative for structures, positive for land cover) :returns: Semantic name string .. py:function:: summarize_voxel_grid(voxel_grid: numpy.ndarray, print_output: bool = True) -> Dict[int, int] Summarize the contents of a voxel grid. :param voxel_grid: 3D numpy array of voxel codes :param print_output: Whether to print the summary :returns: Dictionary mapping voxel codes to counts .. py:function:: summarize_land_cover_grid(land_cover_grid: numpy.ndarray, print_output: bool = True) -> Dict[int, int] Summarize the contents of a land cover grid. :param land_cover_grid: 2D numpy array of land cover class indices :param print_output: Whether to print the summary :returns: Dictionary mapping class indices to counts