Skip to content

viewshed() mutates the caller's input raster (dtype/array-type) #2852

@brendancol

Description

@brendancol

Describe the bug

viewshed() mutates the caller's input raster in place.

  • CPU path, xrspatial/viewshed.py:1584: raster.data = raster.data.astype(np.float64, copy=False) replaces the input DataArray's backing array with a float64 version.
  • CuPy fallback (no rtxpy), xrspatial/viewshed.py:1735: raster.data = cp.asnumpy(raster.data) swaps the caller's CuPy array for a numpy one.

So an int16 (or any non-float64) input comes back as float64 after the call, and a CuPy-backed input gets silently converted to numpy. A library function shouldn't change its caller's input, and this bites hard when downstream code reuses the same raster after calling viewshed.

Repro

import numpy as np
import xarray as xr
from xrspatial import viewshed

arr = xr.DataArray(
    np.zeros((5, 5), dtype="int16"),
    coords={"y": np.arange(5.0), "x": np.arange(5.0)},
    dims=["y", "x"],
)
print(arr.dtype)        # int16
viewshed(arr, x=2, y=2)
print(arr.dtype)        # int16 expected, but now float64

Expected behavior

The internal dtype/array-type conversion should run on a copy. After viewshed(...) returns, the input DataArray's dtype and data are unchanged. Applies to both the numpy/CPU path and the CuPy fallback path.

Additional context

Found during a review of the viewshed module. Pure bug fix, no public API change.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    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