Skip to content

Raster to DGGS

Raster to DGGS conversion functions.

This submodule provides functions to convert raster data to various discrete global grid systems (DGGS).

raster2olc_cli()

Command line interface for raster to OLC conversion

Source code in vgrid/conversion/raster2dggs/raster2olc.py
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
def raster2olc_cli():
    """Command line interface for raster to OLC conversion"""
    parser = argparse.ArgumentParser(
        description="Convert Raster in Geographic CRS to OLC/ Google Plus Code DGGS"
    )
    parser.add_argument("-raster", type=str, required=True, help="Raster file path")

    parser.add_argument(
        "-r",
        "--resolution",
        type=int,
        required=False,
        choices=olc_resolutions,
        default=None,
        help="OLC resolution",
    )

    parser.add_argument(
        "-f",
        "--output_format",
        type=str,
        choices=OUTPUT_FORMATS,
        default="gpd",
    )
    parser.add_argument(
        "-m",
        "--method",
        type=str,
        choices=RASTER2DGGS_METHODS,
        default="binning",
        help="binning: aggregate pixels into OLC cells; nearest_neighbour: nearest pixel center",
    )
    parser.add_argument(
        "-s",
        "--stats",
        type=str,
        choices=RASTER_STATS_OPTIONS,
        default="mean",
        help="Band statistic for binning method only",
    )

    args = parser.parse_args()
    if not os.path.exists(args.raster):
        print(f"Error: The file {args.raster} does not exist.")
        return

    result = raster2olc(
        args.raster,
        args.resolution,
        args.output_format,
        method=args.method,
        stats=args.stats,
    )
    if args.output_format in STRUCTURED_FORMATS:
        print(result)

raster2qtm_cli()

Command line interface for raster2qtm conversion

Source code in vgrid/conversion/raster2dggs/raster2qtm.py
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
def raster2qtm_cli():
    """Command line interface for raster2qtm conversion"""
    parser = argparse.ArgumentParser(
        description="Convert Raster in Geographic CRS to QTM DGGS"
    )
    parser.add_argument("-raster", type=str, required=True, help="Raster file path")
    parser.add_argument(
        "-r",
        "--resolution",
        type=int,
        required=False,
        default=None,
        help=f"QTM resolution [{min_res}..{max_res}]",
    )
    parser.add_argument(
        "-f",
        "--output_format",
        type=str,
        choices=OUTPUT_FORMATS,
        default="gpd",
    )
    parser.add_argument(
        "-m",
        "--method",
        type=str,
        choices=RASTER2DGGS_METHODS,
        default="binning",
        help="binning: aggregate pixels into QTM cells; nearest_neighbour: nearest pixel center",
    )
    parser.add_argument(
        "-s",
        "--stats",
        type=str,
        choices=RASTER_STATS_OPTIONS,
        default="mean",
        help="Band statistic for binning method only",
    )

    args = parser.parse_args()
    if not os.path.exists(args.raster):
        print(f"Error: The file {args.raster} does not exist.")
        return

    result = raster2qtm(
        args.raster,
        args.resolution,
        args.output_format,
        method=args.method,
        stats=args.stats,
    )
    if args.output_format in STRUCTURED_FORMATS:
        print(result)

raster2rhealpix_cli()

Command line interface for raster2rhealpix

Source code in vgrid/conversion/raster2dggs/raster2rhealpix.py
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
def raster2rhealpix_cli():
    """Command line interface for raster2rhealpix"""
    parser = argparse.ArgumentParser(
        description="Convert Raster in Geographic CRS to rHEALPix DGGS"
    )
    parser.add_argument("-raster", type=str, required=True, help="Raster file path")
    parser.add_argument(
        "-r",
        "--resolution",
        type=int,
        required=False,
        default=None,
        help=f"rHEALPix resolution [{min_res}..{max_res}]. Required when topology=False, auto-calculated when topology=True",
    )
    parser.add_argument(
        "-f",
        "--output_format",
        type=str,
        choices=OUTPUT_FORMATS,
        default="gpd",
    )

    parser.add_argument(
        "-m",
        "--method",
        type=str,
        choices=RASTER2DGGS_METHODS,
        default="binning",
        help="binning: aggregate pixels into rHEALPix cells; nearest_neighbour: nearest pixel center",
    )

    parser.add_argument(
        "-fix",
        "--fix_antimeridian",
        type=str,
        choices=[
            "shift",
            "shift_balanced",
            "shift_west",
            "shift_east",
            "split",
            "none",
        ],
        default=None,
        help="Antimeridian fixing method: shift, shift_balanced, shift_west, shift_east, split, none",
    )
    parser.add_argument(
        "-s",
        "--stats",
        type=str,
        choices=RASTER_STATS_OPTIONS,
        default="mean",
        help="Band statistic for binning method only",
    )
    args = parser.parse_args()
    if not os.path.exists(args.raster):
        raise FileNotFoundError(f"The file {args.raster} does not exist.")

    result = raster2rhealpix(
        args.raster,
        args.resolution,
        args.output_format,
        fix_antimeridian=args.fix_antimeridian,
        method=args.method,
        stats=args.stats,
    )
    if args.output_format in STRUCTURED_FORMATS:
        print(result)

Raster to H3 Module

Convert raster data to H3 DGGS using either:

  • binning — pixel centroids are aggregated into H3 cells (stats required).
  • nearest_neighbour — H3 grid over the raster bbox; each cell takes the value of the nearest raster pixel center (LAEA planar distance).

get_nearest_h3_resolution(raster_path)

Automatically determine the optimal H3 resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate H3 resolution that best matches the raster's spatial resolution.

