Skip to content

Commit da825a8

Browse files
committed
py2mat: xarray
1 parent 1ec7240 commit da825a8

File tree

4 files changed

+43
-2
lines changed

4 files changed

+43
-2
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
*.pkl
2+
*.asv

TestPy2Mat.m

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,23 @@ function test_py2mat_scalar(tc, matlabS)
7070

7171
end
7272

73+
74+
function test_xarray_dataarray(tc)
75+
76+
t0 = datetime(2021, 12, 25, 1, 2, 34.56);
77+
A = pi;
78+
79+
coords = dictionary("time", t0);
80+
81+
% https://docs.xarray.dev/en/latest/generated/xarray.DataArray.html
82+
pyDataArray = py.xarray.DataArray(A, coords);
83+
84+
B = py2mat(pyDataArray);
85+
86+
tc.verifyEqual(B, A);
87+
88+
end
89+
7390
end
7491

7592
end

buildfile.m

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
function plan = buildfile
22
plan = buildplan(localfunctions);
33
plan.DefaultTasks = "test";
4-
plan("test").Dependencies = "check";
54
end
65

76
function checkTask(~)
@@ -11,7 +10,7 @@ function checkTask(~)
1110
end
1211

1312
function testTask(context)
14-
r = runtests(context.Plan.RootFolder, strict=true);
13+
r = runtests(context.Plan.RootFolder, IncludeSubfolders=true, strict=true);
1514
assert(~isempty(r), "No tests were run")
1615
assertSuccess(r)
1716
end

py2mat.m

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,9 @@
194194
x_mat.(string(k{1})) = py2mat(x_py.get(k{1}));
195195
end
196196

197+
case 'py.xarray.core.dataarray.DataArray'
198+
x_mat = double(py.numpy.asfortranarray(x_py));
199+
197200
% punt
198201
otherwise
199202
% return the original item? nothing?
@@ -202,3 +205,24 @@
202205
x_mat = [];
203206
end
204207
end
208+
209+
210+
function I = xarrayind2vector(V, key) %#ok<DEFNU>
211+
%% XARRAYIND2VECTOR convert xarray Index to Matlab vector array
212+
% by SciVision
213+
214+
C = cell(V.indexes{key}.values.tolist);
215+
% might be numeric or cell array of strings
216+
217+
if iscellstr(C) || (length(C) > 1 && isa(C{1}, 'py.str'))
218+
I = cellfun(@char, C, 'uniformoutput', false);
219+
elseif isa(C{1}, 'py.datetime.datetime')
220+
I = char(C{1}.isoformat());
221+
elseif isa(C{1}, 'py.int') && C{1} > 1e12
222+
C = cellfun(@double,C)/1e9;
223+
I = datetime(C, 'convertfrom','posixtime');
224+
else
225+
I = cell2mat(C);
226+
end
227+
228+
end

0 commit comments

Comments
 (0)