forked from Blosc/python-blosc2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_lazyexpr.py
More file actions
1838 lines (1612 loc) · 65.5 KB
/
Copy pathtest_lazyexpr.py
File metadata and controls
1838 lines (1612 loc) · 65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#######################################################################
# Copyright (c) 2019-present, Blosc Development Team <blosc@blosc.org>
# All rights reserved.
#
# This source code is licensed under a BSD-style license (found in the
# LICENSE file in the root directory of this source tree)
#######################################################################
import math
import pathlib
import numpy as np
import pytest
import torch
import blosc2
from blosc2.lazyexpr import ne_evaluate
from blosc2.ndarray import get_chunks_idx, npvecdot
NITEMS_SMALL = 100
NITEMS = 1000
@pytest.fixture(params=[np.float32, np.float64])
def dtype_fixture(request):
return request.param
@pytest.fixture(params=[(NITEMS_SMALL,), (NITEMS,), (NITEMS // 10, 100)])
def shape_fixture(request):
return request.param
# params: (same_chunks, same_blocks)
@pytest.fixture(
params=[
(True, True),
(True, False),
pytest.param((False, True), marks=pytest.mark.heavy),
pytest.param((False, False), marks=pytest.mark.heavy),
]
)
def chunks_blocks_fixture(request):
return request.param
@pytest.fixture
def array_fixture(dtype_fixture, shape_fixture, chunks_blocks_fixture):
nelems = np.prod(shape_fixture)
na1 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
chunks = chunks1 = blocks = blocks1 = None # silence linter
same_chunks_blocks = chunks_blocks_fixture[0] and chunks_blocks_fixture[1]
same_chunks = chunks_blocks_fixture[0]
same_blocks = chunks_blocks_fixture[1]
if same_chunks_blocks:
# For full generality, use partitions with padding
chunks = chunks1 = [c // 11 for c in na1.shape]
blocks = blocks1 = [c // 71 for c in na1.shape]
elif same_chunks:
chunks = [c // 11 for c in na1.shape]
blocks = [c // 71 for c in na1.shape]
chunks1 = [c // 11 for c in na1.shape]
blocks1 = [c // 51 for c in na1.shape]
elif same_blocks:
chunks = [c // 11 for c in na1.shape]
blocks = [c // 71 for c in na1.shape]
chunks1 = [c // 23 for c in na1.shape]
blocks1 = [c // 71 for c in na1.shape]
else:
# Different chunks and blocks
chunks = [c // 17 for c in na1.shape]
blocks = [c // 19 for c in na1.shape]
chunks1 = [c // 23 for c in na1.shape]
blocks1 = [c // 29 for c in na1.shape]
a1 = blosc2.asarray(na1, chunks=chunks, blocks=blocks)
na2 = np.copy(na1)
a2 = blosc2.asarray(na2, chunks=chunks, blocks=blocks)
na3 = np.copy(na1)
# Let other operands have chunks1 and blocks1
a3 = blosc2.asarray(na3, chunks=chunks1, blocks=blocks1)
na4 = np.copy(na1)
a4 = blosc2.asarray(na4, chunks=chunks1, blocks=blocks1)
return a1, a2, a3, a4, na1, na2, na3, na4
def test_simple_getitem(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = a1 + a2 - a3 * a4
nres = ne_evaluate("na1 + na2 - na3 * na4")
sl = slice(100)
res = expr[sl]
np.testing.assert_allclose(res, nres[sl])
# Mix Proxy and NDArray operands
def test_proxy_simple_getitem(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
a1 = blosc2.Proxy(a1)
a2 = blosc2.Proxy(a2)
expr = a1 + a2 - a3 * a4
nres = ne_evaluate("na1 + na2 - na3 * na4")
sl = slice(100)
res = expr[sl]
np.testing.assert_allclose(res, nres[sl])
@pytest.mark.heavy
def test_mix_operands(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = a1 + na2
nres = ne_evaluate("na1 + na2")
sl = slice(100)
res = expr[sl]
np.testing.assert_allclose(res, nres[sl])
np.testing.assert_allclose(expr[:], nres)
np.testing.assert_allclose(expr.compute()[:], nres)
# TODO: fix this
# expr = na2 + a1
# nres = ne_evaluate("na2 + na1")
# sl = slice(100)
# res = expr[sl]
# np.testing.assert_allclose(res, nres[sl])
# np.testing.assert_allclose(expr[:], nres)
# np.testing.assert_allclose(expr.compute()[:], nres)
expr = a1 + na2 + a3
nres = ne_evaluate("na1 + na2 + na3")
res = expr[sl]
np.testing.assert_allclose(res, nres[sl])
np.testing.assert_allclose(expr[:], nres)
np.testing.assert_allclose(expr.compute()[:], nres)
expr = a1 * na2 + a3
nres = ne_evaluate("na1 * na2 + na3")
res = expr[sl]
np.testing.assert_allclose(res, nres[sl])
np.testing.assert_allclose(expr[:], nres)
np.testing.assert_allclose(expr.compute()[:], nres)
expr = a1 * na2 * a3
nres = ne_evaluate("na1 * na2 * na3")
res = expr[sl]
np.testing.assert_allclose(res, nres[sl])
np.testing.assert_allclose(expr[:], nres)
np.testing.assert_allclose(expr.compute()[:], nres)
expr = blosc2.LazyExpr(new_op=(na2, "*", a3))
nres = ne_evaluate("na2 * na3")
res = expr[sl]
np.testing.assert_allclose(res, nres[sl])
np.testing.assert_allclose(expr[:], nres)
np.testing.assert_allclose(expr.compute()[:], nres)
# TODO: support this case
# expr = a1 + na2 * a3
# print("--------------------------------------------------------")
# print(type(expr))
# print(expr.expression)
# print(expr.operands)
# print("--------------------------------------------------------")
# nres = ne_evaluate("na1 + na2 * na3")
# sl = slice(100)
# res = expr[sl]
# np.testing.assert_allclose(res, nres[sl])
# np.testing.assert_allclose(expr[:], nres)
# np.testing.assert_allclose(expr.compute()[:], nres)
# Add more test functions to test different aspects of the code
def test_simple_expression(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = a1 + a2 - a3 * a4
nres = ne_evaluate("na1 + na2 - na3 * na4")
res = expr.compute(cparams=blosc2.CParams())
np.testing.assert_allclose(res[:], nres)
# Mix Proxy and NDArray operands
def test_proxy_simple_expression(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
a1 = blosc2.Proxy(a1)
a3 = blosc2.Proxy(a3)
expr = a1 + a2 - a3 * a4
nres = ne_evaluate("na1 + na2 - na3 * na4")
res = expr.compute(storage=blosc2.Storage())
np.testing.assert_allclose(res[:], nres)
def test_iXXX(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = a1**3 + a2**2 + a3**3 - a4 + 3
expr += 5 # __iadd__
expr -= 15 # __isub__
expr *= 2 # __imul__
expr /= 7 # __itruediv__
if not blosc2.IS_WASM:
expr **= 2.3 # __ipow__
res = expr.compute()
if not blosc2.IS_WASM:
nres = ne_evaluate("(((((na1 ** 3 + na2 ** 2 + na3 ** 3 - na4 + 3) + 5) - 15) * 2) / 7) ** 2.3")
else:
nres = ne_evaluate("(((((na1 ** 3 + na2 ** 2 + na3 ** 3 - na4 + 3) + 5) - 15) * 2) / 7)")
np.testing.assert_allclose(res[:], nres)
def test_complex_evaluate(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = blosc2.tan(a1) * (blosc2.sin(a2) * blosc2.sin(a2) + blosc2.cos(a3)) + (blosc2.sqrt(a4) * 2)
expr += 2
nres = ne_evaluate("tan(na1) * (sin(na2) * sin(na2) + cos(na3)) + (sqrt(na4) * 2) + 2")
res = expr.compute()
np.testing.assert_allclose(res[:], nres)
def test_complex_getitem(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = blosc2.tan(a1) * (blosc2.sin(a2) * blosc2.sin(a2) + blosc2.cos(a3)) + (blosc2.sqrt(a4) * 2)
expr += 2
nres = ne_evaluate("tan(na1) * (sin(na2) * sin(na2) + cos(na3)) + (sqrt(na4) * 2) + 2")
res = expr[:]
np.testing.assert_allclose(res, nres)
def test_complex_getitem_slice(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = blosc2.tan(a1) * (blosc2.sin(a2) * blosc2.sin(a2) + blosc2.cos(a3)) + (blosc2.sqrt(a4) * 2)
expr += 2
nres = ne_evaluate("tan(na1) * (sin(na2) * sin(na2) + cos(na3)) + (sqrt(na4) * 2) + 2")
sl = slice(100)
res = expr[sl]
np.testing.assert_allclose(res, nres[sl])
def test_func_expression(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = (a1 + a2) * a3 - a4
expr = blosc2.sin(expr) + blosc2.cos(expr)
nres = ne_evaluate("sin((na1 + na2) * na3 - na4) + cos((na1 + na2) * na3 - na4)")
res = expr.compute(storage={})
np.testing.assert_allclose(res[:], nres)
def test_expression_with_constants(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
# Test with operands with same chunks and blocks
expr = a1 + 2 - a3 * 3.14
nres = ne_evaluate("na1 + 2 - na3 * 3.14")
np.testing.assert_allclose(expr[:], nres)
@pytest.mark.parametrize("compare_expressions", [True, False])
@pytest.mark.parametrize("comparison_operator", ["==", "!=", ">=", ">", "<=", "<"])
def test_comparison_operators(dtype_fixture, compare_expressions, comparison_operator):
reshape = [30, 4]
nelems = np.prod(reshape)
cparams = {"clevel": 0, "codec": blosc2.Codec.LZ4} # Compression parameters
na1 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(reshape)
na2 = np.copy(na1)
a1 = blosc2.asarray(na1, cparams=cparams)
a2 = blosc2.asarray(na1, cparams=cparams)
# Construct the lazy expression
if compare_expressions:
expr = eval(f"a1 ** 2 {comparison_operator} (a1 + a2)", {"a1": a1, "a2": a2})
expr_string = f"na1 ** 2 {comparison_operator} (na1 + na2)"
else:
expr = eval(f"a1 {comparison_operator} a2", {"a1": a1, "a2": a2})
expr_string = f"na1 {comparison_operator} na2"
res_lazyexpr = expr.compute(dparams={})
# Evaluate using NumExpr
res_numexpr = ne_evaluate(expr_string)
# Compare the results
np.testing.assert_allclose(res_lazyexpr[:], res_numexpr)
# Skip this test for blosc2.IS_WASM
@pytest.mark.skipif(blosc2.IS_WASM, reason="This test is not supported in WASM")
@pytest.mark.parametrize(
"function",
[
"sin",
"cos",
"tan",
"sqrt",
"sinh",
"cosh",
"tanh",
"arcsin",
"arccos",
"arctan",
"arcsinh",
"arccosh",
"arctanh",
"exp",
"expm1",
"log",
"log10",
"log1p",
"conj",
"real",
"imag",
],
)
def test_functions(function, dtype_fixture, shape_fixture):
nelems = np.prod(shape_fixture)
cparams = {"clevel": 0, "codec": blosc2.Codec.LZ4} # Compression parameters
na1 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
a1 = blosc2.asarray(na1, cparams=cparams)
# Construct the lazy expression based on the function name
expr = blosc2.LazyExpr(new_op=(a1, function, None))
res_lazyexpr = expr.compute(cparams={})
# Evaluate using NumExpr
expr_string = f"{function}(na1)"
res_numexpr = ne_evaluate(expr_string)
# Compare the results
np.testing.assert_allclose(res_lazyexpr[:], res_numexpr)
np.testing.assert_allclose(expr.slice(slice(0, 10, 1)), res_numexpr[:10]) # slice test
np.testing.assert_allclose(expr[:10], res_numexpr[:10]) # getitem test
# For some reason real and imag are not supported by numpy's assert_allclose
# (TypeError: bad operand type for abs(): 'LazyExpr' and segfaults are observed)
if function in ("real", "imag"):
return
# Using numpy functions
expr = eval(f"np.{function}(a1)", {"a1": a1, "np": np})
# Compare the results
np.testing.assert_allclose(expr[()], res_numexpr)
# In combination with other operands
na2 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
a2 = blosc2.asarray(na2, cparams=cparams)
# All the next work
# expr = blosc2.lazyexpr(f"a1 + {function}(a2)", {"a1": a1, "a2": a2})
# expr = eval(f"a1 + blosc2.{function}(a2)", {"a1": a1, "a2": a2, "blosc2": blosc2})
expr = eval(f"a1 + np.{function}(a2)", {"a1": a1, "a2": a2, "np": np})
res_lazyexpr = expr.compute(cparams={})
# Evaluate using NumExpr
expr_string = f"na1 + {function}(na2)"
res_numexpr = ne_evaluate(expr_string)
# Compare the results
np.testing.assert_allclose(res_lazyexpr[:], res_numexpr)
# Functions of the form np.function(a1 + a2)
expr = eval(f"np.{function}(a1 + a2)", {"a1": a1, "a2": a2, "np": np})
# Evaluate using NumExpr
expr_string = f"{function}(na1 + na2)"
res_numexpr = ne_evaluate(expr_string)
# Compare the results
np.testing.assert_allclose(expr[()], res_numexpr)
@pytest.mark.parametrize(
"urlpath",
["arr.b2nd", None],
)
@pytest.mark.parametrize(
"function",
["arctan2", "**"],
)
@pytest.mark.parametrize(
("value1", "value2"),
[("NDArray", "scalar"), ("NDArray", "NDArray"), ("scalar", "NDArray"), ("scalar", "scalar")],
)
def test_arctan2_pow(urlpath, shape_fixture, dtype_fixture, function, value1, value2):
nelems = np.prod(shape_fixture)
if urlpath is None:
urlpath1 = urlpath2 = urlpath_save = None
else:
urlpath1 = "a.b2nd"
urlpath2 = "a2.b2nd"
urlpath_save = "expr.b2nd"
if value1 == "NDArray": # ("NDArray", "scalar"), ("NDArray", "NDArray")
na1 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
a1 = blosc2.asarray(na1, urlpath=urlpath1, mode="w")
if value2 == "NDArray": # ("NDArray", "NDArray")
na2 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
a2 = blosc2.asarray(na1, urlpath=urlpath2, mode="w")
# Construct the lazy expression based on the function name
expr = blosc2.LazyExpr(new_op=(a1, function, a2))
if urlpath is not None:
expr.save(urlpath=urlpath_save)
expr = blosc2.open(urlpath_save)
res_lazyexpr = expr.compute()
# Evaluate using NumExpr
if function == "**":
res_numexpr = ne_evaluate("na1**na2")
else:
expr_string = f"{function}(na1, na2)"
res_numexpr = ne_evaluate(expr_string)
else: # ("NDArray", "scalar")
value2 = 3
# Construct the lazy expression based on the function name
expr = blosc2.LazyExpr(new_op=(a1, function, value2))
if urlpath is not None:
expr.save(urlpath=urlpath_save)
expr = blosc2.open(urlpath_save)
res_lazyexpr = expr.compute()
# Evaluate using NumExpr
if function == "**":
res_numexpr = ne_evaluate("na1**value2")
else:
expr_string = f"{function}(na1, value2)"
res_numexpr = ne_evaluate(expr_string)
elif value2 == "NDArray": # ("scalar", "NDArray")
value1 = 12
na2 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
a2 = blosc2.asarray(na2, urlpath=urlpath2, mode="w")
# Construct the lazy expression based on the function name
expr = blosc2.LazyExpr(new_op=(value1, function, a2))
if urlpath is not None:
expr.save(urlpath=urlpath_save)
expr = blosc2.open(urlpath_save)
res_lazyexpr = expr.compute()
# Evaluate using NumExpr
if function == "**":
res_numexpr = ne_evaluate("value1**na2")
else:
expr_string = f"{function}(value1, na2)"
res_numexpr = ne_evaluate(expr_string)
else: # ("scalar", "scalar")
value1 = 12
value2 = 3
# Construct the lazy expression based on the function name
expr = blosc2.LazyExpr(new_op=(value1, function, value2))
res_lazyexpr = expr.compute()
# Evaluate using NumExpr
if function == "**":
res_numexpr = ne_evaluate("value1**value2")
else:
expr_string = f"{function}(value1, value2)"
res_numexpr = ne_evaluate(expr_string)
# Compare the results
tol = 1e-15 if dtype_fixture == "float64" else 1e-6
np.testing.assert_allclose(res_lazyexpr[()], res_numexpr, atol=tol, rtol=tol)
for path in [urlpath1, urlpath2, urlpath_save]:
blosc2.remove_urlpath(path)
def test_abs(shape_fixture, dtype_fixture):
nelems = np.prod(shape_fixture)
na1 = np.linspace(-1, 1, nelems, dtype=dtype_fixture).reshape(shape_fixture)
a1 = blosc2.asarray(na1)
expr = blosc2.LazyExpr(new_op=(a1, "abs", None))
res_lazyexpr = expr.compute(dparams={})
res_np = np.abs(na1)
np.testing.assert_allclose(res_lazyexpr[:], res_np)
# Using np.abs
expr = np.abs(a1)
res_lazyexpr = expr.compute(dparams={})
np.testing.assert_allclose(res_lazyexpr[:], res_np)
@pytest.mark.skipif(blosc2.IS_WASM, reason="This test is not supported in WASM")
@pytest.mark.parametrize("values", [("NDArray", "str"), ("NDArray", "NDArray"), ("str", "NDArray")])
def test_contains(values):
# Unpack the value fixture
value1, value2 = values
if value1 == "NDArray":
a1 = np.array([b"abc", b"def", b"aterr", b"oot", b"zu", b"ab c"])
a1_blosc = blosc2.asarray(a1)
if value2 == "str": # ("NDArray", "str")
value2 = b"test abc here"
# Construct the lazy expression
expr_lazy = blosc2.LazyExpr(new_op=(a1_blosc, "contains", value2))
# Evaluate using NumExpr
expr_numexpr = f"{'contains'}(a1, value2)"
res_numexpr = ne_evaluate(expr_numexpr)
else: # ("NDArray", "NDArray")
a2 = np.array([b"abc", b"ab c", b" abc", b" abc ", b"\tabc", b"c h"])
a2_blosc = blosc2.asarray(a2)
# Construct the lazy expression
expr_lazy = blosc2.LazyExpr(new_op=(a1_blosc, "contains", a2_blosc))
# Evaluate using NumExpr
res_numexpr = ne_evaluate("contains(a2, a1)")
else: # ("str", "NDArray")
value1 = b"abc"
a2 = np.array([b"abc", b"def", b"aterr", b"oot", b"zu", b"ab c"])
a2_blosc = blosc2.asarray(a2)
# Construct the lazy expression
expr_lazy = blosc2.LazyExpr(new_op=(value1, "contains", a2_blosc))
# Evaluate using NumExpr
res_numexpr = ne_evaluate("contains(value1, a2)")
res_lazyexpr = expr_lazy.compute()
# Compare the results
np.testing.assert_array_equal(res_lazyexpr[:], res_numexpr)
def test_negate(dtype_fixture, shape_fixture):
nelems = np.prod(shape_fixture)
na1 = np.linspace(-1, 1, nelems, dtype=dtype_fixture).reshape(shape_fixture)
a1 = blosc2.asarray(na1)
# Test with a single NDArray
expr = -a1
res_lazyexpr = expr.compute()
res_np = -na1
np.testing.assert_allclose(res_lazyexpr[:], res_np)
# Test with a proper expression
expr = -(a1 + 2)
res_lazyexpr = expr.compute()
res_np = -(na1 + 2)
np.testing.assert_allclose(res_lazyexpr[:], res_np)
@pytest.mark.skipif(blosc2.IS_WASM, reason="This test is not supported in WASM")
def test_params(array_fixture):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
expr = a1 + a2 - a3 * a4
nres = ne_evaluate("na1 + na2 - na3 * na4")
urlpath = "eval_expr.b2nd"
blosc2.remove_urlpath(urlpath)
cparams = blosc2.CParams(nthreads=2)
dparams = {"nthreads": 4}
chunks = tuple(i // 2 for i in nres.shape)
blocks = tuple(i // 4 for i in nres.shape)
res = expr.compute(urlpath=urlpath, cparams=cparams, dparams=dparams, chunks=chunks, blocks=blocks)
np.testing.assert_allclose(res[:], nres)
assert res.schunk.urlpath == urlpath
assert res.schunk.cparams.nthreads == cparams.nthreads
assert res.schunk.dparams.nthreads == dparams["nthreads"]
assert res.chunks == chunks
assert res.blocks == blocks
blosc2.remove_urlpath(urlpath)
# Tests related with save method
def test_save():
tol = 1e-17
shape = (23, 23)
nelems = np.prod(shape)
na1 = np.linspace(0, 10, nelems, dtype=np.float32).reshape(shape)
na2 = np.linspace(10, 20, nelems, dtype=np.float32).reshape(shape)
na3 = np.linspace(0, 10, nelems).reshape(shape)
na4 = np.linspace(0, 10, nelems).reshape(shape)
a1 = blosc2.asarray(na1)
a2 = blosc2.asarray(na2)
a3 = blosc2.asarray(na3)
a4 = blosc2.asarray(na4)
ops = [a1, a2, a3, a4]
op_urlpaths = ["a1.b2nd", "a2.b2nd", "a3.b2nd", "a4.b2nd"]
for i, urlpath in enumerate(op_urlpaths):
ops[i] = ops[i].copy(urlpath=urlpath, mode="w")
# Construct the lazy expression with the on-disk operands
da1, da2, da3, da4 = ops
expr = da1 / da2 + da2 - da3 * da4
nres = ne_evaluate("na1 / na2 + na2 - na3 * na4")
urlpath_save = "expr.b2nd"
expr.save(urlpath=urlpath_save)
if not blosc2.IS_WASM:
cparams = {"nthreads": 2}
dparams = {"nthreads": 4}
else:
cparams = {}
dparams = {}
chunks = tuple(i // 2 for i in nres.shape)
blocks = tuple(i // 4 for i in nres.shape)
urlpath_eval = "eval_expr.b2nd"
res = expr.compute(
storage=blosc2.Storage(urlpath=urlpath_eval, mode="w"),
chunks=chunks,
blocks=blocks,
cparams=cparams,
dparams=dparams,
)
np.testing.assert_allclose(res[:], nres, rtol=tol, atol=tol)
expr = blosc2.open(urlpath_save)
# After opening, check that a lazy expression does have an array
# and schunk attributes. This is to allow the .info() method to work.
assert hasattr(expr, "array") is True
assert hasattr(expr, "schunk") is True
# Check the dtype (should be upcasted to float64)
assert expr.array.dtype == np.float64
res = expr.compute()
assert res.dtype == np.float64
np.testing.assert_allclose(res[:], nres, rtol=tol, atol=tol)
# Test getitem
np.testing.assert_allclose(expr[:], nres, rtol=tol, atol=tol)
urlpath_save2 = "expr_str.b2nd"
x = 3
expr = "a1 / a2 + a2 - a3 * a4**x"
var_dict = {"a1": ops[0], "a2": ops[1], "a3": ops[2], "a4": ops[3], "x": x}
lazy_expr = eval(expr, var_dict)
lazy_expr.save(urlpath=urlpath_save2)
expr = blosc2.open(urlpath_save2)
assert expr.array.dtype == np.float64
res = expr.compute()
nres = ne_evaluate("na1 / na2 + na2 - na3 * na4**3")
np.testing.assert_allclose(res[:], nres, rtol=tol, atol=tol)
# Test getitem
np.testing.assert_allclose(expr[:], nres, rtol=tol, atol=tol)
for urlpath in op_urlpaths + [urlpath_save, urlpath_eval, urlpath_save2]:
blosc2.remove_urlpath(urlpath)
@pytest.mark.skipif(blosc2.IS_WASM, reason="This test is not supported in WASM")
def test_save_unsafe():
na = np.arange(1000)
nb = np.arange(1000)
a = blosc2.asarray(na, urlpath="a.b2nd", mode="w")
b = blosc2.asarray(nb, urlpath="b.b2nd", mode="w")
disk_arrays = ["a.b2nd", "b.b2nd"]
expr = a + b
urlpath = "expr.b2nd"
expr.save(urlpath=urlpath)
disk_arrays.append(urlpath)
expr = blosc2.open(urlpath)
# Replace expression by a (potentially) unsafe expression
expr.expression = "import os; os.system('touch /tmp/unsafe')"
with pytest.raises(ValueError) as excinfo:
expr.compute()
assert expr.expression in str(excinfo.value)
# Check that an invalid expression cannot be easily saved.
# Although, as this can easily be worked around, the best protection is
# during loading time (tested above).
expr.expression_tosave = "import os; os.system('touch /tmp/unsafe')"
with pytest.raises(ValueError) as excinfo:
expr.save(urlpath=urlpath)
assert expr.expression_tosave in str(excinfo.value)
for urlpath in disk_arrays:
blosc2.remove_urlpath(urlpath)
@pytest.mark.skipif(blosc2.IS_WASM, reason="This test is not supported in WASM")
@pytest.mark.parametrize(
"function",
[
"sin",
"sqrt",
"cosh",
"arctan",
"arcsinh",
"exp",
"expm1",
"log",
"conj",
"real",
"imag",
],
)
def test_save_functions(function, dtype_fixture, shape_fixture):
nelems = np.prod(shape_fixture)
cparams = {"clevel": 0, "codec": blosc2.Codec.LZ4} # Compression parameters
na1 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
urlpath_op = "a1.b2nd"
a1 = blosc2.asarray(na1, cparams=cparams, urlpath=urlpath_op, mode="w")
urlpath_save = "expr.b2nd"
# Construct the lazy expression based on the function name
expr = blosc2.LazyExpr(new_op=(a1, function, None))
expr.save(urlpath=urlpath_save)
del expr
expr = blosc2.open(urlpath_save)
res_lazyexpr = expr.compute()
# Evaluate using NumExpr
expr_string = f"{function}(na1)"
res_numexpr = ne_evaluate(expr_string)
# Compare the results
np.testing.assert_allclose(res_lazyexpr[:], res_numexpr)
expr_string = f"blosc2.{function}(a1)"
expr = eval(expr_string, {"a1": a1, "blosc2": blosc2})
expr.save(urlpath=urlpath_save)
res_lazyexpr = expr.compute()
np.testing.assert_allclose(res_lazyexpr[:], res_numexpr)
expr = blosc2.open(urlpath_save)
res_lazyexpr = expr.compute()
np.testing.assert_allclose(res_lazyexpr[:], res_numexpr)
for urlpath in [urlpath_op, urlpath_save]:
blosc2.remove_urlpath(urlpath)
@pytest.mark.skipif(blosc2.IS_WASM, reason="This test is not supported in WASM")
@pytest.mark.parametrize("values", [("NDArray", "str"), ("NDArray", "NDArray"), ("str", "NDArray")])
def test_save_contains(values):
# Unpack the value fixture
value1, value2 = values
urlpath = "a.b2nd"
urlpath2 = "a2.b2nd"
urlpath_save = "expr.b2nd"
if value1 == "NDArray":
a1 = np.array([b"abc(", b"def", b"aterr", b"oot", b"zu", b"ab c"])
a1_blosc = blosc2.asarray(a1, urlpath=urlpath, mode="w")
if value2 == "str": # ("NDArray", "str")
value2 = b"test abc( here"
# Construct the lazy expression
expr_lazy = blosc2.LazyExpr(new_op=(a1_blosc, "contains", value2))
expr_lazy.save(urlpath=urlpath_save)
expr_lazy = blosc2.open(urlpath_save)
# Evaluate using NumExpr
expr_numexpr = f"{'contains'}(a1, value2)"
res_numexpr = ne_evaluate(expr_numexpr)
else: # ("NDArray", "NDArray")
a2 = np.array([b"abc(", b"ab c", b" abc", b" abc ", b"\tabc", b"c h"])
a2_blosc = blosc2.asarray(a2, urlpath=urlpath2, mode="w")
# Construct the lazy expression
expr_lazy = blosc2.LazyExpr(new_op=(a1_blosc, "contains", a2_blosc))
expr_lazy.save(urlpath=urlpath_save)
expr_lazy = blosc2.open(urlpath_save)
# Evaluate using NumExpr
res_numexpr = ne_evaluate("contains(a2, a1)")
else: # ("str", "NDArray")
value1 = b"abc"
a2 = np.array([b"abc(", b"def", b"aterr", b"oot", b"zu", b"ab c"])
a2_blosc = blosc2.asarray(a2, urlpath=urlpath2, mode="w")
# Construct the lazy expression
expr_lazy = blosc2.LazyExpr(new_op=(value1, "contains", a2_blosc))
expr_lazy.save(urlpath=urlpath_save)
expr_lazy = blosc2.open(urlpath_save)
# Evaluate using NumExpr
res_numexpr = ne_evaluate("contains(value1, a2)")
res_lazyexpr = expr_lazy.compute()
# Compare the results
np.testing.assert_array_equal(res_lazyexpr[:], res_numexpr)
for path in [urlpath, urlpath2, urlpath_save]:
blosc2.remove_urlpath(path)
@pytest.mark.skipif(blosc2.IS_WASM, reason="This test is not supported in WASM")
def test_save_many_functions(dtype_fixture, shape_fixture):
rtol = 1e-6 if dtype_fixture == np.float32 else 1e-15
atol = 1e-6 if dtype_fixture == np.float32 else 1e-15
nelems = np.prod(shape_fixture)
cparams = {"clevel": 0, "codec": blosc2.Codec.LZ4} # Compression parameters
na1 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
na2 = np.linspace(0, 10, nelems, dtype=dtype_fixture).reshape(shape_fixture)
urlpath_op = "a1.b2nd"
urlpath_op2 = "a1.b2nd"
a1 = blosc2.asarray(na1, cparams=cparams, urlpath=urlpath_op, mode="w")
a2 = blosc2.asarray(na2, cparams=cparams, urlpath=urlpath_op2, mode="w")
# Evaluate using NumExpr
expr_string = "sin(x)**3 + cos(y)**2 + cos(x) * arcsin(y) + arcsinh(x) + sinh(x)"
res_numexpr = ne_evaluate(expr_string, {"x": na1, "y": na2})
urlpath_save = "expr.b2nd"
expr = blosc2.lazyexpr(expr_string, {"x": a1, "y": a2})
expr.save(urlpath=urlpath_save)
res_lazyexpr = expr.compute()
np.testing.assert_allclose(res_lazyexpr[:], res_numexpr, rtol=rtol, atol=atol)
expr = blosc2.open(urlpath_save)
res_lazyexpr = expr.compute()
np.testing.assert_allclose(res_lazyexpr[:], res_numexpr, rtol=rtol, atol=atol)
for urlpath in [urlpath_op, urlpath_op2, urlpath_save]:
blosc2.remove_urlpath(urlpath)
@pytest.mark.skipif(blosc2.IS_WASM, reason="This test is not supported in WASM")
@pytest.mark.parametrize(
"constructor", ["arange", "linspace", "fromiter", "reshape", "zeros", "ones", "full"]
)
@pytest.mark.parametrize("shape", [(10,), (10, 10), (10, 10, 10)])
@pytest.mark.parametrize("dtype", ["int32", "float64", "i2"])
@pytest.mark.parametrize("disk", [True, False])
def test_save_constructor(disk, shape, dtype, constructor): # noqa: C901
lshape = math.prod(shape)
urlpath = "a.b2nd" if disk else None
b2func = getattr(blosc2, constructor)
a, expr = None, None
if constructor in ("zeros", "ones"):
a = b2func(shape, dtype=dtype, urlpath=urlpath, mode="w")
expr = f"a + {constructor}({shape}, dtype={dtype}) + 1"
elif constructor == "full":
a = b2func(shape, 10, dtype=dtype, urlpath=urlpath, mode="w")
expr = f"a + {constructor}(10, {shape}, dtype={dtype}) + 1"
elif constructor == "fromiter":
a = b2func(range(lshape), dtype=dtype, shape=shape, urlpath=urlpath, mode="w")
expr = f"a + {constructor}(range({lshape}), dtype={dtype}, shape={shape}) + 1"
elif constructor == "reshape":
# Let's put a nested arange array here
a = blosc2.arange(lshape, dtype=dtype, shape=shape, urlpath=urlpath, mode="w")
b = f"arange({lshape}, dtype={dtype})"
# Both expressions below are equivalent, but use the method variant for testing purposes
# expr = f"a + {constructor}({b}, shape={shape}) + 1"
expr = f"a + {b}.reshape({shape}) + 1"
# The one below is also supported, but should be rarely used
# expr = f"a + {b}.reshape(shape={shape}) + 1"
elif constructor == "linspace":
a = b2func(0, 10, lshape, dtype=dtype, shape=shape, urlpath=urlpath, mode="w")
expr = f"a + {constructor}(0, 10, {lshape}, dtype={dtype}, shape={shape}) + 1"
elif constructor == "arange":
a = b2func(lshape, dtype=dtype, shape=shape, urlpath=urlpath, mode="w")
expr = f"a + {constructor}({lshape}, dtype={dtype}, shape={shape}) + 1"
if disk:
a = blosc2.open(urlpath)
npfunc = getattr(np, constructor)
if constructor == "linspace":
na = npfunc(0, 10, lshape, dtype=dtype).reshape(shape)
elif constructor == "fromiter":
na = np.fromiter(range(lshape), dtype=dtype, count=lshape).reshape(shape)
elif constructor == "reshape":
na = np.arange(lshape, dtype=dtype).reshape(shape)
elif constructor == "full":
na = npfunc(shape, 10, dtype=dtype)
else:
na = npfunc(lshape, dtype=dtype).reshape(shape)
# An expression involving the constructor
lexpr = blosc2.lazyexpr(expr)
assert lexpr.shape == a.shape
if disk:
lexpr.save("out.b2nd")
lexpr = blosc2.open("out.b2nd")
res = lexpr.compute()
nres = na + na + 1
assert np.allclose(res[()], nres)
if disk:
blosc2.remove_urlpath("a.b2nd")
blosc2.remove_urlpath("out.b2nd")
@pytest.mark.parametrize("shape", [(10,), (10, 10), (10, 10, 10)])
@pytest.mark.parametrize("disk", [True, False])
def test_save_2_constructors(shape, disk):
lshape = math.prod(shape)
urlpath_a = "a.b2nd" if disk else None
urlpath_b = "b.b2nd" if disk else None
a = blosc2.arange(lshape, shape=shape, urlpath=urlpath_a, mode="w")
b = blosc2.ones(shape, urlpath=urlpath_b, mode="w")
expr = f"arange({lshape}, shape={shape}) + a + ones({shape}) + b + 1"
lexpr = blosc2.lazyexpr(expr)
if disk:
lexpr.save("out.b2nd")
lexpr = blosc2.open("out.b2nd")
res = lexpr.compute()
na = np.arange(lshape).reshape(shape)
nb = np.ones(shape)
nres = na + a[:] + nb + b[:] + 1
assert np.allclose(res[()], nres)
if disk:
blosc2.remove_urlpath(urlpath_a)
blosc2.remove_urlpath(urlpath_b)
blosc2.remove_urlpath("out.b2nd")
@pytest.mark.parametrize("shape", [(10,), (10, 10), (10, 10, 10)])
@pytest.mark.parametrize("disk", [True, False])
def test_save_constructor_reshape(shape, disk):
lshape = math.prod(shape)
urlpath_a = "a.b2nd" if disk else None
urlpath_b = "b.b2nd" if disk else None
a = blosc2.arange(lshape, shape=shape, urlpath=urlpath_a, mode="w")
b = blosc2.ones(shape, urlpath=urlpath_b, mode="w")
# All the next work
# expr = f"arange({lshape}).reshape({shape}) + a + ones({shape}) + b + 1"
# expr = f"arange({lshape}).reshape(shape={shape}) + a + ones({shape}) + b + 1"
expr = f"arange({lshape}).reshape(shape = {shape}) + a + ones({shape}) + b + 1"
lexpr = blosc2.lazyexpr(expr)
if disk:
lexpr.save("out.b2nd")
lexpr = blosc2.open("out.b2nd")
res = lexpr.compute()
na = np.arange(lshape).reshape(shape)
nb = np.ones(shape)
nres = na + a[:] + nb + b[:] + 1
assert np.allclose(res[()], nres)
if disk:
blosc2.remove_urlpath(urlpath_a)
blosc2.remove_urlpath(urlpath_b)
blosc2.remove_urlpath("out.b2nd")
@pytest.mark.parametrize("shape", [(10,), (10, 10), (10, 10, 10)])
@pytest.mark.parametrize("disk", [True, False])
def test_save_2equal_constructors(shape, disk):
lshape = math.prod(shape)
urlpath_a = "a.b2nd" if disk else None
urlpath_b = "b.b2nd" if disk else None
a = blosc2.ones(shape, dtype=np.int8, urlpath=urlpath_a, mode="w")
b = blosc2.ones(shape, urlpath=urlpath_b, mode="w")
expr = f"ones({shape}, dtype=int8) + a + ones({shape}) + b + 1"
lexpr = blosc2.lazyexpr(expr)
if disk:
lexpr.save("out.b2nd")
lexpr = blosc2.open("out.b2nd")
res = lexpr.compute()
na = np.ones(shape, dtype=np.int8)
nb = np.ones(shape)
nres = na + a[:] + nb + b[:] + 1
assert np.allclose(res[()], nres)
assert res.dtype == nres.dtype
if disk:
blosc2.remove_urlpath(urlpath_a)
blosc2.remove_urlpath(urlpath_b)
blosc2.remove_urlpath("out.b2nd")
@pytest.fixture(
params=[
((10, 1), (10,)),
((2, 5), (5,)),
((2, 1), (5,)),
((2, 5, 3), (5, 3)),
((2, 5, 3), (5, 1)),
((2, 1, 3), (5, 3)),
((2, 5, 3, 2), (5, 3, 2)),
((2, 5, 3, 2), (5, 3, 1)),
pytest.param(((2, 5, 3, 2), (5, 1, 2)), marks=pytest.mark.heavy),
((2, 1, 3, 2), (5, 3, 2)),
pytest.param(((2, 1, 3, 2), (5, 1, 2)), marks=pytest.mark.heavy),
pytest.param(((2, 5, 3, 2, 2), (5, 3, 2, 2)), marks=pytest.mark.heavy),
pytest.param(((100, 100, 100), (100, 100)), marks=pytest.mark.heavy),
((1_000, 1), (1_000,)),
]
)
def broadcast_shape(request):
return request.param
# Test broadcasting
@pytest.fixture
def broadcast_fixture(dtype_fixture, broadcast_shape):
shape1, shape2 = broadcast_shape
na1 = np.linspace(0, 1, np.prod(shape1), dtype=dtype_fixture).reshape(shape1)
na2 = np.linspace(1, 2, np.prod(shape2), dtype=dtype_fixture).reshape(shape2)
a1 = blosc2.asarray(na1)
a2 = blosc2.asarray(na2)
return a1, a2, na1, na2
def test_broadcasting(broadcast_fixture):
a1, a2, na1, na2 = broadcast_fixture
expr1 = a1 + a2
assert expr1.shape == np.broadcast_shapes(a1.shape, a2.shape)
expr2 = a1 * a2 + 1
assert expr2.shape == np.broadcast_shapes(a1.shape, a2.shape)
expr = expr1 - expr2
assert expr.shape == np.broadcast_shapes(expr1.shape, expr2.shape)
nres = ne_evaluate("na1 + na2 - (na1 * na2 + 1)")
res = expr.compute()
np.testing.assert_allclose(res[:], nres)
res = expr[:]
np.testing.assert_allclose(res, nres)
def test_broadcasting_str(broadcast_fixture):
a1, a2, na1, na2 = broadcast_fixture
expr1 = blosc2.lazyexpr("a1 + a2")
assert expr1.shape == np.broadcast_shapes(a1.shape, a2.shape)
expr2 = blosc2.lazyexpr("a1 * a2 + 1")
assert expr2.shape == np.broadcast_shapes(a1.shape, a2.shape)
expr = blosc2.lazyexpr("expr1 - expr2")
assert expr.shape == np.broadcast_shapes(expr1.shape, expr2.shape)
nres = ne_evaluate("na1 + na2 - (na1 * na2 + 1)")
assert expr.shape == nres.shape
res = expr.compute()
np.testing.assert_allclose(res[:], nres)
res = expr[:]
np.testing.assert_allclose(res, nres)
@pytest.mark.parametrize(
"operand_mix",
[
("NDArray", "numpy"),
("NDArray", "NDArray"),
("numpy", "NDArray"),
("numpy", "numpy"),
],
)
@pytest.mark.parametrize("operand_guess", [True, False])
def test_lazyexpr(array_fixture, operand_mix, operand_guess):
a1, a2, a3, a4, na1, na2, na3, na4 = array_fixture
if operand_mix[0] == "NDArray" and operand_mix[1] == "NDArray":
operands = {"a1": a1, "a2": a2, "a3": a3, "a4": a4}
elif operand_mix[0] == "NDArray" and operand_mix[1] == "numpy":
operands = {"a1": a1, "a2": na2, "a3": a3, "a4": na4}
elif operand_mix[0] == "numpy" and operand_mix[1] == "NDArray":
operands = {"a1": na1, "a2": a2, "a3": na3, "a4": a4}
else:
operands = {"a1": na1, "a2": na2, "a3": na3, "a4": na4}
# Check eval()
if operand_guess:
expr = blosc2.lazyexpr("a1 + a2 - a3 * a4")
else:
expr = blosc2.lazyexpr("a1 + a2 - a3 * a4", operands=operands)
nres = ne_evaluate("na1 + na2 - na3 * na4")
assert expr.shape == nres.shape
res = expr.compute()
np.testing.assert_allclose(res[:], nres)