Source code in vgrid/conversion/raster2dggs/raster2h3.py
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
def get_nearest_h3_resolution(raster_path):
    """
    Automatically determine the optimal H3 resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate H3 resolution
    that best matches the raster's spatial resolution.
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. H3 conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            meter_per_degree_lat = 111_320
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))
            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        avg_area = h3.average_hexagon_area(res, unit="m^2")
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2h3(raster_path, resolution=None, output_format='gpd', fix_antimeridian=None, method='binning', stats='mean')

Convert raster data to H3 DGGS format.

Parameters

raster_path : str Path to the raster file (must have a defined CRS). resolution : int, optional H3 resolution [0..15]. If None, matched to pixel size. output_format : str, optional See :func:~vgrid.utils.io.convert_to_output_format. fix_antimeridian : str, optional Passed to H3 grid / geometry builders. method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation when multiple pixels map to one H3 cell (see RASTER_STATS_OPTIONS). Ignored for nearest_neighbour.

Source code in vgrid/conversion/raster2dggs/raster2h3.py
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
def raster2h3(
    raster_path,
    resolution=None,
    output_format="gpd",
    fix_antimeridian=None,
    method="binning",
    stats="mean",
):
    """
    Convert raster data to H3 DGGS format.

    Parameters
    ----------
    raster_path : str
        Path to the raster file (must have a defined CRS).
    resolution : int, optional
        H3 resolution [0..15]. If None, matched to pixel size.
    output_format : str, optional
        See :func:`~vgrid.utils.io.convert_to_output_format`.
    fix_antimeridian : str, optional
        Passed to H3 grid / geometry builders.
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation when multiple pixels map
        to one H3 cell (see ``RASTER_STATS_OPTIONS``). Ignored for ``nearest_neighbour``.
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_h3_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"H3 resolution: {resolution}")
    else:
        resolution = validate_h3_resolution(resolution)

    print(f"Method: {method}")

    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2h3_binning(
            raster_path, resolution, stats, fix_antimeridian=fix_antimeridian
        )
    else:
        gdf = _raster2h3_nearest_neighbour(
            raster_path, resolution, fix_antimeridian=fix_antimeridian
        )

    if gdf.empty:
        raise ValueError("No H3 cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2h3" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to S2 Module

This module provides functionality to convert raster data to S2 DGGS format with automatic resolution determination and multi-band support.

Key Functions

get_nearest_s2_resolution(raster_path)

Automatically determine the optimal S2 resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate S2 resolution that best matches the raster's spatial resolution.

Parameters

raster_path : str Path to the raster file to analyze.

Returns

tuple A tuple containing (cell_size, resolution) where: - cell_size: The calculated cell size in square meters - resolution: The optimal S2 resolution level

Examples

cell_size, resolution = get_nearest_s2_resolution("data.tif") print(f"Cell size: {cell_size} m², Resolution: {resolution}") Cell size: 1000000.0 m², Resolution: 5

Source code in vgrid/conversion/raster2dggs/raster2s2.py
 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
def get_nearest_s2_resolution(raster_path):
    """
    Automatically determine the optimal S2 resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate S2 resolution
    that best matches the raster's spatial resolution.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to analyze.

    Returns
    -------
    tuple
        A tuple containing (cell_size, resolution) where:
        - cell_size: The calculated cell size in square meters
        - resolution: The optimal S2 resolution level

    Examples
    --------
    >>> cell_size, resolution = get_nearest_s2_resolution("data.tif")
    >>> print(f"Cell size: {cell_size} m², Resolution: {resolution}")
    Cell size: 1000000.0 m², Resolution: 5
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. S2 conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            # Latitude of the raster center
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            # Convert degrees to meters
            meter_per_degree_lat = 111_320  # Roughly 1 degree latitude in meters
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))

            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    # Check resolutions from 0 to 15
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = s2_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        # If the difference is smaller than the current minimum, update the nearest resolution
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2s2(raster_path, resolution=None, output_format='gpd', fix_antimeridian=None, method='binning', stats='mean')

Convert raster data to S2 DGGS format.

Converts raster data to S2 DGGS format with automatic resolution determination and multi-band support. Each pixel is assigned to an S2 cell and the first sample value per cell is preserved.

Parameters

raster_path : str Path to the raster file to convert. resolution : int, optional S2 resolution level. If None, automatically determined based on raster pixel size. Valid range: 0-30. output_format : str, default "gpd" Output format. Options: - "gpd": Returns GeoPandas GeoDataFrame (default) - "csv": Returns CSV file path - "geojson": Returns GeoJSON file path - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict - "parquet": Returns Parquet file path - "shapefile"/"shp": Returns Shapefile file path - "gpkg"/"geopackage": Returns GeoPackage file path fix_antimeridian : str, optional Antimeridian fixing method: shift, shift_balanced, shift_west, shift_east, split, none Defaults to None when omitted. method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation (see RASTER_STATS_OPTIONS). Returns


geopandas.GeoDataFrame or str or dict The converted data in the specified format. Each row represents an S2 cell with geometry and band values from the original raster.

Examples

Convert with automatic resolution

result = raster2s2("data.tif") print(f"Converted {len(result)} S2 cells")

Convert with specific resolution

result = raster2s2("data.tif", resolution=10)

Convert to GeoJSON file

result = raster2s2("data.tif", output_format="geojson") print(f"Saved to: {result}")

Source code in vgrid/conversion/raster2dggs/raster2s2.py
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
def raster2s2(
    raster_path,
    resolution=None,
    output_format="gpd",
    fix_antimeridian=None,
    method="binning",
    stats="mean",
):
    """
    Convert raster data to S2 DGGS format.

    Converts raster data to S2 DGGS format with automatic resolution
    determination and multi-band support. Each pixel is assigned to an S2 cell and
    the first sample value per cell is preserved.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to convert.
    resolution : int, optional
        S2 resolution level. If None, automatically determined based on raster pixel size.
        Valid range: 0-30.
    output_format : str, default "gpd"
        Output format. Options:
        - "gpd": Returns GeoPandas GeoDataFrame (default)
        - "csv": Returns CSV file path
        - "geojson": Returns GeoJSON file path
        - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict
        - "parquet": Returns Parquet file path
        - "shapefile"/"shp": Returns Shapefile file path
        - "gpkg"/"geopackage": Returns GeoPackage file path
    fix_antimeridian : str, optional
        Antimeridian fixing method: shift, shift_balanced, shift_west, shift_east, split, none
        Defaults to None when omitted.
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation (see ``RASTER_STATS_OPTIONS``).
    Returns
    -------
    geopandas.GeoDataFrame or str or dict
        The converted data in the specified format. Each row represents an S2 cell
        with geometry and band values from the original raster.

    Examples
    --------
    >>> # Convert with automatic resolution
    >>> result = raster2s2("data.tif")
    >>> print(f"Converted {len(result)} S2 cells")

    >>> # Convert with specific resolution
    >>> result = raster2s2("data.tif", resolution=10)

    >>> # Convert to GeoJSON file
    >>> result = raster2s2("data.tif", output_format="geojson")
    >>> print(f"Saved to: {result}")
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_s2_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest S2 resolution determined: {resolution}")
    else:
        resolution = validate_s2_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2s2_binning(
            raster_path, resolution, stats, fix_antimeridian=fix_antimeridian
        )
    else:
        gdf = _raster2s2_nearest_neighbour(
            raster_path, resolution, fix_antimeridian=fix_antimeridian
        )

    if gdf.empty:
        raise ValueError("No S2 cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2s2" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to A5 Module

This module provides functionality to convert raster data to A5 DGGS format with automatic resolution determination and multi-band support.

Key Functions

get_nearest_a5_resolution(raster_path)

Automatically determine the optimal A5 resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate A5 resolution that best matches the raster's spatial resolution.

Parameters

raster_path : str Path to the raster file to analyze.

Returns

tuple A tuple containing (cell_size, resolution) where: - cell_size: The calculated cell size in square meters - resolution: The optimal A5 resolution level

Examples

cell_size, resolution = get_nearest_a5_resolution("data.tif") print(f"Cell size: {cell_size} m², Resolution: {resolution}") Cell size: 1000000.0 m², Resolution: 5

Source code in vgrid/conversion/raster2dggs/raster2a5.py
 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
def get_nearest_a5_resolution(raster_path):
    """
    Automatically determine the optimal A5 resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate A5 resolution
    that best matches the raster's spatial resolution.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to analyze.

    Returns
    -------
    tuple
        A tuple containing (cell_size, resolution) where:
        - cell_size: The calculated cell size in square meters
        - resolution: The optimal A5 resolution level

    Examples
    --------
    >>> cell_size, resolution = get_nearest_a5_resolution("data.tif")
    >>> print(f"Cell size: {cell_size} m², Resolution: {resolution}")
    Cell size: 1000000.0 m², Resolution: 5
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. A5 conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            # Latitude of the raster center
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            # Convert degrees to meters
            meter_per_degree_lat = 111_320  # Roughly 1 degree latitude in meters
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))

            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res
    for res in range(min_res, max_res + 1):
        avg_area = cell_area(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        # If the difference is smaller than the current minimum, update the nearest resolution
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2a5(raster_path, resolution=None, output_format='gpd', options=None, split_antimeridian=False, method='binning', stats='mean')

Convert raster data to A5 DGGS format.

Converts raster data to A5 (Adaptive 5) DGGS format with automatic resolution determination and multi-band support.

Parameters

raster_path : str Path to the raster file to convert. resolution : int, optional A5 resolution level. If None, automatically determined based on raster pixel size. Valid range: 0-15. output_format : str, default "gpd" Output format. Options: - "gpd": Returns GeoPandas GeoDataFrame (default) - "csv": Returns CSV file path - "geojson": Returns GeoJSON file path - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict - "parquet": Returns Parquet file path - "shapefile"/"shp": Returns Shapefile file path - "gpkg"/"geopackage": Returns GeoPackage file path options : dict, optional Options for a52geo. split_antimeridian : bool, optional When True, apply antimeridian fixing to the resulting polygons. Defaults to False when None or omitted. method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation (see RASTER_STATS_OPTIONS). Returns


geopandas.GeoDataFrame or str or dict The converted data in the specified format. Each row represents an A5 cell with geometry and band values from the original raster.

Examples

Convert with automatic resolution

result = raster2a5("data.tif") print(f"Converted {len(result)} A5 cells")

Convert with specific resolution

result = raster2a5("data.tif", resolution=5)

Convert to GeoJSON file

result = raster2a5("data.tif", output_format="geojson") print(f"Saved to: {result}")

Source code in vgrid/conversion/raster2dggs/raster2a5.py
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
def raster2a5(
    raster_path,
    resolution=None,
    output_format="gpd",
    options=None,
    split_antimeridian=False,
    method="binning",
    stats="mean",
):
    """
    Convert raster data to A5 DGGS format.

    Converts raster data to A5 (Adaptive 5) DGGS format with automatic resolution
    determination and multi-band support.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to convert.
    resolution : int, optional
        A5 resolution level. If None, automatically determined based on raster pixel size.
        Valid range: 0-15.
    output_format : str, default "gpd"
        Output format. Options:
        - "gpd": Returns GeoPandas GeoDataFrame (default)
        - "csv": Returns CSV file path
        - "geojson": Returns GeoJSON file path
        - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict
        - "parquet": Returns Parquet file path
        - "shapefile"/"shp": Returns Shapefile file path
        - "gpkg"/"geopackage": Returns GeoPackage file path
    options : dict, optional
        Options for a52geo.
    split_antimeridian : bool, optional
        When True, apply antimeridian fixing to the resulting polygons.
        Defaults to False when None or omitted.
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation (see ``RASTER_STATS_OPTIONS``).
    Returns
    -------
    geopandas.GeoDataFrame or str or dict
        The converted data in the specified format. Each row represents an A5 cell
        with geometry and band values from the original raster.

    Examples
    --------
    >>> # Convert with automatic resolution
    >>> result = raster2a5("data.tif")
    >>> print(f"Converted {len(result)} A5 cells")

    >>> # Convert with specific resolution
    >>> result = raster2a5("data.tif", resolution=5)

    >>> # Convert to GeoJSON file
    >>> result = raster2a5("data.tif", output_format="geojson")
    >>> print(f"Saved to: {result}")
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_a5_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest A5 resolution determined: {resolution}")
    else:
        resolution = validate_a5_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2a5_binning(
            raster_path,
            resolution,
            stats,
            options=options,
            split_antimeridian=split_antimeridian,
        )
    else:
        gdf = _raster2a5_nearest_neighbour(
            raster_path,
            resolution,
            options=options,
            split_antimeridian=split_antimeridian,
        )

    if gdf.empty:
        raise ValueError("No A5 cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2a5" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to RHEALPix Module

This module provides functionality to convert raster data to RHEALPix (Rectified HEALPix) DGGS format with automatic resolution determination and multi-band support.

Key Functions

get_nearest_rhealpix_resolution(raster_path)

Automatically determine the optimal RHEALPix resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate RHEALPix resolution that best matches the raster's spatial resolution.

Parameters

raster_path : str Path to the raster file to analyze.

Returns

tuple A tuple containing (cell_size, resolution) where: - cell_size: The calculated cell size in square meters - resolution: The optimal RHEALPix resolution level

Examples

cell_size, resolution = get_nearest_rhealpix_resolution("data.tif") print(f"Cell size: {cell_size} m², Resolution: {resolution}") Cell size: 1000000.0 m², Resolution: 5

Source code in vgrid/conversion/raster2dggs/raster2rhealpix.py
 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
def get_nearest_rhealpix_resolution(raster_path):
    """
    Automatically determine the optimal RHEALPix resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate RHEALPix resolution
    that best matches the raster's spatial resolution.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to analyze.

    Returns
    -------
    tuple
        A tuple containing (cell_size, resolution) where:
        - cell_size: The calculated cell size in square meters
        - resolution: The optimal RHEALPix resolution level

    Examples
    --------
    >>> cell_size, resolution = get_nearest_rhealpix_resolution("data.tif")
    >>> print(f"Cell size: {cell_size} m², Resolution: {resolution}")
    Cell size: 1000000.0 m², Resolution: 5
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. rHEALPix conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            # Latitude of the raster center
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            # Convert degrees to meters
            meter_per_degree_lat = 111_320  # Roughly 1 degree latitude in meters
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))

            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = rhealpix_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        # If the difference is smaller than the current minimum, update the nearest resolution
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2rhealpix(raster_path, resolution=None, output_format='gpd', fix_antimeridian=None, method='binning', stats='mean')

Convert raster data to RHEALPix DGGS format.

Converts raster data to RHEALPix (Rectified HEALPix) DGGS format with automatic resolution determination and multi-band support.

Parameters

raster_path : str Path to the raster file to convert. resolution : int, optional RHEALPix resolution level. If None, automatically determined based on raster pixel size. Valid range: 0-30. output_format : str, default "gpd" Output format. Options: - "gpd": Returns GeoPandas GeoDataFrame (default) - "csv": Returns CSV file path - "geojson": Returns GeoJSON file path - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict - "parquet": Returns Parquet file path - "shapefile"/"shp": Returns Shapefile file path - "gpkg"/"geopackage": Returns GeoPackage file path fix_antimeridian : str, optional Antimeridian fixing method: shift, shift_balanced, shift_west, shift_east, split, none method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation (see RASTER_STATS_OPTIONS).

Returns

geopandas.GeoDataFrame or str or dict The converted data in the specified format. Each row represents a RHEALPix cell with geometry and band values from the original raster.

Examples

Convert with automatic resolution

result = raster2rhealpix("data.tif") print(f"Converted {len(result)} RHEALPix cells")

Convert with specific resolution

result = raster2rhealpix("data.tif", resolution=10)

Convert to GeoJSON file

result = raster2rhealpix("data.tif", output_format="geojson") print(f"Saved to: {result}")

Source code in vgrid/conversion/raster2dggs/raster2rhealpix.py
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
def raster2rhealpix(
    raster_path,
    resolution=None,
    output_format="gpd",
    fix_antimeridian=None,
    method="binning",
    stats="mean",
):
    """
    Convert raster data to RHEALPix DGGS format.

    Converts raster data to RHEALPix (Rectified HEALPix) DGGS format with automatic resolution
    determination and multi-band support.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to convert.
    resolution : int, optional
        RHEALPix resolution level. If None, automatically determined based on raster pixel size.
        Valid range: 0-30.
    output_format : str, default "gpd"
        Output format. Options:
        - "gpd": Returns GeoPandas GeoDataFrame (default)
        - "csv": Returns CSV file path
        - "geojson": Returns GeoJSON file path
        - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict
        - "parquet": Returns Parquet file path
        - "shapefile"/"shp": Returns Shapefile file path
        - "gpkg"/"geopackage": Returns GeoPackage file path
    fix_antimeridian : str, optional
        Antimeridian fixing method: shift, shift_balanced, shift_west, shift_east, split, none
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation (see ``RASTER_STATS_OPTIONS``).

    Returns
    -------
    geopandas.GeoDataFrame or str or dict
        The converted data in the specified format. Each row represents a RHEALPix cell
        with geometry and band values from the original raster.

    Examples
    --------
    >>> # Convert with automatic resolution
    >>> result = raster2rhealpix("data.tif")
    >>> print(f"Converted {len(result)} RHEALPix cells")

    >>> # Convert with specific resolution
    >>> result = raster2rhealpix("data.tif", resolution=10)

    >>> # Convert to GeoJSON file
    >>> result = raster2rhealpix("data.tif", output_format="geojson")
    >>> print(f"Saved to: {result}")
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_rhealpix_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest rHEALPix resolution determined: {resolution}")
    else:
        resolution = validate_rhealpix_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2rhealpix_binning(
            raster_path, resolution, stats, fix_antimeridian=fix_antimeridian
        )
    else:
        gdf = _raster2rhealpix_nearest_neighbour(
            raster_path, resolution, fix_antimeridian=fix_antimeridian
        )

    if gdf.empty:
        raise ValueError("No rHEALPix cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2rhealpix" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

raster2rhealpix_cli()

Command line interface for raster2rhealpix

Source code in vgrid/conversion/raster2dggs/raster2rhealpix.py
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
def raster2rhealpix_cli():
    """Command line interface for raster2rhealpix"""
    parser = argparse.ArgumentParser(
        description="Convert Raster in Geographic CRS to rHEALPix DGGS"
    )
    parser.add_argument("-raster", type=str, required=True, help="Raster file path")
    parser.add_argument(
        "-r",
        "--resolution",
        type=int,
        required=False,
        default=None,
        help=f"rHEALPix resolution [{min_res}..{max_res}]. Required when topology=False, auto-calculated when topology=True",
    )
    parser.add_argument(
        "-f",
        "--output_format",
        type=str,
        choices=OUTPUT_FORMATS,
        default="gpd",
    )

    parser.add_argument(
        "-m",
        "--method",
        type=str,
        choices=RASTER2DGGS_METHODS,
        default="binning",
        help="binning: aggregate pixels into rHEALPix cells; nearest_neighbour: nearest pixel center",
    )

    parser.add_argument(
        "-fix",
        "--fix_antimeridian",
        type=str,
        choices=[
            "shift",
            "shift_balanced",
            "shift_west",
            "shift_east",
            "split",
            "none",
        ],
        default=None,
        help="Antimeridian fixing method: shift, shift_balanced, shift_west, shift_east, split, none",
    )
    parser.add_argument(
        "-s",
        "--stats",
        type=str,
        choices=RASTER_STATS_OPTIONS,
        default="mean",
        help="Band statistic for binning method only",
    )
    args = parser.parse_args()
    if not os.path.exists(args.raster):
        raise FileNotFoundError(f"The file {args.raster} does not exist.")

    result = raster2rhealpix(
        args.raster,
        args.resolution,
        args.output_format,
        fix_antimeridian=args.fix_antimeridian,
        method=args.method,
        stats=args.stats,
    )
    if args.output_format in STRUCTURED_FORMATS:
        print(result)

Raster to DGGAL Module

Convert raster data to DGGAL DGGS using either binning or nearest-neighbour assignment.

get_nearest_dggal_resolution(dggs_type, raster_path)

Automatically determine the optimal DGGAL resolution for a given raster.

Source code in vgrid/conversion/raster2dggs/raster2dggal.py
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
def get_nearest_dggal_resolution(dggs_type, raster_path):
    """Automatically determine the optimal DGGAL resolution for a given raster."""
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. DGGAL conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            meter_per_degree_lat = 111_320
            meter_per_degree_lon = meter_per_degree_lat * math.cos(
                math.radians(center_latitude)
            )
            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    min_res = int(DGGAL_TYPES[dggs_type]["min_res"])
    max_res = int(DGGAL_TYPES[dggs_type]["max_res"])
    nearest_resolution = min_res
    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = dggal_metrics(dggs_type, res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = math.fabs(avg_area - cell_size)
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2dggal(dggs_type, raster_path, resolution=None, output_format='gpd', split_antimeridian=False, method='binning', stats='mean')

Convert raster data to DGGAL DGGS format.

Parameters

method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning" (see RASTER_STATS_OPTIONS).

Source code in vgrid/conversion/raster2dggs/raster2dggal.py
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
def raster2dggal(
    dggs_type: str,
    raster_path,
    resolution: int | None = None,
    output_format: str = "gpd",
    split_antimeridian: bool = False,
    method: str = "binning",
    stats: str = "mean",
):
    """
    Convert raster data to DGGAL DGGS format.

    Parameters
    ----------
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"`` (see ``RASTER_STATS_OPTIONS``).
    """
    dggs_type = validate_dggal_type(dggs_type)
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_dggal_resolution(dggs_type, raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest {dggs_type.upper()} resolution determined: {resolution}")
    else:
        resolution = validate_dggal_resolution(dggs_type, resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2dggal_binning(
            dggs_type,
            raster_path,
            resolution,
            stats,
            split_antimeridian=split_antimeridian,
        )
    else:
        gdf = _raster2dggal_nearest_neighbour(
            dggs_type,
            raster_path,
            resolution,
            split_antimeridian=split_antimeridian,
        )

    if gdf.empty:
        raise ValueError("No DGGAL cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2dggal" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to DGGRID Module

Convert raster data to DGGRID DGGS using either binning or nearest-neighbour assignment.

get_nearest_dggrid_resolution(dggrid_instance, dggs_type, raster_path)

Automatically determine the optimal DGGRID resolution for a given raster.

Source code in vgrid/conversion/raster2dggs/raster2dggrid.py
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
def get_nearest_dggrid_resolution(dggrid_instance, dggs_type, raster_path):
    """Automatically determine the optimal DGGRID resolution for a given raster."""
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. DGGRID conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            meter_per_degree_lat = 111_320
            meter_per_degree_lon = meter_per_degree_lat * math.cos(
                math.radians(center_latitude)
            )
            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    min_res = int(DGGRID_TYPES[dggs_type]["min_res"])
    max_res = int(DGGRID_TYPES[dggs_type]["max_res"])
    nearest_resolution = min_res

    try:
        grid_stats = dggridstats(dggrid_instance, dggs_type, unit="m")
        for res in range(min_res, max_res + 1):
            res_stats = grid_stats[grid_stats["resolution"] == res]
            if res_stats.empty:
                continue
            avg_area_m2 = res_stats["area_m2"].iloc[0]
            if avg_area_m2 < MIN_CELL_AREA:
                break
            diff = math.fabs(avg_area_m2 - cell_size)
            if diff < min_diff:
                min_diff = diff
                nearest_resolution = res
    except Exception:
        nearest_resolution = min_res

    return cell_size, nearest_resolution

raster2dggrid(dggrid_instance, dggs_type, raster_path, resolution=None, output_format='gpd', split_antimeridian=False, aggregate=False, options=None, method='binning', stats='mean')

Convert raster data to DGGRID DGGS format.

Parameters

method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning" (see RASTER_STATS_OPTIONS).

Source code in vgrid/conversion/raster2dggs/raster2dggrid.py
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
def raster2dggrid(
    dggrid_instance,
    dggs_type: str,
    raster_path,
    resolution: int | None = None,
    output_format: str = "gpd",
    split_antimeridian: bool = False,
    aggregate: bool = False,
    options=None,
    method: str = "binning",
    stats: str = "mean",
):
    """
    Convert raster data to DGGRID DGGS format.

    Parameters
    ----------
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"`` (see ``RASTER_STATS_OPTIONS``).
    """
    dggs_type = validate_dggrid_type(dggs_type)
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_dggrid_resolution(
            dggrid_instance, dggs_type, raster_path
        )
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest {dggs_type.upper()} resolution determined: {resolution}")
    else:
        resolution = validate_dggrid_resolution(dggs_type, resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2dggrid_binning(
            dggrid_instance,
            dggs_type,
            raster_path,
            resolution,
            stats,
            split_antimeridian=split_antimeridian,
            aggregate=aggregate,
            options=options,
        )
    else:
        gdf = _raster2dggrid_nearest_neighbour(
            dggrid_instance,
            dggs_type,
            raster_path,
            resolution,
            split_antimeridian=split_antimeridian,
        )

    if gdf.empty:
        raise ValueError("No DGGRID cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2dggrid" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to ISEA4T Module

Convert raster data to ISEA4T DGGS using either binning or nearest-neighbour assignment.

Note: This module is only supported on Windows systems due to OpenEaggr dependency.

get_nearest_isea4t_resolution(raster_path)

Automatically determine the optimal ISEA4T resolution for a given raster.

Source code in vgrid/conversion/raster2dggs/raster2isea4t.py
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
def get_nearest_isea4t_resolution(raster_path):
    """Automatically determine the optimal ISEA4T resolution for a given raster."""
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. ISEA4T conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            meter_per_degree_lat = 111_320
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))
            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = isea4t_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2isea4t(raster_path, resolution=None, output_format='gpd', fix_antimeridian=None, method='binning', stats='mean')

Convert raster data to ISEA4T DGGS format.

Parameters

method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning" (see RASTER_STATS_OPTIONS).

Source code in vgrid/conversion/raster2dggs/raster2isea4t.py
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
def raster2isea4t(
    raster_path,
    resolution=None,
    output_format="gpd",
    fix_antimeridian=None,
    method="binning",
    stats="mean",
):
    """
    Convert raster data to ISEA4T DGGS format.

    Parameters
    ----------
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"`` (see ``RASTER_STATS_OPTIONS``).
    """
    _require_windows()
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_isea4t_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest ISEA4T resolution determined: {resolution}")
    else:
        resolution = validate_isea4t_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2isea4t_binning(
            raster_path, resolution, stats, fix_antimeridian=fix_antimeridian
        )
    else:
        gdf = _raster2isea4t_nearest_neighbour(
            raster_path, resolution, fix_antimeridian=fix_antimeridian
        )

    if gdf.empty:
        raise ValueError("No ISEA4T cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2isea4t" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to QTM Module

This module provides functionality to convert raster data to QTM (Quaternary Triangular Mesh) DGGS format with automatic resolution determination and multi-band support.

Key Functions

get_nearest_qtm_resolution(raster_path)

Automatically determine the optimal QTM resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate QTM resolution that best matches the raster's spatial resolution.

Parameters

raster_path : str Path to the raster file to analyze.

Returns

tuple A tuple containing (cell_size, resolution) where: - cell_size: The calculated cell size in square meters - resolution: The optimal QTM resolution level

Examples

cell_size, resolution = get_nearest_qtm_resolution("data.tif") print(f"Cell size: {cell_size} m², Resolution: {resolution}") Cell size: 1000000.0 m², Resolution: 5

Source code in vgrid/conversion/raster2dggs/raster2qtm.py
 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
def get_nearest_qtm_resolution(raster_path):
    """
    Automatically determine the optimal QTM resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate QTM resolution
    that best matches the raster's spatial resolution.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to analyze.

    Returns
    -------
    tuple
        A tuple containing (cell_size, resolution) where:
        - cell_size: The calculated cell size in square meters
        - resolution: The optimal QTM resolution level

    Examples
    --------
    >>> cell_size, resolution = get_nearest_qtm_resolution("data.tif")
    >>> print(f"Cell size: {cell_size} m², Resolution: {resolution}")
    Cell size: 1000000.0 m², Resolution: 5
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError("Raster CRS is undefined. QTM conversion requires a valid CRS.")
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            # Latitude of the raster center
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            # Convert degrees to meters
            meter_per_degree_lat = 111_320  # Roughly 1 degree latitude in meters
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))

            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = qtm_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        # If the difference is smaller than the current minimum, update the nearest resolution
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2qtm(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to QTM DGGS format.

Converts raster data to QTM (Quaternary Triangular Mesh) DGGS format with automatic resolution determination and multi-band support. Each pixel is assigned to a QTM cell and the first sample value per cell is preserved.

Parameters

raster_path : str Path to the raster file to convert. resolution : int, optional QTM resolution level. If None, automatically determined based on raster pixel size. Valid range: 1-30. output_format : str, default "gpd" Output format. Options: - "gpd": Returns GeoPandas GeoDataFrame (default) - "csv": Returns CSV file path - "geojson": Returns GeoJSON file path - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict - "parquet": Returns Parquet file path - "shapefile"/"shp": Returns Shapefile file path - "gpkg"/"geopackage": Returns GeoPackage file path method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation (see RASTER_STATS_OPTIONS).

Returns

geopandas.GeoDataFrame or str or dict The converted data in the specified format. Each row represents a QTM cell with geometry and band values from the original raster.

Examples

Convert with automatic resolution

result = raster2qtm("data.tif") print(f"Converted {len(result)} QTM cells")

Convert with specific resolution

result = raster2qtm("data.tif", resolution=10)

Convert to GeoJSON file

result = raster2qtm("data.tif", output_format="geojson") print(f"Saved to: {result}")

Source code in vgrid/conversion/raster2dggs/raster2qtm.py
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
def raster2qtm(
    raster_path, resolution=None, output_format="gpd", method="binning", stats="mean"
):
    """
    Convert raster data to QTM DGGS format.

    Converts raster data to QTM (Quaternary Triangular Mesh) DGGS format with automatic resolution
    determination and multi-band support. Each pixel is assigned to a QTM cell and
    the first sample value per cell is preserved.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to convert.
    resolution : int, optional
        QTM resolution level. If None, automatically determined based on raster pixel size.
        Valid range: 1-30.
    output_format : str, default "gpd"
        Output format. Options:
        - "gpd": Returns GeoPandas GeoDataFrame (default)
        - "csv": Returns CSV file path
        - "geojson": Returns GeoJSON file path
        - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict
        - "parquet": Returns Parquet file path
        - "shapefile"/"shp": Returns Shapefile file path
        - "gpkg"/"geopackage": Returns GeoPackage file path
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation (see ``RASTER_STATS_OPTIONS``).

    Returns
    -------
    geopandas.GeoDataFrame or str or dict
        The converted data in the specified format. Each row represents a QTM cell
        with geometry and band values from the original raster.

    Examples
    --------
    >>> # Convert with automatic resolution
    >>> result = raster2qtm("data.tif")
    >>> print(f"Converted {len(result)} QTM cells")

    >>> # Convert with specific resolution
    >>> result = raster2qtm("data.tif", resolution=10)

    >>> # Convert to GeoJSON file
    >>> result = raster2qtm("data.tif", output_format="geojson")
    >>> print(f"Saved to: {result}")
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_qtm_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest QTM resolution determined: {resolution}")
    else:
        resolution = validate_qtm_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2qtm_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2qtm_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No QTM cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2qtm" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

raster2qtm_cli()

Command line interface for raster2qtm conversion

Source code in vgrid/conversion/raster2dggs/raster2qtm.py
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
def raster2qtm_cli():
    """Command line interface for raster2qtm conversion"""
    parser = argparse.ArgumentParser(
        description="Convert Raster in Geographic CRS to QTM DGGS"
    )
    parser.add_argument("-raster", type=str, required=True, help="Raster file path")
    parser.add_argument(
        "-r",
        "--resolution",
        type=int,
        required=False,
        default=None,
        help=f"QTM resolution [{min_res}..{max_res}]",
    )
    parser.add_argument(
        "-f",
        "--output_format",
        type=str,
        choices=OUTPUT_FORMATS,
        default="gpd",
    )
    parser.add_argument(
        "-m",
        "--method",
        type=str,
        choices=RASTER2DGGS_METHODS,
        default="binning",
        help="binning: aggregate pixels into QTM cells; nearest_neighbour: nearest pixel center",
    )
    parser.add_argument(
        "-s",
        "--stats",
        type=str,
        choices=RASTER_STATS_OPTIONS,
        default="mean",
        help="Band statistic for binning method only",
    )

    args = parser.parse_args()
    if not os.path.exists(args.raster):
        print(f"Error: The file {args.raster} does not exist.")
        return

    result = raster2qtm(
        args.raster,
        args.resolution,
        args.output_format,
        method=args.method,
        stats=args.stats,
    )
    if args.output_format in STRUCTURED_FORMATS:
        print(result)

Raster to OLC Module

This module provides functionality to convert raster data to OLC (Open Location Code) DGGS format with automatic resolution determination and multi-band support.

Key Functions

get_nearest_olc_resolution(raster_path)

Automatically determine the optimal OLC resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate OLC resolution that best matches the raster's spatial resolution.

Parameters

raster_path : str Path to the raster file to analyze.

Returns

tuple A tuple containing (cell_size, resolution) where: - cell_size: The calculated cell size in square meters - resolution: The optimal OLC resolution level

Examples

cell_size, resolution = get_nearest_olc_resolution("data.tif") print(f"Cell size: {cell_size} m², Resolution: {resolution}") Cell size: 1000000.0 m², Resolution: 8

Source code in vgrid/conversion/raster2dggs/raster2olc.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
def get_nearest_olc_resolution(raster_path):
    """
    Automatically determine the optimal OLC resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate OLC resolution
    that best matches the raster's spatial resolution.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to analyze.

    Returns
    -------
    tuple
        A tuple containing (cell_size, resolution) where:
        - cell_size: The calculated cell size in square meters
        - resolution: The optimal OLC resolution level

    Examples
    --------
    >>> cell_size, resolution = get_nearest_olc_resolution("data.tif")
    >>> print(f"Cell size: {cell_size} m², Resolution: {resolution}")
    Cell size: 1000000.0 m², Resolution: 8
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError("Raster CRS is undefined. OLC conversion requires a valid CRS.")
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            # Latitude of the raster center
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            # Convert degrees to meters
            meter_per_degree_lat = 111_320  # Roughly 1 degree latitude in meters
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))

            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    # Find the nearest s2 resolution by comparing the pixel size to the s2 edge lengths
    nearest_resolution = None
    min_diff = float("inf")

    for res in olc_resolutions:
        _, _, avg_area, _ = olc_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        # If the difference is smaller than the current minimum, update the nearest resolution
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2olc(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to OLC DGGS format.

Converts raster data to OLC (Open Location Code) DGGS format with automatic resolution determination and multi-band support. Each pixel is assigned to an OLC cell and the first sample value per cell is preserved.

Parameters

raster_path : str Path to the raster file to convert. resolution : int, optional OLC resolution level. If None, automatically determined based on raster pixel size. Valid values: see olc_resolutions in vgrid.utils.io. output_format : str, default "gpd" Output format. Options: - "gpd": Returns GeoPandas GeoDataFrame (default) - "csv": Returns CSV file path - "geojson": Returns GeoJSON file path - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict - "parquet": Returns Parquet file path - "shapefile"/"shp": Returns Shapefile file path - "gpkg"/"geopackage": Returns GeoPackage file path method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation (see RASTER_STATS_OPTIONS).

Returns

geopandas.GeoDataFrame or str or dict The converted data in the specified format. Each row represents an OLC cell with geometry and band values from the original raster.

Examples

Convert with automatic resolution

result = raster2olc("data.tif") print(f"Converted {len(result)} OLC cells")

Convert with specific resolution

result = raster2olc("data.tif", resolution=8)

Convert to GeoJSON file

result = raster2olc("data.tif", output_format="geojson") print(f"Saved to: {result}")

Source code in vgrid/conversion/raster2dggs/raster2olc.py
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
def raster2olc(
    raster_path, resolution=None, output_format="gpd", method="binning", stats="mean"
):
    """
    Convert raster data to OLC DGGS format.

    Converts raster data to OLC (Open Location Code) DGGS format with automatic resolution
    determination and multi-band support. Each pixel is assigned to an OLC cell and
    the first sample value per cell is preserved.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to convert.
    resolution : int, optional
        OLC resolution level. If None, automatically determined based on raster pixel size.
        Valid values: see ``olc_resolutions`` in ``vgrid.utils.io``.
    output_format : str, default "gpd"
        Output format. Options:
        - "gpd": Returns GeoPandas GeoDataFrame (default)
        - "csv": Returns CSV file path
        - "geojson": Returns GeoJSON file path
        - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict
        - "parquet": Returns Parquet file path
        - "shapefile"/"shp": Returns Shapefile file path
        - "gpkg"/"geopackage": Returns GeoPackage file path
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation (see ``RASTER_STATS_OPTIONS``).

    Returns
    -------
    geopandas.GeoDataFrame or str or dict
        The converted data in the specified format. Each row represents an OLC cell
        with geometry and band values from the original raster.

    Examples
    --------
    >>> # Convert with automatic resolution
    >>> result = raster2olc("data.tif")
    >>> print(f"Converted {len(result)} OLC cells")

    >>> # Convert with specific resolution
    >>> result = raster2olc("data.tif", resolution=8)

    >>> # Convert to GeoJSON file
    >>> result = raster2olc("data.tif", output_format="geojson")
    >>> print(f"Saved to: {result}")
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_olc_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest OLC resolution determined: {resolution}")
    else:
        resolution = validate_olc_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2olc_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2olc_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No OLC cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2olc" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

raster2olc_cli()

Command line interface for raster to OLC conversion

Source code in vgrid/conversion/raster2dggs/raster2olc.py
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
def raster2olc_cli():
    """Command line interface for raster to OLC conversion"""
    parser = argparse.ArgumentParser(
        description="Convert Raster in Geographic CRS to OLC/ Google Plus Code DGGS"
    )
    parser.add_argument("-raster", type=str, required=True, help="Raster file path")

    parser.add_argument(
        "-r",
        "--resolution",
        type=int,
        required=False,
        choices=olc_resolutions,
        default=None,
        help="OLC resolution",
    )

    parser.add_argument(
        "-f",
        "--output_format",
        type=str,
        choices=OUTPUT_FORMATS,
        default="gpd",
    )
    parser.add_argument(
        "-m",
        "--method",
        type=str,
        choices=RASTER2DGGS_METHODS,
        default="binning",
        help="binning: aggregate pixels into OLC cells; nearest_neighbour: nearest pixel center",
    )
    parser.add_argument(
        "-s",
        "--stats",
        type=str,
        choices=RASTER_STATS_OPTIONS,
        default="mean",
        help="Band statistic for binning method only",
    )

    args = parser.parse_args()
    if not os.path.exists(args.raster):
        print(f"Error: The file {args.raster} does not exist.")
        return

    result = raster2olc(
        args.raster,
        args.resolution,
        args.output_format,
        method=args.method,
        stats=args.stats,
    )
    if args.output_format in STRUCTURED_FORMATS:
        print(result)

Raster to Geohash Module

This module provides functionality to convert raster data to Geohash DGGS format with automatic resolution determination and multi-band support.

Key Functions

get_nearest_geohash_resolution(raster_path)

Automatically determine the optimal Geohash resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate Geohash resolution that best matches the raster's spatial resolution.

Parameters

raster_path : str Path to the raster file to analyze.

Returns

tuple A tuple containing (cell_size, resolution) where: - cell_size: The calculated cell size in square meters - resolution: The optimal Geohash resolution level

Examples

cell_size, resolution = get_nearest_geohash_resolution("data.tif") print(f"Cell size: {cell_size} m², Resolution: {resolution}") Cell size: 1000000.0 m², Resolution: 5

Source code in vgrid/conversion/raster2dggs/raster2geohash.py
 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
def get_nearest_geohash_resolution(raster_path):
    """
    Automatically determine the optimal Geohash resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate Geohash resolution
    that best matches the raster's spatial resolution.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to analyze.

    Returns
    -------
    tuple
        A tuple containing (cell_size, resolution) where:
        - cell_size: The calculated cell size in square meters
        - resolution: The optimal Geohash resolution level

    Examples
    --------
    >>> cell_size, resolution = get_nearest_geohash_resolution("data.tif")
    >>> print(f"Cell size: {cell_size} m², Resolution: {resolution}")
    Cell size: 1000000.0 m², Resolution: 5
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. Geohash conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            # Latitude of the raster center
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            # Convert degrees to meters
            meter_per_degree_lat = 111_320  # Roughly 1 degree latitude in meters
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))

            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = geohash_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        # If the difference is smaller than the current minimum, update the nearest resolution
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res
    return cell_size, nearest_resolution

raster2geohash(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to Geohash DGGS format.

Converts raster data to Geohash DGGS format with automatic resolution determination and multi-band support.

Parameters

raster_path : str Path to the raster file to convert. resolution : int, optional Geohash resolution level. If None, automatically determined based on raster pixel size. Valid range: 1-12. output_format : str, default "gpd" Output format. Options: - "gpd": Returns GeoPandas GeoDataFrame (default) - "csv": Returns CSV file path - "geojson": Returns GeoJSON file path - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict - "parquet": Returns Parquet file path - "shapefile"/"shp": Returns Shapefile file path - "gpkg"/"geopackage": Returns GeoPackage file path method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation (see RASTER_STATS_OPTIONS).

Returns

geopandas.GeoDataFrame or str or dict The converted data in the specified format. Each row represents a Geohash cell with geometry and band values from the original raster.

Examples

Convert with automatic resolution

result = raster2geohash("data.tif") print(f"Converted {len(result)} Geohash cells")

Convert with specific resolution

result = raster2geohash("data.tif", resolution=5)

Convert to GeoJSON file

result = raster2geohash("data.tif", output_format="geojson") print(f"Saved to: {result}")

Source code in vgrid/conversion/raster2dggs/raster2geohash.py
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
def raster2geohash(
    raster_path,
    resolution=None,
    output_format="gpd",
    method="binning",
    stats="mean",
):
    """
    Convert raster data to Geohash DGGS format.

    Converts raster data to Geohash DGGS format with automatic resolution
    determination and multi-band support.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to convert.
    resolution : int, optional
        Geohash resolution level. If None, automatically determined based on raster pixel size.
        Valid range: 1-12.
    output_format : str, default "gpd"
        Output format. Options:
        - "gpd": Returns GeoPandas GeoDataFrame (default)
        - "csv": Returns CSV file path
        - "geojson": Returns GeoJSON file path
        - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict
        - "parquet": Returns Parquet file path
        - "shapefile"/"shp": Returns Shapefile file path
        - "gpkg"/"geopackage": Returns GeoPackage file path
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation (see ``RASTER_STATS_OPTIONS``).

    Returns
    -------
    geopandas.GeoDataFrame or str or dict
        The converted data in the specified format. Each row represents a Geohash cell
        with geometry and band values from the original raster.

    Examples
    --------
    >>> # Convert with automatic resolution
    >>> result = raster2geohash("data.tif")
    >>> print(f"Converted {len(result)} Geohash cells")

    >>> # Convert with specific resolution
    >>> result = raster2geohash("data.tif", resolution=5)

    >>> # Convert to GeoJSON file
    >>> result = raster2geohash("data.tif", output_format="geojson")
    >>> print(f"Saved to: {result}")
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_geohash_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest Geohash resolution determined: {resolution}")
    else:
        resolution = validate_geohash_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2geohash_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2geohash_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No Geohash cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2geohash" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to GEOREF Module

Convert raster pixels to GEOREF cells using either binning or nearest-neighbour assignment.

get_nearest_georef_resolution(raster_path)

Pick a GEOREF resolution whose typical cell area is closest to the raster pixel area (m²).

Source code in vgrid/conversion/raster2dggs/raster2georef.py
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
def get_nearest_georef_resolution(raster_path):
    """Pick a GEOREF resolution whose typical cell area is closest to the raster pixel area (m²)."""
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. GEOREF conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            meter_per_degree_lat = 111_320
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))
            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = georef_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res
    return cell_size, nearest_resolution

raster2georef(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to GEOREF DGGS format.

Parameters

method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning" (see RASTER_STATS_OPTIONS).

Source code in vgrid/conversion/raster2dggs/raster2georef.py
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
def raster2georef(
    raster_path,
    resolution=None,
    output_format="gpd",
    method="binning",
    stats="mean",
):
    """
    Convert raster data to GEOREF DGGS format.

    Parameters
    ----------
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"`` (see ``RASTER_STATS_OPTIONS``).
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_georef_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest GEOREF resolution determined: {resolution}")
    else:
        resolution = validate_georef_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2georef_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2georef_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No GEOREF cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2georef" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to Tilecode Module

This module provides functionality to convert raster data to Tilecode DGGS format with automatic resolution determination and multi-band support.

Key Functions

get_nearest_tilecode_resolution(raster_path)

Automatically determine the optimal Tilecode resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate Tilecode resolution that best matches the raster's spatial resolution.

Parameters

raster_path : str Path to the raster file to analyze.

Returns

tuple A tuple containing (cell_size, resolution) where: - cell_size: The calculated cell size in square meters - resolution: The optimal Tilecode resolution level

Examples

cell_size, resolution = get_nearest_tilecode_resolution("data.tif") print(f"Cell size: {cell_size} m², Resolution: {resolution}") Cell size: 1000000.0 m², Resolution: 5

Source code in vgrid/conversion/raster2dggs/raster2tilecode.py
 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
def get_nearest_tilecode_resolution(raster_path):
    """
    Automatically determine the optimal Tilecode resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate Tilecode resolution
    that best matches the raster's spatial resolution.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to analyze.

    Returns
    -------
    tuple
        A tuple containing (cell_size, resolution) where:
        - cell_size: The calculated cell size in square meters
        - resolution: The optimal Tilecode resolution level

    Examples
    --------
    >>> cell_size, resolution = get_nearest_tilecode_resolution("data.tif")
    >>> print(f"Cell size: {cell_size} m², Resolution: {resolution}")
    Cell size: 1000000.0 m², Resolution: 5
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. Tilecode conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            # Latitude of the raster center
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            # Convert degrees to meters
            meter_per_degree_lat = 111_320  # Roughly 1 degree latitude in meters
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))

            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = tilecode_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        # If the difference is smaller than the current minimum, update the nearest resolution
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2tilecode(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to Tilecode DGGS format.

Converts raster data to Tilecode DGGS format with automatic resolution determination and multi-band support. Each pixel is assigned to a Tilecode cell and the first sample value per cell is preserved.

Parameters

raster_path : str Path to the raster file to convert. resolution : int, optional Tilecode resolution level. If None, automatically determined based on raster pixel size. Valid range: 0-26. output_format : str, default "gpd" Output format. Options: - "gpd": Returns GeoPandas GeoDataFrame (default) - "csv": Returns CSV file path - "geojson": Returns GeoJSON file path - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict - "parquet": Returns Parquet file path - "shapefile"/"shp": Returns Shapefile file path - "gpkg"/"geopackage": Returns GeoPackage file path method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation (see RASTER_STATS_OPTIONS).

Returns

geopandas.GeoDataFrame or str or dict The converted data in the specified format. Each row represents a Tilecode cell with geometry and band values from the original raster.

Examples

Convert with automatic resolution

result = raster2tilecode("data.tif") print(f"Converted {len(result)} Tilecode cells")

Convert with specific resolution

result = raster2tilecode("data.tif", resolution=10)

Convert to GeoJSON file

result = raster2tilecode("data.tif", output_format="geojson") print(f"Saved to: {result}")

Source code in vgrid/conversion/raster2dggs/raster2tilecode.py
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
def raster2tilecode(
    raster_path, resolution=None, output_format="gpd", method="binning", stats="mean"
):
    """
    Convert raster data to Tilecode DGGS format.

    Converts raster data to Tilecode DGGS format with automatic resolution
    determination and multi-band support. Each pixel is assigned to a Tilecode cell and
    the first sample value per cell is preserved.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to convert.
    resolution : int, optional
        Tilecode resolution level. If None, automatically determined based on raster pixel size.
        Valid range: 0-26.
    output_format : str, default "gpd"
        Output format. Options:
        - "gpd": Returns GeoPandas GeoDataFrame (default)
        - "csv": Returns CSV file path
        - "geojson": Returns GeoJSON file path
        - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict
        - "parquet": Returns Parquet file path
        - "shapefile"/"shp": Returns Shapefile file path
        - "gpkg"/"geopackage": Returns GeoPackage file path
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation (see ``RASTER_STATS_OPTIONS``).

    Returns
    -------
    geopandas.GeoDataFrame or str or dict
        The converted data in the specified format. Each row represents a Tilecode cell
        with geometry and band values from the original raster.

    Examples
    --------
    >>> # Convert with automatic resolution
    >>> result = raster2tilecode("data.tif")
    >>> print(f"Converted {len(result)} Tilecode cells")

    >>> # Convert with specific resolution
    >>> result = raster2tilecode("data.tif", resolution=10)

    >>> # Convert to GeoJSON file
    >>> result = raster2tilecode("data.tif", output_format="geojson")
    >>> print(f"Saved to: {result}")
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_tilecode_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest Tilecode resolution determined: {resolution}")
    else:
        resolution = validate_tilecode_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2tilecode_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2tilecode_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No Tilecode cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2tilecode" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to Quadkey Module

This module provides functionality to convert raster data to Quadkey DGGS format with automatic resolution determination and multi-band support.

Key Functions

get_nearest_quadkey_resolution(raster_path)

Automatically determine the optimal Quadkey resolution for a given raster.

Analyzes the raster's pixel size and determines the most appropriate Quadkey resolution that best matches the raster's spatial resolution.

Parameters

raster_path : str Path to the raster file to analyze.

Returns

tuple A tuple containing (cell_size, resolution) where: - cell_size: The calculated cell size in square meters - resolution: The optimal Quadkey resolution level

Examples

cell_size, resolution = get_nearest_quadkey_resolution("data.tif") print(f"Cell size: {cell_size} m², Resolution: {resolution}") Cell size: 1000000.0 m², Resolution: 5

Source code in vgrid/conversion/raster2dggs/raster2quadkey.py
 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
def get_nearest_quadkey_resolution(raster_path):
    """
    Automatically determine the optimal Quadkey resolution for a given raster.

    Analyzes the raster's pixel size and determines the most appropriate Quadkey resolution
    that best matches the raster's spatial resolution.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to analyze.

    Returns
    -------
    tuple
        A tuple containing (cell_size, resolution) where:
        - cell_size: The calculated cell size in square meters
        - resolution: The optimal Quadkey resolution level

    Examples
    --------
    >>> cell_size, resolution = get_nearest_quadkey_resolution("data.tif")
    >>> print(f"Cell size: {cell_size} m², Resolution: {resolution}")
    Cell size: 1000000.0 m², Resolution: 5
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. Quadkey conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            # Latitude of the raster center
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            # Convert degrees to meters
            meter_per_degree_lat = 111_320  # Roughly 1 degree latitude in meters
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))

            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = quadkey_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        # If the difference is smaller than the current minimum, update the nearest resolution
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2quadkey(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to Quadkey DGGS format.

Converts raster data to Quadkey DGGS format with automatic resolution determination and multi-band support. Each pixel is assigned to a Quadkey cell and the first sample value per cell is preserved.

Parameters

raster_path : str Path to the raster file to convert. resolution : int, optional Quadkey resolution level. If None, automatically determined based on raster pixel size. Valid range: 0-29. output_format : str, default "gpd" Output format. Options: - "gpd": Returns GeoPandas GeoDataFrame (default) - "csv": Returns CSV file path - "geojson": Returns GeoJSON file path - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict - "parquet": Returns Parquet file path - "shapefile"/"shp": Returns Shapefile file path - "gpkg"/"geopackage": Returns GeoPackage file path method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning": per-cell aggregation (see RASTER_STATS_OPTIONS).

Returns

geopandas.GeoDataFrame or str or dict The converted data in the specified format. Each row represents a Quadkey cell with geometry and band values from the original raster.

Examples

Convert with automatic resolution

result = raster2quadkey("data.tif") print(f"Converted {len(result)} Quadkey cells")

Convert with specific resolution

result = raster2quadkey("data.tif", resolution=10)

Convert to GeoJSON file

result = raster2quadkey("data.tif", output_format="geojson") print(f"Saved to: {result}")

Source code in vgrid/conversion/raster2dggs/raster2quadkey.py
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
def raster2quadkey(
    raster_path, resolution=None, output_format="gpd", method="binning", stats="mean"
):
    """
    Convert raster data to Quadkey DGGS format.

    Converts raster data to Quadkey DGGS format with automatic resolution
    determination and multi-band support. Each pixel is assigned to a Quadkey cell and
    the first sample value per cell is preserved.

    Parameters
    ----------
    raster_path : str
        Path to the raster file to convert.
    resolution : int, optional
        Quadkey resolution level. If None, automatically determined based on raster pixel size.
        Valid range: 0-29.
    output_format : str, default "gpd"
        Output format. Options:
        - "gpd": Returns GeoPandas GeoDataFrame (default)
        - "csv": Returns CSV file path
        - "geojson": Returns GeoJSON file path
        - "geojson_dict": Returns GeoJSON FeatureCollection as Python dict
        - "parquet": Returns Parquet file path
        - "shapefile"/"shp": Returns Shapefile file path
        - "gpkg"/"geopackage": Returns GeoPackage file path
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"``: per-cell aggregation (see ``RASTER_STATS_OPTIONS``).

    Returns
    -------
    geopandas.GeoDataFrame or str or dict
        The converted data in the specified format. Each row represents a Quadkey cell
        with geometry and band values from the original raster.

    Examples
    --------
    >>> # Convert with automatic resolution
    >>> result = raster2quadkey("data.tif")
    >>> print(f"Converted {len(result)} Quadkey cells")

    >>> # Convert with specific resolution
    >>> result = raster2quadkey("data.tif", resolution=10)

    >>> # Convert to GeoJSON file
    >>> result = raster2quadkey("data.tif", output_format="geojson")
    >>> print(f"Saved to: {result}")
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_quadkey_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest Quadkey resolution determined: {resolution}")
    else:
        resolution = validate_quadkey_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2quadkey_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2quadkey_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No Quadkey cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2quadkey" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to Maidenhead Module

Convert raster pixels to Maidenhead locator cells using either binning or nearest-neighbour assignment.

get_nearest_maidenhead_resolution(raster_path)

Pick a Maidenhead resolution whose typical cell area is closest to the raster pixel area (m²).

Source code in vgrid/conversion/raster2dggs/raster2maidenhead.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
def get_nearest_maidenhead_resolution(raster_path):
    """Pick a Maidenhead resolution whose typical cell area is closest to the raster pixel area (m²)."""
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. Maidenhead conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            meter_per_degree_lat = 111_320
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))
            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = maidenhead_metrics(res, unit="m")
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res
    return cell_size, nearest_resolution

raster2maidenhead(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to Maidenhead DGGS format.

Parameters

method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning" (see RASTER_STATS_OPTIONS).

Source code in vgrid/conversion/raster2dggs/raster2maidenhead.py
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
def raster2maidenhead(
    raster_path,
    resolution=None,
    output_format="gpd",
    method="binning",
    stats="mean",
):
    """
    Convert raster data to Maidenhead DGGS format.

    Parameters
    ----------
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"`` (see ``RASTER_STATS_OPTIONS``).
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_maidenhead_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest Maidenhead resolution determined: {resolution}")
    else:
        resolution = validate_maidenhead_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2maidenhead_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2maidenhead_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No Maidenhead cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2maidenhead" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to GARS Module

Convert raster pixels to GARS cells using either binning or nearest-neighbour assignment.

get_nearest_gars_resolution(raster_path)

Pick a GARS resolution whose typical cell area is closest to the raster pixel area (m²).

Source code in vgrid/conversion/raster2dggs/raster2gars.py
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
def get_nearest_gars_resolution(raster_path):
    """Pick a GARS resolution whose typical cell area is closest to the raster pixel area (m²)."""
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. GARS conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            meter_per_degree_lat = 111_320
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))
            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = gars_metrics(res, unit="m")
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res
    return cell_size, nearest_resolution

raster2gars(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to GARS DGGS format.

Parameters

method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning" (see RASTER_STATS_OPTIONS).

Source code in vgrid/conversion/raster2dggs/raster2gars.py
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
def raster2gars(
    raster_path,
    resolution=None,
    output_format="gpd",
    method="binning",
    stats="mean",
):
    """
    Convert raster data to GARS DGGS format.

    Parameters
    ----------
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"`` (see ``RASTER_STATS_OPTIONS``).
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_gars_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest GARS resolution determined: {resolution}")
    else:
        resolution = validate_gars_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2gars_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2gars_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No GARS cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2gars" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)

Raster to DIGIPIN Module

Convert raster data to DIGIPIN DGGS using either:

  • binning — pixel centroids aggregated into DIGIPIN cells (stats required).
  • nearest_neighbour — DIGIPIN grid over the raster bbox; each cell takes the nearest raster pixel center.

get_nearest_digipin_resolution(raster_path)

Automatically determine the optimal DIGIPIN resolution for a given raster.

Source code in vgrid/conversion/raster2dggs/raster2digipin.py
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
def get_nearest_digipin_resolution(raster_path):
    """
    Automatically determine the optimal DIGIPIN resolution for a given raster.
    """
    with rasterio.open(raster_path) as src:
        transform = src.transform
        crs = src.crs
        if crs is None:
            raise ValueError(
                "Raster CRS is undefined. DIGIPIN conversion requires a valid CRS."
            )
        pixel_width = transform.a
        pixel_height = -transform.e
        cell_size = pixel_width * pixel_height

        if crs.is_geographic:
            center_latitude = (src.bounds.top + src.bounds.bottom) / 2
            meter_per_degree_lat = 111_320
            meter_per_degree_lon = meter_per_degree_lat * cos(radians(center_latitude))
            pixel_width_m = pixel_width * meter_per_degree_lon
            pixel_height_m = pixel_height * meter_per_degree_lat
            cell_size = pixel_width_m * pixel_height_m

    min_diff = float("inf")
    nearest_resolution = min_res

    for res in range(min_res, max_res + 1):
        _, _, avg_area, _ = digipin_metrics(res)
        if avg_area < MIN_CELL_AREA:
            break
        diff = abs(avg_area - cell_size)
        if diff < min_diff:
            min_diff = diff
            nearest_resolution = res

    return cell_size, nearest_resolution

raster2digipin(raster_path, resolution=None, output_format='gpd', method='binning', stats='mean')

Convert raster data to DIGIPIN DGGS format.

Parameters

raster_path : str Path to the raster file. resolution : int, optional DIGIPIN resolution [1..10]. If None, matched to pixel size. output_format : str, optional See :func:~vgrid.utils.io.convert_to_output_format. method : str, optional "binning" (default) or "nearest_neighbour" (see RASTER2DGGS_METHODS). stats : str, optional Used when method="binning" (see RASTER_STATS_OPTIONS).

Source code in vgrid/conversion/raster2dggs/raster2digipin.py
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
def raster2digipin(
    raster_path,
    resolution=None,
    output_format="gpd",
    method="binning",
    stats="mean",
):
    """
    Convert raster data to DIGIPIN DGGS format.

    Parameters
    ----------
    raster_path : str
        Path to the raster file.
    resolution : int, optional
        DIGIPIN resolution [1..10]. If None, matched to pixel size.
    output_format : str, optional
        See :func:`~vgrid.utils.io.convert_to_output_format`.
    method : str, optional
        ``"binning"`` (default) or ``"nearest_neighbour"`` (see ``RASTER2DGGS_METHODS``).
    stats : str, optional
        Used when ``method="binning"`` (see ``RASTER_STATS_OPTIONS``).
    """
    method = normalize_raster2dggs_method(method)

    if resolution is None:
        cell_size, resolution = get_nearest_digipin_resolution(raster_path)
        print(f"Cell size: {cell_size} m2")
        print(f"Nearest DIGIPIN resolution determined: {resolution}")
    else:
        resolution = validate_digipin_resolution(resolution)

    print(f"Method: {method}")
    if method == "binning":
        stats = validate_raster_stats_option(stats)
        print(f"Stats: {stats}")
        gdf = _raster2digipin_binning(raster_path, resolution, stats)
    else:
        gdf = _raster2digipin_nearest_neighbour(raster_path, resolution)

    if gdf.empty:
        raise ValueError("No DIGIPIN cells were produced from the raster.")

    base_name = os.path.splitext(os.path.basename(raster_path))[0]
    output_name = f"{base_name}2digipin" if output_format is not None else None
    return convert_to_output_format(gdf, output_format, output_name)