Skip to content

Commit 6db5c4e

Browse files
committed
Add an example on using xarray with blosc2
1 parent 684ef75 commit 6db5c4e

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#######################################################################
2+
# Copyright (c) 2019-present, Blosc Development Team <[email protected]>
3+
# All rights reserved.
4+
#
5+
# This source code is licensed under a BSD-style license (found in the
6+
# LICENSE file in the root directory of this source tree)
7+
#######################################################################
8+
9+
# Example on how to use xarray containers as operands in Blosc2 expressions
10+
# Note that there is no special support for xarray in Blosc2; the techniques
11+
# below works for any object that implements the Array protocol (i.e. having
12+
# a shape and dtype attributes, and a __getitem__ method and a __len__ method.
13+
14+
import numpy as np
15+
import xarray
16+
17+
import blosc2
18+
19+
20+
class NewObj(blosc2.Array):
21+
def __init__(self, a):
22+
self.a = a
23+
24+
@property
25+
def shape(self):
26+
return self.a.shape
27+
28+
@property
29+
def dtype(self):
30+
return self.a.dtype
31+
32+
def __getitem__(self, key):
33+
return self.a[key]
34+
35+
def __len__(self):
36+
return len(self.a)
37+
38+
39+
a = np.arange(100, dtype=np.int64).reshape(10, 10)
40+
res = a + np.sin(a) + np.hypot(a, a) + 1
41+
42+
a = xarray.DataArray(a) # supported natively by blosc2; no copies
43+
b = NewObj(a) # minimal Array protocol implementation; no copies
44+
assert isinstance(b, blosc2.Array) # any Array compliant object works
45+
c = blosc2.asarray(a) # convert into a blosc2.NDArray; data is copied
46+
d = blosc2.SimpleProxy(a) # SimpleProxy conversion; no copies
47+
lb = blosc2.lazyexpr("a + sin(b) + hypot(c, d) + 1")
48+
49+
# Check!
50+
np.testing.assert_array_equal(lb[:], res)

0 commit comments

Comments
 (0)