### Setup and example area for demonstrations Source: https://voxcity.readthedocs.io/en/latest/examples/demo_data_sources.html Imports VoxCity generator functions and defines a rectangle around Tokyo for use in examples. ```python # Setup from voxcity.generator import get_voxcity, auto_select_data_sources # Example area for demonstrations rectangle_vertices = [ (139.760, 35.680), # Tokyo area (139.760, 35.690), (139.770, 35.690), (139.770, 35.680) ] ``` -------------------------------- ### Full import and export example Source: https://voxcity.readthedocs.io/en/latest/guides/rhino_obj_import.html Complete workflow: get a VoxCity model, import buildings from an OBJ file with anchor and move parameters, then export the result. Iterate on rotation/move and re-export to verify placement. ```python from voxcity.generator import get_voxcity from voxcity.importer import add_buildings_from_obj from voxcity.exporter.obj import export_obj vc = get_voxcity(rectangle_vertices, meshsize=2.0) vc = add_buildings_from_obj( vc, "design.obj", anchor_lonlat=(139.7536, 35.6841), anchor_elevation=12.0, anchor_model_point=(0.0, 0.0, 0.0), rotation=0.0, move=(0.0, 0.0, 0.0), units="m", ) export_obj(vc, "output", "with_imported_building") ``` -------------------------------- ### Install VoxCity with pip Source: https://voxcity.readthedocs.io/en/latest/examples/demo_quickstart.html Uncomment and run this cell to install VoxCity if it is not already installed. Skip if already installed. ```python # Uncomment and run if you need to install VoxCity # %pip install voxcity ``` -------------------------------- ### Verify the installation Source: https://voxcity.readthedocs.io/en/latest/installation.html Imports voxcity and prints its version to confirm the installation. ```python import voxcity print(voxcity.__version__) ``` -------------------------------- ### Install VoxCity and dependencies in fresh environment Source: https://voxcity.readthedocs.io/en/latest/examples/demo_solar.html Installation commands for a fresh environment, with pip installs commented out. Includes VoxCity and additional dependencies: contextily, osmnx, geopandas, matplotlib, timezonefinder. ```python # Installation (uncomment if running in a fresh environment) # %pip install voxcity # %pip install contextily osmnx geopandas matplotlib timezonefinder ``` -------------------------------- ### Setup VoxCity and get building data Source: https://voxcity.readthedocs.io/en/latest/examples/demo_landmark.html Import VoxCity modules, define a study area rectangle, and create a VoxCity object with specified data sources. Access the building GeoDataFrame from the object's extras. ```python # %pip install voxcity from voxcity.generator import get_voxcity from voxcity.geoprocessor.draw import draw_rectangle_map_cityname from voxcity.simulator.view import get_landmark_visibility_map meshsize = 5 cityname = "Tokyo, Japan" rectangle_vertices = [ (139.760, 35.680), # SW (139.760, 35.690), # NW (139.770, 35.690), # NE (139.770, 35.680) # SE ] city = get_voxcity( rectangle_vertices, meshsize=meshsize, building_source='OpenStreetMap', land_cover_source='OpenStreetMap', canopy_height_source='High Resolution 1m Global Canopy Height Maps', dem_source='DeltaDTM', output_dir='output/landmark_demo' ) # Access building_gdf from the VoxCity object building_gdf = city.extras.get('building_gdf', None) len(building_gdf) if building_gdf is not None else 0 ``` -------------------------------- ### Install VoxCity and visualization dependencies Source: https://voxcity.readthedocs.io/en/latest/examples/demo_3d_visualization.html Install the required packages for VoxCity and its visualization tools. ```bash pip install voxcity plotly pyvista ``` -------------------------------- ### Install VoxCity and system dependencies Source: https://voxcity.readthedocs.io/en/latest/examples/demo_basic.html Installs the voxcity package and required system libraries (xvfb, libgl1-mesa-glx) for headless rendering. Run this in a Colab notebook. ```bash #@title 1.1. Install voxcity !pip install voxcity !apt-get update !apt-get install -y xvfb libgl1-mesa-glx ``` -------------------------------- ### Install VoxCity with pip Source: https://voxcity.readthedocs.io/en/latest/examples/demo_landmark.html Install the VoxCity package using pip. This is a prerequisite for running the tutorial. ```bash pip install voxcity ``` -------------------------------- ### Set up local development environment with virtualenvwrapper Source: https://voxcity.readthedocs.io/en/latest/contributing.html Creates a virtual environment, enters the project directory, and installs the package in development mode using setup.py develop. ```bash $ mkvirtualenv voxcity $ cd voxcity/ $ python setup.py develop ``` -------------------------------- ### Example: setup_transformer Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/geoprocessor/utils/index.html Shows how to set up a coordinate transformer between EPSG:4326 and EPSG:3857, then transform coordinates. The transformer uses always_xy=True for consistent (x,y) order. ```python >>> transformer = setup_transformer("EPSG:4326", "EPSG:3857") >>> x, y = transformer.transform(longitude, latitude) ``` -------------------------------- ### Get raster bounding box with get_raster_bbox Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/geoprocessor/utils/index.html Example of retrieving the bounding box of a raster file using get_raster_bbox. The example prints the bounds of the raster extent. ```python >>> bbox = get_raster_bbox("elevation.tif") >>> print(f"Raster extent: {bbox.bounds}") # (minx, miny, maxx, maxy) ``` -------------------------------- ### Get land cover classes for Urbanwatch source Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/utils/lc/index.html Example usage of get_land_cover_classes to retrieve the RGB-to-class mapping for the 'Urbanwatch' source. The example shows that the tuple (255, 0, 0) maps to 'Building'. ```python >>> classes = get_land_cover_classes("Urbanwatch") >>> print(classes[(255, 0, 0)]) # Returns 'Building' ``` -------------------------------- ### get_building_height_grid function definition and setup Source: https://voxcity.readthedocs.io/en/latest/_modules/voxcity/generator/grids.html This snippet shows the start of the get_building_height_grid function, including imports, rectangle normalization, Earth Engine initialization for the 'Open Building 2.5D Temporal' source, logging, and cache kwargs setup. ```python [docs] def get_building_height_grid(rectangle_vertices, meshsize, source, output_dir, building_gdf=None, **kwargs): from ..downloader.gee import ( initialize_earth_engine, get_roi, save_geotiff_open_buildings_temporal, save_geotiff_dsm_minus_dtm, ) if rectangle_vertices is not None: rectangle_vertices = normalize_rectangle_vertices(rectangle_vertices) ee_required_sources = {"Open Building 2.5D Temporal"} if source in ee_required_sources: initialize_earth_engine() quiet = kwargs.get('quiet', False) if not quiet: _logger.info("Creating Building Height grid\n ") _logger.info(f"Base data source: {source}") # Forward the on-disk download cache controls to any @cached_download # downloader calls below (they are consumed there, not by this function). _cache_kwargs = { "use_download_cache": kwargs.get("use_download_cache", True), "force_refresh": kwargs.get("force_refresh", False), } os.makedirs(output_dir, exist_ok=True) ``` -------------------------------- ### prepare_cumulative_simulation_input example Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/simulator_gpu/solar/epw/index.html Shows how to prepare solar simulation input data from an EPW file, returning azimuth, elevation, DNI, DHI, and location metadata, then printing location and daytime hours. ```python >>> az, el, dni, dhi, loc = prepare_cumulative_simulation_input("weather.epw") >>> print(f"Location: {loc.city}, {loc.country}") >>> print(f"Daytime hours: {len(az)}") ``` -------------------------------- ### convert_colormap_indices example Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/exporter/index.html Doctest example showing how to convert a color map with arbitrary integer keys to sequential indices starting from 0. The output is logged via _logger.info and shows the new map with keys 0, 1, 2. ```python >>> original = {5: [255, 0, 0], 10: [0, 255, 0], 15: [0, 0, 255]} >>> new_map = convert_colormap_indices(original) >>> _logger.info(new_map) {0: [255, 0, 0], 1: [0, 255, 0], 2: [0, 0, 255]} ``` -------------------------------- ### Static rendering with simulation overlays Source: https://voxcity.readthedocs.io/en/latest/_modules/voxcity/visualizer/renderer.html Demonstrates static rendering with a building simulation mesh (svf_mesh) and an output directory. Returns a list of (view_name, filepath) tuples. ```python >>> visualize_voxcity(city, mode="static", ... building_sim_mesh=svf_mesh, ... output_directory="renders") ``` -------------------------------- ### Setup: Get rectangle vertices for an area Source: https://voxcity.readthedocs.io/en/latest/examples/demo_data_sources.html Initializes a rectangle around a center point (Marunouchi, Tokyo) using get_rectangle_vertices. This rectangle is used as input for data download functions. ```python # Setup from voxcity.geo.utils import get_rectangle_vertices # Example area: Marunouchi, Tokyo center = (139.7671, 35.6812) # (lon, lat) rectangle_vertices = get_rectangle_vertices(center, 200, 200) ``` -------------------------------- ### Prepare cumulative simulation input and bin sun positions Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/simulator_gpu/solar/sky/index.html Shows how to load weather data and bin sun positions to sky patches using prepare_cumulative_simulation_input and bin_sun_positions_to_patches. The example prints the number of active patches. ```python >>> from palm_solar.epw import prepare_cumulative_simulation_input >>> az, el, dni, dhi, loc = prepare_cumulative_simulation_input("weather.epw") >>> binned = bin_sun_positions_to_patches(az, el, dni, dhi) >>> print(f"Active patches: {(binned.hours_per_patch > 0).sum()}") ``` -------------------------------- ### Interactive 3D visualization with Plotly Source: https://voxcity.readthedocs.io/en/latest/examples/demo_quickstart.html Creates an interactive 3D viewer using Plotly. Requires plotly (pip install plotly). Use mode='interactive', show=False, and return_fig=True to get the figure, then call fig.show(). ```python # Interactive visualization using Plotly # (Requires plotly: pip install plotly) fig = visualize_voxcity(city, mode="interactive", show=False, return_fig=True) fig.show() ``` -------------------------------- ### UI setup for tree editor Source: https://voxcity.readthedocs.io/en/latest/_modules/voxcity/geoprocessor/draw/edit_tree.html Creates HTML style, input widgets for tree dimensions, buttons for adding/removing trees, and a status bar. ```python # --- UI --- style_html = HTML(generate_editor_css( "gm-tree-root", drawing_mode_class="tree-drawing-mode", delete_mode_class="tree-delete-mode", )) top_height_input = FloatText( value=10.0, description="Top (m):", layout=Layout(width="160px", height="24px"), style={"description_width": "62px"}, ) bottom_height_input = FloatText( value=4.0, description="Trunk (m):", layout=Layout(width="160px", height="24px"), style={"description_width": "62px"}, ) crown_diameter_input = FloatText( value=6.0, description="Dia. (m):", layout=Layout(width="160px", height="24px"), style={"description_width": "62px"}, ) fixed_prop_checkbox = Checkbox( value=True, description="Fixed proportion", indent=False, layout=Layout(width="auto", height="20px"), ) add_click_button = Button(description="Click", button_style="success", layout=Layout(flex="1", height="26px")) add_area_button = ToggleButton( value=False, description="Area", button_style="", layout=Layout(flex="1", height="26px"), tooltip="Draw polygon to fill with trees", ) remove_click_button = Button(description="Click", button_style="", layout=Layout(flex="1", height="26px")) remove_area_button = ToggleButton( value=False, description="Area", button_style="", layout=Layout(flex="1", height="26px"), tooltip="Draw polygon to remove trees & canopy inside", ) status_bar = HTML( value="
Ready
" ) hover_info = HTML("") _set_status = make_status_setter(status_bar, use_gm_class=False) add_row = HBox([add_click_button, add_area_button], layout=Layout(margin="0", gap="4px")) remove_row = HBox([remove_click_button, remove_area_button], layout=Layout(margin="0", gap="4px")) param_col = VBox( [top_height_input, bottom_height_input, crown_diameter_input, fixed_prop_checkbox], layout=Layout(margin="0", gap="0px"), ) crown_diameter_input.layout.display = "" ``` -------------------------------- ### Get patch info for Reinhart method Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/simulator_gpu/solar/sky/index.html Shows how to retrieve information about a sky discretization method using get_patch_info. The example uses the 'reinhart' method with mf=4 and prints the method name and number of patches. ```python >>> info = get_patch_info("reinhart", mf=4) >>> print(f"{info['method']}: {info['n_patches']} patches") ``` -------------------------------- ### GPURenderer initialization and custom lighting Source: https://voxcity.readthedocs.io/en/latest/_modules/voxcity/visualizer/renderer_gpu.html Initializes the GPURenderer with specified parameters and applies custom lighting if any lighting parameters are provided. ```python renderer = GPURenderer( width=width, height=height, samples_per_pixel=samples_per_pixel, max_depth=max_depth, arch=arch ) # Apply custom lighting if specified if light_direction is not None or direct is not None or ambient is not None: current_direction = light_direction if light_direction is not None else light_direction_from_angles(220, 45) current_color = direct if direct is not None else (0.9, 0.9, 0.85) current_ambient = ambient if ambient is not None else (0.15, 0.15, 0.18) renderer.taichi_renderer.set_lighting( direction=current_direction, color=current_color, ambient=current_ambient, light_noise=0.3 ) ``` -------------------------------- ### Initialize WGS84 Geod and perform inverse calculation Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/geoprocessor/utils/index.html Example usage of initialize_geod to get a Geod object and then use its inv method to calculate forward azimuth, back azimuth, and distance between two points. ```python >>> geod = initialize_geod() >>> fwd_az, back_az, dist = geod.inv(lon1, lat1, lon2, lat2) ``` -------------------------------- ### Region selection and output directory setup Source: https://voxcity.readthedocs.io/en/latest/_modules/voxcity/utils/weather/onebuilding.html Creates the output directory and builds a dictionary of regions to scan based on the 'region' parameter. Handles auto-detection, 'all', a single region, or a list of regions, raising ValueError for invalid selections. ```python try: Path(output_dir).mkdir(parents=True, exist_ok=True) regions_to_scan = {} def _add_selection(selection_name: str, mapping: Dict[str, str], out: Dict[str, str]): if selection_name in REGION_DATASET_GROUPS: for key in REGION_DATASET_GROUPS[selection_name]: if key in KML_SOURCES: out[key] = KML_SOURCES[key] elif selection_name in KML_SOURCES: out[selection_name] = KML_SOURCES[selection_name] else: valid = sorted(list(REGION_DATASET_GROUPS.keys()) + list(KML_SOURCES.keys())) raise ValueError(f"Invalid region/dataset: '{selection_name}'. Valid options include: {', '.join(valid)}") if region is None: detected_regions = detect_regions(longitude, latitude) if detected_regions: print(f"Auto-detected regions: {', '.join(detected_regions)}") for r in detected_regions: _add_selection(r, KML_SOURCES, regions_to_scan) else: print("Could not determine region from coordinates. Scanning all regions.") regions_to_scan = dict(KML_SOURCES) elif isinstance(region, str): if region.lower() == "all": regions_to_scan = dict(KML_SOURCES) else: _add_selection(region, KML_SOURCES, regions_to_scan) else: for r in region: _add_selection(r, KML_SOURCES, regions_to_scan) ``` -------------------------------- ### Quick start: Generate a voxel model with get_voxcity Source: https://voxcity.readthedocs.io/en/latest/ Use the get_voxcity function to generate a voxel model for a specified area. The example uses a small area in Seattle with a mesh size of 5 meters. Sources are auto-selected based on location. ```python from voxcity.generator import get_voxcity # A small area in Seattle; sources auto-selected by location voxcity = get_voxcity(rectangle_vertices, meshsize=5) ``` -------------------------------- ### convert_colormap_indices function Source: https://voxcity.readthedocs.io/en/latest/_modules/voxcity/exporter/obj.html Converts a color map with arbitrary integer keys to sequential indices starting from 0, preserving RGB values. Logs the new map for debugging. Example usage shows input {5: [255,0,0], 10: [0,255,0], 15: [0,0,255]} producing {0: [255,0,0], 1: [0,255,0], 2: [0,0,255]}. ```python [docs] def convert_colormap_indices(original_map): """ Convert a color map with arbitrary indices to sequential indices starting from 0. This function takes a color map with arbitrary integer keys and creates a new map with sequential indices starting from 0, maintaining the original color values. This is useful for ensuring consistent material indexing in OBJ files. Args: original_map (dict): Dictionary with integer keys and RGB color value lists. Each value should be a list of 3 integers (0-255) representing RGB colors. Returns: dict: New color map with sequential indices starting from 0. The values maintain their original RGB color assignments. Example: >>> original = {5: [255, 0, 0], 10: [0, 255, 0], 15: [0, 0, 255]} >>> new_map = convert_colormap_indices(original) >>> _logger.info(new_map) {0: [255, 0, 0], 1: [0, 255, 0], 2: [0, 0, 255]} """ # Sort the original keys to maintain consistent ordering keys = sorted(original_map.keys()) new_map = {} # Create new map with sequential indices for new_idx, old_idx in enumerate(keys): new_map[new_idx] = original_map[old_idx] # Print the new colormap for debugging/reference _logger.info("new_colormap = {") for key, value in new_map.items(): original_key = keys[key] original_line = str(original_map[original_key]) comment = "" if "#" in original_line: comment = "#" + original_line.split("#")[1].strip() _logger.info(f" {key}: {value}, {comment}") _logger.info("}") return new_map ``` -------------------------------- ### Import and use voxcity.simulator_gpu Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/simulator_gpu/index.html Shows how to import the solar and visibility submodules and call their main functions. The example uses get_global_solar_irradiance_using_epw for solar radiation and get_view_index with mode='green' for view analysis. ```python from voxcity.simulator_gpu import solar, visibility # Solar radiation irradiance = solar.get_global_solar_irradiance_using_epw(voxcity, …) # View analysis gvi = visibility.get_view_index(voxcity, mode='green') ``` -------------------------------- ### Helper function _require_trimesh Source: https://voxcity.readthedocs.io/en/latest/_modules/voxcity/exporter/obj.html Raises ConfigurationError if trimesh is not installed, instructing to install via 'pip install trimesh'. ```python def _require_trimesh(): if not _HAS_TRIMESH: raise ConfigurationError( "This operation requires the optional dependency 'trimesh'. " "Install it via 'pip install trimesh'." ) ``` -------------------------------- ### Building solar irradiance overlay example Source: https://voxcity.readthedocs.io/en/latest/_modules/voxcity/visualizer/renderer_gpu.html Renders with a building simulation mesh for solar irradiance, using the 'global' value name and 'magma' colormap. ```python >>> building_mesh = get_building_solar_irradiance(city, ...) >>> img = visualize_voxcity_gpu(city, building_sim_mesh=building_mesh, ... building_value_name='global', building_colormap='magma') ``` -------------------------------- ### Canopy Height Parameters Example Source: https://voxcity.readthedocs.io/en/latest/examples/demo_data_sources.html Defines canopy height configuration parameters including minimum canopy height, trunk height ratio, and static tree height. Prints the configuration options. ```python # Canopy height parameters canopy_params = { "min_canopy_height": 2.0, # Ignore trees shorter than this (meters) "trunk_height_ratio": 0.59, # Trunk height / total height "static_tree_height": 10.0 # Default height for 'Static' source } print("Canopy configuration options:") for param, value in canopy_params.items(): print(f" {param}: {value}") ``` -------------------------------- ### Install with conda + pip (recommended) Source: https://voxcity.readthedocs.io/en/latest/installation.html Creates a conda environment named 'voxcity' with Python 3.12, installs GDAL and timezonefinder from conda-forge, then installs voxcity via pip. ```bash conda create --name voxcity python=3.12 conda activate voxcity conda install -c conda-forge gdal timezonefinder pip install voxcity ``` -------------------------------- ### Static rendering with simulation overlays: visualize_voxcity with output_directory Source: https://voxcity.readthedocs.io/en/latest/autoapi/voxcity/visualizer/renderer/index.html Usage example for static rendering mode with building simulation mesh and output directory. ```python >>> visualize_voxcity(city, mode="static", … ... building_sim_mesh=svf_mesh, … ... output_directory="renders") ```