Skip to content

rasterize: tighten resolution= shape and type validation #2576

@brendancol

Description

@brendancol

Describe the bug

rasterize() accepts a resolution= argument that should be either a scalar number or a length-2 (x_res, y_res) tuple. The code at xrspatial/rasterize.py:3211-3215 does not check shape or element types, so several bad inputs either slip past or fail with confusing errors:

  • resolution=(1, 2, 3) is silently accepted. The third element is dropped without a warning.
  • resolution=(1,) raises IndexError: tuple index out of range from resolution[1].
  • resolution='foo' raises ValueError: could not convert string to float: 'f' because it iterates the string character-by-character.
  • resolution={'x': 1, 'y': 1} raises KeyError: 0 from resolution[0].

None of these name the offending input or explain what was expected.

Expected behavior

A single readable ValueError for anything that is not a scalar number or a length-2 sequence of numbers, naming the offending value:

  • Scalar int or float: accepted.
  • Length-2 tuple/list of numbers: accepted.
  • Length-0, length-1, length-3+ sequences: clean ValueError.
  • Strings, dicts, non-numeric elements: clean ValueError.

Repro

from xrspatial.rasterize import rasterize
from shapely.geometry import box
import geopandas as gpd

g = gpd.GeoDataFrame({'geometry': [box(0,0,10,10)], 'val': [1.0]})
rasterize(g, column='val', resolution=(1, 2, 3), bounds=(0,0,10,10))  # silent drop of third
rasterize(g, column='val', resolution=(1,), bounds=(0,0,10,10))       # IndexError
rasterize(g, column='val', resolution='foo', bounds=(0,0,10,10))      # raw float() error

Additional context

Surfaced in a code review of xrspatial/rasterize.py. Filed as a bug because the 3-tuple silently produces incorrect output, and the other cases produce noisy errors that should collapse into a single clean ValueError.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions