def _check_field( cls, xr_dataset: xr.Dataset, field_spec: Spec, field: Hashable, add_comment_attr: bool = False, ) -> None: from sgkit.utils import check_array_like assert isinstance( field_spec, ArrayLikeSpec ), "ArrayLikeSpec is the only currently supported variable spec" try: arr = xr_dataset[field] try: check_array_like(arr, kind=field_spec.kind, ndim=field_spec.ndim) if add_comment_attr and field_spec.__doc__ is not None: arr.attrs["comment"] = field_spec.__doc__.strip() except (TypeError, ValueError) as e: raise ValueError( f"{field} does not match the spec, see the error above for more detail" ) from e except KeyError: raise ValueError(f"{field} not present in {xr_dataset}")
def _check_field(cls, xr_dataset: xr.Dataset, field_spec: Spec, field: Hashable) -> None: from sgkit.utils import check_array_like assert isinstance( field_spec, ArrayLikeSpec ), "ArrayLikeSpec is the only currently supported variable spec" if field not in xr_dataset: raise ValueError(f"{field} not present in {xr_dataset}") try: check_array_like(xr_dataset[field], kind=field_spec.kind, ndim=field_spec.ndim) except (TypeError, ValueError) as e: raise ValueError( f"{field} does not match the spec, see the error above for more detail" ) from e
def test_check_array_like(): with pytest.raises(TypeError, match=r"Not an array. Missing attribute 'ndim'"): check_array_like("foo") a = np.arange(100, dtype="i4") with pytest.raises(TypeError, match=r"Array dtype \(int32\) does not match int64"): check_array_like(a, dtype="i8") with pytest.raises( TypeError, match= r"Array dtype \(int32\) does not match one of (\{dtype\('int8'\), dtype\('int16'\)\}|\{dtype\('int16'\), dtype\('int8'\)\})", ): check_array_like(a, dtype={"i1", "i2"}) with pytest.raises(TypeError, match=r"Array dtype kind \(i\) does not match f"): check_array_like(a, kind="f") with pytest.raises( TypeError, match= r"Array dtype kind \(i\) does not match one of (\{'f', 'S'\}|\{'S', 'f'\})", ): check_array_like(a, kind={"f", "S"}) with pytest.raises(ValueError, match=r"Number of dimensions \(1\) does not match 2"): check_array_like(a, ndim=2) with pytest.raises( ValueError, match= r"Number of dimensions \(1\) does not match one of (\{2, 3\}|\{3, 2\})", ): check_array_like(a, ndim={2, 3})
def test_check_array_like(): with pytest.raises(TypeError): check_array_like("foo") a = np.arange(100, dtype="i4") with pytest.raises(TypeError): check_array_like(a, dtype="i8") with pytest.raises(TypeError): check_array_like(a, dtype={"i1", "i2"}) with pytest.raises(TypeError): check_array_like(a, kind="f") with pytest.raises(ValueError): check_array_like(a, ndim=2) with pytest.raises(ValueError): check_array_like(a, ndim={2, 3})