Repository: ecmwf/earthkit-data
Pull request #564 (2024-12-10 11:25:38)

Fix sel for xarray created from single field
Fixes #554 

This PR fixes the issue when `sel()` did not work on Xarray created from a single GRIB field with the "earthkit" Xarray engine.

E.g. the following code previously failed when calling `sel()`:

```python
import earthkit.data
ds = earthkit.data.from_source("ecmwf-open-data",
source='aws',
model='ifs',
param=["2t"],
step=[24],
)
ds_xr_earthkit = ds.to_xarray()
ds_xr_earthkit['2t'].sel(latitude=35, longitude=-90, method='nearest').values
``` 
Now it produces the correct output:
```
array([281.03421021])
```


codecov-commenter: ## [Codecov](https://app.codecov.io/gh/ecmwf/earthkit-data/pull/564?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ecmwf) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 90.13%. Comparing base [(`ed78a5f`)](https://app.codecov.io/gh/ecmwf/earthkit-data/commit/ed78a5fef1dbb3f6a490149e0fa48bd91f7df1bb?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ecmwf) to head [(`6e0bcdf`)](https://app.codecov.io/gh/ecmwf/earthkit-data/commit/6e0bcdf9e566d8d5692d97c25ca45982b239ec8d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ecmwf).

<details><summary>Additional details and impacted files</summary>


```diff
@@           Coverage Diff            @@
##           develop     #564   +/-   ##
========================================
  Coverage    90.12%   90.13%           
========================================
  Files          149      149           
  Lines        10950    10960   +10     
  Branches       518      518           
========================================
+ Hits          9869     9879   +10     
  Misses         914      914           
  Partials       167      167           
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/ecmwf/earthkit-data/pull/564?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ecmwf).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=ecmwf).


Patch:
diff --git a/src/earthkit/data/indexing/tensor.py b/src/earthkit/data/indexing/tensor.py
index 84dc295..4d38c31 100644
--- a/src/earthkit/data/indexing/tensor.py
+++ b/src/earthkit/data/indexing/tensor.py
@@ -390,7 +390,7 @@ class FieldListTensor(TensorCore):
             n = self.source.to_numpy(index=index, **kwargs)
             shape = list(self._user_shape)
             shape += list(n.shape[1:])
-            return n.reshape(*shape)
+            return n.reshape(*shape) if len(shape) > 0 else n
 
     @flatten_arg
     def latitudes(self, **kwargs):


Test patch:
diff --git a/tests/xr_engine/test_xr_engine.py b/tests/xr_engine/test_xr_engine.py
index 40735b6..4aa3794 100644
--- a/tests/xr_engine/test_xr_engine.py
+++ b/tests/xr_engine/test_xr_engine.py
@@ -464,6 +464,8 @@ def test_xr_engine_single_field():
         squeeze=True,
     )
 
+    vals_ref = ds_ek.to_numpy()
+
     lats = np.linspace(90, -90, 19)
     lons = np.linspace(0, 350, 36)
 
@@ -506,6 +508,19 @@ def test_xr_engine_single_field():
         assert np.allclose(ds.coords[k].values, v)
     assert [v for v in ds.data_vars] == data_vars
 
+    da = ds["t"]
+
+    r = da[:, :]
+    r.shape == (19, 36)
+    assert np.allclose(r.values, vals_ref)
+
+    r = da[2:4, 6:8]
+    assert r.shape == (2, 2)
+    assert np.allclose(r.values, vals_ref[2:4, 6:8])
+
+    v = da.sel(latitude=0, longitude=0, method="nearest")
+    assert np.allclose(v, vals_ref[9, 0])
+
 
 @pytest.mark.cache
 @pytest.mark.parametrize("add", [False, True])