voxcity 1.0.2__py3-none-any.whl → 1.0.15__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. voxcity/downloader/ocean.py +559 -0
  2. voxcity/generator/api.py +6 -0
  3. voxcity/generator/grids.py +45 -32
  4. voxcity/generator/pipeline.py +327 -27
  5. voxcity/geoprocessor/draw.py +14 -8
  6. voxcity/geoprocessor/raster/__init__.py +2 -0
  7. voxcity/geoprocessor/raster/core.py +31 -0
  8. voxcity/geoprocessor/raster/landcover.py +173 -49
  9. voxcity/geoprocessor/raster/raster.py +1 -1
  10. voxcity/models.py +2 -0
  11. voxcity/simulator/solar/__init__.py +13 -0
  12. voxcity/simulator_gpu/__init__.py +90 -0
  13. voxcity/simulator_gpu/core.py +322 -0
  14. voxcity/simulator_gpu/domain.py +36 -0
  15. voxcity/simulator_gpu/init_taichi.py +154 -0
  16. voxcity/simulator_gpu/raytracing.py +776 -0
  17. voxcity/simulator_gpu/solar/__init__.py +222 -0
  18. voxcity/simulator_gpu/solar/core.py +66 -0
  19. voxcity/simulator_gpu/solar/csf.py +1249 -0
  20. voxcity/simulator_gpu/solar/domain.py +618 -0
  21. voxcity/simulator_gpu/solar/epw.py +421 -0
  22. voxcity/simulator_gpu/solar/integration.py +4322 -0
  23. voxcity/simulator_gpu/solar/mask.py +459 -0
  24. voxcity/simulator_gpu/solar/radiation.py +3019 -0
  25. voxcity/simulator_gpu/solar/raytracing.py +182 -0
  26. voxcity/simulator_gpu/solar/reflection.py +533 -0
  27. voxcity/simulator_gpu/solar/sky.py +907 -0
  28. voxcity/simulator_gpu/solar/solar.py +337 -0
  29. voxcity/simulator_gpu/solar/svf.py +446 -0
  30. voxcity/simulator_gpu/solar/volumetric.py +2099 -0
  31. voxcity/simulator_gpu/visibility/__init__.py +109 -0
  32. voxcity/simulator_gpu/visibility/geometry.py +278 -0
  33. voxcity/simulator_gpu/visibility/integration.py +808 -0
  34. voxcity/simulator_gpu/visibility/landmark.py +753 -0
  35. voxcity/simulator_gpu/visibility/view.py +944 -0
  36. voxcity/visualizer/renderer.py +2 -1
  37. {voxcity-1.0.2.dist-info → voxcity-1.0.15.dist-info}/METADATA +16 -53
  38. {voxcity-1.0.2.dist-info → voxcity-1.0.15.dist-info}/RECORD +41 -16
  39. {voxcity-1.0.2.dist-info → voxcity-1.0.15.dist-info}/WHEEL +0 -0
  40. {voxcity-1.0.2.dist-info → voxcity-1.0.15.dist-info}/licenses/AUTHORS.rst +0 -0
  41. {voxcity-1.0.2.dist-info → voxcity-1.0.15.dist-info}/licenses/LICENSE +0 -0
