/usr/share/pyshared/tables/expression.py is in python-tables 2.3.1-2ubuntu3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | ########################################################################
#
# License: BSD
# Created: June 12, 2009
# Author: Francesc Alted - faltet@pytables.com
#
# $Id$
#
########################################################################
"""Here is defined the Expr class.
See `Expr` class docstring for more info.
Classes:
Expr
Functions:
"""
import sys
import numpy as np
import tables as tb
import numexpr as ne
from numexpr.necompiler import (
getContext, getExprNames, getType, NumExpr)
from numexpr.expressions import functions as numexpr_functions
from tables.utilsExtension import lrange, getIndices
from tables.exceptions import PerformanceWarning
from tables.parameters import IO_BUFFER_SIZE, BUFFER_TIMES
class Expr(object):
"""A class for evaluating expressions with arbitrary array-like objects.
`Expr` is a class for evaluating expressions containing array-like
objects. With it, you can evaluate expressions (like '3*a+4*b')
that operate on arbitrary large arrays while optimizing the
resources (basically main memory and CPU cache memory) required to
perform them. It is similar to the Numexpr package, but in addition
to NumPy objects, it also accepts disk-based homogeneous arrays,
like the `Array`, `CArray`, `EArray` and `Column` PyTables objects.
All the internal computations are performed via the integrated
Numexpr package, so all the broadcast and upcasting rules applies
here too. These rules are very similar to the NumPy ones, but with
some exceptions due to the particularities of having to deal with
disk-based arrays. Be sure to read the documentation of the `Expr`
constructor and methods as well as that of Numexpr, if you want to
grasp these particularities.
"""
_exprvarsCache = {}
"""Cache of variables participating in expressions."""
def __init__(self, expr, uservars=None, **kwargs):
"""Compile the expression and initialize internal structures.
`expr` must be specified as a string like "2*a+3*b".
The `uservars` mapping may be used to define the variable names
appearing in `expr`. This mapping should consist of
identifier-like strings pointing to any `Array`, `CArray`,
`EArray`, `Column` or NumPy ndarray instances (or even others
which will tried to be converted to ndarrays).
When `uservars` is not provided or `None`, the current local and
global namespace is sought instead of `uservars`. It is also
possible to pass just some of the variables in expression via
the `uservars` mapping, and the rest will be retrieved from the
current local and global namespaces.
`**kwargs` is meant to pass additional parameters to the Numexpr
kernel. This is basically the same as the `**kwargs` argument
in `Numexpr.evaluate()`, and is mainly meant for advanced
use.
After initialized, an `Expr` instance can be evaluated via its
`eval()` method. This class also provides an `__iter__()`
method that iterates over all the resulting rows in expression.
Example of use:
>>> a = f.createArray('/', 'a', np.array([1,2,3]))
>>> b = f.createArray('/', 'b', np.array([3,4,5]))
>>> c = np.array([4,5,6])
>>> expr = tb.Expr("2*a+b*c") # initialize the expression
>>> expr.eval() # evaluate it
array([14, 24, 36])
>>> sum(expr) # use as an iterator
74
where you can see that you can mix different containers in the
expression (whenever shapes are consistent).
You can also work with multidimensional arrays:
>>> a2 = f.createArray('/', 'a2', np.array([[1,2],[3,4]]))
>>> b2 = f.createArray('/', 'b2', np.array([[3,4],[5,6]]))
>>> c2 = np.array([4,5]) # This will be broadcasted
>>> expr = tb.Expr("2*a2+b2-c2")
>>> expr.eval()
array([[1, 3],
[7, 9]])
>>> sum(expr)
array([ 8, 12])
"""
self.append_mode = False
"""The append mode for user-provided output containers."""
self.maindim = 0
"""Common main dimension for inputs in expression."""
self.names = []
"""The names of variables in expression (list)."""
self.out = None
"""The user-provided container (if any) for the expression outcome."""
self.o_start, self.o_stop, self.o_step = (None,)*3
"""The range selection for the user-provided output."""
self.shape = None
"""Common shape for the arrays in expression."""
self.start, self.stop, self.step = (None,)*3
"""The range selection for all the inputs."""
self.values = []
"""The values of variables in expression (list)."""
self._compiled_expr = None
"""The compiled expression."""
self._single_row_out = None
"""A sample of the output with just a single row."""
# First, get the signature for the arrays in expression
vars_ = self._requiredExprVars(expr, uservars)
context = getContext(kwargs)
self.names, _ = getExprNames(expr, context)
# Raise a ValueError in case we have unsupported objects
for name, var in vars_.items():
if type(var) in (int, long, float, str):
continue
if not isinstance(var, (tb.Leaf, tb.Column)):
if hasattr(var, "dtype"):
# Quacks like a NumPy object
continue
raise TypeError("Unsupported variable type: %r" % var)
objname = var.__class__.__name__
if objname not in ("Array", "CArray", "EArray", "Column"):
raise TypeError("Unsupported variable type: %r" % var)
# NumPy arrays to be copied? (we don't need to worry about
# PyTables objects, as the reads always return contiguous and
# aligned objects, or at least I think so).
copy_args = []
for name, var in vars_.items():
if type(var) == np.ndarray:
# See numexpr.necompiler.evaluate for a rational
# of the code below
if not var.flags.aligned:
if var.ndim == 1:
copy_args.append(name)
else:
# Do a copy of this variable
var = var.copy()
# Update the vars_ dictionary
vars_[name] = var
# Get the variables and types
values = self.values
types = []
for name in self.names:
value = vars_[name]
if hasattr(value, 'atom'):
types.append(value.atom)
elif hasattr(value, 'dtype'):
types.append(value)
else:
# try to convert into a NumPy array
value = np.array(value)
types.append(value)
values.append(value)
# Create a signature for the expression
signature = [(name, getType(type_))
for (name, type_) in zip(self.names, types)]
# Compile the expression
self._compiled_expr = NumExpr(expr, signature, copy_args, **kwargs)
# Guess the shape for the outcome and the maindim of inputs
self.shape, self.maindim = self._guess_shape()
# The next method is similar to their counterpart in `Table`, but
# adapted to the `Expr` own requirements.
def _requiredExprVars(self, expression, uservars, depth=2):
"""
Get the variables required by the `expression`.
A new dictionary defining the variables used in the `expression`
is returned. Required variables are first looked up in the
`uservars` mapping, then in the set of top-level columns of the
table. Unknown variables cause a `NameError` to be raised.
When `uservars` is `None`, the local and global namespace where
the API callable which uses this method is called is sought
instead. To disable this mechanism, just specify a mapping as
`uservars`.
Nested columns and variables with an ``uint64`` type are not
allowed (`TypeError` and `NotImplementedError` are raised,
respectively).
`depth` specifies the depth of the frame in order to reach local
or global variables.
"""
# Get the names of variables used in the expression.
exprvarsCache = self._exprvarsCache
if not expression in exprvarsCache:
# Protection against growing the cache too much
if len(exprvarsCache) > 256:
# Remove 10 (arbitrary) elements from the cache
for k in exprvarsCache.keys()[:10]:
del exprvarsCache[k]
cexpr = compile(expression, '<string>', 'eval')
exprvars = [ var for var in cexpr.co_names
if var not in ['None', 'False', 'True']
and var not in numexpr_functions ]
exprvarsCache[expression] = exprvars
else:
exprvars = exprvarsCache[expression]
# Get the local and global variable mappings of the user frame
# if no mapping has been explicitly given for user variables.
user_locals, user_globals = {}, {}
if uservars is None:
user_frame = sys._getframe(depth)
user_locals = user_frame.f_locals
user_globals = user_frame.f_globals
# Look for the required variables first among the ones
# explicitly provided by the user.
reqvars = {}
for var in exprvars:
# Get the value.
if uservars is not None and var in uservars:
val = uservars[var]
elif uservars is None and var in user_locals:
val = user_locals[var]
elif uservars is None and var in user_globals:
val = user_globals[var]
else:
raise NameError("name ``%s`` is not defined" % var)
# Check the value.
if hasattr(val, 'dtype') and val.dtype.str[1:] == 'u8':
raise NotImplementedError(
"variable ``%s`` refers to "
"a 64-bit unsigned integer object, that is "
"not yet supported in expressions, sorry; " % var )
elif hasattr(val, '_v_colpathnames'): # nested column
# This branch is never reached because the compile step
# above already raise a ``TypeError`` for nested
# columns, but that could change in the future. So it
# is best to let this here.
raise TypeError(
"variable ``%s`` refers to a nested column, "
"not allowed in expressions" % var )
reqvars[var] = val
return reqvars
def setInputsRange(self, start=None, stop=None, step=None):
"""Define a range for all inputs in expression.
The computation will only take place for the range defined by
the `start`, `stop` and `step` parameters in the main dimension
of inputs (or the leading one, if the object lacks the concept
of main dimension, like a NumPy container). If not a common
main dimension exists for all inputs, the leading dimension will
be used instead.
"""
self.start = start
self.stop = stop
self.step = step
def setOutput(self, out, append_mode=False):
"""Set `out` as container for output as well as the `append_mode`.
The `out` must be a container that is meant to keep the outcome
of the expression. It should be an homogeneous type container
and can typically be an `Array`, `CArray`, `EArray`, `Column` or
a NumPy ndarray.
The `append_mode` specifies the way of which the output is
filled. If true, the rows of the outcome are ``appended`` to
the `out` container. Of course, for doing this it is necessary
that `out` would have an `append()` method (like an `EArray`,
for example).
If `append_mode` is false, the output is set via the
`__setitem__()` method (see the `Expr.setOutputRange()` for info
on how to select the rows to be updated). If `out` is smaller
than what is required by the expression, only the computations
that are needed to fill up the container are carried out. If it
is larger, the excess elements are unaffected.
"""
if not (hasattr(out, "shape") and hasattr(out, "__setitem__")):
raise ValueError(
"You need to pass a settable multidimensional container "
"as output")
self.out = out
if append_mode and not hasattr(out, "append"):
raise ValueError(
"For activating the ``append`` mode, you need a container "
"with an `append()` method (like the `EArray`)")
self.append_mode = append_mode
def setOutputRange(self, start=None, stop=None, step=None):
"""Define a range for user-provided output object.
The output object will only be modified in the range specified
by the `start`, `stop` and `step` parameters in the main
dimension of output (or the leading one, if the object does not
have the concept of main dimension, like a NumPy container).
"""
if self.out is None:
raise IndexError(
"You need to pass an output object to `setOut()` first")
self.o_start = start
self.o_stop = stop
self.o_step = step
# Although the next code is similar to the method in `Leaf`, it
# allows the use of pure NumPy objects.
def _calc_nrowsinbuf(self, object_):
"""Calculate the number of rows that will fit in a buffer."""
# Compute the rowsize for the *leading* dimension
shape_ = list(object_.shape)
if shape_:
expectedrows = shape_[0]
shape_[0] = 1
else:
expectedrows = 0
rowsize = np.prod(shape_) * object_.dtype.itemsize
# Compute the nrowsinbuf
# Multiplying the I/O buffer size by 4 gives optimal results
# in my benchmarks with `tables.Expr` (see ``bench/poly.py``)
buffersize = IO_BUFFER_SIZE*4
nrowsinbuf = buffersize // rowsize
# Safeguard against row sizes being extremely large
if nrowsinbuf == 0:
nrowsinbuf = 1
# If rowsize is too large, issue a Performance warning
maxrowsize = BUFFER_TIMES * buffersize
if rowsize > maxrowsize:
warnings.warn("""\
The object ``%s`` is exceeding the maximum recommended rowsize (%d
bytes); be ready to see PyTables asking for *lots* of memory and
possibly slow I/O. You may want to reduce the rowsize by trimming the
value of dimensions that are orthogonal (and preferably close) to the
*leading* dimension of this object."""
% (object, maxrowsize),
PerformanceWarning)
return nrowsinbuf
def _guess_shape(self):
"""Guess the shape of the output of the expression."""
# First, compute the maximum dimension of inputs and maindim
# (if it exists)
maxndim = 0
maindims = []
for val in self.values:
# Get the minimum of the lengths
if len(val.shape) > maxndim:
maxndim = len(val.shape)
if hasattr(val, "maindim"):
maindims.append(val.maindim)
if maxndim == 0:
self._single_row_out = out = self._compiled_expr(*self.values)
return (), None
if maindims and [maindims[0]]*len(maindims) == maindims:
# If all maindims detected are the same, use this as maindim
maindim = maindims[0]
else:
# If not, the main dimension will be the default one
maindim = 0
# The slices parameter for inputs
slices = (slice(None),)*maindim + (0,)
# Now, collect the values in first row of arrays with maximum dims
vals = []; lens = []
for val in self.values:
shape = val.shape
# Warning: don't use len(val) below or it will raise an
# `Overflow` error on 32-bit platforms for large enough arrays.
if shape != () and shape[maindim] == 0:
vals.append(val[:])
lens.append(0)
elif len(shape) < maxndim:
vals.append(val)
else:
vals.append(val.__getitem__(slices))
lens.append(shape[maindim])
minlen = min(lens)
self._single_row_out = out = self._compiled_expr(*vals)
shape = list(out.shape)
if minlen > 0:
shape.insert(maindim, minlen)
return shape, maindim
def _get_info(self, shape, maindim, itermode=False):
"""Return various info needed for evaluating the computation loop."""
# Compute the shape of the resulting container having
# in account new possible values of start, stop and step in
# the inputs range
if maindim is not None:
(start, stop, step) = getIndices(
self.start, self.stop, self.step, shape[maindim])
shape[maindim] = min(
shape[maindim], lrange(start, stop, step).length)
i_nrows = shape[maindim]
else:
start, stop, step = 0, 0, None
i_nrows = 0
if not itermode:
# Create a container for output if not defined yet
o_maindim = 0 # Default maindim
if self.out is None:
out = np.empty(shape, dtype=self._single_row_out.dtype)
# Get the trivial values for start, stop and step
if maindim is not None:
(o_start, o_stop, o_step) = (0, shape[maindim], 1)
else:
(o_start, o_stop, o_step) = (0, 0, 1)
else:
out = self.out
# Out container already provided. Do some sanity checks.
if hasattr(out, "maindim"):
o_maindim = out.maindim
# Refine the shape of the resulting container having in
# account new possible values of start, stop and step in
# the output range
o_shape = list(out.shape)
(o_start, o_stop, o_step) = getIndices(
self.o_start, self.o_stop, self.o_step, o_shape[o_maindim])
o_shape[o_maindim] = min(o_shape[o_maindim],
lrange(o_start, o_stop, o_step).length)
o_nrows = o_shape[o_maindim]
# Check that the shape of output is consistent with inputs
tr_oshape = list(o_shape) # this implies a copy
olen_ = tr_oshape.pop(o_maindim)
tr_shape = list(shape) # do a copy
if maindim is not None:
len_ = tr_shape.pop(o_maindim)
else:
len_ = 1
if tr_oshape != tr_shape:
raise ValueError(
"Shape for out container does not match expression")
# Force the input length to fit in `out`
if not self.append_mode and olen_ < len_:
shape[o_maindim] = olen_
stop = start + olen_
# Get the positions of inputs that should be sliced (the others
# will be broadcasted)
ndim = len(shape)
slice_pos = [i for i, val in enumerate(self.values)
if len(val.shape) == ndim]
# The size of the I/O buffer
nrowsinbuf = 1
for i, val in enumerate(self.values):
# Skip scalar values in variables
if i in slice_pos:
nrows = self._calc_nrowsinbuf(val)
if nrows > nrowsinbuf:
nrowsinbuf = nrows
if not itermode:
return (i_nrows, slice_pos, start, stop, step, nrowsinbuf,
out, o_maindim, o_start, o_stop, o_step)
else:
# For itermode, we don't need the out info
return (i_nrows, slice_pos, start, stop, step, nrowsinbuf)
def eval(self):
"""Evaluate the expression and return the outcome.
Because of performance reasons, the computation order tries to
go along the common main dimension of all inputs. If not such a
common main dimension is found, the iteration will go along the
leading dimension instead.
For non-consistent shapes in inputs (i.e. shapes having a
different number of dimensions), the regular NumPy broadcast
rules applies. There is one exception to this rule though: when
the dimensions orthogonal to the main dimension of the
expression are consistent, but the main dimension itself differs
among the inputs, then the shortest one is chosen for doing the
computations. This is so because trying to expand very large
on-disk arrays could be too expensive or simply not possible.
Also, the regular Numexpr casting rules (which are similar to
those of NumPy, although you should check the Numexpr manual for
the exceptions) are applied to determine the output type.
Finally, if the `setOuput()` method specifiying a user container
has already been called, the output is sent to this user-provided
container. If not, a fresh NumPy container is returned instead.
For some examples of use see the `Expr.__init__()` docstrings.
.. Warning:: When dealing with large on-disk inputs, failing to
specify an on-disk container may consume all your available
memory.
"""
values, shape, maindim = self.values, self.shape, self.maindim
# Get different info we need for the main computation loop
(i_nrows, slice_pos, start, stop, step, nrowsinbuf,
out, o_maindim, o_start, o_stop, o_step) = \
self._get_info(shape, maindim)
if i_nrows == 0:
# No elements to compute
return self._single_row_out
# Create a key that selects every element in inputs and output
# (including the main dimension)
i_slices = [slice(None)]*(maindim+1)
o_slices = [slice(None)]*(o_maindim+1)
# This is a hack to prevent doing unnecessary flavor conversions
# while reading buffers
for val in values:
if hasattr(val, 'maindim'):
val._v_convert = False
# Start the computation itself
for start2 in lrange(start, stop, step*nrowsinbuf):
stop2 = start2 + step * nrowsinbuf
if stop2 > stop:
stop2 = stop
# Set the proper slice for inputs
i_slices[maindim] = slice(start2, stop2, step)
# Get the input values
vals = []
for i, val in enumerate(values):
if i in slice_pos:
vals.append(val.__getitem__(tuple(i_slices)))
else:
# A read of values is not apparently needed, as PyTables
# leaves seems to work just fine inside Numexpr
vals.append(val)
# Do the actual computation for this slice
rout = self._compiled_expr(*vals)
# Set the values into the out buffer
if self.append_mode:
out.append(rout)
else:
# Compute the slice to be filled in output
start3 = o_start + (start2-start)/step
stop3 = start3 + nrowsinbuf*o_step
if stop3 > o_stop:
stop3 = o_stop
o_slices[o_maindim] = slice(start3, stop3, o_step)
# Set the slice
out[tuple(o_slices)] = rout
# Activate the conversion again (default)
for val in values:
if hasattr(val, 'maindim'):
val._v_convert = True
return out
def __iter__(self):
"""Iterate over the rows of the outcome of the expression.
This iterator always returns rows as NumPy objects, so a
possible `out` container specified in `Expr.setOutput()` method
is ignored here.
See the `Expr.eval()` documentation for details on how the
computation is carried out. Also, for some examples of use see
the `Expr.__init__()` docstrings.
"""
values, shape, maindim = self.values, self.shape, self.maindim
# Get different info we need for the main computation loop
(i_nrows, slice_pos, start, stop, step, nrowsinbuf) = \
self._get_info(shape, maindim, itermode=True)
if i_nrows == 0:
# No elements to compute
return
# Create a key that selects every element in inputs
# (including the main dimension)
i_slices = [slice(None)]*(maindim+1)
# This is a hack to prevent doing unnecessary flavor conversions
# while reading buffers
for val in values:
if hasattr(val, 'maindim'):
val._v_convert = False
# Start the computation itself
for start2 in lrange(start, stop, step*nrowsinbuf):
stop2 = start2 + step * nrowsinbuf
if stop2 > stop:
stop2 = stop
# Set the proper slice in the main dimension
i_slices[maindim] = slice(start2, stop2, step)
# Get the values for computing the buffer
vals = []
for i, val in enumerate(values):
if i in slice_pos:
vals.append(val.__getitem__(tuple(i_slices)))
else:
# A read of values is not apparently needed, as PyTables
# leaves seems to work just fine inside Numexpr
vals.append(val)
# Do the actual computation
rout = self._compiled_expr(*vals)
# Return one row per call
for row in rout:
yield row
# Activate the conversion again (default)
for val in values:
if hasattr(val, 'maindim'):
val._v_convert = True
if __name__=="__main__":
#shape = (10000,10000)
shape = (10,10000)
f = tb.openFile("/tmp/expression.h5", "w")
# Create some arrays
a = f.createCArray(f.root, 'a', tb.Float32Atom(dflt=1.), shape)
b = f.createCArray(f.root, 'b', tb.Float32Atom(dflt=2.), shape)
c = f.createCArray(f.root, 'c', tb.Float32Atom(dflt=3.), shape)
out = f.createCArray(f.root, 'out', tb.Float32Atom(dflt=3.), shape)
expr = Expr("a*b+c")
expr.setOutput(out)
d = expr.eval()
print "returned-->", `d`
#print `d[:]`
f.close()
## Local Variables:
## mode: python
## py-indent-offset: 4
## tab-width: 4
## fill-column: 72
## End:
|