numexpr 2.14.2__cp313-cp313-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
numexpr/expressions.py ADDED
@@ -0,0 +1,546 @@
1
+ ###################################################################
2
+ # Numexpr - Fast numerical array expression evaluator for NumPy.
3
+ #
4
+ # License: MIT
5
+ # Author: See AUTHORS.txt
6
+ #
7
+ # See LICENSE.txt and LICENSES/*.txt for details about copyright and
8
+ # rights to use.
9
+ ####################################################################
10
+
11
+ __all__ = ['E']
12
+
13
+ import operator
14
+ import sys
15
+ import threading
16
+
17
+ import numpy
18
+
19
+ # Declare a double type that does not exist in Python space
20
+ double = numpy.double
21
+
22
+ # The default kind for undeclared variables
23
+ default_kind = 'double'
24
+ int_ = numpy.int32
25
+ long_ = numpy.int64
26
+
27
+ type_to_kind = {bool: 'bool', int_: 'int', long_: 'long', float: 'float',
28
+ double: 'double', complex: 'complex', bytes: 'bytes', str: 'str'}
29
+ kind_to_type = {'bool': bool, 'int': int_, 'long': long_, 'float': float,
30
+ 'double': double, 'complex': complex, 'bytes': bytes, 'str': str}
31
+ kind_rank = ('bool', 'int', 'long', 'float', 'double', 'complex', 'none')
32
+ scalar_constant_types = [bool, int_, int, float, double, complex, bytes, str]
33
+
34
+ scalar_constant_types = tuple(scalar_constant_types)
35
+
36
+ from numexpr import interpreter
37
+
38
+
39
+ class Expression():
40
+
41
+ def __getattr__(self, name):
42
+ if name.startswith('_'):
43
+ try:
44
+ return self.__dict__[name]
45
+ except KeyError:
46
+ raise AttributeError
47
+ else:
48
+ return VariableNode(name, default_kind)
49
+
50
+
51
+ E = Expression()
52
+
53
+
54
+ class Context(threading.local):
55
+
56
+ def get(self, value, default):
57
+ return self.__dict__.get(value, default)
58
+
59
+ def get_current_context(self):
60
+ return self.__dict__
61
+
62
+ def set_new_context(self, dict_):
63
+ self.__dict__.update(dict_)
64
+
65
+ # This will be called each time the local object is used in a separate thread
66
+ _context = Context()
67
+
68
+
69
+ def get_optimization():
70
+ return _context.get('optimization', 'none')
71
+
72
+
73
+ # helper functions for creating __magic__ methods
74
+ def ophelper(f):
75
+ def func(*args):
76
+ args = list(args)
77
+ for i, x in enumerate(args):
78
+ if isConstant(x):
79
+ args[i] = x = ConstantNode(x)
80
+ if not isinstance(x, ExpressionNode):
81
+ raise TypeError("unsupported object type: %s" % type(x))
82
+ return f(*args)
83
+
84
+ func.__name__ = f.__name__
85
+ func.__doc__ = f.__doc__
86
+ func.__dict__.update(f.__dict__)
87
+ return func
88
+
89
+
90
+ def allConstantNodes(args):
91
+ "returns True if args are all ConstantNodes."
92
+ for x in args:
93
+ if not isinstance(x, ConstantNode):
94
+ return False
95
+ return True
96
+
97
+
98
+ def isConstant(ex):
99
+ "Returns True if ex is a constant scalar of an allowed type."
100
+ return isinstance(ex, scalar_constant_types)
101
+
102
+
103
+ def commonKind(nodes):
104
+ node_kinds = [node.astKind for node in nodes]
105
+ str_count = node_kinds.count('bytes') + node_kinds.count('str')
106
+ if 0 < str_count < len(node_kinds): # some args are strings, but not all
107
+ raise TypeError("strings can only be operated with strings")
108
+ if str_count > 0: # if there are some, all of them must be
109
+ return 'bytes'
110
+ n = -1
111
+ for x in nodes:
112
+ n = max(n, kind_rank.index(x.astKind))
113
+ return kind_rank[n]
114
+
115
+
116
+ max_int32 = 2147483647
117
+ min_int32 = -max_int32 - 1
118
+
119
+
120
+ def bestConstantType(x):
121
+ # ``numpy.string_`` is a subclass of ``bytes``
122
+ if isinstance(x, (bytes, str)):
123
+ return bytes
124
+ # Numeric conversion to boolean values is not tried because
125
+ # ``bool(1) == True`` (same for 0 and False), so 0 and 1 would be
126
+ # interpreted as booleans when ``False`` and ``True`` are already
127
+ # supported.
128
+ if isinstance(x, (bool, numpy.bool_)):
129
+ return bool
130
+ # ``long`` objects are kept as is to allow the user to force
131
+ # promotion of results by using long constants, e.g. by operating
132
+ # a 32-bit array with a long (64-bit) constant.
133
+ if isinstance(x, (long_, numpy.int64)):
134
+ return long_
135
+ # ``double`` objects are kept as is to allow the user to force
136
+ # promotion of results by using double constants, e.g. by operating
137
+ # a float (32-bit) array with a double (64-bit) constant.
138
+ if isinstance(x, double):
139
+ return double
140
+ if isinstance(x, numpy.float32):
141
+ return float
142
+ if isinstance(x, (int, numpy.integer)):
143
+ # Constants needing more than 32 bits are always
144
+ # considered ``long``, *regardless of the platform*, so we
145
+ # can clearly tell 32- and 64-bit constants apart.
146
+ if not (min_int32 <= x <= max_int32):
147
+ return long_
148
+ return int_
149
+ # The duality of float and double in Python avoids that we have to list
150
+ # ``double`` too.
151
+ for converter in float, complex:
152
+ try:
153
+ y = converter(x)
154
+ except Exception as err:
155
+ continue
156
+ if y == x or numpy.isnan(y):
157
+ return converter
158
+
159
+
160
+ def getKind(x):
161
+ converter = bestConstantType(x)
162
+ return type_to_kind[converter]
163
+
164
+
165
+ def binop(opname, reversed=False, kind=None):
166
+ # Getting the named method from self (after reversal) does not
167
+ # always work (e.g. int constants do not have a __lt__ method).
168
+ opfunc = getattr(operator, "__%s__" % opname)
169
+
170
+ @ophelper
171
+ def operation(self, other):
172
+ if reversed:
173
+ self, other = other, self
174
+ if allConstantNodes([self, other]):
175
+ return ConstantNode(opfunc(self.value, other.value))
176
+ else:
177
+ return OpNode(opname, (self, other), kind=kind)
178
+
179
+ return operation
180
+
181
+
182
+ def func(func, minkind=None, maxkind=None):
183
+ @ophelper
184
+ def function(*args):
185
+ if allConstantNodes(args):
186
+ return ConstantNode(func(*[x.value for x in args]))
187
+ kind = commonKind(args)
188
+ if kind in ('int', 'long'):
189
+ if func.__name__ not in ('copy', 'abs', 'ones_like', 'round', 'sign'):
190
+ # except for these special functions (which return ints for int inputs in NumPy)
191
+ # just do a cast to double
192
+ # FIXME: 'fmod' outputs ints for NumPy when inputs are ints, but need to
193
+ # add new function signatures FUNC_LLL FUNC_III to support this
194
+ kind = 'double'
195
+ else:
196
+ # Apply regular casting rules
197
+ if minkind and kind_rank.index(minkind) > kind_rank.index(kind):
198
+ kind = minkind
199
+ if maxkind and kind_rank.index(maxkind) < kind_rank.index(kind):
200
+ kind = maxkind
201
+ return FuncNode(func.__name__, args, kind)
202
+
203
+ return function
204
+
205
+
206
+ @ophelper
207
+ def where_func(a, b, c):
208
+ if isinstance(a, ConstantNode):
209
+ return b if a.value else c
210
+ if allConstantNodes([a, b, c]):
211
+ return ConstantNode(numpy.where(a, b, c))
212
+ return FuncNode('where', [a, b, c])
213
+
214
+
215
+ def encode_axis(axis):
216
+ if isinstance(axis, ConstantNode):
217
+ axis = axis.value
218
+ if axis is None:
219
+ axis = interpreter.allaxes
220
+ else:
221
+ if axis < 0:
222
+ raise ValueError("negative axis are not supported")
223
+ if axis > 254:
224
+ raise ValueError("cannot encode axis")
225
+ return RawNode(axis)
226
+
227
+
228
+ def gen_reduce_axis_func(name):
229
+ def _func(a, axis=None):
230
+ axis = encode_axis(axis)
231
+ if isinstance(a, ConstantNode):
232
+ return a
233
+ if isinstance(a, (bool, int_, long_, float, double, complex)):
234
+ a = ConstantNode(a)
235
+ return FuncNode(name, [a, axis], kind=a.astKind)
236
+ return _func
237
+
238
+
239
+ @ophelper
240
+ def contains_func(a, b):
241
+ return FuncNode('contains', [a, b], kind='bool')
242
+
243
+
244
+ @ophelper
245
+ def div_op(a, b):
246
+ if get_optimization() in ('moderate', 'aggressive'):
247
+ if (isinstance(b, ConstantNode) and
248
+ (a.astKind == b.astKind) and
249
+ a.astKind in ('float', 'double', 'complex')):
250
+ return OpNode('mul', [a, ConstantNode(1. / b.value)])
251
+ return OpNode('div', [a, b])
252
+
253
+
254
+ @ophelper
255
+ def truediv_op(a, b):
256
+ if get_optimization() in ('moderate', 'aggressive'):
257
+ if (isinstance(b, ConstantNode) and
258
+ (a.astKind == b.astKind) and
259
+ a.astKind in ('float', 'double', 'complex')):
260
+ return OpNode('mul', [a, ConstantNode(1. / b.value)])
261
+ kind = commonKind([a, b])
262
+ if kind in ('bool', 'int', 'long'):
263
+ kind = 'double'
264
+ return OpNode('div', [a, b], kind=kind)
265
+
266
+
267
+ @ophelper
268
+ def rtruediv_op(a, b):
269
+ return truediv_op(b, a)
270
+
271
+
272
+ @ophelper
273
+ def pow_op(a, b):
274
+
275
+ if isinstance(b, ConstantNode):
276
+ x = b.value
277
+ if ( a.astKind in ('int', 'long') and
278
+ b.astKind in ('int', 'long') and x < 0) :
279
+ raise ValueError(
280
+ 'Integers to negative integer powers are not allowed.')
281
+ if get_optimization() == 'aggressive':
282
+ RANGE = 50 # Approximate break even point with pow(x,y)
283
+ # Optimize all integral and half integral powers in [-RANGE, RANGE]
284
+ # Note: for complex numbers RANGE could be larger.
285
+ if (int(2 * x) == 2 * x) and (-RANGE <= abs(x) <= RANGE):
286
+ n = int_(abs(x))
287
+ ishalfpower = int_(abs(2 * x)) % 2
288
+
289
+ def multiply(x, y):
290
+ if x is None: return y
291
+ return OpNode('mul', [x, y])
292
+
293
+ r = None
294
+ p = a
295
+ mask = 1
296
+ while True:
297
+ if (n & mask):
298
+ r = multiply(r, p)
299
+ mask <<= 1
300
+ if mask > n:
301
+ break
302
+ p = OpNode('mul', [p, p])
303
+ if ishalfpower:
304
+ kind = commonKind([a])
305
+ if kind in ('int', 'long'):
306
+ kind = 'double'
307
+ r = multiply(r, OpNode('sqrt', [a], kind))
308
+ if r is None:
309
+ r = OpNode('ones_like', [a])
310
+ if x < 0:
311
+ # Issue #428
312
+ r = truediv_op(ConstantNode(1), r)
313
+ return r
314
+ if get_optimization() in ('moderate', 'aggressive'):
315
+ if x == -1:
316
+ return OpNode('div', [ConstantNode(1), a])
317
+ if x == 0:
318
+ return OpNode('ones_like', [a])
319
+ if x == 0.5:
320
+ kind = a.astKind
321
+ if kind in ('int', 'long'): kind = 'double'
322
+ return FuncNode('sqrt', [a], kind=kind)
323
+ if x == 1:
324
+ return a
325
+ if x == 2:
326
+ return OpNode('mul', [a, a])
327
+ return OpNode('pow', [a, b])
328
+
329
+ # The functions and the minimum and maximum types accepted
330
+ numpy.expm1x = numpy.expm1
331
+ functions = {
332
+ 'copy': func(numpy.copy),
333
+ 'ones_like': func(numpy.ones_like),
334
+ 'sqrt': func(numpy.sqrt, 'float'),
335
+
336
+ 'sin': func(numpy.sin, 'float'),
337
+ 'cos': func(numpy.cos, 'float'),
338
+ 'tan': func(numpy.tan, 'float'),
339
+ 'arcsin': func(numpy.arcsin, 'float'),
340
+ 'arccos': func(numpy.arccos, 'float'),
341
+ 'arctan': func(numpy.arctan, 'float'),
342
+
343
+ 'sinh': func(numpy.sinh, 'float'),
344
+ 'cosh': func(numpy.cosh, 'float'),
345
+ 'tanh': func(numpy.tanh, 'float'),
346
+ 'arcsinh': func(numpy.arcsinh, 'float'),
347
+ 'arccosh': func(numpy.arccosh, 'float'),
348
+ 'arctanh': func(numpy.arctanh, 'float'),
349
+
350
+ 'fmod': func(numpy.fmod, 'float'),
351
+ 'arctan2': func(numpy.arctan2, 'float'),
352
+ 'hypot': func(numpy.hypot, 'double'),
353
+ 'nextafter': func(numpy.nextafter, 'double'),
354
+ 'copysign': func(numpy.copysign, 'double'),
355
+ 'maximum': func(numpy.maximum, 'double'),
356
+ 'minimum': func(numpy.minimum, 'double'),
357
+
358
+
359
+ 'log': func(numpy.log, 'float'),
360
+ 'log1p': func(numpy.log1p, 'float'),
361
+ 'log10': func(numpy.log10, 'float'),
362
+ 'log2': func(numpy.log2, 'float'),
363
+ 'exp': func(numpy.exp, 'float'),
364
+ 'expm1': func(numpy.expm1, 'float'),
365
+
366
+ 'abs': func(numpy.absolute, 'float'),
367
+ 'ceil': func(numpy.ceil, 'float', 'double'),
368
+ 'floor': func(numpy.floor, 'float', 'double'),
369
+ 'round': func(numpy.round, 'double'),
370
+ 'trunc': func(numpy.trunc, 'double'),
371
+ 'sign': func(numpy.sign, 'double'),
372
+
373
+ 'where': where_func,
374
+
375
+ 'real': func(numpy.real, 'double', 'double'),
376
+ 'imag': func(numpy.imag, 'double', 'double'),
377
+ 'complex': func(complex, 'complex'),
378
+ 'conj': func(numpy.conj, 'complex'),
379
+
380
+ 'isnan': func(numpy.isnan, 'double'),
381
+ 'isfinite': func(numpy.isfinite, 'double'),
382
+ 'isinf': func(numpy.isinf, 'double'),
383
+ 'signbit': func(numpy.signbit, 'double'),
384
+
385
+ 'sum': gen_reduce_axis_func('sum'),
386
+ 'prod': gen_reduce_axis_func('prod'),
387
+ 'min': gen_reduce_axis_func('min'),
388
+ 'max': gen_reduce_axis_func('max'),
389
+ 'contains': contains_func,
390
+ }
391
+
392
+
393
+ class ExpressionNode():
394
+ """
395
+ An object that represents a generic number object.
396
+
397
+ This implements the number special methods so that we can keep
398
+ track of how this object has been used.
399
+ """
400
+ astType = 'generic'
401
+
402
+ def __init__(self, value=None, kind=None, children=None):
403
+ self.value = value
404
+ if kind is None:
405
+ kind = 'none'
406
+ self.astKind = kind
407
+ if children is None:
408
+ self.children = ()
409
+ else:
410
+ self.children = tuple(children)
411
+
412
+ def get_real(self):
413
+ if self.astType == 'constant':
414
+ return ConstantNode(complex(self.value).real)
415
+ return OpNode('real', (self,), 'double')
416
+
417
+ real = property(get_real)
418
+
419
+ def get_imag(self):
420
+ if self.astType == 'constant':
421
+ return ConstantNode(complex(self.value).imag)
422
+ return OpNode('imag', (self,), 'double')
423
+
424
+ imag = property(get_imag)
425
+
426
+ def __str__(self):
427
+ return '%s(%s, %s, %s)' % (self.__class__.__name__, self.value,
428
+ self.astKind, self.children)
429
+
430
+ def __repr__(self):
431
+ return self.__str__()
432
+
433
+ def __neg__(self):
434
+ return OpNode('neg', (self,))
435
+
436
+ def __invert__(self):
437
+ return OpNode('invert', (self,))
438
+
439
+ def __pos__(self):
440
+ return self
441
+
442
+ # The next check is commented out. See #24 for more info.
443
+
444
+ def __bool__(self):
445
+ raise TypeError("You can't use Python's standard boolean operators in "
446
+ "NumExpr expressions. You should use their bitwise "
447
+ "counterparts instead: '&' instead of 'and', "
448
+ "'|' instead of 'or', and '~' instead of 'not'.")
449
+
450
+ __add__ = __radd__ = binop('add')
451
+ __sub__ = binop('sub')
452
+ __rsub__ = binop('sub', reversed=True)
453
+ __mul__ = __rmul__ = binop('mul')
454
+ __truediv__ = truediv_op
455
+ __rtruediv__ = rtruediv_op
456
+ __floordiv__ = binop("floordiv")
457
+ __pow__ = pow_op
458
+ __rpow__ = binop('pow', reversed=True)
459
+ __mod__ = binop('mod')
460
+ __rmod__ = binop('mod', reversed=True)
461
+
462
+ __lshift__ = binop('lshift')
463
+ __rlshift__ = binop('lshift', reversed=True)
464
+ __rshift__ = binop('rshift')
465
+ __rrshift__ = binop('rshift', reversed=True)
466
+
467
+ # bitwise or logical operations
468
+ __and__ = binop('and')
469
+ __or__ = binop('or')
470
+ __xor__ = binop('xor')
471
+
472
+ __gt__ = binop('gt', kind='bool')
473
+ __ge__ = binop('ge', kind='bool')
474
+ __eq__ = binop('eq', kind='bool')
475
+ __ne__ = binop('ne', kind='bool')
476
+ __lt__ = binop('gt', reversed=True, kind='bool')
477
+ __le__ = binop('ge', reversed=True, kind='bool')
478
+
479
+
480
+ class LeafNode(ExpressionNode):
481
+ leafNode = True
482
+
483
+
484
+ class VariableNode(LeafNode):
485
+ astType = 'variable'
486
+
487
+ def __init__(self, value=None, kind=None, children=None):
488
+ LeafNode.__init__(self, value=value, kind=kind)
489
+
490
+
491
+ class RawNode():
492
+ """
493
+ Used to pass raw integers to interpreter.
494
+ For instance, for selecting what function to use in func1.
495
+ Purposely don't inherit from ExpressionNode, since we don't wan't
496
+ this to be used for anything but being walked.
497
+ """
498
+ astType = 'raw'
499
+ astKind = 'none'
500
+
501
+ def __init__(self, value):
502
+ self.value = value
503
+ self.children = ()
504
+
505
+ def __str__(self):
506
+ return 'RawNode(%s)' % (self.value,)
507
+
508
+ __repr__ = __str__
509
+
510
+
511
+ class ConstantNode(LeafNode):
512
+ astType = 'constant'
513
+
514
+ def __init__(self, value=None, children=None):
515
+ kind = getKind(value)
516
+ # Python float constants are double precision by default
517
+ if kind == 'float' and isinstance(value, float):
518
+ kind = 'double'
519
+ LeafNode.__init__(self, value=value, kind=kind)
520
+
521
+ def __neg__(self):
522
+ return ConstantNode(-self.value)
523
+
524
+ def __invert__(self):
525
+ return ConstantNode(~self.value)
526
+
527
+
528
+ class OpNode(ExpressionNode):
529
+ astType = 'op'
530
+
531
+ def __init__(self, opcode=None, args=None, kind=None):
532
+ if (kind is None) and (args is not None):
533
+ kind = commonKind(args)
534
+ if kind=='bool': # handle bool*bool and bool+bool cases
535
+ opcode = 'and' if opcode=='mul' else opcode
536
+ opcode = 'or' if opcode=='add' else opcode
537
+ ExpressionNode.__init__(self, value=opcode, kind=kind, children=args)
538
+
539
+
540
+ class FuncNode(OpNode):
541
+ def __init__(self, opcode=None, args=None, kind=None):
542
+ if (kind is None) and (args is not None):
543
+ kind = commonKind(args)
544
+ if opcode in ("isnan", "isfinite", "isinf", "signbit"): # bodge for boolean return functions
545
+ kind = 'bool'
546
+ OpNode.__init__(self, opcode, args, kind)