Data Processing Module Documentation
Overview
The Data Processing module provides utility functions for spatial data processing, file management, and data transformation in the 3-30-300 analysis framework. This module handles tile name translation, spatial filtering, geometry operations, and file format conversions.
Module Information
filter_buffer_geometries(sedona, geo_level, geo_code, table_name, buffer=None)
Filters the buffer geometries for a given geo_code.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sedona
|
SparkSession
|
The Spark session. |
required |
geo_level
|
str
|
The geo_level. |
required |
geo_code
|
str
|
The geo_code. |
required |
table_name
|
str
|
The table name. |
required |
buffer
|
int
|
The buffer size. |
None
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
DataFrame
|
The filtered buffer geometries dataframe. |
Source code in src/utils/data_processing.py
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 |
|
generate_tile_paths(geo_level, geo_code, output_areas_os_tile_overlay_df, vom_raster_paths_df, tree_vector_paths_df)
Generates the tile paths for a given geo_code.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
geo_level
|
str
|
The geo_level. |
required |
geo_code
|
str
|
The geo_code. |
required |
output_areas_os_tile_overlay_df
|
GeoDataFrame
|
The output areas OS tile overlay dataframe. |
required |
vom_raster_paths_df
|
DataFrame
|
The VOM raster paths dataframe. |
required |
tree_vector_paths_df
|
DataFrame
|
The tree vector paths dataframe. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: The tile paths dataframe. |
Source code in src/utils/data_processing.py
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 |
|
get_geometries(sedona, geo_level, geo_code, dissolve=True)
Gets the geometries for a given geo_code.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sedona
|
SparkSession
|
The Spark session. |
required |
geo_level
|
str
|
The geo_level. |
required |
geo_code
|
str
|
The geo_code. |
required |
dissolve
|
bool
|
Whether to dissolve the geometries. |
True
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
DataFrame
|
The geometries dataframe. |
Source code in src/utils/data_processing.py
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 |
|
get_overlapping_grid_tiles(output_areas_boundaries_gdf, os_tile_boundaries_gdf, geo_level, geo_code, tile_level)
Gets the overlapping grid tiles for a given geo_code and tile_level.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output_areas_boundaries_gdf
|
GeoDataFrame
|
The output areas boundaries dataframe. |
required |
os_tile_boundaries_gdf
|
GeoDataFrame
|
The OS tile boundaries dataframe. |
required |
geo_level
|
str
|
The geo_level. |
required |
geo_code
|
str
|
The geo_code. |
required |
tile_level
|
str
|
The tile_level. |
required |
Returns:
Name | Type | Description |
---|---|---|
list |
list
|
The overlapping grid tiles. |
Source code in src/utils/data_processing.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
|
save_csv_as_parquet(in_directory, path_pattern, out_path)
Saves the CSV files as a parquet file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
in_directory
|
Path
|
The input directory. |
required |
path_pattern
|
str
|
The path pattern. |
required |
out_path
|
Path
|
The output path. |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: The concatenated dataframe. |
Source code in src/utils/data_processing.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
|
save_temp_file(spark_df, output_path, coalesce=1, file_format='csv')
Saves a Spark DataFrame to a single named file and returns a Pandas DataFrame.
This function is a workaround for the fact that Spark normally writes to a directory. It works by coalescing the DataFrame to a single partition, writing to a temporary directory, and then moving the single generated data file to the final destination.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spark_df
|
DataFrame
|
The Spark DataFrame to save. |
required |
output_path
|
Path
|
The final, full path for the output file (e.g., Path("/data/my_file.parquet")). |
required |
file_format
|
str
|
The format to save the file in ("parquet", "csv", etc.). |
'csv'
|
Returns:
Type | Description |
---|---|
DataFrame
|
pd.DataFrame: The saved data loaded into a Pandas DataFrame. |
Source code in src/utils/data_processing.py
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 |
|
translate_tile_name(tile_name)
Translates a tile name between two formats:
- Format 1: TL0045 (where '0045' represents coordinates)
- Format 2: TL04NW (where 'NW' represents directions)
The function converts: - From Format 1 to Format 2 by interpreting the numeric coordinates and converting them to directional codes. - From Format 2 to Format 1 by interpreting the directional codes and converting them to numeric coordinates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tile_name
|
str
|
The tile name to be translated. It should be a string of length 6. |
required |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The translated tile name in the opposite format. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the input tile_name is not of length 6. |
ValueError
|
If the numeric part of the tile name cannot be converted to an integer when expected. |
Source code in src/utils/data_processing.py
12 13 14 15 16 17 18 19 20 21 22 23 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 |
|
Usage Examples
Basic Workflow
The typical workflow for data processing involves:
- Tile name translation - Converting between different tile naming formats
- Spatial filtering - Extracting geometries for specific geographic areas
- Path generation - Creating file paths for VOM and tree data
- File conversion - Converting between different file formats
Example: Translating Tile Names
from src.utils.data_processing import translate_tile_name
# Convert from numeric to directional format
numeric_tile = "TL0045"
directional_tile = translate_tile_name(numeric_tile)
print(f"{numeric_tile} -> {directional_tile}") # TL0045 -> TL04NW
# Convert from directional to numeric format
directional_tile = "TL04NW"
numeric_tile = translate_tile_name(directional_tile)
print(f"{directional_tile} -> {numeric_tile}") # TL04NW -> tl0045
Example: Getting Overlapping Grid Tiles
from src.utils.data_processing import get_overlapping_grid_tiles
# Get overlapping tiles for a geographic area
overlapping_tiles = get_overlapping_grid_tiles(
output_areas_boundaries_gdf=boundaries_gdf,
os_tile_boundaries_gdf=tiles_gdf,
geo_level="LAD22CD",
geo_code="E06000001",
tile_level="TILE_NAME_5KM"
)
Example: Generating Tile Paths
from src.utils.data_processing import generate_tile_paths
# Generate paths for VOM and tree data
tile_paths_df = generate_tile_paths(
geo_level="LAD22CD",
geo_code="E06000001",
output_areas_os_tile_overlay_df=overlay_df,
vom_raster_paths_df=vom_paths_df,
tree_vector_paths_df=tree_paths_df
)
Example: Filtering Buffer Geometries
from src.utils.data_processing import filter_buffer_geometries
# Filter buildings with buffer
buildings_buffer_sdf = filter_buffer_geometries(
sedona=sedona,
geo_level="LAD22CD",
geo_code="E06000001",
table_name="buildings",
buffer=100
)
Example: Getting Geometries
from src.utils.data_processing import get_geometries
# Get dissolved geometries for an area
boundary_sdf = get_geometries(
sedona=sedona,
geo_level="LAD22CD",
geo_code="E06000001",
dissolve=True
)
Example: Saving Files
from src.utils.data_processing import save_temp_file, save_csv_as_parquet
from pathlib import Path
# Save Spark DataFrame as single file
output_path = Path("output/data.parquet")
pandas_df = save_temp_file(
spark_df=result_sdf,
output_path=output_path,
coalesce=1,
file_format="parquet"
)
# Convert CSV files to parquet
csv_df = save_csv_as_parquet(
in_directory=Path("input/"),
path_pattern="*.csv",
out_path=Path("output/combined.parquet")
)
Tile Name Translation
Tile Name Formats
Format 1: Numeric Coordinates
- Pattern:
TL0045
(where '0045' represents coordinates) - Structure: 2-letter prefix + 4-digit numeric code
- Example:
TL0045
,SU1234
,SP5678
Format 2: Directional Codes
- Pattern:
TL04NW
(where 'NW' represents directions) - Structure: 2-letter prefix + 2-digit number + 2-letter direction
- Example:
TL04NW
,SU12SE
,SP56NE
Translation Logic
- Numeric to Directional: Converts coordinate numbers to directional codes
- Directional to Numeric: Converts directional codes to coordinate numbers
- Case Handling: Maintains appropriate case for each format
- Validation: Ensures input tile names are 6 characters long
Spatial Operations
Grid Tile Overlap
- Spatial Intersection: Finds tiles that overlap with geographic areas
- Efficient Filtering: Uses spatial indexing for performance
- Result Aggregation: Returns unique tile names for processing
- Coordinate System: Works with project coordinate reference system
Geometry Filtering
- Spatial Joins: Uses ST_Intersects for spatial relationships
- Buffer Operations: Creates spatial buffers around geometries
- Dissolution: Combines multiple geometries into single boundary
- Temporary Views: Creates Spark SQL views for efficient querying
File Management
Path Generation
- Tile Matching: Matches geographic areas with available data tiles
- Year Sorting: Orders data by year (newest first)
- Duplicate Removal: Eliminates duplicate tile-year combinations
- Path Validation: Ensures file paths exist and are accessible
File Format Conversion
- CSV to Parquet: Converts CSV files to efficient parquet format
- Spark to Pandas: Converts Spark DataFrames to Pandas DataFrames
- Single File Output: Ensures single output file instead of directory
- Format Validation: Supports multiple output formats
Key Parameters
Tile Translation Parameters
- tile_name: 6-character tile name to translate
- format: Source format (numeric or directional)
- case: Output case (upper or lower)
Spatial Operation Parameters
- geo_level: Geographic level (LAD22CD, MSOA21CD, etc.)
- geo_code: Specific geographic code
- buffer: Buffer distance in meters
- dissolve: Whether to dissolve geometries
File Operation Parameters
- output_path: Target file path
- file_format: Output format (parquet, csv)
- coalesce: Number of partitions for output
- path_pattern: File pattern for glob matching
Data Flow
Input Data
- Geographic Boundaries: Output area boundaries and tile boundaries
- VOM Data: Raster file paths and metadata
- Tree Data: Vector file paths and metadata
- Building Data: Building geometries and attributes
Processing Steps
- Tile Name Translation: Converts between naming formats
- Spatial Filtering: Extracts relevant geographic areas
- Path Generation: Creates file paths for data access
- Geometry Operations: Performs spatial analysis
- File Conversion: Converts between file formats
Output Data
- Translated Names: Tile names in target format
- Filtered Geometries: Spatial data for specific areas
- File Paths: Organized paths for data access
- Converted Files: Data in target format
Performance Optimizations
Spatial Operations
- Spatial Indexing: Uses spatial indices for efficient queries
- Partitioning: Distributes processing across cluster nodes
- Caching: Caches frequently accessed geometries
- Batch Processing: Processes multiple areas efficiently
File Operations
- Coalescing: Reduces number of output files
- Compression: Uses efficient file compression
- Parallel Processing: Processes files in parallel
- Memory Management: Optimizes memory usage for large files
Error Handling
The module includes comprehensive error handling for:
- Invalid tile names: Validates tile name format and length
- Missing files: Handles missing data files gracefully
- Spatial errors: Manages spatial operation failures
- File system issues: Handles file permission and path issues
- Memory errors: Manages large dataset memory requirements
Dependencies
This module requires:
pandas
for data manipulationgeopandas
for spatial data handlingpyspark
for distributed processingpathlib
for cross-platform path handlingtempfile
for temporary file managementshutil
for file operations
Notes
- The module provides standardized data processing utilities
- All spatial operations use the project's coordinate reference system
- Tile name translation supports OS (Ordnance Survey) conventions
- File operations are optimized for large-scale processing
- The module includes comprehensive error handling and validation
- Supports both local and distributed processing scenarios
- Maintains data integrity throughout processing pipeline