Skip to content

DataArrayXxx: InterpKernelException raised for arrays with unused but non-standard strides #12

Description

@j-demersseman

Description:

MEDCoupling raises an exception when constructing a DataArray from a numpy array that is logically contiguous but whose unused stride does not match the item size. This happens in at least two cases:

  • Column vector of shape (N, 1) — the stride along axis 1 is irrelevant since there is only one column, but MEDCoupling validates it anyway.
  • Single-element 1-D array — the stride is irrelevant since there is only one element.

Version: MEDCoupling 9.14.0

Steps to reproduce:

import medcoupling as mc
import numpy as np

# Case 1: column vector with non-standard (but unused) column stride
base = np.arange(10, dtype=np.float64)
col = np.lib.stride_tricks.as_strided(base, shape=(10, 1), strides=(8, 1928))
da = mc.DataArrayDouble(col)  # raises InterpKernelException

# Case 2: single-element array with non-standard stride
base = np.arange(1, dtype=np.float64)
single = np.lib.stride_tricks.as_strided(base, shape=(1,), strides=(4,))
da = mc.DataArrayDouble(single)  # raises InterpKernelException

Workaround

NPT = TypeVar("NPT", bound=np.generic)

def as_contiguous_for_mc(arr: npt.NDArray[np.generic], dtype: type[NPT]) -> npt.NDArray[NPT]:
    """Ensure the numpy array is C-contiguous and of the specified dtype for MEDCoupling."""
    array = np.ascontiguousarray(arr, dtype=dtype)
    if array.ndim == 2 and array.strides[1] != array.itemsize and array.shape[1] == 1:
        # For column (n, 1), Numpy don't check for column contiguity (because this stride is useless)
        array = array.reshape(-1, 1)  # force to redo the column stride
    elif array.ndim == 1 and array.size == 1:
        # For single element array, Numpy don't check for contiguity
        array = array.copy()
    return array

Root cause analysis:

  • For a (N, 1) array, the stride of the second dimension is never used during data traversal; only the first-dimension stride matters.
  • For a single-element array, no stride is ever applied.

In both cases, NumPy may assign an arbitrary stride value to the unused dimension, which MEDCoupling's validator incorrectly rejects.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions