forked from inaos/iron-array-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhigh_level.py
More file actions
734 lines (543 loc) · 21.1 KB
/
Copy pathhigh_level.py
File metadata and controls
734 lines (543 loc) · 21.1 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
###########################################################################################
# Copyright INAOS GmbH, Thalwil, 2018.
# Copyright Francesc Alted, 2018.
#
# All rights reserved.
#
# This software is the confidential and proprietary information of INAOS GmbH
# and Francesc Alted ("Confidential Information"). You shall not disclose such Confidential
# Information and shall use it only in accordance with the terms of the license agreement.
###########################################################################################
import numpy as np
import numexpr as ne
import iarray as ia
from iarray import iarray_ext as ext
from itertools import zip_longest as zip
from collections import namedtuple
import warnings
def get_ncores(max_ncores=0):
"""Return the number of logical cores in the system.
This number is capped at `max_ncores`. When `max_ncores` is 0,
there is no cap at all.
"""
ncores = ext.get_ncores(max_ncores)
if ncores < 0:
warnings.warn("Error getting the number of cores in this system (please report this)."
" Falling back to 1.",
UserWarning)
return 1
return ncores
# List of all know universal functions
UFUNC_LIST = (
"abs", "arccos", "arcsin", "arctan", "arctan2", "ceil",
"cos", "cosh", "exp", "floor", "log", "log10", "negative",
"power", "sin", "sinh", "sqrt", "tan", "tanh",
)
def cmp_arrays(a, b, success=None):
if type(a) is ia.high_level.IArray:
a = ia.iarray2numpy(a)
if type(b) is ia.high_level.IArray:
b = ia.iarray2numpy(b)
if a.dtype == np.float64 and b.dtype == np.float64:
tol = 1e-14
else:
tol = 1e-6
np.testing.assert_allclose(a, b, rtol=tol, atol=tol)
if success is not None:
print(success)
def fuse_operands(operands1, operands2):
new_operands = {}
dup_operands = {}
new_pos = len(operands1)
for k2, v2 in operands2.items():
try:
k1 = list(operands1.keys())[list(operands1.values()).index(v2)]
# The operand is duplicated; keep track of it
dup_operands[k2] = k1
except ValueError:
# The value is not among operands1, so rebase it
new_op = f"o{new_pos}"
new_pos += 1
new_operands[new_op] = operands2[k2]
return new_operands, dup_operands
def fuse_expressions(expr, new_base, dup_op):
new_expr = ""
skip_to_char = 0
old_base = 0
for i in range(len(expr)):
if i < skip_to_char:
continue
if expr[i] == 'o':
try:
j = expr[i + 1:].index(' ')
except ValueError:
j = expr[i + 1:].index(')')
if expr[i + j] == ')':
j -= 1
old_pos = int(expr[i+1:i+j+1])
old_op = f"o{old_pos}"
if old_op not in dup_op:
new_pos = old_base + new_base
new_expr += f"o{new_pos}"
old_base += 1
else:
new_expr += dup_op[old_op]
skip_to_char = i + j + 1
else:
new_expr += expr[i]
return new_expr
class RandomContext(ext.RandomContext):
def __init__(self, **kwargs):
cfg = Config(**kwargs)
super().__init__(cfg)
class Config(ext._Config):
def __init__(self, clib=ia.LZ4, clevel=5, use_dict=0, filter_flags=ia.SHUFFLE, nthreads=0,
fp_mantissa_bits=0, blocksize=0, storage=None, eval_method=None, seed=0):
self._clib = clib
self._clevel = clevel
self._use_dict = use_dict
self._fp_mantissa_bits = fp_mantissa_bits
if fp_mantissa_bits > 0:
filter_flags |= ia.TRUNC_PREC
self._filter_flags = filter_flags
self._blocksize = blocksize
# Get the number of cores using nthreads as a maximum
self._nthreads = nthreads = get_ncores(nthreads)
self._seed = seed
# TODO: should we move this to its own eval configuration?
self._eval_method = ia.EVAL_AUTO if eval_method is None else eval_method
self._storage = ia.StorageProperties() if storage is None else storage
super().__init__(clib, clevel, use_dict, filter_flags, nthreads,
fp_mantissa_bits, self._eval_method)
@property
def clib(self):
clibs = ["BloscLZ", "LZ4", "LZ4HC", "Snappy", "Zlib", "Zstd", "Lizard"]
return clibs[self._clib]
@property
def clevel(self):
return self._clevel
@property
def filter_flags(self):
flags = {0: "NOFILTER", 1: "SHUFFLE", 2: "BITSHUFFLE", 4: "DELTA", 8: "TRUNC_PREC"}
return flags[self._filter_flags]
@property
def nthreads(self):
return self._nthreads
@property
def fp_mantissa_bits(self):
return self._fp_mantissa_bits
@property
def blocksize(self):
return self._blocksize
@property
def filename(self):
return self._filename
@property
def eval_method(self):
return self._eval_method
@property
def seed(self):
return self._seed
def __str__(self):
return (
"IArray Config object:\n"
f" Compression library: {self.clib}\n"
f" Compression level: {self.clevel}\n"
f" Filter flags: {self.filter_flags}\n"
f" Number of threads: {self.nthreads}\n"
f" Floating point mantissa bits: {self.fp_mantissa_bits}\n"
f" Blocksize: {self.blocksize}\n"
f" Filename: {self.filename}\n"
f" Eval flags: {self.eval_method}\n"
)
class LazyExpr:
def __init__(self, new_op):
value1, op, value2 = new_op
if value2 is None:
# ufunc
if isinstance(value1, LazyExpr):
self.expression = f"{op}({self.expression})"
else:
self.operands = {"o0": value1}
self.expression = f"{op}(o0)"
return
elif op in ("atan2", "pow"):
self.operands = {"o0": value1, "o1": value2}
self.expression = f"{op}(o0, o1)"
return
if isinstance(value1, (int, float)) and isinstance(value2, (int, float)):
self.expression = f"({value1} {op} {value2})"
elif isinstance(value2, (int, float)):
self.operands = {"o0": value1}
self.expression = f"(o0 {op} {value2})"
elif isinstance(value1, (int, float)):
self.operands = {"o0": value2}
self.expression = f"({value1} {op} o0)"
else:
if value1 == value2:
self.operands = {"o0": value1}
self.operands = {"o0": value1}
self.expression = f"(o0 {op} o0)"
elif isinstance(value1, LazyExpr) or isinstance(value2, LazyExpr):
if isinstance(value1, LazyExpr):
self.expression = value1.expression
self.operands = {"o0": value2}
else:
self.expression = value2.expression
self.operands = {"o0": value1}
self.update_expr(new_op)
else:
# This is the very first time that a LazyExpr is formed from two operands
# that are not LazyExpr themselves
self.operands = {"o0": value1, "o1": value2}
self.expression = f"(o0 {op} o1)"
def update_expr(self, new_op):
# One of the two operands are LazyExpr instances
value1, op, value2 = new_op
if isinstance(value1, LazyExpr) and isinstance(value2, LazyExpr):
# Expression fusion
# Fuse operands in expressions and detect duplicates
new_op, dup_op = fuse_operands(value1.operands, value2.operands)
# Take expression 2 and rebase the operands while removing duplicates
new_expr = fuse_expressions(value2.expression, len(value1.operands), dup_op)
self.expression = f"({self.expression} {op} {new_expr})"
self.operands.update(new_op)
elif isinstance(value1, LazyExpr):
if isinstance(value2, (int, float)):
self.expression = f"({self.expression} {op} {value2})"
else:
try:
op_name = list(value1.operands.keys())[list(value1.operands.values()).index(value2)]
except ValueError:
op_name = f"o{len(self.operands)}"
self.operands[op_name] = value2
self.expression = f"({self.expression} {op} {op_name})"
else:
if isinstance(value1, (int, float)):
self.expression = f"({value1} {op} {self.expression})"
else:
try:
op_name = list(value2.operands.keys())[list(value2.operands.values()).index(value1)]
except ValueError:
op_name = f"o{len(self.operands)}"
self.operands[op_name] = value1
self.expression = f"({op_name} {op} {self.expression})"
return self
def __add__(self, value):
return self.update_expr(new_op=(self, '+', value))
def __radd__(self, value):
return self.update_expr(new_op=(value, '+', self))
def __sub__(self, value):
return self.update_expr(new_op=(self, '-', value))
def __rsub__(self, value):
return self.update_expr(new_op=(value, '-', self))
def __mul__(self, value):
return self.update_expr(new_op=(self, '*', value))
def __rmul__(self, value):
return self.update_expr(new_op=(value, '*', self))
def __truediv__(self, value):
return self.update_expr(new_op=(self, '/', value))
def __rtruediv__(self, value):
return self.update_expr(new_op=(value, '/', self))
def eval(self, method="iarray_eval", dtype=None, **kwargs):
# TODO: see if shape and chunkshape can be instance variables, or better stay like this
o0 = self.operands['o0']
shape_ = o0.shape
cfg = Config(**kwargs)
chunkshape = shape_ if cfg._storage.chunkshape is None else cfg._storage.chunkshape
# TODO: figure out a better way to set a default for the dtype
dtype = o0.dtype if dtype is None else dtype
if method == "iarray_eval":
expr = Expr(**kwargs)
for k, v in self.operands.items():
if isinstance(v, IArray):
expr.bind(k, v)
dtshape = ia.dtshape(shape_, dtype)
expr.bind_out_properties(dtshape, cfg._storage)
expr.compile(self.expression)
out = expr.eval()
elif method == "numexpr":
out = ia.empty(ia.dtshape(shape=shape_, dtype=dtype), **kwargs)
operand_iters = tuple(o.iter_read_block(chunkshape)
for o in self.operands.values()
if isinstance(o, IArray))
# put the iterator for the output at the end
all_iters = operand_iters + (out.iter_write_block(chunkshape),)
for block in zip(*all_iters):
block_operands = {o: block[i][1] for (i, o) in enumerate(self.operands.keys(), start=0)}
out_block = block[-1][1] # the block for output is at the end, by construction
# block_operands = {o: block[i][1] for (i, o) in enumerate(self.operands.keys(), start=1)}
# out_block = block[0][1] # the block for output is at the front, by construction
ne.evaluate(self.expression, local_dict=block_operands, out=out_block)
else:
raise ValueError(f"Unrecognized '{method}' method")
return out
def __str__(self):
expression = f"{self.expression}"
return expression
# The main IronArray container (not meant to be called from user space)
class IArray(ext.Container):
def copy(self, view=False, **kwargs):
cfg = Config(**kwargs) # TODO: Pass chunkshape
return ext.copy(cfg, self, view)
def __add__(self, value):
return LazyExpr(new_op=(self, '+', value))
def __radd__(self, value):
return LazyExpr(new_op=(value, '+', self))
def __sub__(self, value):
return LazyExpr(new_op=(self, '-', value))
def __rsub__(self, value):
return LazyExpr(new_op=(value, '-', self))
def __mul__(self, value):
return LazyExpr(new_op=(self, '*', value))
def __rmul__(self, value):
return LazyExpr(new_op=(value, '*', self))
def __truediv__(self, value):
return LazyExpr(new_op=(self, '/', value))
def __rtruediv__(self, value):
return LazyExpr(new_op=(value, '/', self))
# def __array_function__(self, func, types, args, kwargs):
# if not all(issubclass(t, np.ndarray) for t in types):
# # Defer to any non-subclasses that implement __array_function__
# return NotImplemented
#
# # Use NumPy's private implementation without __array_function__
# # dispatching
# return func._implementation(*args, **kwargs)
# def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
# print("method:", method)
def abs(self):
return LazyExpr(new_op=(self, 'abs', None))
def arccos(self):
return LazyExpr(new_op=(self, 'acos', None))
def arcsin(self):
return LazyExpr(new_op=(self, 'asin', None))
def arctan(self):
return LazyExpr(new_op=(self, 'atan', None))
def arctan2(self, op2):
return LazyExpr(new_op=(self, 'atan2', op2))
def ceil(self):
return LazyExpr(new_op=(self, 'ceil', None))
def cos(self):
return LazyExpr(new_op=(self, 'cos', None))
def cosh(self):
return LazyExpr(new_op=(self, 'cosh', None))
def exp(self):
return LazyExpr(new_op=(self, 'exp', None))
def floor(self):
return LazyExpr(new_op=(self, 'floor', None))
def log(self):
return LazyExpr(new_op=(self, 'log', None))
def log10(self):
return LazyExpr(new_op=(self, 'log10', None))
def negative(self):
return LazyExpr(new_op=(self, 'negate', None))
def power(self, op2):
return LazyExpr(new_op=(self, 'pow', op2))
def sin(self):
return LazyExpr(new_op=(self, 'sin', None))
def sinh(self):
return LazyExpr(new_op=(self, 'sinh', None))
def sqrt(self):
return LazyExpr(new_op=(self, 'sqrt', None))
def tan(self):
return LazyExpr(new_op=(self, 'tan', None))
def tanh(self):
return LazyExpr(new_op=(self, 'tanh', None))
# The main expression class
class Expr(ext.Expression):
def __init__(self, **kwargs):
cfg = Config(**kwargs)
super().__init__(cfg)
class dtshape:
def __init__(self, shape=None, dtype=np.float64):
self.shape = shape
self.dtype = dtype
def to_tuple(self):
Dtshape = namedtuple('dtshape', 'shape dtype')
return Dtshape(self.shape, self.dtype)
class StorageProperties:
def __init__(self, backend="plainbuffer", chunkshape=None, blockshape=None, enforce_frame=False, filename=None):
if backend not in ("blosc", "plainbuffer"):
raise ValueError("backend can only be 'blosc' or 'plainbuffer'")
self.backend = backend
self.enforce_frame = True if filename else enforce_frame
self.filename = filename
if backend == "blosc" and (chunkshape is None or blockshape is None):
raise AttributeError("If the backend is a blosc schunk, the chunkshape/blockshape can not be None")
self.chunkshape = chunkshape
self.blockshape = blockshape
def to_tuple(self):
StoreProp = namedtuple('store_properties', 'backend chunkshape blockshape enforce_frame filename')
return StoreProp(self.backend, self.chunkshape, self.backend, self.enforce_frame, self.filename)
#
# Constructors
#
def empty(dtshape, **kwargs):
if dtshape.shape is None:
return AttributeError
cfg = Config(**kwargs)
return ext.empty(cfg, dtshape)
def arange(dtshape, start=None, stop=None, step=None, **kwargs):
cfg = Config(**kwargs)
if (start, stop, step) == (None, None, None):
stop = np.prod(dtshape.shape)
start = 0
step = 1
elif (stop, step) == (None, None):
stop = start
start = 0
step = 1
elif step is None:
stop = stop
start = start
if dtshape.shape is None:
step = 1
else:
step = (stop - start) / np.prod(dtshape.shape)
slice_ = slice(start, stop, step)
return ext.arange(cfg, slice_, dtshape)
def linspace(dtshape, start, stop, nelem=50, **kwargs):
cfg = Config(**kwargs)
shape, dtype = dtshape.to_tuple()
nelem = np.prod(shape) if dtshape is not None else nelem
return ext.linspace(cfg, nelem, start, stop, dtshape)
def zeros(dtshape, **kwargs):
cfg = Config(**kwargs)
if dtshape.shape is None:
return AttributeError
return ext.zeros(cfg, dtshape)
def ones(dtshape, **kwargs):
cfg = Config(**kwargs)
if dtshape.shape is None:
return AttributeError
return ext.ones(cfg, dtshape)
def full(dtshape, fill_value, **kwargs):
cfg = Config(**kwargs)
if dtshape.shape is None:
return AttributeError
return ext.full(cfg, fill_value, dtshape)
def save(c, filename, **kwargs):
cfg = Config(**kwargs)
return ext.save(cfg, c, filename)
def load(filename, load_in_mem=False, **kwargs):
cfg = Config(**kwargs)
return ext.load(cfg, filename, load_in_mem)
def iarray2numpy(iarr, **kwargs):
cfg = Config(**kwargs)
return ext.iarray2numpy(cfg, iarr)
def numpy2iarray(c, **kwargs):
cfg = Config(**kwargs)
if c.dtype == np.float64:
dtype = np.float64
elif c.dtype == np.float32:
dtype = np.float32
else:
raise NotImplementedError("Only float32 and float64 types are supported for now")
dtshape = ia.dtshape(c.shape, dtype)
return ext.numpy2iarray(cfg, c, dtshape)
def random_set_seed(seed):
ia.RANDOM_SEED = seed
def random_pre(**kwargs):
ia.RANDOM_SEED += 1
kwargs["seed"] = ia.RANDOM_SEED
return kwargs
def random_rand(dtshape, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_rand(cfg, dtshape)
def random_randn(dtshape, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_randn(cfg, dtshape)
def random_beta(dtshape, alpha, beta, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_beta(cfg, alpha, beta, dtshape)
def random_lognormal(dtshape, mu, sigma, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_lognormal(cfg, mu, sigma, dtshape)
def random_exponential(dtshape, beta, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_exponential(cfg, beta, dtshape)
def random_uniform(dtshape, a, b, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_uniform(cfg, a, b, dtshape)
def random_normal(dtshape, mu, sigma, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_normal(cfg, mu, sigma, dtshape)
def random_bernoulli(dtshape, p, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_bernoulli(cfg, p, dtshape)
def random_binomial(dtshape, m, p, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_binomial(cfg, m, p, dtshape)
def random_poisson(dtshape, lamb, **kwargs):
kwargs = random_pre(**kwargs)
cfg = Config(**kwargs)
return ext.random_poisson(cfg, lamb, dtshape)
def random_kstest(a, b, **kwargs):
cfg = Config(**kwargs)
return ext.random_kstest(cfg, a, b)
def matmul(a, b, block_a, block_b, **kwargs):
cfg = Config(**kwargs)
return ext.matmul(cfg, a, b, block_a, block_b)
def abs(iarr):
return iarr.abs()
def arccos(iarr):
return iarr.arccos()
def arcsin(iarr):
return iarr.arcsin()
def arctan(iarr):
return iarr.arctan()
def arctan2(iarr1, iarr2):
return iarr1.arctan2(iarr2)
def ceil(iarr):
return iarr.ceil()
def cos(iarr):
return iarr.cos()
def cosh(iarr):
return iarr.cosh()
def exp(iarr):
return iarr.exp()
def floor(iarr):
return iarr.floor()
def log(iarr):
return iarr.log()
def log10(iarr):
return iarr.log10()
def negative(iarr):
return iarr.negative()
def power(iarr1, iarr2):
return iarr1.power(iarr2)
def sin(iarr):
return iarr.sin()
def sinh(iarr):
return iarr.sinh()
def sqrt(iarr):
return iarr.sqrt()
def tan(iarr):
return iarr.tan()
def tanh(iarr):
return iarr.tanh()
if __name__ == "__main__":
# Create initial containers
shape = ia.dtshape([40], [20])
a1 = ia.linspace(shape, 0, 10)
# Evaluate with different methods
a3 = a1.sin() + 2 * a1 + 1
print(a3)
a3 += 2
print(a3)
a3_np = np.sin(ia.iarray2numpy(a1)) + 2 * ia.iarray2numpy(a1) + 1 + 2
# a4 = a3.eval(method="numexpr")
a4 = a3.eval(method="iarray_eval")
a4_np = ia.iarray2numpy(a4)
print(a4_np)
np.testing.assert_allclose(a3_np, a4_np)