Generators Module¶
gigaspatial.generators
¶
poi
¶
PoiViewGenerator
¶
POI View Generator for integrating various geospatial datasets such as Google Open Buildings, Microsoft Global Buildings, GHSL Built Surface, and GHSL Settlement Model (SMOD) data with Points of Interest (POIs).
This class provides methods to load, process, and map external geospatial data to a given set of POIs, enriching them with relevant attributes. It leverages handler/reader classes for efficient data access and processing.
The POIs can be initialized from a list of (latitude, longitude) tuples, a list of dictionaries, a pandas DataFrame, or a geopandas GeoDataFrame.
Source code in gigaspatial/generators/poi.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 |
|
points_gdf: gpd.GeoDataFrame
property
¶
Gets the internal GeoDataFrame of points of interest.
view: pd.DataFrame
property
¶
The DataFrame representing the current point of interest view.
__init__(points, poi_id_column='poi_id', config=None, data_store=None, logger=None)
¶
Initializes the PoiViewGenerator with the input points and configurations.
The input points
are converted into an internal GeoDataFrame (_points_gdf
) for consistent geospatial operations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points | Union[List[Tuple[float, float]], List[dict], DataFrame, GeoDataFrame] | The input points of interest. Can be: - A list of (latitude, longitude) tuples. - A list of dictionaries, where each dict must contain 'latitude' and 'longitude' keys. - A pandas DataFrame with 'latitude' and 'longitude' columns. - A geopandas GeoDataFrame (expected to have a 'geometry' column representing points). | required |
generator_config | Optional[PoiViewGeneratorConfig] | Configuration for the POI view generation process. If None, a default | required |
data_store | Optional[DataStore] | An instance of a data store for managing data access (e.g., LocalDataStore). If None, a default | None |
Source code in gigaspatial/generators/poi.py
chain_operations(operations)
¶
Chain multiple mapping operations for fluent interface.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
operations | List[dict] | List of dicts with 'method' and 'kwargs' keys | required |
Example
generator.chain_operations([ {'method': 'map_google_buildings', 'kwargs': {}}, {'method': 'map_built_s', 'kwargs': {'map_radius_meters': 200}}, ])
Source code in gigaspatial/generators/poi.py
map_built_s(map_radius_meters=150, stat='sum', dataset_year=2020, dataset_resolution=100, output_column='built_surface_m2', **kwargs)
¶
Maps GHSL Built Surface (GHS_BUILT_S) data to the POIs.
Calculates the sum of built surface area within a specified buffer radius around each POI. Enriches points_gdf
with the 'built_surface_m2' column.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_config | Optional[GHSLDataConfig] | Configuration for accessing GHSL Built Surface data. If None, a default | required |
map_radius_meters | float | The buffer distance in meters around each POI to calculate zonal statistics for built surface. Defaults to 150 meters. | 150 |
**kwargs | Additional keyword arguments passed to the data reader (if applicable). | {} |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The updated GeoDataFrame with a new column: 'built_surface_m2'. Returns a copy of the current |
Source code in gigaspatial/generators/poi.py
map_google_buildings(handler=None, **kwargs)
¶
Maps Google Open Buildings data to the POIs by finding the nearest building.
Enriches the points_gdf
with the ID and distance to the nearest Google Open Building for each POI.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_config | Optional[GoogleOpenBuildingsConfig] | Configuration for accessing Google Open Buildings data. If None, a default | required |
**kwargs | Additional keyword arguments passed to the data reader (if applicable). | {} |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The updated GeoDataFrame with new columns: 'nearest_google_building_id' and 'nearest_google_building_distance'. Returns a copy of the current |
Source code in gigaspatial/generators/poi.py
map_ms_buildings(handler=None, **kwargs)
¶
Maps Microsoft Global Buildings data to the POIs by finding the nearest building.
Enriches the points_gdf
with the ID and distance to the nearest Microsoft Global Building for each POI. If buildings don't have an ID column, creates a unique ID using the building's coordinates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_config | Optional[MSBuildingsConfig] | Configuration for accessing Microsoft Global Buildings data. If None, a default | required |
**kwargs | Additional keyword arguments passed to the data reader (if applicable). | {} |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The updated GeoDataFrame with new columns: 'nearest_ms_building_id' and 'nearest_ms_building_distance'. Returns a copy of the current |
Source code in gigaspatial/generators/poi.py
map_nearest_points(points_df, id_column, lat_column=None, lon_column=None, output_prefix='nearest', **kwargs)
¶
Maps nearest points from a given DataFrame to the POIs.
Enriches the points_gdf
with the ID and distance to the nearest point from the input DataFrame for each POI.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points_df | Union[DataFrame, GeoDataFrame] | DataFrame containing points to find nearest neighbors from. Must have latitude and longitude columns or point geometries. | required |
id_column | str | Name of the column containing unique identifiers for each point. | required |
lat_column | str | Name of the latitude column in points_df. If None, will attempt to detect it or extract from geometry if points_df is a GeoDataFrame. | None |
lon_column | str | Name of the longitude column in points_df. If None, will attempt to detect it or extract from geometry if points_df is a GeoDataFrame. | None |
output_prefix | str | Prefix for the output column names. Defaults to "nearest". | 'nearest' |
**kwargs | Additional keyword arguments passed to the data reader (if applicable). | {} |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The updated GeoDataFrame with new columns: '{output_prefix}_id' and '{output_prefix}_distance'. Returns a copy of the current |
Raises:
Type | Description |
---|---|
ValueError | If required columns are missing from points_df or if coordinate columns cannot be detected or extracted from geometry. |
Source code in gigaspatial/generators/poi.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 |
|
map_smod(stat='median', dataset_year=2020, dataset_resolution=1000, output_column='smod_class', **kwargs)
¶
Maps GHSL Settlement Model (SMOD) data to the POIs.
Samples the SMOD class value at each POI's location. Enriches points_gdf
with the 'smod_class' column.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_config | Optional[GHSLDataConfig] | Configuration for accessing GHSL SMOD data. If None, a default | required |
**kwargs | Additional keyword arguments passed to the data reader (if applicable). | {} |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The updated GeoDataFrame with a new column: 'smod_class'. Returns a copy of the current |
Source code in gigaspatial/generators/poi.py
map_zonal_stats(data, stat='mean', map_radius_meters=None, output_column='zonal_stat', value_column=None, area_weighted=False, **kwargs)
¶
Maps zonal statistics from raster or polygon data to POIs.
Can operate in three modes: 1. Raster point sampling: Directly samples raster values at POI locations 2. Raster zonal statistics: Creates buffers around POIs and calculates statistics within them 3. Polygon aggregation: Aggregates polygon data to POI buffers with optional area weighting
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data | Union[List[TifProcessor], GeoDataFrame] | Either a list of TifProcessor objects containing raster data to sample, or a GeoDataFrame containing polygon data to aggregate. | required |
stat | str | For raster data: Statistic to calculate ("sum", "mean", "median", "min", "max"). For polygon data: Aggregation method to use. Defaults to "mean". | 'mean' |
map_radius_meters | float | If provided, creates circular buffers of this radius around each POI and calculates statistics within the buffers. If None, samples directly at POI locations (only for raster data). | None |
output_column | str | Name of the output column to store the results. Defaults to "zonal_stat". | 'zonal_stat' |
value_column | str | For polygon data: Name of the column to aggregate. Required for polygon data. Not used for raster data. | None |
area_weighted | bool | For polygon data: Whether to weight values by fractional area of intersection. Defaults to False. | False |
**kwargs | Additional keyword arguments passed to the sampling/aggregation functions. | {} |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The updated GeoDataFrame with a new column containing the calculated statistics. Returns a copy of the current |
Raises:
Type | Description |
---|---|
ValueError | If no valid data is provided, if parameters are incompatible, or if required parameters (value_column) are missing for polygon data. |
Source code in gigaspatial/generators/poi.py
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 |
|
save_view(name, output_format=None)
¶
Saves the current POI view (the enriched DataFrame) to a file.
The output path and format are determined by the config
or overridden by the output_format
parameter.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name | str | The base name for the output file (without extension). | required |
output_format | Optional[str] | The desired output format (e.g., "csv", "geojson"). If None, the | None |
Returns:
Name | Type | Description |
---|---|---|
Path | Path | The full path to the saved output file. |
Source code in gigaspatial/generators/poi.py
to_dataframe()
¶
Returns the current POI view as a DataFrame.
This method combines all accumulated variables in the view
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The current view. |
to_geodataframe()
¶
Returns the current POI view merged with the original point geometries as a GeoDataFrame.
This method combines all accumulated variables in the view with the corresponding point geometries, providing a spatially-enabled DataFrame for further analysis or export.
Returns:
Type | Description |
---|---|
GeoDataFrame | gpd.GeoDataFrame: The current view merged with point geometries. |
Source code in gigaspatial/generators/poi.py
validate_data_coverage(data_bounds)
¶
Validate how many POIs fall within the data coverage area.
Returns:
Name | Type | Description |
---|---|---|
dict | dict | Coverage statistics |
Source code in gigaspatial/generators/poi.py
PoiViewGeneratorConfig
¶
Configuration for POI (Point of Interest) view generation.
Attributes:
Name | Type | Description |
---|---|---|
base_path | Path | The base directory where generated POI views will be saved. Defaults to a path retrieved from |
output_format | str | The default format for saving output files (e.g., "csv", "geojson"). Defaults to "csv". |
Source code in gigaspatial/generators/poi.py
zonal
¶
admin
¶
AdminBoundariesViewGenerator
¶
Bases: GeometryBasedZonalViewGenerator[T]
Generates zonal views using administrative boundaries as the zones.
This class specializes in creating zonal views where the zones are defined by administrative boundaries (e.g., countries, states, districts) at a specified administrative level. It extends the GeometryBasedZonalViewGenerator
and leverages the AdminBoundaries
handler to load the necessary geographical data.
The administrative boundaries serve as the base geometries to which other geospatial data (points, polygons, rasters) can be mapped and aggregated.
Attributes:
Name | Type | Description |
---|---|---|
country | str | The name or code of the country for which to load administrative boundaries. |
admin_level | int | The administrative level to load (e.g., 0 for country, 1 for states/provinces). |
admin_path | Union[str, Path] | Optional path to a local GeoJSON/Shapefile containing the administrative boundaries. If provided, this local file will be used instead of downloading. |
config | Optional[ZonalViewGeneratorConfig] | Configuration for the zonal view generation process. |
data_store | Optional[DataStore] | A DataStore instance for accessing data. |
logger | Optional[Logger] | A logger instance for logging messages. |
Source code in gigaspatial/generators/zonal/admin.py
__init__(country, admin_level, data_store=None, admin_path=None, config=None, logger=None)
¶
Initializes the AdminBoundariesViewGenerator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
country | str | The name or code of the country (e.g., "USA", "Germany"). | required |
admin_level | int | The administrative level to load (e.g., 0 for country, 1 for states, 2 for districts). | required |
admin_path | Union[str, Path] | Path to a local administrative boundaries file (GeoJSON, Shapefile). If provided, overrides default data loading. | None |
config | Optional[ZonalViewGeneratorConfig] | Configuration for the zonal view generator. If None, a default config will be used. | None |
data_store | Optional[DataStore] | Data storage interface. If None, LocalDataStore is used. | None |
logger | Optional[Logger] | Custom logger instance. If None, a default logger is used. | None |
Source code in gigaspatial/generators/zonal/admin.py
base
¶
ZonalViewGenerator
¶
Bases: ABC
, Generic[T]
Base class for mapping data to zonal datasets.
This class provides the framework for mapping various data sources (points, polygons, rasters) to zonal geometries like grid tiles or catchment areas. It serves as an abstract base class that must be subclassed to implement specific zonal systems.
The class supports three main types of data mapping: - Point data aggregation to zones - Polygon data aggregation with optional area weighting - Raster data sampling and statistics
Attributes:
Name | Type | Description |
---|---|---|
data_store | DataStore | The data store for accessing input data. |
generator_config | ZonalViewGeneratorConfig | Configuration for the generator. |
logger | Logger instance for this class. |
Source code in gigaspatial/generators/zonal/base.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 |
|
view: pd.DataFrame
property
¶
The DataFrame representing the current zonal view.
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The DataFrame containing zone IDs, and any added variables. If no variables have been added, it returns the base |
zone_gdf: gpd.GeoDataFrame
property
¶
Cached GeoDataFrame of zones.
Returns:
Type | Description |
---|---|
GeoDataFrame | gpd.GeoDataFrame: Lazily-computed and cached GeoDataFrame of zone geometries and identifiers. |
__init__(config=None, data_store=None, logger=None)
¶
Initialize the ZonalViewGenerator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
generator_config | ZonalViewGeneratorConfig | Configuration for the generator. If None, uses default configuration. | required |
data_store | DataStore | The data store for accessing input data. If None, uses LocalDataStore. | None |
Source code in gigaspatial/generators/zonal/base.py
add_variable_to_view(data_dict, column_name)
¶
Adds a new variable (column) to the zonal view GeoDataFrame.
This method takes a dictionary (typically the result of map_points or map_polygons) and adds its values as a new column to the internal _view
(or zone_gdf
if not yet initialized). The dictionary keys are expected to be the zone_id
values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dict | Dict | A dictionary where keys are | required |
column_name | str | The name of the new column to be added to the GeoDataFrame. | required |
Source code in gigaspatial/generators/zonal/base.py
get_zonal_geometries()
abstractmethod
¶
Get the geometries of the zones.
This method must be implemented by subclasses to return the actual geometric shapes of the zones (e.g., grid tiles, catchment boundaries, administrative areas).
Returns:
Type | Description |
---|---|
List[Polygon] | List[Polygon]: A list of Shapely Polygon objects representing zone geometries. |
Source code in gigaspatial/generators/zonal/base.py
get_zone_geodataframe()
¶
Convert zones to a GeoDataFrame.
Creates a GeoDataFrame containing zone identifiers and their corresponding geometries in WGS84 (EPSG:4326) coordinate reference system.
Returns:
Type | Description |
---|---|
GeoDataFrame | gpd.GeoDataFrame: A GeoDataFrame with 'zone_id' and 'geometry' columns, where zone_id contains the identifiers and geometry contains the corresponding Polygon objects. |
Source code in gigaspatial/generators/zonal/base.py
get_zone_identifiers()
abstractmethod
¶
Get unique identifiers for each zone.
This method must be implemented by subclasses to return identifiers that correspond one-to-one with the geometries returned by get_zonal_geometries().
Returns:
Type | Description |
---|---|
List[T] | List[T]: A list of zone identifiers (e.g., quadkeys, H3 indices, tile IDs). The type T is determined by the specific zonal system implementation. |
Source code in gigaspatial/generators/zonal/base.py
map_points(points, value_columns=None, aggregation='count', predicate='within', output_suffix='', mapping_function=None, **mapping_kwargs)
¶
Map point data to zones with spatial aggregation.
Aggregates point data to zones using spatial relationships. Points can be counted or have their attribute values aggregated using various statistical methods.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
points | Union[DataFrame, GeoDataFrame] | The point data to map. Must contain geometry information if DataFrame. | required |
value_columns | Union[str, List[str]] | Column name(s) containing values to aggregate. If None, only point counts are performed. | None |
aggregation | Union[str, Dict[str, str]] | Aggregation method(s) to use. Can be a single string ("count", "mean", "sum", "min", "max", etc.) or a dictionary mapping column names to aggregation methods. | 'count' |
predicate | str | Spatial predicate for point-to-zone relationship. Options include "within", "intersects", "contains". Defaults to "within". | 'within' |
output_suffix | str | Suffix to add to output column names. Defaults to empty string. | '' |
mapping_function | Callable | Custom function for mapping points to zones. If provided, signature should be mapping_function(self, points, **mapping_kwargs). When used, all other parameters except mapping_kwargs are ignored. | None |
**mapping_kwargs | Additional keyword arguments passed to the mapping function. | {} |
Returns:
Name | Type | Description |
---|---|---|
Dict | Dict | Dictionary with zone IDs as keys and aggregated values as values. If value_columns is None, returns point counts per zone. If value_columns is specified, returns aggregated values per zone. |
Source code in gigaspatial/generators/zonal/base.py
map_polygons(polygons, value_columns=None, aggregation='count', predicate='intersects', **kwargs)
¶
Maps polygon data to the instance's zones and aggregates values.
This method leverages aggregate_polygons_to_zones
to perform a spatial aggregation of polygon data onto the zones stored within this object instance. It can count polygons, or aggregate their values, based on different spatial relationships defined by the predicate
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
polygons | Union[DataFrame, GeoDataFrame] | The polygon data to map. Must contain geometry information if a DataFrame. | required |
value_columns | Union[str, List[str]] | The column name(s) from the | None |
aggregation | Union[str, Dict[str, str]] | The aggregation method(s) to use. Can be a single string (e.g., "sum", "mean", "max") or a dictionary mapping column names to specific aggregation methods. This is ignored and set to "count" if | 'count' |
predicate | Literal[intersects, within, fractional] | The spatial relationship to use for aggregation: - "intersects": Counts or aggregates values for any polygon that intersects a zone. - "within": Counts or aggregates values for polygons that are entirely contained within a zone. - "fractional": Performs area-weighted aggregation. The value of a polygon is distributed proportionally to the area of its overlap with each zone. Defaults to "intersects". | 'intersects' |
**kwargs | Additional keyword arguments to be passed to the underlying | {} |
Returns:
Name | Type | Description |
---|---|---|
Dict | Dict | A dictionary or a nested dictionary containing the aggregated values, with zone IDs as keys. If |
Raises:
Type | Description |
---|---|
ValueError | If |
Example
Assuming 'self' is an object with a 'zone_gdf' attribute¶
Count all land parcels that intersect each zone¶
parcel_counts = self.map_polygons(landuse_polygons)
Aggregate total population within zones using area weighting¶
population_by_zone = self.map_polygons( ... landuse_polygons, ... value_columns="population", ... predicate="fractional", ... aggregation="sum" ... )
Get the sum of residential area and count of buildings within each zone¶
residential_stats = self.map_polygons( ... building_polygons, ... value_columns=["residential_area_sqm", "building_id"], ... aggregation={"residential_area_sqm": "sum", "building_id": "count"}, ... predicate="intersects" ... )
Source code in gigaspatial/generators/zonal/base.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 |
|
map_rasters(tif_processors, mapping_function=None, stat='mean', **mapping_kwargs)
¶
Map raster data to zones using zonal statistics.
Samples raster values within each zone and computes statistics. Automatically handles coordinate reference system transformations between raster and zone data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tif_processors | List[TifProcessor] | List of TifProcessor objects for accessing raster data. All processors should have the same CRS. | required |
mapping_function | Callable | Custom function for mapping rasters to zones. If provided, signature should be mapping_function(self, tif_processors, **mapping_kwargs). When used, stat and other parameters except mapping_kwargs are ignored. | None |
stat | str | Statistic to calculate when aggregating raster values within each zone. Options include "mean", "sum", "min", "max", "std", etc. Defaults to "mean". | 'mean' |
**mapping_kwargs | Additional keyword arguments passed to the mapping function. | {} |
Returns:
Type | Description |
---|---|
Union[ndarray, Dict] | Union[np.ndarray, Dict]: By default, returns a NumPy array of sampled values with shape (n_zones, 1), taking the first non-nodata value encountered. Custom mapping functions may return different data structures. |
Note
If the coordinate reference system of the rasters differs from the zones, the zone geometries will be automatically transformed to match the raster CRS.
Source code in gigaspatial/generators/zonal/base.py
save_view(name, output_format=None)
¶
Save the generated zonal view to disk.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name | str | Base name for the output file (without extension). | required |
output_format | str | File format to save in (e.g., "parquet", "geojson", "shp"). If None, uses the format specified in config. | None |
Returns:
Name | Type | Description |
---|---|---|
Path | Path | The full path where the view was saved. |
Note
The output directory is determined by the config.base_path setting. The file extension is automatically added based on the output format. This method now saves the internal self.view
.
Source code in gigaspatial/generators/zonal/base.py
to_dataframe()
¶
Returns the current zonal view as a DataFrame.
This method combines all accumulated variables in the view
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: The current view. |
Source code in gigaspatial/generators/zonal/base.py
to_geodataframe()
¶
Returns the current zonal view merged with zone geometries as a GeoDataFrame.
This method combines all accumulated variables in the view with the corresponding zone geometries, providing a spatially-enabled DataFrame for further analysis or export.
Returns:
Type | Description |
---|---|
GeoDataFrame | gpd.GeoDataFrame: The current view merged with zone geometries. |
Source code in gigaspatial/generators/zonal/base.py
ZonalViewGeneratorConfig
¶
Bases: BaseModel
Configuration for zonal view generation.
Attributes:
Name | Type | Description |
---|---|---|
base_path | Path | Base directory path for storing zonal views. Defaults to configured zonal views path. |
output_format | str | Default output format for saved views. Defaults to "parquet". |
Source code in gigaspatial/generators/zonal/base.py
geometry
¶
GeometryBasedZonalViewGenerator
¶
Bases: ZonalViewGenerator[T]
Mid-level class for zonal view generation based on geometries with identifiers.
This class serves as an intermediate between the abstract ZonalViewGenerator and specific implementations like MercatorViewGenerator or H3ViewGenerator. It handles the common case where zones are defined by a mapping between zone identifiers and geometries, either provided as a dictionary or as a GeoDataFrame.
The class extends the base functionality with methods for mapping common geospatial datasets including GHSL (Global Human Settlement Layer), Google Open Buildings, and Microsoft Global Buildings data.
Attributes:
Name | Type | Description |
---|---|---|
zone_dict | Dict[T, Polygon] | Mapping of zone identifiers to geometries. |
zone_id_column | str | Name of the column containing zone identifiers. |
zone_data_crs | str | Coordinate reference system of the zone data. |
_zone_gdf | GeoDataFrame | Cached GeoDataFrame representation of zones. |
data_store | DataStore | For accessing input data. |
config | ZonalViewGeneratorConfig | Configuration for view generation. |
logger | ZonalViewGeneratorConfig | Logger instance for this class. |
Source code in gigaspatial/generators/zonal/geometry.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 |
|
__init__(zone_data, zone_id_column='zone_id', zone_data_crs='EPSG:4326', config=None, data_store=None, logger=None)
¶
Initialize with zone geometries and identifiers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
zone_data | Union[Dict[T, Polygon], GeoDataFrame] | Zone definitions. Either a dictionary mapping zone identifiers to Polygon/MultiPolygon geometries, or a GeoDataFrame with geometries and a zone identifier column. | required |
zone_id_column | str | Name of the column containing zone identifiers. Only used if zone_data is a GeoDataFrame. Defaults to "zone_id". | 'zone_id' |
zone_data_crs | str | Coordinate reference system of the zone data. Defaults to "EPSG:4326" (WGS84). | 'EPSG:4326' |
config | ZonalViewGeneratorConfig | Generator configuration. If None, uses default configuration. | None |
data_store | DataStore | Data store for accessing input data. If None, uses LocalDataStore. | None |
Raises:
Type | Description |
---|---|
TypeError | If zone_data is not a dictionary or GeoDataFrame, or if dictionary values are not Polygon/MultiPolygon geometries. |
ValueError | If zone_id_column is not found in GeoDataFrame, or if the provided CRS doesn't match the GeoDataFrame's CRS. |
Source code in gigaspatial/generators/zonal/geometry.py
get_zonal_geometries()
¶
Get the geometry of each zone.
Returns:
Type | Description |
---|---|
List[Polygon] | List[Polygon]: A list of zone geometries in the order they appear in the underlying GeoDataFrame. |
Source code in gigaspatial/generators/zonal/geometry.py
get_zone_geodataframe()
¶
Convert zones to a GeoDataFrame with standardized column names.
Returns:
Type | Description |
---|---|
GeoDataFrame | gpd.GeoDataFrame: A GeoDataFrame with 'zone_id' and 'geometry' columns. The zone_id column is renamed from the original zone_id_column if different. |
Source code in gigaspatial/generators/zonal/geometry.py
get_zone_identifiers()
¶
Get the identifier for each zone.
Returns:
Type | Description |
---|---|
List[T] | List[T]: A list of zone identifiers in the order they appear in the underlying GeoDataFrame. |
Source code in gigaspatial/generators/zonal/geometry.py
map_built_s(year=2020, resolution=100, stat='sum', name_prefix='built_surface_m2_', **kwargs)
¶
Map GHSL Built-up Surface data to zones.
Convenience method for mapping Global Human Settlement Layer Built-up Surface data using appropriate default parameters for built surface analysis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ghsl_data_config | GHSLDataConfig | Configuration for GHSL Built-up Surface data. Defaults to GHS_BUILT_S product for 2020 at 100m resolution. | required |
stat | str | Statistic to calculate for built surface values within each zone. Defaults to "sum" which gives total built surface area. | 'sum' |
name_prefix | str | Prefix for the output column name. Defaults to "built_surface_m2_". | 'built_surface_m2_' |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: Updated GeoDataFrame with zones and built surface metrics. Adds a column named "{name_prefix}{stat}" containing the aggregated values. |
Source code in gigaspatial/generators/zonal/geometry.py
map_ghsl(handler, stat, name_prefix=None, **kwargs)
¶
Map Global Human Settlement Layer data to zones.
Loads and processes GHSL raster data for the intersecting tiles, then samples the raster values within each zone using the specified statistic.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ghsl_data_config | GHSLDataConfig | Configuration specifying which GHSL product, year, resolution, and coordinate system to use. | required |
stat | str | Statistic to calculate for raster values within each zone. Common options: "mean", "sum", "median", "min", "max". | required |
name_prefix | str | Prefix for the output column name. If None, uses the GHSL product name in lowercase followed by underscore. | None |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: Updated DataFrame with GHSL metrics. Adds a column named "{name_prefix}{stat}" containing the sampled values. |
Note
The method automatically determines which GHSL tiles intersect with the zones and loads only the necessary data for efficient processing.
Source code in gigaspatial/generators/zonal/geometry.py
map_google_buildings(handler=None, use_polygons=False)
¶
Map Google Open Buildings data to zones.
Processes Google Open Buildings dataset to calculate building counts and total building area within each zone. Can use either point centroids (faster) or polygon geometries (more accurate) for spatial operations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
google_open_buildings_config | GoogleOpenBuildingsConfig | Configuration for accessing Google Open Buildings data. Uses default configuration if not provided. | required |
use_polygons | bool | Whether to use polygon geometries for buildings. If True, uses actual building polygons for more accurate area calculations but with slower performance. If False, uses building centroids with area values from attributes for faster processing. Defaults to False. | False |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: Updated DataFrame with building metrics. Adds columns: - 'google_buildings_count': Number of buildings in each zone - 'google_buildings_area_in_meters': Total building area in square meters |
Note
If no Google Buildings data is found for the zones, returns the original GeoDataFrame unchanged with a warning logged.
Source code in gigaspatial/generators/zonal/geometry.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 |
|
map_ms_buildings(handler=None, use_polygons=False)
¶
Map Microsoft Global Buildings data to zones.
Processes Microsoft Global Buildings dataset to calculate building counts and total building area within each zone. Can use either centroid points (faster) or polygon geometries (more accurate) for spatial operations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ms_buildings_config | MSBuildingsConfig | Configuration for accessing Microsoft Global Buildings data. If None, uses default configuration. | required |
use_polygons | bool | Whether to use polygon geometries for buildings. If True, uses actual building polygons for more accurate area calculations but with slower performance. If False, uses building centroids with area values from attributes for faster processing. Defaults to False. | False |
Returns:
Type | Description |
---|---|
GeoDataFrame | gpd.GeoDataFrame: Updated GeoDataFrame with zones and building metrics. Adds columns: - 'ms_buildings_count': Number of buildings in each zone - 'ms_buildings_area_in_meters': Total building area in square meters |
Note
If no Microsoft Buildings data is found for the zones, returns the original GeoDataFrame unchanged with a warning logged. Building areas are calculated in meters using appropriate UTM projections.
Source code in gigaspatial/generators/zonal/geometry.py
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 |
|
map_smod(year=2020, resolution=1000, stat='median', name_prefix='smod_class_', **kwargs)
¶
Map GHSL Settlement Model data to zones.
Convenience method for mapping Global Human Settlement Layer Settlement Model data using appropriate default parameters for settlement classification analysis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ghsl_data_config | GHSLDataConfig | Configuration for GHSL Settlement Model data. Defaults to GHS_SMOD product for 2020 at 1000m resolution in Mollweide projection. | required |
stat | str | Statistic to calculate for settlement class values within each zone. Defaults to "median" which gives the predominant settlement class. | 'median' |
name_prefix | str | Prefix for the output column name. Defaults to "smod_class_". | 'smod_class_' |
Returns:
Type | Description |
---|---|
DataFrame | pd.DataFrame: Updated DataFrame with zones and settlement classification. Adds a column named "{name_prefix}{stat}" containing the aggregated values. |
Source code in gigaspatial/generators/zonal/geometry.py
mercator
¶
MercatorViewGenerator
¶
Bases: GeometryBasedZonalViewGenerator[T]
Generates zonal views using Mercator tiles as the zones.
This class specializes in creating zonal views where the zones are defined by Mercator tiles. It extends the GeometryBasedZonalViewGenerator
and leverages the MercatorTiles
and CountryMercatorTiles
classes to generate tiles based on various input sources.
The primary input source defines the geographical area of interest. This can be a country, a specific geometry, a set of points, or even a list of predefined quadkeys. The zoom_level
determines the granularity of the Mercator tiles.
Attributes:
Name | Type | Description |
---|---|---|
source | Union[str, BaseGeometry, GeoDataFrame, List[Union[Point, Tuple[float, float]]], List[str]] | Specifies the geographic area or specific tiles to use. Can be: - A country name (str): Uses |
zoom_level | int | The zoom level of the Mercator tiles. Higher zoom levels result in smaller, more detailed tiles. |
predicate | str | The spatial predicate used when filtering tiles based on a spatial source (e.g., "intersects", "contains"). Defaults to "intersects". |
config | Optional[ZonalViewGeneratorConfig] | Configuration for the zonal view generation process. |
data_store | Optional[DataStore] | A DataStore instance for accessing data. |
logger | Optional[Logger] | A logger instance for logging. |
Methods:
Name | Description |
---|---|
_init_zone_data | Initializes the Mercator tile GeoDataFrame based on the input source. |
# Inherits other methods from GeometryBasedZonalViewGenerator, such as | |
Example
Create a MercatorViewGenerator for tiles covering Germany at zoom level 6¶
generator = MercatorViewGenerator(source="Germany", zoom_level=6)
Create a MercatorViewGenerator for tiles intersecting a specific polygon¶
polygon = ... # Define a Shapely Polygon generator = MercatorViewGenerator(source=polygon, zoom_level=8)
Create a MercatorViewGenerator from a list of quadkeys¶
quadkeys = ["0020023131023032", "0020023131023033"] generator = MercatorViewGenerator(source=quadkeys, zoom_level=12)