Skip to content

Commit 6dd52f7

Browse files
authored
Fix dimension ordering when converting a DataArray to DimArray (#971)
Previously the code would temporarily store the dimension => lookup mapping in a Dict, but that doesn't maintain insertion order. So later on it was possible for the DimArray to be created with the dimensions in the wrong order, which would cause an exception.
1 parent 87a0b40 commit 6dd52f7

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

ext/DimensionalDataPythonCall.jl

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,20 +53,20 @@ function PythonCall.pyconvert(::Type{DimArray}, x::Py, d=nothing)
5353

5454
dim_names = Symbol.(collect(x.dims))
5555
coord_names = Symbol.(collect(x.coords.keys()))
56-
lookups_dict = Dict{Symbol, Any}()
57-
for dim in dim_names
56+
lookups_vec = Pair{Symbol, Any}[]
57+
for dim in reverse(dim_names) # Iterate in reverse order because of row/col major
5858
if dim in coord_names
5959
coord = getproperty(x, dim).data
6060
coord_type = dtype2type(string(coord.dtype.name))
6161
coord_ndim = pyconvert(Int, coord.ndim)
6262

63-
lookups_dict[dim] = pyconvert(Array{coord_type, coord_ndim}, coord)
63+
push!(lookups_vec, dim => pyconvert(Array{coord_type, coord_ndim}, coord))
6464
else
65-
lookups_dict[dim] = NoLookup()
65+
push!(lookups_vec, dim => NoLookup())
6666
end
6767
end
6868

69-
lookups = NamedTuple(lookups_dict)
69+
lookups = NamedTuple(lookups_vec)
7070

7171
metadata = pyconvert(Dict, x.attrs)
7272

test/xarray.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ x2 = xr.DataArray(data2,
3838

3939
@test_throws ArgumentError pyconvert(DimArray, xr)
4040
@test pyconvert(DimArray, xr, 42) == 42
41+
42+
# Sanity test for higher-dimensional arrays
43+
x3 = xr.DataArray(rand(2, 5, 5, 3),
44+
dims=("w", "x", "y", "z"),
45+
coords=Dict("w" => [1, 2], "z" => [1, 2, 3]))
46+
y = pyconvert(DimArray, x3)
47+
@test lookup(y, :w) == [1, 2]
48+
@test lookup(y, :z) == [1, 2, 3]
4149
end
4250

4351
@testset "Dataset to DimStack" begin

0 commit comments

Comments
 (0)