@@ -58,7 +58,7 @@ def create_land_cover_grid_from_geotiff_polygon(
58
58
  xs, ys = new_affine * (cols, rows)
59
59
  xs_flat, ys_flat = xs.flatten(), ys.flatten()
60
60
 
61
- row, col = src.index(xs_flat, ys_flat)
61
+ row, col = rasterio.transform.rowcol(src.transform, xs_flat, ys_flat)
62
62
  row, col = np.array(row), np.array(col)
63
63
 
64
64
  valid = (row >= 0) & (row < src.height) & (col >= 0) & (col < src.width)
@@ -79,14 +79,35 @@ def create_land_cover_grid_from_gdf_polygon(
79
79
  meshsize: float,
80
80
  source: str,
81
81
  rectangle_vertices: List[Tuple[float, float]],
82
- default_class: str = 'Developed space'
82
+ default_class: str = 'Developed space',
83
+ detect_ocean: bool = True,
84
+ land_polygon = "NOT_PROVIDED"
83
85
  ) -> np.ndarray:
84
- """Create a grid of land cover classes from GeoDataFrame polygon data."""
86
+ """
87
+ Create a grid of land cover classes from GeoDataFrame polygon data.
88
+
89
+ Uses vectorized rasterization for ~100x speedup over cell-by-cell intersection.
90
+
91
+ Args:
92
+ gdf: GeoDataFrame with land cover polygons and 'class' column
93
+ meshsize: Grid cell size in meters
94
+ source: Land cover data source name (e.g., 'OpenStreetMap')
95
+ rectangle_vertices: List of (lon, lat) tuples defining the area
96
+ default_class: Default class for cells not covered by any polygon
97
+ detect_ocean: If True, use OSM land polygons to detect ocean areas.
98
+ Areas outside land polygons will be classified as 'Water'
99
+ instead of the default class.
100
+ land_polygon: Optional pre-computed land polygon from OSM coastlines.
101
+ If provided (including None), this is used directly.
102
+ If "NOT_PROVIDED", coastlines will be queried when detect_ocean=True.
103
+
104
+ Returns:
105
+ 2D numpy array of land cover class names
106
+ """
85
107
  import numpy as np
86
108
  import geopandas as gpd
87
- from shapely.geometry import box
88
- from shapely.errors import GEOSException
89
- from rtree import index
109
+ from rasterio import features
110
+ from shapely.geometry import box, Polygon as ShapelyPolygon
90
111
 
91
112
  class_priority = get_class_priority(source)
92
113
 
@@ -95,8 +116,9 @@ def create_land_cover_grid_from_gdf_polygon(
95
116
  calculate_distance,
96
117
  normalize_to_one_meter,
97
118
  )
98
- from .core import calculate_grid_size, create_cell_polygon
119
+ from .core import calculate_grid_size
99
120
 
121
+ # Calculate grid dimensions
100
122
  geod = initialize_geod()
101
123
  vertex_0, vertex_1, vertex_3 = rectangle_vertices[0], rectangle_vertices[1], rectangle_vertices[3]
102
124
  dist_side_1 = calculate_distance(geod, vertex_0[0], vertex_0[1], vertex_1[0], vertex_1[1])
@@ -107,51 +129,153 @@ def create_land_cover_grid_from_gdf_polygon(
107
129
  u_vec = normalize_to_one_meter(side_1, dist_side_1)
108
130
  v_vec = normalize_to_one_meter(side_2, dist_side_2)
109
131
 
110
- origin = np.array(rectangle_vertices[0])
111
132
  grid_size, adjusted_meshsize = calculate_grid_size(side_1, side_2, u_vec, v_vec, meshsize)
133
+ rows, cols = grid_size
134
+
135
+ # Get bounding box for the raster
136
+ min_lon = min(coord[0] for coord in rectangle_vertices)
137
+ max_lon = max(coord[0] for coord in rectangle_vertices)
138
+ min_lat = min(coord[1] for coord in rectangle_vertices)
139
+ max_lat = max(coord[1] for coord in rectangle_vertices)
140
+
141
+ # Create affine transform (top-left origin, pixel size)
142
+ pixel_width = (max_lon - min_lon) / cols
143
+ pixel_height = (max_lat - min_lat) / rows
144
+ transform = Affine(pixel_width, 0, min_lon, 0, -pixel_height, max_lat)
145
+
146
+ # Build class name to priority mapping, then sort classes by priority (highest priority = lowest number = rasterize last)
147
+ unique_classes = gdf['class'].unique().tolist()
148
+ if default_class not in unique_classes:
149
+ unique_classes.append(default_class)
150
+
151
+ # Map class names to integer codes
152
+ class_to_code = {cls: i for i, cls in enumerate(unique_classes)}
153
+ code_to_class = {i: cls for cls, i in class_to_code.items()}
154
+ default_code = class_to_code[default_class]
155
+
156
+ # Initialize grid with default class code
157
+ grid_int = np.full((rows, cols), default_code, dtype=np.int32)
158
+
159
+ # Sort classes by priority (highest priority last so they overwrite lower priority)
160
+ # Lower priority number = higher priority = should be drawn last
161
+ sorted_classes = sorted(unique_classes, key=lambda c: class_priority.get(c, 999), reverse=True)
162
+
163
+ # Rasterize each class in priority order (lowest priority first, highest priority last overwrites)
164
+ for lc_class in sorted_classes:
165
+ if lc_class == default_class:
166
+ continue # Already filled as default
167
+
168
+ class_gdf = gdf[gdf['class'] == lc_class]
169
+ if class_gdf.empty:
170
+ continue
171
+
172
+ # Get all geometries for this class
173
+ geometries = class_gdf.geometry.tolist()
174
+
175
+ # Filter out invalid geometries and fix them
176
+ valid_geometries = []
177
+ for geom in geometries:
178
+ if geom is None or geom.is_empty:
179
+ continue
180
+ if not geom.is_valid:
181
+ geom = geom.buffer(0)
182
+ if geom.is_valid and not geom.is_empty:
183
+ valid_geometries.append(geom)
184
+
185
+ if not valid_geometries:
186
+ continue
187
+
188
+ # Create shapes for rasterization: (geometry, value) pairs
189
+ class_code = class_to_code[lc_class]
190
+ shapes = [(geom, class_code) for geom in valid_geometries]
191
+
192
+ # Rasterize this class onto the grid (overwrites previous values)
193
+ try:
194
+ features.rasterize(
195
+ shapes=shapes,
196
+ out=grid_int,
197
+ transform=transform,
198
+ all_touched=False, # Only cells whose center is inside
199
+ )
200
+ except Exception:
201
+ # Fallback: try each geometry individually
202
+ for geom, val in shapes:
203
+ try:
204
+ features.rasterize(
205
+ shapes=[(geom, val)],
206
+ out=grid_int,
207
+ transform=transform,
208
+ all_touched=False,
209
+ )
210
+ except Exception:
211
+ continue
212
+
213
+ # Convert integer codes back to class names
214
+ grid = np.empty((rows, cols), dtype=object)
215
+ for code, cls_name in code_to_class.items():
216
+ grid[grid_int == code] = cls_name
112
217
 
113
- grid = np.full(grid_size, default_class, dtype=object)
114
-
115
- extent = [min(coord[1] for coord in rectangle_vertices), max(coord[1] for coord in rectangle_vertices),
116
- min(coord[0] for coord in rectangle_vertices), max(coord[0] for coord in rectangle_vertices)]
117
- plotting_box = box(extent[2], extent[0], extent[3], extent[1])
118
-
119
- land_cover_polygons = []
120
- idx = index.Index()
121
- for i, row in gdf.iterrows():
122
- polygon = row.geometry
123
- land_cover_class = row['class']
124
- land_cover_polygons.append((polygon, land_cover_class))
125
- idx.insert(i, polygon.bounds)
126
-
127
- for i in range(grid_size[0]):
128
- for j in range(grid_size[1]):
129
- land_cover_class = default_class
130
- cell = create_cell_polygon(origin, i, j, adjusted_meshsize, u_vec, v_vec)
131
- for k in idx.intersection(cell.bounds):
132
- polygon, land_cover_class_temp = land_cover_polygons[k]
218
+ # Apply ocean detection BEFORE flipping if requested
219
+ # This uses land polygons from OSM coastlines to classify ocean areas
220
+ if detect_ocean:
221
+ try:
222
+ from ...downloader.ocean import get_land_polygon_for_area, get_ocean_class_for_source
223
+
224
+ ocean_class = get_ocean_class_for_source(source)
225
+
226
+ # Use provided land_polygon or query from coastlines if not provided
227
+ if land_polygon == "NOT_PROVIDED":
228
+ land_polygon = get_land_polygon_for_area(rectangle_vertices, use_cache=False)
229
+
230
+ if land_polygon is not None:
231
+ # Rasterize land polygon - cells inside are land, outside are ocean
232
+ land_mask = np.zeros((rows, cols), dtype=np.uint8)
233
+
133
234
  try:
134
- if cell.intersects(polygon):
135
- intersection = cell.intersection(polygon)
136
- if intersection.area > cell.area / 2:
137
- rank = class_priority[land_cover_class]
138
- rank_temp = class_priority[land_cover_class_temp]
139
- if rank_temp < rank:
140
- land_cover_class = land_cover_class_temp
141
- grid[i, j] = land_cover_class
142
- except GEOSException as e:
143
- try:
144
- fixed_polygon = polygon.buffer(0)
145
- if cell.intersects(fixed_polygon):
146
- intersection = cell.intersection(fixed_polygon)
147
- if intersection.area > cell.area / 2:
148
- rank = class_priority[land_cover_class]
149
- rank_temp = class_priority[land_cover_class_temp]
150
- if rank_temp < rank:
151
- land_cover_class = land_cover_class_temp
152
- grid[i, j] = land_cover_class
153
- except Exception:
154
- continue
235
+ if land_polygon.geom_type == 'Polygon':
236
+ land_geometries = [(land_polygon, 1)]
237
+ else: # MultiPolygon
238
+ land_geometries = [(geom, 1) for geom in land_polygon.geoms]
239
+
240
+ features.rasterize(
241
+ shapes=land_geometries,
242
+ out=land_mask,
243
+ transform=transform,
244
+ all_touched=False
245
+ )
246
+
247
+ # Apply ocean class to cells that are:
248
+ # 1. Outside land polygon (land_mask == 0)
249
+ # 2. Currently classified as the default class
250
+ ocean_cells = (land_mask == 0) & (grid == default_class)
251
+ ocean_count = np.sum(ocean_cells)
252
+
253
+ if ocean_count > 0:
254
+ grid[ocean_cells] = ocean_class
255
+ pct = 100 * ocean_count / grid.size
256
+ print(f" Ocean detection: {ocean_count:,} cells ({pct:.1f}%) classified as '{ocean_class}'")
257
+
258
+ except Exception as e:
259
+ print(f" Warning: Ocean rasterization failed: {e}")
260
+ else:
261
+ # No coastlines - check if area is all ocean or all land
262
+ from ...downloader.ocean import check_if_area_is_ocean_via_land_features
263
+ is_ocean = check_if_area_is_ocean_via_land_features(rectangle_vertices)
264
+ if is_ocean:
265
+ # Convert all default class cells to water
266
+ ocean_cells = (grid == default_class)
267
+ ocean_count = np.sum(ocean_cells)
268
+ if ocean_count > 0:
269
+ grid[ocean_cells] = ocean_class
270
+ pct = 100 * ocean_count / grid.size
271
+ print(f" Ocean detection: {ocean_count:,} cells ({pct:.1f}%) classified as '{ocean_class}' (open ocean)")
272
+
273
+ except Exception as e:
274
+ print(f" Warning: Ocean detection failed: {e}")
275
+
276
+ # Flip to match expected orientation (north-up)
277
+ grid = np.flipud(grid)
278
+
155
279
  return grid
156
280
 
157
281
 
@@ -38,7 +38,7 @@ def create_height_grid_from_geotiff_polygon(
38
38
  xs, ys = new_affine * (cols, rows)
39
39
  xs_flat, ys_flat = xs.flatten(), ys.flatten()
40
40
 
41
- row, col = src.index(xs_flat, ys_flat)
41
+ row, col = rasterio.transform.rowcol(src.transform, xs_flat, ys_flat)
42
42
  row, col = np.array(row), np.array(col)
43
43
 
44
44
  valid = (row >= 0) & (row < src.height) & (col >= 0) & (col < src.width)
voxcity/models.py CHANGED
@@ -70,6 +70,8 @@ class PipelineConfig:
70
70
  remove_perimeter_object: Optional[float] = None
71
71
  mapvis: bool = False
72
72
  gridvis: bool = True
73
+ # Parallel download mode: if True, downloads run concurrently using ThreadPoolExecutor
74
+ parallel_download: bool = False
73
75
  # Structured options for strategies and I/O/visualization
74
76
  land_cover_options: Dict[str, Any] = field(default_factory=dict)
75
77
  building_options: Dict[str, Any] = field(default_factory=dict)
@@ -64,3 +64,16 @@ from .integration import ( # noqa: F401
64
64
  save_irradiance_mesh,
65
65
  load_irradiance_mesh,
66
66
  )
67
+
68
+ # Computation mask utilities (re-export from simulator_gpu for convenience)
69
+ try:
70
+ from voxcity.simulator_gpu.solar.mask import ( # noqa: F401
71
+ create_computation_mask,
72
+ draw_computation_mask,
73
+ get_mask_from_drawing,
74
+ visualize_computation_mask,
75
+ get_mask_info,
76
+ )
77
+ except ImportError:
78
+ # simulator_gpu may not be installed
79
+ pass
@@ -0,0 +1,90 @@
1
+ """simulator_gpu: GPU-accelerated urban simulation using Taichi.
2
+
3
+ This package provides GPU-accelerated implementations for:
4
+ - Solar radiation simulation (direct, diffuse, cumulative)
5
+ - View analysis (green view index, sky view factor)
6
+ - Landmark visibility analysis
7
+
8
+ Submodules:
9
+ solar: Solar radiation calculations
10
+ visibility: View and visibility analysis
11
+
12
+ Example:
13
+ from voxcity.simulator_gpu import solar, visibility
14
+
15
+ # Solar radiation
16
+ irradiance = solar.get_global_solar_irradiance_using_epw(voxcity, ...)
17
+
18
+ # View analysis
19
+ gvi = visibility.get_view_index(voxcity, mode='green')
20
+ """
21
+
22
+ import os
23
+
24
+ # Disable Numba caching to prevent stale cache issues
25
+ os.environ.setdefault("NUMBA_CACHE_DIR", "")
26
+ os.environ.setdefault("NUMBA_DISABLE_JIT", "0")
27
+
28
+ # Taichi initialization
29
+ from .init_taichi import init_taichi, ensure_initialized, is_initialized
30
+
31
+ # Core utilities
32
+ from .core import (
33
+ Vector3, Point3,
34
+ PI, TWO_PI, DEG_TO_RAD, RAD_TO_DEG,
35
+ SOLAR_CONSTANT, EXT_COEF,
36
+ )
37
+
38
+ # Domain (shared between solar and visibility)
39
+ from .domain import Domain, Surfaces, extract_surfaces_from_domain
40
+ from .domain import IUP, IDOWN, INORTH, ISOUTH, IEAST, IWEST
41
+
42
+ # Submodules
43
+ from . import solar
44
+ from . import visibility
45
+
46
+ # Convenience imports from solar
47
+ from .solar import (
48
+ get_global_solar_irradiance_using_epw,
49
+ get_building_global_solar_irradiance_using_epw,
50
+ get_direct_solar_irradiance_map,
51
+ get_diffuse_solar_irradiance_map,
52
+ get_global_solar_irradiance_map,
53
+ )
54
+
55
+ # Convenience imports from visibility
56
+ from .visibility import (
57
+ get_view_index,
58
+ get_sky_view_factor_map,
59
+ get_surface_view_factor,
60
+ get_landmark_visibility_map,
61
+ get_surface_landmark_visibility,
62
+ )
63
+
64
+ __version__ = "0.1.0"
65
+
66
+ __all__ = [
67
+ # Initialization
68
+ 'init_taichi', 'ensure_initialized', 'is_initialized',
69
+ # Core
70
+ 'Vector3', 'Point3',
71
+ 'PI', 'TWO_PI', 'DEG_TO_RAD', 'RAD_TO_DEG',
72
+ 'SOLAR_CONSTANT', 'EXT_COEF',
73
+ # Domain
74
+ 'Domain', 'Surfaces', 'extract_surfaces_from_domain',
75
+ 'IUP', 'IDOWN', 'INORTH', 'ISOUTH', 'IEAST', 'IWEST',
76
+ # Submodules
77
+ 'solar', 'visibility',
78
+ # Solar (convenience)
79
+ 'get_global_solar_irradiance_using_epw',
80
+ 'get_building_global_solar_irradiance_using_epw',
81
+ 'get_direct_solar_irradiance_map',
82
+ 'get_diffuse_solar_irradiance_map',
83
+ 'get_global_solar_irradiance_map',
84
+ # Visibility (convenience)
85
+ 'get_view_index',
86
+ 'get_sky_view_factor_map',
87
+ 'get_surface_view_factor',
88
+ 'get_landmark_visibility_map',
89
+ 'get_surface_landmark_visibility',
90
+ ]