-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy path__init__.py
More file actions
814 lines (734 loc) · 16 KB
/
__init__.py
File metadata and controls
814 lines (734 loc) · 16 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
#######################################################################
# 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)
#######################################################################
# Hey Ruff, please ignore the next violations
# ruff: noqa: E402 - Module level import not at top of file
# ruff: noqa: F401 - `var` imported but unused
import platform
from enum import Enum
import numpy as np
# Do the platform check once at module level
IS_WASM = platform.machine() == "wasm32"
# IS_WASM = True # for testing (comment this line out for production)
"""
Flag for WebAssembly platform.
"""
if not IS_WASM:
import numexpr
from .version import __array_api_version__, __version__
__version__ = __version__
__array_api_version__ = __array_api_version__
"""
Python-Blosc2 version.
"""
class Codec(Enum):
"""
Available codecs.
"""
BLOSCLZ = 0
LZ4 = 1
LZ4HC = 2
ZLIB = 4
ZSTD = 5
NDLZ = 32
ZFP_ACC = 33
ZFP_PREC = 34
ZFP_RATE = 35
#: Needs to be installed with ``pip install blosc2-openhtj2k``
OPENHTJ2K = 36
#: Needs to be installed with ``pip install blosc2-grok``
GROK = 37
class Filter(Enum):
"""
Available filters.
"""
NOFILTER = 0
SHUFFLE = 1
BITSHUFFLE = 2
DELTA = 3
TRUNC_PREC = 4
NDCELL = 32
NDMEAN = 33
BYTEDELTA = 35
INT_TRUNC = 36
class SplitMode(Enum):
"""
Available split modes.
"""
ALWAYS_SPLIT = 1
NEVER_SPLIT = 2
AUTO_SPLIT = 3
FORWARD_COMPAT_SPLIT = 4
class SpecialValue(Enum):
"""
Possible special values in a chunk.
"""
NOT_SPECIAL = 0
ZERO = 1
NAN = 2
VALUE = 3
UNINIT = 4
class Tuner(Enum):
"""
Available tuners.
"""
#: A 'simple' tuner. This is the default in the Blosc2 library
STUNE = 0
#: A more sophisticated tuner that can select different codecs/filters for different chunks
#: (more info `here <https://github.com/Blosc/blosc2_btune/>`_); Needs to be installed with
#: ``pip install blosc2-btune``
BTUNE = 32
from .blosc2_ext import (
DEFINED_CODECS_STOP,
EXTENDED_HEADER_LENGTH,
GLOBAL_REGISTERED_CODECS_STOP,
MAX_BLOCKSIZE,
MAX_BUFFERSIZE,
MAX_DIM,
MAX_OVERHEAD,
MAX_TYPESIZE,
MIN_HEADER_LENGTH,
USER_REGISTERED_CODECS_STOP,
VERSION_DATE,
VERSION_STRING,
)
DEFINED_CODECS_STOP = DEFINED_CODECS_STOP
"""
Maximum possible Blosc2-defined codec id."""
GLOBAL_REGISTERED_CODECS_STOP = GLOBAL_REGISTERED_CODECS_STOP
"""
Maximum possible Blosc2 global registered codec id."""
USER_REGISTERED_CODECS_STOP = USER_REGISTERED_CODECS_STOP
"""
Maximum possible Blosc2 user registered codec id."""
EXTENDED_HEADER_LENGTH = EXTENDED_HEADER_LENGTH
"""
Blosc2 extended header length in bytes."""
MAX_BUFFERSIZE = MAX_BUFFERSIZE
"""
Maximum buffer size in bytes for a Blosc2 chunk."""
MAX_FAST_PATH_SIZE = 2**30
"""
Maximum size in bytes for a fast path evaluation.
"""
MAX_OVERHEAD = MAX_OVERHEAD
"""
Maximum overhead during compression (in bytes). This is
equal to :py:obj:`blosc2.EXTENDED_HEADER_LENGTH <EXTENDED_HEADER_LENGTH>`."""
MAX_TYPESIZE = MAX_TYPESIZE
"""
Blosc2 maximum type size (in bytes)."""
MIN_HEADER_LENGTH = MIN_HEADER_LENGTH
"""
Blosc2 minimum header length (in bytes)."""
VERSION_DATE = VERSION_DATE
"""
The C-Blosc2 version's date."""
VERSION_STRING = VERSION_STRING
"""
The C-Blosc2 version's string."""
# For array-api compatibility
iinfo = np.iinfo
finfo = np.finfo
def isdtype(a_dtype: np.dtype, kind: str | np.dtype | tuple):
"""
Returns a boolean indicating whether a provided dtype is of a specified data type "kind".
Parameters
----------
dtype: dtype
The input dtype.
kind: str | dtype | Tuple[str, dtype]
Data type kind.
If kind is a dtype, return boolean indicating whether the input dtype is equal to the dtype specified by kind.
If kind is a string, return boolean indicating whether the input dtype is of a specified data type kind.
The following dtype kinds are supporte:
* 'bool': boolean data types (e.g., bool).
* 'signed integer': signed integer data types (e.g., int8, int16, int32, int64).
* 'unsigned integer': unsigned integer data types (e.g., uint8, uint16, uint32, uint64).
* 'integral': integer data types. Shorthand for ('signed integer', 'unsigned integer').
* 'real floating': real-valued floating-point data types (e.g., float32, float64).
* 'complex floating': complex floating-point data types (e.g., complex64, complex128).
* 'numeric': numeric data types. Shorthand for ('integral', 'real floating', 'complex floating').
Returns
-------
out: bool
Boolean indicating whether a provided dtype is of a specified data type kind.
"""
kind = (kind,) if not isinstance(kind, tuple) else kind
for _ in kind:
if a_dtype == kind:
return True
_complex, _signedint, _uint, _rfloat = False, False, False, False
if a_dtype in (complex64, complex128):
_complex = True
if "complex floating" in kind:
return True
if a_dtype == bool_ and "bool" in kind:
return True
if a_dtype in (int8, int16, int32, int64):
_signedint = True
if "signed integer" in kind:
return True
if a_dtype in (uint8, uint16, uint32, uint64):
_uint = True
if "unsigned integer" in kind:
return True
if a_dtype in (float16, float32, float64):
_rfloat = True
if "real floating" in kind:
return True
if "integral" in kind and (_signedint or _uint):
return True
return "numeric" in kind and (
_signedint or _uint or _rfloat or _complex
) # checked everything, otherwise False
# dtypes for array-api
str_ = np.str_
bytes_ = np.bytes_
object_ = np.object_
from numpy import (
bool_,
complex64,
complex128,
e,
euler_gamma,
float16,
float32,
float64,
inf,
int8,
int16,
int32,
int64,
nan,
newaxis,
pi,
uint8,
uint16,
uint32,
uint64,
)
bool = bool
DEFAULT_COMPLEX = complex128
"""
Default complex floating dtype."""
DEFAULT_FLOAT = float64
"""
Default real floating dtype."""
DEFAULT_INT = int64
"""
Default integer dtype."""
DEFAULT_INDEX = int64
"""
Default indexing dtype."""
class Info:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def __array_namespace_info__() -> Info:
"""
Return information about the array namespace following the Array API specification.
"""
def _raise(exc):
raise exc
return Info(
capabilities=lambda: {
"boolean indexing": True,
"data-dependent shapes": False,
"max dimensions": MAX_DIM,
},
default_device=lambda: "cpu",
default_dtypes=lambda device=None: {
"real floating": DEFAULT_FLOAT,
"complex floating": DEFAULT_COMPLEX,
"integral": DEFAULT_INT,
"indexing": DEFAULT_INDEX,
}
if (device == "cpu" or device is None)
else _raise(ValueError("Only cpu devices allowed")),
dtypes=lambda device=None, kind=None: np.__array_namespace_info__().dtypes(kind=kind, device=device)
if (device == "cpu" or device is None)
else _raise(ValueError("Only cpu devices allowed")),
devices=lambda: ["cpu"],
name="blosc2",
version=__version__,
)
# Public API for container module
from .core import (
clib_info,
compress,
compress2,
compressor_list,
compute_chunks_blocks,
decompress,
decompress2,
detect_number_of_cores,
free_resources,
from_cframe,
get_blocksize,
get_cbuffer_sizes,
get_clib,
get_compressor,
get_cpu_info,
load_array,
load_tensor,
ndarray_from_cframe,
pack,
pack_array,
pack_array2,
pack_tensor,
print_versions,
register_codec,
register_filter,
remove_urlpath,
save_array,
save_tensor,
schunk_from_cframe,
set_blocksize,
set_compressor,
set_nthreads,
set_releasegil,
unpack,
unpack_array,
unpack_array2,
unpack_tensor,
)
# Internal Blosc threading
# Get CPU info
cpu_info = get_cpu_info()
nthreads = ncores = cpu_info.get("count", 1)
"""Number of threads to be used in compression/decompression.
"""
# Protection against too many threads
nthreads = min(nthreads, 64)
# Experiments say that, when using a large number of threads, it is better to not use them all
if nthreads > 16:
nthreads -= nthreads // 8
if not IS_WASM:
# WASM does not support threading
numexpr.set_num_threads(nthreads)
# This import must be before ndarray and schunk
from .storage import ( # noqa: I001
CParams,
cparams_dflts,
DParams,
dparams_dflts,
Storage,
storage_dflts,
)
from .ndarray import (
Array,
NDArray,
NDField,
Operand,
are_partitions_aligned,
are_partitions_behaved,
arange,
broadcast_to,
linspace,
eye,
asarray,
astype,
indices,
sort,
reshape,
copy,
concat,
expand_dims,
empty,
empty_like,
frombuffer,
fromiter,
get_slice_nchunks,
meshgrid,
nans,
uninit,
zeros,
zeros_like,
ones,
ones_like,
full,
full_like,
save,
stack,
)
from .embed_store import EmbedStore, estore_from_cframe
from .dict_store import DictStore
from .tree_store import TreeStore
from .c2array import c2context, C2Array, URLPath
from .lazyexpr import (
LazyExpr,
lazyudf,
lazyexpr,
LazyArray,
_open_lazyarray,
get_expr_operands,
validate_expr,
evaluate,
result_type,
can_cast,
)
from .proxy import Proxy, ProxySource, ProxyNDSource, ProxyNDField, SimpleProxy, jit, as_simpleproxy
from .schunk import SChunk, open
from . import linalg
from .linalg import tensordot, vecdot, permute_dims, matrix_transpose, matmul, transpose, diagonal, outer
from . import fft
# Registry for postfilters
postfilter_funcs = {}
"""
Registry for postfilter functions. For more info see
:func:`SChunk.postfilter <blosc2.schunk.SChunk.postfilter>`"""
# Registry for prefilters
prefilter_funcs = {}
"""
Registry for prefilter functions. For more info see
:func:`SChunk.prefilter <blosc2.schunk.SChunk.prefilter>`"""
# Registry for user-defined codecs
ucodecs_registry = {}
"""
Registry for user-defined codecs. For more info see
:func:`blosc2.register_codec <blosc2.register_codec>`"""
# Registry for user-defined filters
ufilters_registry = {}
"""
Registry for user-defined filters. For more info see
:func:`blosc2.register_filter <blosc2.register_filter>`"""
blosclib_version = f"{VERSION_STRING} ({VERSION_DATE})"
"""
The blosc2 version + date.
"""
# Private global variables
_disable_overloaded_equal = False
"""
Disable the overloaded equal operator.
"""
# Delayed imports for avoiding overwriting of python builtins
from .ndarray import (
abs,
acos,
acosh,
add,
all,
any,
arccos,
arccosh,
arcsin,
arcsinh,
arctan,
arctan2,
arctanh,
array_from_ffi_ptr,
asin,
asinh,
atan,
atan2,
atanh,
bitwise_and,
bitwise_invert,
bitwise_left_shift,
bitwise_or,
bitwise_right_shift,
bitwise_xor,
ceil,
clip,
conj,
contains,
copysign,
cos,
cosh,
count_nonzero,
divide,
equal,
exp,
expm1,
floor,
floor_divide,
greater,
greater_equal,
hypot,
imag,
isfinite,
isinf,
isnan,
lazywhere,
less,
less_equal,
log,
log1p,
log2,
log10,
logaddexp,
logical_and,
logical_not,
logical_or,
logical_xor,
max,
maximum,
mean,
min,
minimum,
multiply,
negative,
nextafter,
not_equal,
positive,
pow,
prod,
real,
reciprocal,
remainder,
round,
sign,
signbit,
sin,
sinh,
sqrt,
square,
squeeze,
std,
subtract,
sum,
take,
take_along_axis,
tan,
tanh,
trunc,
var,
where,
)
__all__ = [ # noqa : RUF022
# Constants
"EXTENDED_HEADER_LENGTH",
"MAX_BUFFERSIZE",
"MAX_TYPESIZE",
"MIN_HEADER_LENGTH",
"VERSION_DATE",
"VERSION_STRING",
# Default dtypes
"DEFAULT_COMPLEX",
"DEFAULT_FLOAT",
"DEFAULT_INDEX",
"DEFAULT_INT",
# Mathematical constants
"e",
"pi",
"inf",
"nan",
"newaxis",
# Classes
"C2Array",
"CParams",
# Enums
"Codec",
"DParams",
"DictStore",
"EmbedStore",
"Filter",
"LazyArray",
"LazyExpr",
"NDArray",
"NDField",
"Operand",
"Proxy",
"ProxyNDField",
"ProxyNDSource",
"ProxySource",
"SChunk",
"SimpleProxy",
"SpecialValue",
"SplitMode",
"Storage",
"TreeStore",
"Tuner",
"URLPath",
# Version
"__version__",
# Functions
"abs",
"acos",
"acosh",
"add",
"all",
"any",
"arange",
"arccos",
"arccosh",
"arcsin",
"arcsinh",
"arctan",
"arctan2",
"arctanh",
"are_partitions_aligned",
"are_partitions_behaved",
"array_from_ffi_ptr",
"asarray",
"asin",
"asinh",
"as_simpleproxy",
"astype",
"atan",
"atan2",
"atanh",
"bitwise_and",
"bitwise_invert",
"bitwise_left_shift",
"bitwise_or",
"bitwise_right_shift",
"bitwise_xor",
"broadcast_to",
"can_cast",
"ceil",
"clib_info",
"clip",
"compress",
"compress2",
"compressor_list",
"compute_chunks_blocks",
"concat",
"conj",
"contains",
"copy",
"copysign",
"cos",
"cosh",
"count_nonzero",
"cparams_dflts",
"cpu_info",
"decompress",
"decompress2",
"detect_number_of_cores",
"divide",
"dparams_dflts",
"empty",
"empty_like",
"equal",
"estore_from_cframe",
"exp",
"expand_dims",
"expm1",
"eye",
"finfo",
"floor",
"floor_divide",
"free_resources",
"from_cframe",
"frombuffer",
"fromiter",
"full",
"full_like",
"get_blocksize",
"get_cbuffer_sizes",
"get_clib",
"get_compressor",
"get_cpu_info",
"get_expr_operands",
"get_slice_nchunks",
"greater",
"greater_equal",
"hypot",
"imag",
"iinfo",
"indices",
"isdtype",
"isfinite",
"isinf",
"isnan",
"jit",
"lazyexpr",
"lazyudf",
"lazywhere",
"less",
"less_equal",
"linspace",
"load_array",
"load_tensor",
"log",
"log1p",
"log2",
"log10",
"logaddexp",
"logical_and",
"logical_not",
"logical_or",
"logical_xor",
"matmul",
"matrix_transpose",
"max",
"maximum",
"mean",
"meshgrid",
"min",
"minimum",
"multiply",
"nans",
"ndarray_from_cframe",
"negative",
"nextafter",
"not_equal",
"ones",
"ones_like",
"open",
"pack",
"pack_array",
"pack_array2",
"pack_tensor",
"permute_dims",
"positive",
"postfilter_funcs",
"pow",
"prefilter_funcs",
"print_versions",
"prod",
"real",
"reciprocal",
"register_codec",
"register_filter",
"remainder",
"remove_urlpath",
"reshape",
"result_type",
"round",
"save",
"save_array",
"save_tensor",
"schunk_from_cframe",
"set_blocksize",
"set_compressor",
"set_nthreads",
"set_releasegil",
"sign",
"signbit",
"sin",
"sinh",
"sort",
"sqrt",
"square",
"squeeze",
"stack",
"std",
"storage_dflts",
"subtract",
"sum",
"take",
"take_along_axis",
"tan",
"tanh",
"tensordot",
"transpose",
"trunc",
"uninit",
"unpack",
"unpack_array",
"unpack_array2",
"unpack_tensor",
"validate_expr",
"var",
"vecdot",
"where",
"zeros",
"zeros_like",
]