-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathlazyexpr.py
More file actions
4333 lines (3876 loc) · 170 KB
/
lazyexpr.py
File metadata and controls
4333 lines (3876 loc) · 170 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.
#
# SPDX-License-Identifier: BSD-3-Clause
#######################################################################
# Avoid checking the name of type annotations at run time
from __future__ import annotations
import ast
import asyncio
import builtins
import concurrent.futures
import copy
import enum
import inspect
import linecache
import math
import os
import pathlib
import re
import sys
import textwrap
import threading
from abc import ABC, abstractmethod, abstractproperty
from dataclasses import asdict
from enum import Enum
from pathlib import Path
from queue import Empty, Queue
from typing import TYPE_CHECKING, Any
from numpy.exceptions import ComplexWarning
from . import exceptions
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
import ndindex
import numpy as np
import blosc2
from .dsl_kernel import DSLKernel, specialize_miniexpr_inputs
if blosc2._HAS_NUMBA:
import numba
from blosc2 import compute_chunks_blocks
from blosc2.info import InfoReporter
from .proxy import _convert_dtype
from .utils import (
NUMPY_GE_2_0,
_get_chunk_operands,
_sliced_chunk_iter,
check_smaller_shape,
compute_smaller_slice,
constructors,
elementwise_funcs,
get_chunks_idx,
get_intersecting_chunks,
infer_shape,
linalg_attrs,
linalg_funcs,
npcumprod,
npcumsum,
npvecdot,
process_key,
reducers,
)
if not blosc2.IS_WASM:
import numexpr
global safe_blosc2_globals
safe_blosc2_globals = {}
global safe_numpy_globals
# Use numpy eval when running in WebAssembly
safe_numpy_globals = {"np": np}
# Add all first-level numpy functions
safe_numpy_globals.update(
{name: getattr(np, name) for name in dir(np) if callable(getattr(np, name)) and not name.startswith("_")}
)
if not NUMPY_GE_2_0: # handle non-array-api compliance
safe_numpy_globals["acos"] = np.arccos
safe_numpy_globals["acosh"] = np.arccosh
safe_numpy_globals["asin"] = np.arcsin
safe_numpy_globals["asinh"] = np.arcsinh
safe_numpy_globals["atan"] = np.arctan
safe_numpy_globals["atanh"] = np.arctanh
safe_numpy_globals["atan2"] = np.arctan2
safe_numpy_globals["permute_dims"] = np.transpose
safe_numpy_globals["pow"] = np.power
safe_numpy_globals["bitwise_left_shift"] = np.left_shift
safe_numpy_globals["bitwise_right_shift"] = np.right_shift
safe_numpy_globals["bitwise_invert"] = np.bitwise_not
safe_numpy_globals["concat"] = np.concatenate
safe_numpy_globals["matrix_transpose"] = np.transpose
safe_numpy_globals["vecdot"] = npvecdot
safe_numpy_globals["cumulative_sum"] = npcumsum
safe_numpy_globals["cumulative_prod"] = npcumprod
# Set this to False if miniexpr should not be tried out
try_miniexpr = True
if blosc2.IS_WASM:
try_miniexpr = False
_MINIEXPR_WINDOWS_OVERRIDE = os.environ.get("BLOSC2_ENABLE_MINIEXPR_WINDOWS", "").strip().lower()
_MINIEXPR_WINDOWS_OVERRIDE = _MINIEXPR_WINDOWS_OVERRIDE not in ("", "0", "false", "no", "off")
def ne_evaluate(expression, local_dict=None, **kwargs):
"""Safely evaluate expressions using numexpr when possible, falling back to numpy."""
if local_dict is None:
local_dict = {}
# Get local vars dict from the stack frame
_frame_depth = kwargs.pop("_frame_depth", 1)
local_dict |= {
k: v
for k, v in dict(sys._getframe(_frame_depth).f_locals).items()
if (
(hasattr(v, "shape") or np.isscalar(v))
and
# Do not overwrite the local_dict with the expression variables
not (k in local_dict or k in ("_where_x", "_where_y"))
)
}
if blosc2.IS_WASM:
global safe_numpy_globals
if "out" in kwargs:
out = kwargs.pop("out")
out[:] = eval(expression, safe_numpy_globals, local_dict)
return out
return eval(expression, safe_numpy_globals, local_dict)
try:
return numexpr.evaluate(expression, local_dict=local_dict, **kwargs)
except ValueError as e:
raise e # unsafe expression
except Exception: # non_numexpr functions present
global safe_blosc2_globals
# ne_evaluate will need safe_blosc2_globals for some functions (e.g. clip, logaddexp)
# that are implemented in python-blosc2 not in numexpr
if len(safe_blosc2_globals) == 0:
# First eval call, fill blosc2_safe_globals for ne_evaluate
safe_blosc2_globals = {"blosc2": blosc2}
# Add all first-level blosc2 functions
safe_blosc2_globals.update(
{
name: getattr(blosc2, name)
for name in dir(blosc2)
if callable(getattr(blosc2, name)) and not name.startswith("_")
}
)
res = eval(expression, safe_blosc2_globals, local_dict)
if "out" in kwargs:
out = kwargs.pop("out")
out[:] = res # will handle calc/decomp if res is lazyarray
return out
return res[()] if isinstance(res, blosc2.Operand) else res
def _get_result(expression, chunk_operands, ne_args, where=None, indices=None, _order=None):
chunk_indices = None
if (expression == "o0" or expression == "(o0)") and where is None:
# We don't have an actual expression, so avoid a copy except to make contiguous (later)
return chunk_operands["o0"], None
# Apply the where condition (in result)
if where is not None and len(where) == 2:
# x = chunk_operands["_where_x"]
# y = chunk_operands["_where_y"]
# result = np.where(result, x, y)
# numexpr is a bit faster than np.where, and we can fuse operations in this case
new_expr = f"where({expression}, _where_x, _where_y)"
return ne_evaluate(new_expr, chunk_operands, **ne_args), None
result = ne_evaluate(expression, chunk_operands, **ne_args)
if where is None:
return result, None
elif len(where) == 1:
x = chunk_operands["_where_x"]
if (indices is not None) or (_order is not None):
# Return indices only makes sense when the where condition is a tuple with one element
# and result is a boolean array
if len(x.shape) > 1:
raise ValueError("indices() and sort() only support 1D arrays")
if result.dtype != np.bool_:
raise ValueError("indices() and sort() only support bool conditions")
if _order:
# We need to cumulate all the fields in _order, as well as indices
chunk_indices = indices[result]
result = x[_order][result]
else:
chunk_indices = None
result = indices[result]
return result, chunk_indices
else:
return x[result], None
raise ValueError("The where condition must be a tuple with one or two elements")
# Define empty ndindex tuple for function defaults
NDINDEX_EMPTY_TUPLE = ndindex.Tuple()
# All the dtypes that are supported by the expression evaluator
dtype_symbols = {
"int8": np.int8,
"int16": np.int16,
"int32": np.int32,
"int64": np.int64,
"uint8": np.uint8,
"uint16": np.uint16,
"uint32": np.uint32,
"uint64": np.uint64,
"float32": np.float32,
"float64": np.float64,
"complex64": np.complex64,
"complex128": np.complex128,
"bool": np.bool_,
"str": np.str_,
"bytes": np.bytes_,
"i1": np.int8,
"i2": np.int16,
"i4": np.int32,
"i8": np.int64,
"u1": np.uint8,
"u2": np.uint16,
"u4": np.uint32,
"u8": np.uint64,
"f4": np.float32,
"f8": np.float64,
"c8": np.complex64,
"c16": np.complex128,
"b1": np.bool_,
"S": np.str_,
"V": np.bytes_,
}
blosc2_funcs = constructors + linalg_funcs + elementwise_funcs + reducers
# functions that have to be evaluated before chunkwise lazyexpr machinery
eager_funcs = linalg_funcs + reducers + ["slice"] + ["." + attr for attr in linalg_attrs]
# Gather all callable functions in numpy
numpy_funcs = {
name
for name, member in inspect.getmembers(np, callable)
if not name.startswith("_") and not isinstance(member, np.ufunc)
}
numpy_ufuncs = {name for name, member in inspect.getmembers(np, lambda x: isinstance(x, np.ufunc))}
# Add these functions to the list of available functions
# (will be evaluated via the array interface)
additional_funcs = sorted((numpy_funcs | numpy_ufuncs) - set(blosc2_funcs))
functions = blosc2_funcs + additional_funcs
_constructor_call_patterns = {name: re.compile(rf"\b{re.escape(name)}\s*\(") for name in constructors}
def _has_constructor_call(expression: str, constructor: str) -> bool:
return _constructor_call_patterns[constructor].search(expression) is not None
def _find_constructor_call(expression: str, constructor: str) -> re.Match | None:
return _constructor_call_patterns[constructor].search(expression)
relational_ops = ["==", "!=", "<", "<=", ">", ">="]
logical_ops = ["&", "|", "^", "~"]
not_complex_ops = ["maximum", "minimum", "<", "<=", ">", ">="]
funcs_2args = (
"arctan2",
"contains",
"pow",
"power",
"nextafter",
"copysign",
"hypot",
"maximum",
"minimum",
)
def get_expr_globals(expression):
"""Build a dictionary of functions needed for evaluating the expression."""
_globals = {"np": np, "blosc2": blosc2}
# Only check for functions that actually appear in the expression
# This avoids many unnecessary string searches
for func in functions:
if func in expression:
# Try blosc2 first
if hasattr(blosc2, func):
_globals[func] = getattr(blosc2, func)
# Fall back to numpy
else:
try:
_globals[func] = safe_numpy_globals[func]
# Function not found in either module
except KeyError as e:
raise AttributeError(f"Function {func} not found in blosc2 or numpy") from e
return _globals
if not hasattr(enum, "member"):
# copy-pasted from Lib/enum.py
class _mymember:
"""
Forces item to become an Enum member during class creation.
"""
def __init__(self, value):
self.value = value
else:
_mymember = enum.member # only available after python 3.11
class ReduceOp(Enum):
"""
Available reduce operations.
"""
# wrap as enum.member so that Python doesn't treat some funcs
# as class methods (rather than Enum members)
SUM = _mymember(np.add)
PROD = _mymember(np.multiply)
MEAN = _mymember(np.mean)
STD = _mymember(np.std)
VAR = _mymember(np.var)
# Computing a median from partial results is not straightforward because the median
# is a positional statistic, which means it depends on the relative ordering of all
# the data points. Unlike statistics such as the sum or mean, you can't compute a median
# from partial results without knowing the entire dataset, and this is way too expensive
# for arrays that cannot typically fit in-memory (e.g. disk-based NDArray).
# MEDIAN = np.median
MAX = _mymember(np.maximum)
MIN = _mymember(np.minimum)
ANY = _mymember(np.any)
ALL = _mymember(np.all)
ARGMAX = _mymember(np.argmax)
ARGMIN = _mymember(np.argmin)
CUMULATIVE_SUM = _mymember(npcumsum)
CUMULATIVE_PROD = _mymember(npcumprod)
class LazyArrayEnum(Enum):
"""
Available LazyArrays.
"""
Expr = 0
UDF = 1
class LazyArray(ABC, blosc2.Operand):
@abstractmethod
def indices(self, order: str | list[str] | None = None) -> blosc2.LazyArray:
"""
Return an :ref:`LazyArray` containing the indices where self is True.
The LazyArray must be of bool dtype (e.g. a condition).
Parameters
----------
order: str, list of str, optional
Specifies which fields to compare first, second, etc. A single
field can be specified as a string. Not all fields need to be
specified, only the ones by which the array is to be sorted.
Returns
-------
out: :ref:`LazyArray`
The indices of the :ref:`LazyArray` self that are True.
"""
pass
@abstractmethod
def sort(self, order: str | list[str] | None = None) -> blosc2.LazyArray:
"""
Return a sorted :ref:`LazyArray`.
This is only valid for LazyArrays with structured dtypes.
Parameters
----------
order: str, list of str, optional
Specifies which fields to compare first, second, etc. A single
field can be specified as a string. Not all fields need to be
specified, only the ones by which the array is to be sorted.
Returns
-------
out: :ref:`LazyArray`
A sorted :ref:`LazyArray`.
"""
pass
@abstractmethod
def compute(
self,
item: slice | list[slice] | None = None,
fp_accuracy: blosc2.FPAccuracy = blosc2.FPAccuracy.DEFAULT,
**kwargs: Any,
) -> blosc2.NDArray:
"""
Return a :ref:`NDArray` containing the evaluation of the :ref:`LazyArray`.
Parameters
----------
item: slice, list of slices, optional
If provided, item is used to slice the operands *prior* to computation; not to retrieve specified slices of
the evaluated result. This difference between slicing operands and slicing the final expression
is important when reductions or a where clause are used in the expression.
fp_accuracy: :ref:`blosc2.FPAccuracy`, optional
Specifies the floating-point accuracy to be used during computation.
By default, :ref:`blosc2.FPAccuracy.DEFAULT` is used.
kwargs: Any, optional
Keyword arguments that are supported by the :func:`empty` constructor.
These arguments will be set in the resulting :ref:`NDArray`.
Additionally, the following special kwargs are supported:
Returns
-------
out: :ref:`NDArray`
A :ref:`NDArray` containing the result of evaluating the
:ref:`LazyUDF` or :ref:`LazyExpr`.
Notes
-----
* If self is a LazyArray from an udf, the kwargs used to store the resulting
array will be the ones passed to the constructor in :func:`lazyudf` (except the
`urlpath`) updated with the kwargs passed when calling this method.
Examples
--------
>>> import blosc2
>>> import numpy as np
>>> dtype = np.float64
>>> shape = [3, 3]
>>> size = shape[0] * shape[1]
>>> a = np.linspace(0, 5, num=size, dtype=dtype).reshape(shape)
>>> b = np.linspace(0, 5, num=size, dtype=dtype).reshape(shape)
>>> # Convert numpy arrays to Blosc2 arrays
>>> a1 = blosc2.asarray(a)
>>> b1 = blosc2.asarray(b)
>>> # Perform the mathematical operation
>>> expr = a1 + b1
>>> output = expr.compute()
>>> f"Result of a + b (lazy evaluation): {output[:]}"
Result of a + b (lazy evaluation):
[[ 0. 1.25 2.5 ]
[ 3.75 5. 6.25]
[ 7.5 8.75 10. ]]
"""
pass
@abstractmethod
def __getitem__(self, item: int | slice | Sequence[slice]) -> np.ndarray:
"""
Return a numpy.ndarray containing the evaluation of the :ref:`LazyArray`.
Parameters
----------
item: int, slice or sequence of slices
If provided, item is used to slice the operands *prior* to computation; not to retrieve specified slices of
the evaluated result. This difference between slicing operands and slicing the final expression
is important when reductions or a where clause are used in the expression.
Returns
-------
out: np.ndarray
An array with the data containing the evaluated slice.
Examples
--------
>>> import blosc2
>>> import numpy as np
>>> dtype = np.float64
>>> shape = [30, 4]
>>> size = shape[0] * shape[1]
>>> a = np.linspace(0, 10, num=size, dtype=dtype).reshape(shape)
>>> b = np.linspace(0, 10, num=size, dtype=dtype).reshape(shape)
>>> # Convert numpy arrays to Blosc2 arrays
>>> a1 = blosc2.asarray(a)
>>> b1 = blosc2.asarray(b)
>>> # Perform the mathematical operation
>>> expr = a1 + b1 # LazyExpr expression
>>> expr[3]
[2.01680672 2.18487395 2.35294118 2.5210084 ]
>>> expr[2:4]
[[1.34453782 1.51260504 1.68067227 1.8487395 ]
[2.01680672 2.18487395 2.35294118 2.5210084 ]]
"""
pass
@abstractmethod
def save(self, **kwargs: Any) -> None:
"""
Save the :ref:`LazyArray` on disk.
Parameters
----------
kwargs: Any, optional
Keyword arguments that are supported by the :func:`empty` constructor.
The `urlpath` must always be provided.
Returns
-------
out: None
Notes
-----
* All the operands of the LazyArray must be Python scalars, or :ref:`blosc2.Array` objects.
* If an operand is a :ref:`Proxy`, keep in mind that Python-Blosc2 will only be able to reopen it as such
if its source is a :ref:`SChunk`, :ref:`NDArray` or a :ref:`C2Array` (see :func:`blosc2.open` notes
section for more info).
* This is currently only supported for :ref:`LazyExpr`.
Examples
--------
>>> import blosc2
>>> import numpy as np
>>> dtype = np.float64
>>> shape = [3, 3]
>>> size = shape[0] * shape[1]
>>> a = np.linspace(0, 5, num=size, dtype=dtype).reshape(shape)
>>> b = np.linspace(0, 5, num=size, dtype=dtype).reshape(shape)
>>> # Define file paths for storing the arrays
>>> a1 = blosc2.asarray(a, urlpath='a_array.b2nd', mode='w')
>>> b1 = blosc2.asarray(b, urlpath='b_array.b2nd', mode='w')
>>> # Perform the mathematical operation to create a LazyExpr expression
>>> expr = a1 + b1
>>> # Save the LazyExpr to disk
>>> expr.save(urlpath='lazy_array.b2nd', mode='w')
>>> # Open and load the LazyExpr from disk
>>> disk_expr = blosc2.open('lazy_array.b2nd')
>>> disk_expr[:2]
[[0. 1.25 2.5 ]
[3.75 5. 6.25]]
"""
pass
# Provide a way to serialize the LazyArray
def to_cframe(self) -> bytes:
"""
Compute LazyArray and convert to cframe.
Returns
-------
out: bytes
The buffer containing the serialized :ref:`NDArray` instance.
"""
return self.compute().to_cframe()
@abstractproperty
def chunks(self) -> tuple[int]:
"""
Return :ref:`LazyArray` chunks.
"""
pass
@abstractproperty
def blocks(self) -> tuple[int]:
"""
Return :ref:`LazyArray` blocks.
"""
pass
def get_chunk(self, nchunk):
"""Get the `nchunk` of the expression, evaluating only that one."""
# Create an empty array with the chunkshape and dtype; this is fast
shape = self.shape
chunks = self.chunks
# Calculate the shape of the (chunk) slice_ (especially at the end of the array)
chunks_idx, _ = get_chunks_idx(shape, chunks)
coords = tuple(np.unravel_index(nchunk, chunks_idx))
slice_ = tuple(
slice(c * s, min((c + 1) * s, shape[i]))
for i, (c, s) in enumerate(zip(coords, chunks, strict=True))
)
loc_chunks = tuple(s.stop - s.start for s in slice_)
out = blosc2.empty(shape=self.chunks, dtype=self.dtype, chunks=self.chunks, blocks=self.blocks)
if loc_chunks == self.chunks:
self.compute(item=slice_, out=out)
else:
_slice_ = tuple(slice(0, s) for s in loc_chunks)
out[_slice_] = self.compute(item=slice_)
return out.schunk.get_chunk(0)
def convert_inputs(inputs):
if not inputs or len(inputs) == 0:
return []
inputs_ = []
for obj in inputs:
if not isinstance(obj, (np.ndarray, blosc2.Operand)) and not np.isscalar(obj):
try:
obj = blosc2.SimpleProxy(obj)
except Exception:
print(
"Inputs not being np.ndarray, Array or Python scalar objects"
" should be convertible to SimpleProxy."
)
raise
inputs_.append(obj)
return inputs_
def compute_broadcast_shape(arrays):
"""
Returns the shape of the outcome of an operation with the input arrays.
"""
# When dealing with UDFs, one can arrive params that are not arrays
shapes = [arr.shape for arr in arrays if hasattr(arr, "shape") and arr is not np]
return np.broadcast_shapes(*shapes) if shapes else None
# Define the patterns for validation
validation_patterns = [
r"[\;]", # Flow control characters
r"(^|[^\w])__[\w]+__($|[^\w])", # Dunder methods
r"\.\b(?!real|imag|T|mT|(\d*[eE]?[+-]?\d+)|(\d*[eE]?[+-]?\d+j)|\d*j\b|(sum|prod|min|max|std|mean|var|any|all|where)"
r"\s*\([^)]*\)|[a-zA-Z_]\w*\s*\([^)]*\))", # Attribute patterns
]
# Compile the blacklist regex
_blacklist_re = re.compile("|".join(validation_patterns))
# Define valid method names
valid_methods = {
"sum",
"prod",
"min",
"max",
"std",
"mean",
"var",
"any",
"all",
"where",
"reshape",
"slice",
}
valid_methods |= {"int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"}
valid_methods |= {"float32", "float64", "complex64", "complex128"}
valid_methods |= {"bool", "str", "bytes"}
valid_methods |= {
name for name in dir(blosc2.NDArray) if not name.startswith("_")
} # allow attributes and methods
def validate_expr(expr: str) -> None:
"""
Validate expression for forbidden syntax and valid method names.
Parameters
----------
expr : str
The expression to validate.
Returns
-------
None
"""
# Remove whitespace and skip quoted strings
no_whitespace = re.sub(r"\s+", "", expr)
skip_quotes = re.sub(r"(\'[^\']*\')", "", no_whitespace)
# Check for forbidden patterns
forbiddens = _blacklist_re.search(skip_quotes)
if forbiddens is not None:
raise ValueError(f"'{expr}' is not a valid expression.")
# Check for invalid characters not covered by the tokenizer
invalid_chars = re.compile(r"[^\w\s+\-*/%()[].,=<>!&|~^]")
if invalid_chars.search(skip_quotes) is not None:
invalid_chars = invalid_chars.findall(skip_quotes)
raise ValueError(f"Expression {expr} contains invalid characters: {invalid_chars}")
# Check for invalid method names
method_calls = re.findall(r"\.\b(\w+)\s*\(", skip_quotes)
for method in method_calls:
if method not in valid_methods:
raise ValueError(f"Invalid method name: {method}")
def extract_and_replace_slices(expr, operands):
"""
Return new expression and operands with op.slice(...) replaced by temporary operands.
"""
# Copy shapes and operands
shapes = {k: () if not hasattr(v, "shape") else v.shape for k, v in operands.items()}
new_ops = operands.copy() # copy dictionary
# Parse the expression
tree = ast.parse(expr, mode="eval")
# Mapping of AST nodes to new variable names
replacements = {}
class SliceCollector(ast.NodeTransformer):
def visit_Call(self, node):
# Recursively visit children first
self.generic_visit(node)
# Detect method calls: obj.slice(...)
if isinstance(node.func, ast.Attribute) and node.func.attr == "slice":
obj = node.func.value
# If the object is already replaced, keep the replacement
base_name = None
if isinstance(obj, ast.Name):
base_name = obj.id
elif isinstance(obj, ast.Call) and obj in replacements:
base_name = replacements[obj]["base_var"]
# Build the full slice chain expression as a string
full_expr = ast.unparse(node)
# Create a new temporary variable
new_var = f"o{len(new_ops)}"
# Infer shape
try:
shape = infer_shape(full_expr, shapes)
except Exception as e:
print(f"Shape inference failed for {full_expr}: {e}")
shape = ()
# Determine dtype
dtype = new_ops[base_name].dtype if base_name else None
# Create placeholder array
if isinstance(new_ops[base_name], blosc2.NDArray):
new_op = blosc2.ones((1,) * len(shape), dtype=dtype)
else:
new_op = np.ones((1,) * len(shape), dtype=dtype)
new_ops[new_var] = new_op
shapes[new_var] = shape
# Record replacement
replacements[node] = {"new_var": new_var, "base_var": base_name}
# Replace the AST node with the new variable
return ast.Name(id=new_var, ctx=ast.Load())
return node
# Transform the AST
transformer = SliceCollector()
new_tree = transformer.visit(tree)
ast.fix_missing_locations(new_tree)
# Convert back to expression string
new_expr = ast.unparse(new_tree)
return new_expr, new_ops
def get_expr_operands(expression: str) -> set:
"""
Given an expression in string form, return its operands.
Parameters
----------
expression : str
The expression in string form.
Returns
-------
set
A set of operands found in the expression.
"""
class OperandVisitor(ast.NodeVisitor):
def __init__(self):
self.operands = set()
self.function_names = set()
def visit_Name(self, node):
if node.id == "np":
# Skip NumPy namespace (e.g. np.int8, which will be treated separately)
return
if node.id not in self.function_names and node.id not in dtype_symbols:
self.operands.add(node.id)
self.generic_visit(node)
def visit_Call(self, node):
if isinstance(node.func, ast.Name):
self.function_names.add(node.func.id)
self.generic_visit(node)
tree = ast.parse(expression)
visitor = OperandVisitor()
visitor.visit(tree)
return set(visitor.operands)
def conserve_functions( # noqa: C901
expression: str,
operands_old: dict[str, blosc2.Array],
operands_new: dict[str, blosc2.Array],
) -> tuple[str, dict[str, blosc2.Array]]:
"""
Given an expression in string form, return its operands.
Parameters
----------
expression : str
The expression in string form.
operands_old: dict[str : blosc2.ndarray | blosc2.LazyExpr]
Dict of operands from expression prior to eval.
operands_new: dict[str : blosc2.ndarray | blosc2.LazyExpr]
Dict of operands from expression after eval.
Returns
-------
newexpression
A modified string expression with the functions/constructors conserved and
true operands rebased and written in o- notation.
newoperands
Dict of the set of rebased operands.
"""
operand_to_key = {id(v): k for k, v in operands_new.items()}
for k, v in operands_old.items(): # extend operands_to_key with old operands
if isinstance(
v, blosc2.LazyExpr
): # unroll operands in LazyExpr (only necessary when have reduced a lazyexpr)
d = v.operands
else:
d = {k: v}
for newk, newv in d.items():
try:
operand_to_key[id(newv)]
except KeyError:
newk = (
f"o{len(operands_new)}" if newk in operands_new else newk
) # possible that names coincide
operand_to_key[id(newv)] = newk
operands_new[newk] = newv
class OperandVisitor(ast.NodeVisitor):
def __init__(self):
self.operandmap = {}
self.operands = {}
self.opcounter = 0
self.function_names = set()
def update_func(self, localop):
k = operand_to_key[id(localop)]
if k not in self.operandmap:
newkey = f"o{self.opcounter}"
self.operands[newkey] = operands_new[k]
self.operandmap[k] = newkey
self.opcounter += 1
return newkey
else:
return self.operandmap[k]
def visit_Name(self, node):
if node.id == "np": # Skip NumPy namespace (e.g. np.int8, which will be treated separately)
return
if node.id in self.function_names: # Skip function names
return
elif node.id not in dtype_symbols:
localop = operands_old[node.id]
if isinstance(localop, blosc2.LazyExpr):
newexpr = localop.expression
for (
opname,
v,
) in localop.operands.items(): # expression operands already in terms of basic operands
# add illegal character ; to track changed operands and not overwrite later
newopname = ";" + self.update_func(v)
newexpr = re.sub(
rf"(?<=\s){opname}|(?<=\(){opname}", newopname, newexpr
) # replace with newopname
# remove all instances of ; as all changes completed
node.id = newexpr.replace(";", "")
else:
node.id = self.update_func(localop)
self.generic_visit(node)
def visit_Call(self, node):
if isinstance(
node.func, ast.Name
): # visits Call first, then Name, so don't increment operandcounter yet
self.function_names.add(node.func.id)
self.generic_visit(node)
tree = ast.parse(expression)
visitor = OperandVisitor()
visitor.visit(tree)
newexpression, newoperands = ast.unparse(tree), visitor.operands
return newexpression, newoperands
def convert_to_slice(expression):
"""
Takes expression and converts all instances of [] to .slice(....)
Parameters
----------
expression: str
Returns
-------
new_expr : str
"""
new_expr = ""
skip_to_char = 0
for i, expr_i in enumerate(expression):
if i < skip_to_char:
continue
if expr_i == "[":
k = expression[i:].find("]") # start checking from after [
slice_convert = expression[i : i + k + 1] # include [ and ]
try:
slicer = eval(f"np.s_{slice_convert}")
slicer = (slicer,) if not isinstance(slicer, tuple) else slicer # standardise to tuple
if any(isinstance(el, str) for el in slicer): # handle fields
raise ValueError("Cannot handle fields for slicing lazy expressions.")
slicer = str(slicer)
# use slice so that lazyexpr uses blosc arrays internally
# (and doesn't decompress according to getitem syntax)
new_expr += f".slice({slicer})"
skip_to_char = i + k + 1
continue
except Exception:
pass
new_expr += expr_i # if slice_convert is e.g. a list, not a slice, do nothing
return new_expr
class TransformNumpyCalls(ast.NodeTransformer):
def __init__(self):
self.replacements = {}
self.tmp_counter = 0
def visit_Call(self, node):
# Check if the call is a numpy type-casting call
if (
isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name)
and node.func.value.id in ["np", "numpy"]
and isinstance(node.args[0], ast.Constant)
):
# Create a new temporary variable name
tmp_var = f"tmp{self.tmp_counter}"
self.tmp_counter += 1
# Evaluate the type-casting call to create the new variable's value
numpy_type = getattr(np, node.func.attr)
self.replacements[tmp_var] = numpy_type(node.args[0].value)
# Replace the call node with a variable node
return ast.copy_location(ast.Name(id=tmp_var, ctx=ast.Load()), node)
return self.generic_visit(node)
def extract_numpy_scalars(expr: str):
# Parse the expression into an AST
tree = ast.parse(expr, mode="eval")
# Transform the AST
transformer = TransformNumpyCalls()
transformed_tree = transformer.visit(tree)
# Generate the modified expression
transformed_expr = ast.unparse(transformed_tree)
return transformed_expr, transformer.replacements
def validate_inputs(inputs: dict, out=None, reduce=False) -> tuple: # noqa: C901
"""Validate the inputs for the expression."""
if not inputs:
if out is None:
raise ValueError(
"You really want to pass at least one input or one output for building a LazyArray."
" Maybe you want blosc2.empty() instead?"
)
if isinstance(out, blosc2.NDArray):
return out.shape, out.chunks, out.blocks, True
else:
return out.shape, None, None, True
inputs = [input for input in inputs.values() if hasattr(input, "shape") and input is not np]
# This will raise an exception if the input shapes are not compatible
shape = compute_broadcast_shape(inputs)
if not all(np.array_equal(shape, input.shape) for input in inputs):
# If inputs have different shapes, we cannot take the fast path
return shape, None, None, False
# More checks specific of NDArray inputs
# NDInputs are either non-SimpleProxy with chunks or are SimpleProxy with src having chunks
NDinputs = [